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 |
|---|---|---|---|---|---|
I get this problem where I am copying words into a list as words are entered. Essentially everytime a word is entered, I create a node and link that into the list.
At the end, I print out the list, but for some reason I only get the last word that I entered printing, several times.
My head and tail are globalsMy head and tail are globalsCode:list print () { list current = head; while(current != NULL) { printf("%s\n", current->string); current = current->next; } return (head); } void list (char *input) { list node; node = makeN(); if(head == NULL) { head = node; tail =node; head->string= input; tail->string = input; } else { tail->next = node; tail = tail->next; tail->word = input; } } | http://cboard.cprogramming.com/c-programming/103372-linked-list-problem.html | CC-MAIN-2014-49 | refinedweb | 116 | 67.28 |
In this tutorial, we will find out about quick find - one of implementations in Union-Find. And understanding Quick Find has advantages and disadvantages that will make us confidence to implement.
Table of contents
Introduction to Quick Find Find is one of the implementations of Union-Find algorithm.
Source code
- Data structure
- Maintain array id[] with name for each component.
- If p and q are connected, then same id.
- Initialize id[i] = i.
Find operation: check if p and q have the same id.
Union operation: to merge components containing p and q, change all entries whose id equals id[p] and id[q]. So, we have a problem: many values can be changed.
- Analysis:
- Find operation takes a constant number of operations.
- Union operation takes time proportional to N. This is very slow.
public class QuickFindUF { private int[] id; // set id of each object to itself (N array access) public QuickFindUF(int N) { id = new int[N]; for (int i = 0; i < N; ++i) { id[i] = i; } } int find(int i) { return id[i]; } // check whether p and q are in the same // component (2 array access) public boolean connected(int p, int q) { return id[p] == id[q]; } // change all entries with id[p] to id[q] // (at most 2N + 2 array access public void union(int p, int q) { int pid = id[p]; int qid = id[q]; for (int i = 0; i < id.length; ++i) { if (id[i] == pid) { id[i] = qid; } } } }
Drawbacks of Quick Find
Cost model: number of array access (for read and write)
Quick find defect: Union operation is too expensive
Takes N^2 array accesses to process sequence of N union commands on N objects.
In particular, if we just have N union commands on N objects which is not unreasonable. They’re either connected or not when that will take quadratic time in squared time. It’s much to slow. And we can not accept quadratic time algorithms for large problems. The reason is they do not scale.
Thanks for your reading. | https://ducmanhphan.github.io/2019-03-19-Quick-Find/ | CC-MAIN-2021-25 | refinedweb | 340 | 72.36 |
Feature #14383
Making prime_division in prime.rb Ruby 3 ready.
Description
I have been running old code in Ruby 2.5.0 (released 2017.12.25) to check for
speed and compatibility. I still see the codebase in
prime.rb hardly has
changed at all (except for replacing
Math.sqrt with
Integer.sqrt).
To achieve the Ruby 3 goal to make it at least three times faster than Ruby 2
there are three general areas where Ruby improvements can occur.
- increase the speed of its implementation at the machine level
- rewrite its existing codebase in a more efficient|faster manner
- use faster algorithms to implement routines and functions
I want to suggest how to address the later two ways to improve performance of
specifically the
prime_division method in the
prime.rb library.
I've raised and made suggestions to some of these issues here
ruby-issues forum and now hope to invigorate additional discussion.
Hopefully with the release of 2.5.0, and Ruby 3 conceptually closer to reality,
more consideration will be given to coding and algorithmic improvements to
increase its performance too.
Mathematical correctness
First I'd like to raise what I consider math bugs in
prime_division, in how
it handles
0 and
-1 inputs.
> -1.prime_division => [[-1,1]] > 0.prime_division Traceback (most recent call last): 4: from /home/jzakiya/.rvm/rubies/ruby-2.5.0/bin/irb:11:in `<main>' 3: from (irb):85 2: from /home/jzakiya/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/prime.rb:30:in `prime_division' 1: from /home/jzakiya/.rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/prime.rb:203:in `prime_division' ZeroDivisionError (ZeroDivisionError)
First,
0 is a perfectly respectable integer, and is non-prime, so its output should be
[],
an empty array to denote it has no prime factors. The existing behavior is solely a matter of
prime_division's' implementation, and does not take this mathematical reality into account.
The output for
-1 is also mathematically wrong because
1 is also non-prime (and correctly
returns
[]), well then mathematically so should
-1. Thus,
prime_division treats
-1 as
a new prime number, and factorization, that has no mathematical basis. Thus, for mathematical
correctness and consistency
-1 and
0 should both return
[], as none have prime factors.
> -1.prime_division => [] > 0.prime_division => [] > 1.prime_division => []
There's a very simple one-line fix to
prime_division to do this:
# prime.rb class Prime def prime_division(value, generator = Prime::Generator23.new) -- raise ZeroDivisionError if value == 0 ++ return [] if (value.abs | 1) == 1
Simple Code and Algorithmic Improvements
As stated above, besides the machine implementation improvements, the other
areas of performance improvements will come from coding rewrites and better
algorithms. Below is the coding of
prime_division. This coding has existed at
least since Ruby 2.0 (the farthest I've gone back).
# prime.rb class Integer # Returns the factorization of +self+. # # See Prime#prime_division for more details. def prime_division(generator = Prime::Generator23.new) Prime.prime_division(self, generator) end end class Prime end
This can be rewritten in more modern and idiomatic Ruby, to become much shorter
and easier to understand.
require 'prime.rb' class Integer def prime_division1(generator = Prime::Generator23.new) Prime.prime_division1(self, generator) end end class Prime def prime_division1(value, generator = Prime::Generator23.new) # raise ZeroDivisionError if value == 0 return [] if (value.abs | 1) == 1 end
By merely rewriting it we get smaller|concise code, that's easier to understand,
which is slightly faster. A triple win! Just paste the above code into a 2.5.0
terminal session, and run the benchmarks below.
Again, we get a triple win to this old codebase by merely rewriting it. It can
be made 3x faster by leveraging the
prime? method from the
OpenSSL library to
perform a more efficient|faster factoring algorithm, and implementation.
require 'prime.rb' require 'openssl' class Integer def prime_division2
Here we're making much better use of Ruby idioms and libraries (
enumerable and
openssl), leading to a much greater performance increase. A bigger triple win.
Pasting this code into a 2.5.0 terminal session gives the following results.
# Hardware: System76 laptop; I7 cpu @ 3.5GHz, 64-bit Linux n = 500_000_000_000_000_000_008_244_213; tm{ pp n.prime_division2 } [[3623, 1], [61283, 1], [352117631, 1], [6395490847, 1]] => 9.39650374
prime_division2 is much more usable for significantly larger numbers and use
cases than
prime_division. I can even do multiple times better than this, if
you review the above cited forum thread.
My emphasis here is to show there are a lot of possible low hanging fruit
performance gains ripe for the picking to achieve Ruby 3 performance goals, if we
look (at minimum) for simpler|better code rewrites, and then algorithmic upgrades.
So the question is, are the devs willing to upgrade the codebase to provide the
demonstrated performance increases shown here for
prime_division?
Files
History
Updated by shevegen (Robert A. Heiler) almost 2 years ago
I won't go into all points since your issue makes even my issue
requests seem small. :-)
It may be easier to split your suggestions into separate issues
though.
For example, the 0 and -1 situation, if it is a bug (probably
is but I have not checked the official math definition for
prime divisions myself yet), it may be better to split it into
another issue and detach it from your other statements made,
e. g. the code quality or the speedup gain from optimizing
the ruby code.
I don't think that the ruby core devs are against smaller
improvements at all, irrespective of the 3.x goal (which I
think will be achieved via the JIT/mjit anyway) but it
may be simpler to have smaller issues. Some of the bigger
issues take longer to resolve. At any rate, that is just my
opinion - feel free to ignore it. :)
You could perhaps also add the overall discussion to:
If an attendee notices the issue here (and if it is worth
discussing; I think you indirectly also pointed out that
some parts of the ruby core/stdlib do not receive equal
attention possibly due to a lack of maintainers; I think
that one problem may also be that many ruby hackers would
not even know which area of core/stdlib may need improvements
or attention. Not just the prime division situation you
described, but also e. g. improvements to the cgi-part of
ruby, even if these are minor - it's not easy to know which
areas of standard distributed ruby need improvements.)
Updated by mrkn (Kenta Murata) almost 2 years ago
Currently,
prime_division can factorize any negative integers that are less than -1 like:
[2] pry(main)> -12.prime_division => [[-1, 1], [2, 2], [3, 1]]
Do you think how to treat these cases?
I think raising Math::DomainError is better for 1, 0, and any negative integers cases.
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
The major problem with
prime_division trying to accommodate negative numbers is
that, mathematically, prime factorization is really only considered over positive integers > 1.
I understand the creators intent, to be able to reconstruct negative integers from their prime factorization,
but that's not what's done mathematically.
1|0 are not primes or composites so they can't be factored
(they have no factors). You can see the Numberphile video explanation of this, or if you prefer, the wikipedia one.
From a serious mathematical perspective,
prime_division (and the whole
prime.rb lib) is inadequate for doing real high-level math. This is why I created
the primes-utils gem, so I could do fast math involving
primes. I also wrote the
Primes-Utils Handbook, to provide and explain all the gem's source code.
The Coureutils library, a part of all
[Li|U]nix systems, provides a world class factorization function
factor. You're not going to create a Ruby version that will come close to it. I use
factor for
my default factoring function. Here's an implementation that mimics
prime_division.
class Integer def factors(p=0) # p is unused variable for method consistency return [] if self | 1 == 1 factors = self < 0 ? [-1] : [] factors += `factor #{self.abs}`.split(' ')[1..-1].map(&:to_i) factors.group_by {|prm| prm }.map {|prm, exp| [prm, exp.size] } end end
And here's the performance difference against
prime_division2, the fastest
version of the previous functions.
n = 500_000_000_000_000_000_008_244_213; tm{ pp n.prime_division2 } [[3623, 1], [61283, 1], [352117631, 1], [6395490847, 1]] => 9.39650374 n = 500_000_000_000_000_000_008_244_213; tm{ pp n.factors } [[3623, 1], [61283, 1], [352117631, 1], [6395490847, 1]] => 0.007200317
If it were up to me, I would deprecate the whole
prime.rb library and use the
capabilities in
primes-utils, to give Ruby a much more useful|fast prime math
library. In fact, I'm doing a serious rewrite of it for version 3.0, using faster
math, with faster implementations. When Ruby ever gets true parallel capabilities
it'll be capable of making use of it.
But again in general, there are articles|videos showing how to speed up Ruby code.
There are projects like Fast Ruby , specifically devoted to identifying and categorizing
specific code constructs for speed. These resources can be used for evaluating the core
codebase to help rewrite it using the fastest coding constructs.
Ruby is 20+ years old now, and I would imagine some (a lot of?) code has probably
never been reviewed|considered for rewriting for performance gains. A lot of
similarly aged languages have gone through this process (Python, Perl, PHP) and
now it's Ruby's turn.
So while it's natural to talk and focus on the future machine implementation of
Ruby 3, I think you can be getting current language speedups by making the
ongoing codebase as efficiently and performantly written now, which will
translate to an even faster Ruby 3.
This is also a way to get more than just the C guru devs involved in creating
Ruby 3. I wouldn't mind evaluating existing libraries for simplicity|speed
rewrites if I knew my work would be truly considered. This would provide casual
users an opportunity to learn more of the internal workings of Ruby, while
contributing to its development, which can only be to Ruby's benefit. How about
a
Library of the Week|Month or
GoSC rewrite project, or a
Make Ruby Faster Now
project! Lots of ways to make this effort fun and interesting.
Updated by graywolf (Gray Wolf) almost 2 years ago
Unless I copy-pasted wrong your
prime_division2 is /significantly/ slower for small numbers:
$ ruby bm.rb prime_division - current in prime.rb prime_division_2 - proposed version in #14383 by jzakiya `factor` - spawning coreutils' factor command `factor` is left out from the first benchmark, spawning 1_000_000 shells proves nothing. 1_000_000 times of 10 user system total real prime_division 1.496456 0.000059 1.496515 ( 1.496532) prime_division_2 104.094586 6.469827 110.564413 (110.565201) 1_000 times of 2**256 user system total real prime_division 0.069389 0.000000 0.069389 ( 0.069391) prime_division_2 0.325075 0.000000 0.325075 ( 0.325088) `factor` 0.163589 0.073234 0.992784 ( 1.021447) 10 times of 500_000_000_000_000_000_008_244_213 user system total real prime_division 328.625069 0.033017 328.658086 (328.801649) prime_division_2 118.690491 0.000119 118.690610 (118.691372) `factor` 0.002487 0.000030 0.024145 ( 0.025040)
script:
require 'prime' require 'openssl' require 'benchmark' class Integer def prime_division_2 def factor(num) return [] if num | 1 == 1 factors = num < 0 ? [-1] : [] factors += `factor #{num.abs}`.split(' ')[1..-1].map(&:to_i) factors.group_by {|prm| prm }.map {|prm, exp| [prm, exp.size] } end puts <<~EOF prime_division - current in prime.rb prime_division_2 - proposed version in #14383 by jzakiya `factor` - spawning coreutils' factor command `factor` is left out from the first benchmark, spawning 1_000_000 shells proves nothing. EOF puts puts "1_000_000 times of 10" puts Benchmark.bm(16) do |x| x.report('prime_division') { 1_000_000.times { 10.prime_division } } x.report('prime_division_2') { 1_000_000.times { 10.prime_division_2 } } end puts puts "1_000 times of 2**256" puts Benchmark.bm(16) do |x| num = 2**256 x.report('prime_division') { 1_000.times { num.prime_division } } x.report('prime_division_2') { 1_000.times { num.prime_division_2 } } x.report('`factor`') { 1_000.times { factor(num) } } end puts puts "10 times of 500_000_000_000_000_000_008_244_213" puts Benchmark.bm(16) do |x| num = 500_000_000_000_000_000_008_244_213 x.report('prime_division') { 10.times { num.prime_division } } x.report('prime_division_2') { 10.times { num.prime_division_2 } } x.report('`factor`') { 10.times { factor(num) } } end
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
Well, I did say "serious" math, didn't I.
2.5.0 :097 > 2**256 => 115792089237316195423570985008687907853269984665640564039457584007913129639936 2.5.0 :099 > n = 2**256 + 1; tm{ pp n.factors } [[1238926361552897, 1], [93461639715357977769163558199606896584051237541638188580280321, 1]] => 11.187528889 2.5.0 :103 > n = 2**256 + 6; tm{ pp n.factors } [[2, 1], [9663703905367, 1], [5991082217089035545953414273093775102416031327093273407023490613, 1]] => 181.896643599 2.5.0 :105 > n = 2**256 + 7; tm{ pp n.factors } [[92243, 1], [14633710594132193, 1], [39071613028785859, 1], [2195480924803008082289717129761953851423, 1]] => 86.285821283 2.5.0 :107 > n = 2**256 + 8; tm{ pp n.factors } [[2, 3], [3, 1], [683, 1], [4049, 1], [85009, 1], [2796203, 1], [31797547, 1], [81776791273, 1], [2822551529460330847604262086149015242689, 1]] => 210.062944465 2.5.0 :109 > n = 2**256 + 9; tm{ pp n.factors } [[5, 1], [37181, 1], [210150995838577, 1], [2963851002430239530676411809410149856603062505748058817897, 1]] => 8.70362184
Updated by mame (Yusuke Endoh) almost 2 years ago
Your
prime_division2 uses
OpenSSL::BN#prime?. You may know, it is a Miller-Rabin probabilistic primality test which may cause a false positive. In short, I suspect that your code may (very rarely) return a wrong result. Am I right? If so, it is unacceptable.
In my personal opinion,
lib/prime.rb is not for practical use, but just for fun. The speed is not so important for
lib/prime.rb. So I think it would be good to keep it idyllic.
BTW, I've released a gem namely faster_prime, a faster substitute for
lib/prime.rb.
prime_division_current - current in prime.rb prime_division_jzakiya - proposed version in #14383 by jzakiya prime_division_mame - 1_000_000 times of 10 user system total real prime_division_current 1.203975 0.000000 1.203975 ( 1.204458) prime_division_jzakiya 50.366586 8.994353 59.360939 ( 59.369606) prime_division_mame 1.031790 0.000000 1.031790 ( 1.031963) 1_000 times of 2**256 user system total real prime_division_current 0.057273 0.000219 0.057492 ( 0.057495) prime_division_jzakiya 0.230237 0.000000 0.230237 ( 0.230288) prime_division_mame 0.074282 0.000106 0.074388 ( 0.074459) 10 times of 500_000_000_000_000_000_008_244_213 user system total real prime_division_current 222.418914 0.032561 222.451475 (222.491855) prime_division_jzakiya 76.686295 0.000191 76.686486 ( 76.694430) prime_division_mame 0.102406 0.000000 0.102406 ( 0.102408)
$ time ruby -rfaster_prime -e 'p (2**256+1).prime_division' [[1238926361552897, 1], [93461639715357977769163558199606896584051237541638188580280321, 1]] real 2m13.676s user 2m13.645s sys 0m0.008s
:-)
My gem is written in pure Ruby (not uses OpenSSL), but not so simple, so I have no intention to replace the standard
lib/prime.rb, though.
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
Hi Yusuke.
Ah, we agree,
prime.rb is not conducive for doing heavy-duty math. :-)
Please look at and play with my primes-utils gem.
It has a minimal universal useful set of methods for doing prime math.
Again, I'm in the process of rewriting it and adding more methods. Maybe you
want to collaborate with me and give Ruby a much better|serious prime math library.
Ruby is a serious language and deserves much better in areas of scientific and
numerical computation. This need has been recognized by such projects as
SciRuby, and I would like Ruby 3 to be better in these areas.
I installed your
faster_prime gem and ran it on my laptop, and started
looking at the code. I haven't thoroughly studied it yet, but may I make
some suggestions to simplify and speed it up.
I don't know if you knew, but starting with Ruby 2.5, it now has
Integer.sqrt.
We had a vigorous discussion on this issue here.
So you can replace your code below:
module Utils module_function FLOAT_BIGNUM = Float::RADIX ** (Float::MANT_DIG - 1) # Find the largest integer m such that m <= sqrt(n) def integer_square_root(n) if n < FLOAT_BIGNUM Math.sqrt(n).floor else # newton method a, b = n, 1 a, b = a / 2, b * 2 until a <= b a = b + 1 a, b = b, (b + n / b) / 2 until a <= b a end end
with
Integer.sqrt. BTW, here's a fast|accurate pure Ruby implementation of it.
class Integer def sqrt # Newton's method version used in Ruby for Integer#sqrt return nil if (n = self) < 0 # or however you want to handle this case return n if n < 2 b = n.bit_length x = 1 << (b-1)/2 | n >> (b/2 + 1) # optimum initial root estimate while (t = n / x) < x; x = ((x + t) >> 1) end x end end
Also in same file, you can do this simplification:
def mod_sqrt(a, prime) return 0 if a == 0 case when prime == 2 a.odd? ? 1 : 0 => a & 1 => or better => a[0] # lsb of number ....
Finally, in
prime_factorization.rb we can simplify and speedup code too. Don't
count the primes factors when you find then, just stick then in an array, then
when finished with factorization process you can use
Enumerable#group_by to
format output of them in one step. Saves code size|complexity, and is faster.
I also restructured the code like mine to make it simpler. Now you don't have
to do so many tests, and you get rid of all those individual
yields, which
complicates and slow things down. You will have to modify the part of your
code that uses
prime_factorization, but that code should be simpler|faster too.
require "faster_prime/utils" module FasterPrime module PrimeFactorization module_function # Factorize an integer def prime_factorization(n) return enum_for(:prime_factorization, n) unless block_given? return if n == 0 if n < 0 yield [-1, 1] n = -n end SMALL_PRIMES.each do |prime| if n % prime == 0 c = 0 begin n /= prime c += 1 end while n % prime == 0 yield [prime, c] end if prime * prime > n yield [n, 1] if n > 1 return end return if n == 1 end if PrimalityTest.prime?(n) yield [n, 1] else d = nil until d [PollardRho, MPQS].each do |algo| begin d = algo.try_find_factor(n) rescue Failed else break end end end pe = Hash.new(0) prime_factorization(n / d) {|p, e| pe[p] += e } prime_factorization(d) {|p, e| pe[p] += e } pe.keys.sort.each do |p| yield [p, pe[p]] end end end end
Change to below, with appropriate changes for factoring algorithm inside loop.
require "faster_prime/utils" module FasterPrime module PrimeFactorization module_function # Factorize an integer def prime_factorization(n) return enum_for(:prime_factorization, n) unless block_given? # 'factors' will hold the number of individual prime factors return [] if n.abs | 1 == 1 # for n = -1, 0, or 1 factors = n < 0 ? [-1] | [] # if you feel compelled for negative nums n = n.abs SMALL_PRIMES.each do |prime| # extract small prime factors, if any (factors << prime; n /= prime) while n % prime == 0 end # at this point n is either a prime, 1, or a composite of non-small primes until PrimalityTest.prime?(n) or n == 1 # exit when n is 1 or prime # if you're in here then 'n' is a composite thats needs factoring # when you find a factor, stick it in 'factors' and reduce 'n' by it # ultimately 'n' will be reduced to a prime or 1 # do whatever needs to be done to make this work right d = nil until d [PollardRho, MPQS].each do |algo| begin d = algo.try_find_factor(n) rescue Failed else break end end end end # at this point 'n' is either a prime or 1 factors << n if n > 1 # stick 'n' in 'factors' if it's a prime # 'factors' now has all the number of individual prime factors # now use Enumerable#group_by to make life simple and easy :-) # the xx.sort is unnecessary if you find the prime factors sequentially factors.group_by(&:itself).sort.map { |prime, exponents| [prime, exponents.size] } end end
This is now a generic template for factorization. To upgrade just use better|faster
PrimalityTest and
factorization functions. You also see it has separated each
distinct algorithmic function into single area of concern, in a conceptually more
functional programming style. This is now also able to be possibly implemented in
parallel because of the isolation of functional areas of concern.
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
Also, FYI, to go along with using
Integer.sqrt, you can save some code (and increase performance)
using the OpenSSL library, which already has some of the methods in
utils.rb.
require 'openssl' mod_pow(a,b,n) => a.to_bn.mod_exp(b,n) mod_inv(a,n) => a.to_bn.mod_inverse(n)
Updated by yugui (Yuki Sonoda) almost 2 years ago
- Target version set to Next Major
- Assignee set to yugui (Yuki Sonoda)
Faster is better -- with certain conditions. Considering those conditions, I would like to take the following approach.
- Remove the dependency from
mathn.rbto
prime.rb
- Move
prime.rbfrom
lib/to a bundled gem
- Apply some of the patches.
This is because of the following conditions I would like the change to satisfy.
- Simplicity of the dependency graph in the standard library
- I don't want to let
mathnhave too much dependency.
- Keeping the focus of the standard library
- We are moving more libraries from
lib/to bundled gems. The solution must be consistent to this trend.
- Certain degree of backward compatibility
- the algorithm must be deterministic.
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
Thank you for taking this project into consideration.
FYI, there is C open source code for both the
Coreutils factor function and the APR-CL deterministic
primality test. However, Miller-Rabin is faster, and can be implemented as deterministic, at least up
to 25-digits, so maybe a good
Integer#prime? method should be a hybrid combination, depending on number size.
The documentation for the APR-CL code says it's good up to 6021-digits on 64-bit systems
(not that anyone should expect to process those size numbers in any reasonable times).
To make sense of all these possibilities, a determination of the max number size|range has
to be made, since we are talking about an infinite set of numbers (primes). I wouldn't
think Ruby (or any general language) would have a primes library that will find the
largest Mersenne Primes, for example. However, with the right math and implementation,
thousands of digits numbers can be easily worked with within reasonable times and memory usage.
As an example, below is output of my
Integer#primesmr method, for numerating primes
within a number range, here for 100, 1000, and 2000 digit numbers. It combines the
M-R
test with my math techniques using
prime generators to identify a minimum set of
prime candidates within the ranges, and then checking their primality.
This is part of my primes-utils gem, which has a Primes-Utils Handbook,
which explains all the math, and provides the full gem source code.
It so far has the methods
primes|mr|f,
primescnt|mr|f,
nthprime,
prime|mr? and
factors|prime_division in current version 2.7. For the (next) 3.0 release I'm adding
next_prime and
prev_prime too. I think these are a good (minimum) set of general
purpose methods that provide the majority of information most people would seek in
a primes library. I'll probably create single hybrid methods also where now I have multiple
versions. I'm playing with JRuby for using parallel algorithms I already have implemented
in C++/Nim until CRuby can provide capability.
Again, thanks for the Ruby team agreeing to take on this effort.
2.5.0 :017 > n= (10**100+267); tm{ p n.primesmr n+5000 } [10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000267, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000949, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001243, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001293, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001983, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002773, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002809, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002911, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002967, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003469, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003501, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003799, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004317, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004447, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004491] => 0.06310091 2.5.0 :018 > n= (10**1000453,132713,004351] => 11.089284953 2.5.0 :019 > n= (10**20004561] => 56.129938705 2.5.0 :020 >
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
FYI, I re-ran the examples above (and an additional one) using the
Miller-Rabin
implementation in my
primes-utls 3.0 development branch. Not only is it
deterministic up to about 25-digits, but it's way faster too. It can probably be
made faster by using a
WITNESS_RANGES list with fewer witnesses, and can now
be easily extended as optimum witnesses are found for larger number ranges.
I provide this to raise the issue that absolute determinism for a primality test
function maybe shouldn't be an absolute criteria for selection. Of course, it is
the ideal, but sometimes
striving for perfection can be the enemy of good enough.
Again, hybrid methods may be able to combine the best of all worlds.
> n= (10**100+267); tm{ p n.primesmr n+5000 } => 0.056422744 3.0 dev => 0.06310091 2.7 > n= (10**1000+267); tm{ p n.primesmr n+5000 } => 7.493292636 3.0 dev => 11.089284953 2.7 > n= (10**2000+267); tm{ p n.primesmr n+5000 } => 36.614877874 3.0 dev => 56.129938705 2.7 > n= (10**3000+267); tm{ p n.primesmr n+5000 } => 10000000000........1027 => 192.866720666 3.0 dev => 286.244139793 2.7
# Miller-Rabin version in Primes-Utils 2.7 def primemr?(k=20) # increase k for more reliability n = self.abs return true if [2,3].include? n return false unless [1,5].include?(n%6) and n > 1 d = n - 1 s = 0 (d >>= 1; s += 1) while d.even? k.times do a = 2 + rand(n-4) x = a.to_bn.mod_exp(d,n) # x = (a**d) mod n next if x == 1 or x == n-1 (s-1).times do x = x.mod_exp(2,n) # x = (x**2) mod n return false if x == 1 break if x == n-1 end return false if x != n-1 end true # n is prime (with high probability) end
# Miller-Rabin version in Primes-Utils 3.0 dev # witnesses.each {|p| return false unless miller_rabin_test(p) } true end private # Returns true if +self+ passes Miller-Rabin Test on witness +b+ def miller_rabin_test(b) # b is a witness to test with n = d = self - 1 d >>= 1 while d.even? y = b.to_bn.mod_exp(d, self) # x = (b**d) mod n until d == n || y == n || y == 1 y = y.mod_exp(2, self) # y = (y**2) mod self d <<= 1 end y == n || d.odd? end WITNESS_RANGES = { 2_047 => [2], 1_373_653 => [2, 3], 25_326_001 => [2, 3, 5], 3_215_031_751 => [2, 3, 5, 7], 2_152_302_898_747 => [2, 3, 5, 7, 11], 3_474_749_660_383 => [2, 3, 5, 7, 11, 13], 341_550_071_728_321 => [2, 3, 5, 7, 11, 13, 17], 3_825_123_056_546_413_051 => [2, 3, 5, 7, 11, 13, 17, 19, 23], 318_665_857_834_031_151_167_461 => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37], 3_317_044_064_679_887_385_961_981 => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] }
Updated by jzakiya (Jabari Zakiya) almost 2 years ago
This version is probably better, as it's a little faster, and takes a complete
list of witnesses for a given number, which can be determined separately.
# miller_rabin_test(witnesses) end private # Returns true if +self+ passes Miller-Rabin Test on witness +b+ def miller_rabin_test(witnesses) # use witness list to test with neg_one_mod = n = d = self - 1 d >>= 1 while d.even? witnesses.each do |b| s = d y = b.to_bn.mod_exp(d, self) # y = (b**d) mod self until s == n || y == 1 || y == neg_one_mod y = y.mod_exp(2, self) # y = (y**2) mod self s <<= 1 end return false unless y == neg_one_mod || s.odd? end true end
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/14383 | CC-MAIN-2019-47 | refinedweb | 4,601 | 66.03 |
React in Real-Time
React in Real-Time
If you're interested in learning how to use React to build awesome web applications, read on to get quick overview of the entire process.
Join the DZone community and get the full member experience.Join For Free
Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.
Single page applications frameworks (SPA) are at the center stage of modern web development. Top notch web applications depend on fast and responsive behavior in both user interface and data. Hence the popularity of frameworks like React, Angular, Vue, and Ember.
This blog post shows how you can get started with React and restdb.io for development of applications with real-time data.
React is an amazing piece of technology. With its real-time DOM manipulation and component thinking, it's just a perfect match for real-time enabled databases and frameworks like Firebase, RethinkDB, Pusher, and RestDB.io.
In this blog post, we'll be developing an application for displaying Nasdaq stock information.
The demo code is nothing fancy but focuses on showing how to set up up your React application and connecting it to a real-time data stream and a REST API.
Highlights
- Standard web browser Eventsource API to connect to the restdb.io real time API.
- Axios for communication with the REST API.
- Dump of Nasdaq stock data stored in the database.
- Deploy the finished application to a restdb.io server.
The screen shot below shows what the finished app looks like:
You can check out a live demo at this link.
Let's look at how this application is made.
Create the Project
Create a directory and install the wonderfully easy-to-use npm package
create-react-app.
mkdir react-demo cd react-demo/ npm install -g create-react-app create-react-app realtime-react cd realtime-react
Utilities
In addition to React, we need Axios for REST communication and Lodash for convenience.
# the -S option adds it to our package.json project file npm install axios -S npm install lodash -S
Create the Database
After creating a new database in restdb.io, we begin with importing data from a local CSV file downloaded from the web:
name,symbol,open,high,low,close,net chg,percent chg,volume,52 wk high,52 wk low,div,yield,P-E,ytd percent chg 1st Constitution Bancorp,FCCY,17.30,17.50,17.25,17.25,...,...,"2,900",20.85,11.83,0.20,1.16,15.83,-7.75 1st Source,SRCE,48.11,48.89,48.02,48.67,0.44,0.91,"31,238",50.77,31.88,0.76,1.56,21.07,8.98 2U,TWOU,45.23,46.37,45.08,46.24,1.30,2.89,"280,877",48.40,29.23,...,...,...,53.37 ...
Because this data is from the Nasdaq stock exchange, we import the data into a new collection that we named
nasdaq.
After the import, we can look at the data inside in the restdb.io data manager:
Yay! The data schema has been created automatically from the import data:
This gives us the following REST endpoint for our stock data:
Which will output a JSON document like the following:
{ _id: "596335cd2b769915000007a6" name: "1st Constitution Bancorp" symbol: "FCCY" open: 17.3 high: 17.5 low: 17.25 net chg: null percent chg: null volume: 2 52 wk high: 20.85 52 wk low: 11.83 div: 0.2 yield: 1.16 P-E: 15.83 ytd percent chg: -7.75 price: 17.25 }, ...
Secure CORS
In order to allow clients to communicate with our database, we must create a CORS api key with a connection profile. The secure CORS key is created in restdb.io under the database settings section.
The screen shot below shows the set up of both REST and Realtime:
The settings above read like this:
- Allow the client to send
GET PUTREST API operations from
*(any) domain.
- Allow the client to listen for real-time events on
POST PUT DELETEoperations to
:*(any) collection.
The database is now ready, and we can move on to create our React application.
Create the React Application
The application consists of 3 main source files (in addition to React files and HTML, CSS, etc.).
helper.js- global settings.
App.js- App component, Ticker component for stock list and real-time changes.
Autotrader.js- Trade component for sending emulated stock price changes to the database.
Global Settings
To keep things DRY we'll create a helper file
helper.js which will contain our global application settings.
// helper.js import axios from 'axios'; // CORS enabled apikey const apikey = '5x5fx501xfcex9e87x11ex6x'; // Autotrade delay const trade_delay = 10000; // millis // REST endpoint let restdb = axios.create({ baseURL: '', timeout: 1000, headers: { 'x-apikey': apikey } }); // Eventsource endpoint const realtimeURL = `{apikey}` export { apikey, restdb, realtimeURL, trade_delay };
Main App Component
In our
App.js file we have 2 components, App and Tickers. App is the main component with the App container, and Tickers renders the stock list data and refreshes on real-time changes.
The code snippet below shows the main container of our application, a heading and two components, Trade and Tickers.
class App extends Component { componentDidMount() { // start trading } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} <h2>React & RestDB.io in Realtime</h2> </div> <h2>Nasdaq trading bots <small>fake</small></h2> <Trade/> <Tickers/> </div> ); } }
Connecting the Eventsource to a Realtime Stream
We can listen for real-time database changes via the browser EventSource API.
// connect to the realtime database stream let eventSource = new EventSource(`{apikey}`);
To make sure the connection is valid you can view the live stream from your browser network inspector, shown in the screen shot below:
The inspector shows that we are receiving server events for
putand
ping. The
putevents are changes in our
nasdaqdata collection. And the
ping events are
keep-alive messages from the server. We will use this to make sure we can re-connect to the EventSource if/when the client looses connection to the server.
The trick is to store a time stamp for the last
pingmessage. This code snippet shows how we add this to the component state:
// listen on ping from server, keep time eventSource.addEventListener('ping', function(e) { this.setState(previousState => { return {ping: new Date(e.data)}; }); }.bind(this), false);
We can now, in an interval, check how long time has passed since the client last got a
ping message from the server. If that time span is too long (e.g. 20 sec), we re-connect our client.
//);
The Ticker Component
The Ticker component retrieves stock data from the database. It also listens for real-time events when data has changed.
// App.js import React, { Component } from 'react'; import _ from 'lodash'; import logo from './logo.svg'; import './App.css'; import Trade from './Autotrader'; import { restdb, realtimeURL } from './helper.js'; class Tickers extends Component { constructor(props) { super(props); this.state = {ping: new Date(), evt: '', tickers: []}; // connect to the realtime database stream let eventSource = new EventSource(realtimeURL); //); // listen on ping from server, keep time eventSource.addEventListener('ping', function(e) { this.setState(previousState => { return {ping: new Date(e.data)}; }); }.bind(this), false); // listen for database REST operations eventSource.addEventListener('put', (e) => { this.getTickerData() }, false); } // GET 20 stocks to display and trade getTickerData = () => { restdb.get("/rest/nasdaq?sort=symbol&max=20&metafields=true") .then(res => { let now = new Date().getTime(); let tickers = res.data; let diff = null; // tag stocks that are changed in the last 10 secs _.each(tickers, (t) => { diff = (now - new Date(t._changed).getTime()) / 1000; if (diff < 10) { t.isChanged = true; } else { t.isChanged = false; } }); this.setState(previousState => { return { tickers }; }); }); } componentDidMount() { console.log("Start client"); this.getTickerData(); } render() { return ( <div className="tickers"> <table className="table"> <thead> <tr> <th>Symbol</th> <th>Company</th> <th className="num">Price</th> <th className="num">Change</th> </tr> </thead> <tbody> {this.state.tickers.map(tic => <tr key={tic._id} className={tic.isChanged ? (tic['net chg'] > 0 ? "up" : "down") : "passive"}> <td>{tic.symbol}</td> <td>{tic.name}</td> <td className="num">{tic.price.toFixed(2) || 0.0}</td> <td className="num">{tic['net chg'] ? tic['net chg'].toFixed(2) : 0.0}</td> </tr> )} </tbody> </table> </div> ); } }
The Trading Component
Our last file,
Autotrader.js, contains one component,
Trade. The component sends updates (
PUT) to a random stock from the list each 10th second.
import React, { Component } from 'react'; import { restdb, trade_delay } from './helper.js'; // emulate price change on stocks class Trader extends Component { constructor(props) { super(props); this.state = {stocks: [], lasttrade: null}; // GET 20 stocks restdb.get("/rest/nasdaq?sort=symbol&max=20") .then(res => { const stocks = res.data; this.setState(previousState => { return { stocks }; }); }); // update a random stock each 10 sec setInterval(() => { let stockpos = Math.floor(Math.random() * 19); if (this.state.stocks[stockpos]) { let stockID = this.state.stocks[stockpos]._id; let newprice = (Math.random() * 1000.0) + 1.0; // PUT new price on one stock restdb.put(`/rest/nasdaq/${stockID}`, {price: newprice} ) .then((response) => { this.setState(previousState => { return {lasttrade: response.data}; }); }) .catch(function (error) { console.log(error); }); } }, trade_delay); } render() { return ( <div className="autotrade"> <p>Trading: {this.state.lasttrade ? (this.state.lasttrade.symbol + ' at ' + this.state.lasttrade.price.toFixed(2)) : 'none'}</p> </div> ); } } export default Trader;
Server Codehook for Validation of Stock Price Change
Our final piece of code is for server side validation of
PUT operations against our
nasdaq database collection. We will create a database Codehook that triggers on
beforePUT. This function validates that the new price if not negative, and it calculates the difference between the new and the old price. The difference is then stored in a property called
['net chg'].
// Codehooks for nasdaq function beforePUT(req, res) { // fetch old value first let query = {_id: req.body._id}; let hint = {}; db.get("/rest/nasdaq", query, hint, function (err, result) { // set the delta value as old - new value req.body['net chg'] = req.body.price - result[0].price; req.body.price = Math.max(req.body.price, 0.0); // return the updated document res.end({"data": req.body}); }); }
This concludes our simple React application. The next step is to run and test it locally and then deploy it to the restdb.io server.
Run Application From a Local Node.js Server
If you install Node.js on your local machine you can take advantage of the rapid development cycle with hot code reloading and debugging. The
create-react-app npm package has a command that spins up a Node server on our local machine.
# start a local node.js server npm start
You should see something like this output in your terminal window:
You can now test your app from.
Build Application
To create a packaged application that can be deployed, you can use the handy build command.
npm run build
After the build you should see something similar to this:
Run Static File Server to Test Build
You can also test your deploy-ready package on a local HTTP server. Here we use the npm package serve:
serve -s build
You should see this output in the terminal window:
You can now test you deployment app package from.
Our final step is to deploy our application to the world. We can deploy our React app to a variety of HTTP servers, but in this example, we'll be using the restdb.io server. Loading the app from the same server/domain that contains the data gives us a significant speed improvement.
Deploy Application to Restdb.io
restdb.io has a built in web server that lets you deploy and serve static files.
E.g.
https://<yourdbname>.restdb.io/static
You can deploy to your database with the restdb-cli command line tool.
To deploy our React app, we run the following command:
restdb-cli --cmd upload --src ./build --dest /reactapp --database reactrealtime-6683 --apikey <your full access api-key here>
However, a much better approach is to add this as a deployment command to our application package.json file instead.
Also, adding relative paths to the build folders lets us deploy both locally and to a server with a different folder structure. We do this by setting the
"homepage": "." property in the package.json file. Our final package.json file looks like this:
{ "name": "realtime-react", "version": "0.1.0", "private": true, "homepage": ".", "dependencies": { "axios": "^0.16.2", "lodash": "^4.17.4", "react": "^15.6.1", "react-dom": "^15.6.1", "react-scripts": "1.0.10" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "deploy": "restdb-cli --cmd upload --src ./build --dest /reactrealtime --database reactrealtime-6683 --apikey <your full access api-key here>" } }
Let's run the deploy command.
npm run deploy
If all goes well, it should display something like this:
> realtime-react@0.1.0 deploy /Users/joneriksolheim/projects/react-demo/realtime-react > restdb-cli --cmd upload --src ./build --dest /reactrealtime --database reactrealtime-6683 --apikey xxxxxxxxxxxxxxxxxxx Upload successful! 3398298 total bytes uploaded
The deployed application is now served from the restdb.io server at this URL:
Conclusion
Coding a real-time app with React is fun, and a lot easier than you might think. Simple state management with automatic DOM sync makes our code clean and small. Using the browsers standard EventSource API to listen for real-time data events are both simple and effective. And finally, using Axios for REST communication just rocks.
View full source code on GitHub here.
Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.
Published at DZone with permission of Jon Erik Solheim , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/react-in-real-time | CC-MAIN-2019-09 | refinedweb | 2,305 | 60.01 |
WebReference.com - Part 1 of Chapter 1: Professional XML Schemas, from Wrox Press Ltd (2/5)
Professional XML Schemas
The W3C XML Schema Recommendation
The W3C Recommendation for XML Schema comes in three parts:
XML Schema Part 0: Primer The first part is a descriptive, example-based document, which introduces some of the key features of XML Schema by way of sample schemas. It is easy to read, and is a good start for getting to grips with XML Schemas and understanding what they are capable of. It can be read at.
XML Schema Part 1: Structures The next part describes how to constrain the structure of XML documents  where the information items (elements, attributes, notations, and so on) can appear in the schema. Once we have declared an element or an attribute, we can then define allowable content or values for each. It also defines the rules governing schema-validation of documents. It can be read at.
XML Schema Part 2: Datatypes The third part defines a set of built-in datatypes, which can be associated with element content and attribute values; further restricting allowable content of conforming documents and facilitating the management of dates, numbers, and other special forms of information by software processing of the XML documents. It also describes ways in which we can control derivation of new types from those that we have defined. It can be read at.
As we shall see throughout the course of this chapter and the rest of the book, there are a number of advantages to using XML Schemas over DTDs. In particular:
As they are written in XML syntax (which DTDs were not), we do not have a new syntax to learn before we can start learning the rules of writing a schema. It also means that we can use any of the tools we would use to work with XML documents (from authoring tools, through SAX and DOM, to XSLT), to work with XML Schemas.
The support for datatypes used in most common programming languages, and the ability to create our own datatypes, means that we can constrain the document content to the appropriate type required by applications, and / or replicate the properties of fields found in databases.
It provides a powerful class and type system allowing an explicit way of extending and re-using markup constructs, such as content models, which is far more powerful than the use of parameter entities in DTDs, and a way of describing classes of elements to facilitate inheritance.
The support for XML Namespaces allows us to validate documents that use markup from multiple namespaces and means that we can re-use constructs from schemas already defined in a different namespace.
They are more powerful than DTDs at constraining mixed content models.
Created: October 18, 2001
Revised: October 18, 2001
URL: | http://www.webreference.com/authoring/languages/xml/schemas/chap1/1/2.html | CC-MAIN-2016-07 | refinedweb | 471 | 53.75 |
Swing and Roundabouts 4: Grid Bag Grease
Ethan Nicholas blogged recently on
"Reinventing GridBagLayout", which enjoyed many comments regarding simplifying
GBL, and problems with GBL. Karsten Lentzsch notes that "SpringLayout is very powerful,
ExplicitLayout is powerful, FormLayout is quite powerful,
HIGLayout is quite powerful, GBL is weak." He compares layout managers at the end of his
Forms whitepaper.
We hear that Netbean's Matisse GroupLayout is state-of-the-art. It does seem
to have a learning curve, for hand coding. So i haven't got around
to trying it yet. Anyway, my requirements are not very stringent,
and so i still just use GridBagLayout, which is my layout comfort zone.
I use spacer panels ie. with fill not NONE,
and assemble subpanels, and get what i want without any constraints,
i mean complaints.
Cay Horstmann introduced
"GBC.java - a convenience class to tame the GridBagLayout" (2002) in
Core Java.
That must have leaked out of my subconscious at some point, and led to me
to implement a similar friendly extension of GridBagConstraints, as follows.
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class Gbc extends GridBagConstraints {
public Gbc(int gridx, int gridy, int anchor, int fill, Insets insets) {
super(gridx, gridy, 1, 1, 0., 0., NORTHWEST, NONE, new Insets(0, 0, 0, 0), 0, 0);
anchor(anchor);
fill(fill);
insets(insets);
}
public Gbc(int gridx, int gridy, Insets insets) {
this(gridx, gridy, 0, 0, insets);
}
public Gbc(int gridx, int gridy) {
this(gridx, gridy, 0, 0, null);
}
public Gbc insets(Insets insets) {
if (insets == null) insets = new Insets(0, 0, 0, 0);
this.insets = insets;
return this;
}
public Gbc anchor(int anchor) {
if (anchor == 0) anchor = NORTHWEST;
this.anchor = anchor;
return this;
}
public Gbc fill(int fill) {
if (fill == 0) fill = NONE;
if (fill == HORIZONTAL || fill == BOTH) weightx = 1;
if (fill == VERTICAL || fill == BOTH) weighty = 1;
this.fill = fill;
return this;
}
public Gbc none() {
return fill(NONE);
}
public Gbc both() {
return fill(BOTH);
}
public Gbc vertical() {
return fill(VERTICAL);
}
public Gbc horizontal() {
return fill(HORIZONTAL);
}
public Gbc center() {
return anchor(CENTER);
}
public Gbc north() {
return anchor(NORTH);
}
public Gbc northeast() {
return anchor(NORTHEAST);
}
public Gbc east() {
return anchor(EAST);
}
public Gbc southeast() {
return anchor(SOUTHEAST);
}
public Gbc south() {
return anchor(SOUTH);
}
public Gbc southwest() {
return anchor(SOUTHWEST);
}
public Gbc west() {
return anchor(WEST);
}
public Gbc northwest() {
return anchor(NORTHWEST);
}
public Gbc top(int top) {
insets.top = top;
return this;
}
public Gbc bottom(int bottom) {
insets.bottom = bottom;
return this;
}
public Gbc right(int right) {
insets.right = right;
return this;
}
public Gbc left(int left) {
insets.left = left;
return this;
}
public Gbc insets(int top, int left, int bottom, int right) {
insets = new Insets(top, left, bottom, right);
return this;
}
public Gbc cloneGbc() {
Gbc gbc = (Gbc) clone();
gbc.insets = (Insets) insets.clone();
return gbc;
}
public static String formatGbcValue(int value) {
if (value == NONE) return "NONE";
if (value == HORIZONTAL) return "HORIZONTAL";
if (value == VERTICAL) return "VERTICAL";
if (value == BOTH) return "BOTH";
if (value == NORTH) return "NORTH";
if (value == NORTHEAST) return "NORTHEAST";
if (value == EAST) return "EAST";
if (value == SOUTHEAST) return "SOUTHEAST";
if (value == SOUTH) return "SOUTH";
if (value == SOUTHWEST) return "SOUTHWEST";
if (value == WEST) return "WEST";
if (value == NORTHWEST) return "NORTHWEST";
if (value == CENTER) return "CENTER";
return "gbcValue=" + value;
}
public String toString() {
StringBuffer buffer = new StringBuffer("Gbc");
buffer.append(" x" + gridx);
buffer.append(" y" + gridy);
buffer.append(" " + formatGbcValue(anchor));
buffer.append(" " + formatGbcValue(fill));
buffer.append(" " + insets.toString());
return buffer.toString();
}
}
where i use weights that are either 0.0 or 1.0, depending on the fill.
Feel free to use and abuse this class as you wish. You can find it
via gridbaglady.dev.java.net,
under the ASL.
So the latest application for which i used the above, is the following, and
this application was used to do the syntax highlighting of the above, in counjunction
with Netbeans' "Print to HTML". Which i'll leave as a topic for an upcoming blog
Plumber's Hack 1: Highlighting Sourcy, so this is a sneak preview :)
Here is the launcher for the above.
(Sourcy, Java5, 195k, unsandboxed)
The screenshot below, of the source of the above, shows Gbc.java in action.
As a further example, the following code uses Gbc to create a simple button panel,
as used for the above demo.
public JPanel createButtonPanel(NAction ... actions) {
JPanel panel = new JPanel(new GridBagLayout());
int index = 0;
for (NAction action : actions) {
panel.add(new JButton(action), new Gbc(index, 0).right(4));
index++;
}
return panel;
}
where the right inset is given as 4, to space the buttons apart.
The next article is this Swing and Roundabouts series is Gooey Maker
which will present a pack of some simple foundation and helper classes for hand-coding
Swing apps (such as the above Web Start demo) including Gbc.java for layout.
- Login or register to post comments
- Printer-friendly version
- evanx's blog
- 1503 reads | http://weblogs.java.net/blog/evanx/archive/2006/07/swing_and_round.html | crawl-003 | refinedweb | 811 | 55.74 |
scratchpad blokhead <blockquote><i>I have set up on a Manchester computer a small programme using only 1000 units of storage, whereby the machine supplied with one sixteen figure number replies with another within two seconds. I would defy anyone to learn from these replies sufficient about the programme to be able to predict any replies to untried values.</i> -- Alan Turing</blockquote> <!-- --> <hr> <h1>for [Limbic~Region]</h1> Here is a somewhat open-ended computational question/puzzle. Bear with me! <p> I'm working on laying out an online photo gallery containing photos of various dimensions. The photos will be laid out in a grid, and each photo has varied dimensions that are multiples of the grid size. So you can think of the photos as sized 1x1, 2x3, 1x4, etc. <p> I came across a Flash app that can display a list of photos in a grid spanning multiple "pages". Since the photos have varied dimensions, you can't just place photos blindly in the grid. So this app goes from left-to-right, top-to-bottom, across the available grid locations, and inserts the first photo in the list that fits legally. When a page is full (or no photos can fit in it anymore), we start the next page. <p> Example: Suppose there's a 4x3 grid to fill, and the photos have dimensions (2x2, 3x1, 1x1, 1x2, 2x1, 1x2, 1x1), in that order: <c> +-+-+-+-+ |?| | | | first step: place a photo in the "?" cell +-+-+-+-+ | | | | | available photos: 2x2, 3x1, 1x1, 1x2, 2x1, 1x2, 1x1 +-+-+-+-+ *** | | | | | +-+-+-+-+ first photo that fits is the 2x2 +---+-+-+ |///|?| | next step: place a photo in the "?" cell |///+-+-+ |///| | | available photos: 3x1, 1x1, 1x2, 2x1, 1x2, 1x1 +-+-+-+-+ *** | | | | | +-+-+-+-+ first photo that fits is the 1x1 +---+-+-+ |///|/|?| next step: place a photo in the "?" cell |///+-+-+ |///| | | available photos: 3x1, 1x2, 2x1, 1x2, 1x1 +-+-+-+-+ *** | | | | | +-+-+-+-+ first photo that fits is the 1x2 +---+-+-+ |///|/|/| next step: place a photo in the "?" cell |///+-+/| |///|?|/| available photos: 3x1, 2x1, 1x2, 1x1 +-+-+-+-+ *** | | | | | +-+-+-+-+ first photo that fits is the 1x2 +---+-+-+ |///|/|/| next step: place a photo in the "?" cell |///+-+/| |///|/|/| available photos: 3x1, 2x1, 1x1 +-+-+/+-+ *** |?| |/| | +-+-+-+-+ first photo that fits is the 2x1 +---+-+-+ |///|/|/| next step: place a photo in the "?" cell |///+-+/| |///|/|/| available photos: 3x1, 1x1 +---+/+-+ *** |///|/|?| +---+-+-+ first photo that fits is the 1x1 </c> After this point, the 3x1 still remains, and would start the next page. <p> Now, the photos look best when the arrangement and dimensions are varied. So the problem is to <b>find an arrangement (permutation) of the given images that looks best</b>. But it's challenging to come up with a metric for what looks good. Ideas I've had so far: <ul> <li> minimize the number of corners in which 4 photos touch (totaled across all pages). The example above is a nice one, since this never happens. But switching two of the photos would give the following arrangement, with 2 "bad" corners: <c> +---+-+-+ |///|/|/| |///|/|/| |///|/|/| +---+-+-+ |///|/|/| +---+-+-+ </c> <li> maximize the number of different photo sizes used per page <li> minimize the number of times the most common image size is used on a page (to reward having an even distribution among a variety of sizes) <li> a weighted combination of all of the above </ul> So my questions are the following: <ol> <li>Given a list of photo dimensions and the size of the grid, find a permutation that results in the best layout. It need not be the <i>globally</i> optimal arrangement, but I would be interested in any approach better than trying a bunch of random permutations and taking the best one.</li> <li>Can you recommend a better metric for measuring the "visual appeal" of an arrangement? </ol> Observations so far: <ul> <li>To keep track of a "bad" corner, just do the following. Every time you place a photo with top-left corner at position (x,y), check whether there is a photo whose bottom-right corner is at (x-1,y-1).</li> </ul> I do have some code that computes the arrangement, given the list of dimensions. And I have an OK scoring metric. But I'm not doing anything smarter than doing lots of random permutations and taking the best one... <hr> <h1>for [Limbic~Region]</h1> <code> { my %seen; my %onstack; my @list; sub how_to_uninstall { my $target = shift; (@list, %seen, %onstack) = (); _traverse($target); return @list; } sub _traverse { my $x = shift; $seen{$x} = $onstack{$x} = 1; foreach package $y that depends on $x { die "cyclic!" if $onstack{$y}; # back edge _traverse($y) unless $seen{$y}; } push @list, $x; $onstack{$x} = 0; } } </code> Returns a topologically sorted list of the packages that must be uninstalled in order to uninstall $target. Convention: If package $y depends on package $x, then package $y must be uninstalled before $x. <hr> <h1>for [ww]</h1> The raw PM markup souce for [id://672880]: <code> <table border=1> <tr><td></td><th>PM Markup:</th><th>Result:</th></tr> <tr><td>paragraphs / line breaks</td><td> <pre> <p>first paragraph</p> <p>second paragraph</p> </pre> </td><td> <p>first paragraph</p> <p>second paragraph</p> </td></tr> <tr><td rowspan=3>link to nodes by name</td><td> <pre> Have you tried [Super Search]? </pre> </td><td> Have you tried [Super Search]? </td></tr> <tr><td> <pre> Thanks for your help, [tye] </pre> </td><td> Thanks for your help, [tye] </td></tr> <tr><td> <pre> Thanks for nothing, [tye|wiseguy] </pre> </td><td> Thanks for nothing, [tye|wiseguy] </td></tr> <tr><td>link to nodes by ID</td><td> <pre> Please consult [id://3989] </pre> </td><td> Please consult [id://3989] </td></tr> <tr><td rowspan=3>other kinds of links<p>([id://43037|more info])</td><td> <pre> Check out [pad://NodeReaper] </pre> </td><td> Check out [pad://NodeReaper] </td></tr> <tr><td> <pre> Did you try []? </pre> </td><td> Did you try []? </td></tr> <tr><td> <pre> Did you check [doc://perlfaq]? </pre> </td><td> Did you check [doc://perlfaq]? </td></tr> <tr><td rowspan=2>including code in text</td><td> <pre> The result is in <c>$array[0]</c> </pre> </td><td> The result is in <c>$array[0]</c> </td></tr> <tr><td> <pre> The code should read: <c> use strict; use warnings; my @array = ("Hello world\n"); if (@ARGV) { print $array[0]; } </c> </pre> </td><td> The code should read: <c> use strict; use warnings; my @array = ("Hello world\n"); if (@ARGV) { print $array[0]; } </c> </td></tr> <tr><td rowspan=3>text/font formatting</td><td> <pre> This will be <b>bold</b> </pre> </td><td> This will be <b>bold</b> </td></tr> <tr><td> <pre> This will be <i>italic</i> </pre> </td><td> This will be <i>italic</i> </td></tr> <tr><td> <pre> This will be <tt>fixed width</tt> </pre> </td><td> This will be <tt>fixed width</tt> </td></tr> <tr><td>quoting / indenting</td><td> <pre> A wise monk once said: <blockquote> "Indenting is good" </blockquote> .. and I agree </pre> </td><td> A wise monk once said: <blockquote> "Indenting is good" </blockquote> .. and I agree </td></tr> <tr><td rowspan=2>lists</td><td> <pre> My favorite flavors are: <ul> <li>vanilla</li> <li>chocolate</li> </ul> </pre> </td><td> My favorite flavors are: <ul> <li>vanilla</li> <li>chocolate</li> </ul> </td></tr> <tr><td> <pre> How to make toast: <ol> <li>insert bread</li> <li>press button</li> </ol> </pre> </td><td> How to make toast: <ol> <li>insert bread</li> <li>press button</li> </ol> </td></tr> </table> </code> <hr> For [Petruchio]: <p> Simple recursive type inferencing engine. Hopefully this contains enough interesting examples. And hopefully you can parse my language-schizophrenic pseudocode. <c> # input: # - env = mapping of variable names to types # - expr = an expression (AST) # # output: # - type = a type "judgment" # - constraints = a list of type constraints that must be satisfied def infer_type( env, expr ): case expr: ## wow, a literal integer has type IntType! LiteralIntExpr( thenumber ): return ( IntType, {} ); # no constraints ## similar rules for other kinds of literals ... ## here's an interesting one: ## empty lists are polymorphic EmptyListExpr(): return( ListExpr( fresh PolymorphicType ), {} ); # no constriants ## fresh PolymorphicType means make a new PolymorphicType with ## a never-before-used identifying number/letter ## list expression: [item1, ... itemn] ## - infer the type of each item ## - pass along constraints from the subexpressions ## - add constraints that all items have the same type ListExpr( item1, ... itemn ): (type1, constr1) = infer_type( env, item1 ); ... (typen, constrn) = infer_type( env, itemn ); ## union of these lists of constraints return ( ListType(type1), constr1 + ... + constrn + "type1==type2" + ... + "type1==typen" ); ## someone names a variable? if it doesn't have a type ## in our environment, we are hosed! otherwise, the ## environment contains a type mapping for the variable VariableExpression( varname ): croak if not exists env{varname}; return ( env{varname}, {} ) # no constraints ## for addition expression: ## - return IntType ## - constrain both args to be IntType ## - pass along constraints from subexpressions AdditionExpression( subexpr1, subexpr2 ): (type1, constr1) = infer_type( env, subexpr1 ); (type2, constr2) = infer_type( env, subexpr2 ); ## union of these lists of constraints return (IntType, constr1 + constr2 + "type1==IntType" + "type2==IntType"); ## for concatenation: ## - same as above, but with StrType ConcatExpression( subexpr1, subexpr2 ): (type1, constr1) = infer_type( env, subexpr1 ); (type2, constr2) = infer_type( env, subexpr2 ); ## union of these lists of constraints return ( StrType, constr1 + constr2 + "type1==StrType" + "type2==StrType" ); ## list cons expression: i.e,: head::tail ## - return the same type as the tail ## - ensure that the head has the same type as ## tail's elements ListConsExpression( head, tail ): (type1, constr1) = infer_type( env, head ); (type2, constr2) = infer_type( env, tail ); return ( type2, constr1 + constr2 + "type2==ListType(type1)" ); ## fun var -> body ## - assign var a fresh type ## - infer the type of the body in a modified environment ## - return an appropriate function type FuncDefExpression( var, body ): vartype = fresh PolymorphicType; (bodytype, bodyconstr) = infer_type( env + "var:vartype", body ); return (FuncType(vartype,bodytype), bodyconstr); ## func(arg): ## - constrain that the argument's type is appropriate ## - this expression's type is the return value type of func ## - easiest to do this by introducing a new polymorphic type FuncAppExpression( func, arg ): (type1, constr1) = infer_type( env, head ); (type2, constr2) = infer_type( env, tail ); resulttype = fresh PolymorphicType; return ( resulttype, constr1 + constr2 + "type1==FuncType(type2,resulttype)" ); </c> The unification part does all the work, but is the easy part to code: <c> # unify a list of constraints: # - input = list of constraints of the form "lhs==rhs" # - output = list of constraints # a unification is an assignment of values to variable that satisfies # the constraints in the most general way. in our case, variables # are the PolymorphicType guys, and values are any Types def unify( constraints ): return [] if constraints is an empty list; (lhs,rhs) = shift constraints; ## if they are already equal, do nothing if lhs = rhs then return unify(constraints); ## orient "variables" on the lhs if lhs is not a PolymorphicType, but rhs is, then (lhs,rhs) = (rhs,lhs); if lhs = PolymorphicType(id) then if PolymorphicType(id) occurs anywhere within constraints, then croak "you're asking for a recursive type!" constraints = map { replace each PolymorphicType(id) with rhs } constraints; ## output this assignment as part of the solution! return "id:rhs" + unify(constraints); ## for 2 FuncTypes to be equal, their components must be equal, ## so add new constraints if lhs = FuncType(l1,l2) and rhs = FuncType(r1,r2) then return unify(constraints + "l1==r1" + "l2==r2"); if lhs = ListType(l1) and rhs = ListType(r1) then return unify(constraints + "l1==r1"); ## we get here if you try to constrain a ListType to equal a ## FuncType, or other such impossible feats else croak "unification impossible!"; </c> Putting it together: <ul> <li> First use infer_type to get a type judgment and constraints on the expression. <li> Unify the constraints. <li> Substitute all the PolymorphicTypes in the judgment according to the unification. <li> Enjoy. </ul> <hr> <h1>What is an alias?</h1> In Perl, a variable is like a container that holds a value. The variable's name is a way to refer to the container. If two different containers hold the same value, they are really holding two separate copies -- changing the value in one container doesn't affect the other. This is what we're used to almost all of the time: <c> ## two containers that have the same value my $x = 1; my $y = 1; $x = 5; ## change the value in one container ... print $y; ## the other container is unaffected </c> Sometimes it's possible for two variables/expressions to refer to the same <i>container</i>! We see a form of this when we use references: <c> my $x = 1; my $y = \$x; ## $y is a reference to $x $x = 5; print $$y; </c> In this example, $x and $$y refer to the same container. So modifying something via $x is the same as modifying it via $$y, <p> However, there is a more subtle way this can happen in Perl, <i>without using references!</i> In other words, you can have two plain scalars that refer to the same container. Changing one changes the other. This is called an <b>alias</b>. <h1>How do I make an alias?</h1> Before going into how to make an alias, let's see why they are so subtle. The biggest reason is that the assignment operator does not preserve aliases! <p> <c>$x = $y</c> means "take a copy of the <i>value</i> in the $y$ container and put it in the $x container." In particular, this does not mean "make $x and $y point to the same container." <p> So aliases are somewhat fragile... <h2>Putting an alias into a variable</h2> Some operations in Perl result in one variable being aliased to another: <dl> <dt>Argument Passing</dt><dd> When a sub is called, its arguments are aliased to the elements of @_: <c> my $x = 0; sub { $_[0] = 5 }->($x); print "$x\n"; </c> Since normal scalar assignment doesn't preserve aliases, the sub can't return an aliased copy of $x: <c> my $x = 0; my $y = sub { $_[0] }->($x); ## my $y = .. assignment operator $y = 5; print "$x\n"; ## still 0 </c> However, array slots <i>do</i> preserve aliasing, so you can return the alias if it's inside an array(ref): <c> my $x = 0; my $arr = sub { \@_ }->($x); $arr->[0] = 5; print "$x\n"; # 5 </c> You can even exploit this to make 2 entries in an array aliased to each other! <c> my $arr = do { my $x; sub { \@_ }->($x, $x); }; $arr->[0] = 0; print "@$arr\n"; ## 0 0 $arr->[0] = 5; print "@$arr\n"; ## 5 5 </c> </dd> <dt>map & grep</dt><dd> The block gets called once for each element of the list. Each time $_ is aliased to the next element of the list. <c> my $x = 0; map { $_ = 5 } $x; print "$x\n"; my $x = 0; grep { $_ = 5 } $x; print "$x\n"; </c> </dd> <dt>foreach</dt><dd> The foreach-style loop has essentially the same aliasing behavior as map and grep. Each time through the loop, the loop variable is aliased to the next item in the list. Of course, with foreach, the loop variable doesn't have to be named $_. <c> my $x = 0; foreach my $y ($x) { $y = 5 } print "$x\n"; </c> </dd> <dt>Typeglobs</dt><dd> <c> my $x = 0; *y = \$x; $y = 5; print "$x\n"; </c> In fact, using typeglobs, you can even alias hashes and arrays! <c> my @x = qw(1 2 3 4); *y = \@x; splice @y, 2, 1, "hi"; print "@x\n"; </c> </dd> <dt>[mod://Lexical::Alias]</dt><dd> The typeglob trick only works with symbol-table variables, and not lexicals. The [mod://Lexical::Alias] module uses some magic to let you do it with lexicals too. <c> use Lexical::Alias; my ($x, $y); alias $x, $y; $y = 5; print "$x\n"; </c> </dd> </dl> <h2>Anonymous aliases</h2> <p> An expression's return value can be aliased. Using it directly as an lvalue works just as if you were using an aliased variable. Assigning scalars <c>$y=EXPR</c> doesn't preserve alias nature of EXPR. The only way to put this kind of an alias in a variable is to use alias-preserving operations like above. <ul> <li>assignment statement: <c>sub { $_[0] = 5}->($x = 1); print $x;</c> <li>pre-increment, pre-decrement: <c>$x=5; sub { $_[0] = 1 }->(++$x); print $x;</c> </ul> <h2>Lots of aliasing!</h2> How many levels of aliasing do you see here? <c> my $x = 0; sub weird { --$_[0]; \@_ } for my $y (++$x) { my ($z) = map { weird($_ = 10) } $y; $z->[0] =~ s/9/hello world!/; } print "$x\n"; </c> <hr><hr><hr><hr> <!-- <blockquote><i>not everyone lives at an xterm. Normal people like fonts. I've met several, and they've told me.</i> -- [Petruchio] (by way of [ysth])</blockquote> --> <b>For [Limbic~Region]</b>: <p> Linear progression (with steps of size b, starting at x) looks like: <c> x + (x+b) + ... + (x+(n-1)b) = k nx + b(1 + 2 + .. + (n-1)) = k nx + b(n(n-1)/2) = k </c> ==> <c> bn^2 + (2x-b)n - 2k = 0 </c> Depending on what you want to do, this may help... if you know n,k,b, you can solve for x... otherwise if you know just n,k, you can probably solve for a space of valid x,b pairs (what remains is a linear constraint in x,b) ... i'm out of time though! <hr> <p> semi-unified interface to all kinds of set partitions we know about: <code> my $p = UnorderedSetPartition->new( items => ['a'..'f'], blocks => [2,2,1,1], ## arrayref list of blocks, num of blocks, or omitted=unrestricted ); my $p = OrderedSetPartition->new( items => ['a'..'f'], blocks => [2,2,1,1], ## arrayref list of blocks, num of blocks, or omitted=unrestricted ); ## or perhaps: ## SetPartition->new( ... ordered => 0 ... ); my $iter = $p->iterator( order => "lex", ## "lex", "colex", "gray", "fastest", etc... representation => "rg", ## "rg", "AoA", etc.. ); @output = $iter->next; $iter->skip($n); $iter->prev; # ?? $iter->reset; ## to the beginning $iter->reset( $some_saved_rank_or_widget ); #### @output = $p->list( order => "lex", representation => "rg" ); ## same as iterator, but returns list of *all* widgets ## maybe allow for a callback #### $r = $p->rank( order => "lex", representation => "rg", $widget ); $widget = $p->rank( order => "lex", representation => "rg", $r ); ## code repetition here? $how_many_partitions = $p->count; </code> <br><br> <hr> <code> sub binomial { my ($n, $k) = @_; my $c = 1; for (0 .. $k-1) { $c *= $n-$_; $c /= $_+1; } $c; } </code> <!-- <code> use Memoize; memoize 'int_partitions'; ## number of integer partitions of $N with smallest part $min sub int_partitions { my ($N, $min) = @_; $min = 1 if not defined $min; ## only one way to split up 0 return 1 if $N == 0; ## the smallest item in the partition can be between $min .. $N ## and after we fix it, we need to partition the remaining ## $N-$_, into pieces that must all be >= $_ my $total = 0; for ($min .. $N) { $total += int_partitions($N-$_, $_); } return $total; } print int_partitions(shift), $/; </code> <code> use Memoize; memoize 'restricted_partitions'; sub restricted_partitions { my ($N, @coins) = @_; ## can't do it if $N is negative (might get called with $N<0 if ## we have coins bigger than $N) ## only one way to make change for 0 return 0 if $N < 0; return 1 if $N == 0; ## pick any available coin to be the coin with the lowest ID in this ## partition. once we pick that, we have left to partition $N-$coin, ## and can't use coins with lower IDs to do it... my $total = 0; for (0 .. $#coins) { $total += restricted_partitions($N-$coins[$_], @coins[$_ .. $#coins]); } return $total; } print restricted_partitions(@ARGV), $/; </code> Try with @ARGV = qw( 100 100 50 25 10 5 1 ), which gives the # of ways to make change for a dollar (including dollar & half-dollar coins). --> <!-- ####################################### --> <h2>Fix [cpan://DBD::mysqlPP]'s ridiculous placeholders bug</h2> <code> --- mysqlPP.pm.orig 2005-02-16 23:40:15.000000000 -0600 +++ mysqlPP.pm 2005-02-16 23:41:17.000000000 -0600 @@ -347,10 +347,10 @@ # ... } my $statement = $sth->{Statement}; - for (my $i = 0; $i < $num_param; $i++) { + { my $dbh = $sth->{Database}; - my $quoted_param = $dbh->quote($params->[$i]); - $statement =~ s/\?/$quoted_param/e; + my $i = 0; + $statement =~ s/\?/$dbh->quote($params->[$i++])/ge; } my $mysql = $sth->FETCH('mysqlpp_handle'); my $result = eval { </code> References: [id://352312], [ RT] <!-- ####################################### --> <h2>Do yourself a favor & make CGI::param non-context-aware</h2> I think we've all been bitten with something like <code> $sth = $dbh->prepare("select * from foo where id=?"); $sth->execute( param("id") ); ## execute failed: called with 0 bind variables when 1 are needed </code> Of course, the problem is that <tt>param</tt> is in list context and so may return an empty list. The solution is to always say <tt>scalar param(..)</tt>. But I almost never write forms that require <tt>param</tt> to return multiple items. So from now on, I'm going to start all CGI scripts like this: <code> # use CGI 'param'; ## not anymore! use CGI; sub param { scalar CGI::param(@_) } </code> Reference: [id://357826] <!-- ####################################### --> <h2>"Fix" bad CSV</h2> I had to work with some legacy CSV that was poorly-formed. It had many records like this (notice the non-escaped double quotes): <code> "Robert "Bob" Smith","42","FooBar" </code> Fields containing double quotes were themselves quoted. So assuming we don't have any fields where a comma is adjacent to a quote in the data (this makes me shudder), we can get [cpan://Text::xSV] to read it as intended like this: <code> use Text::xSV; sub filter { local $_ = shift; chomp; s/(?<=[^,])\"(?=[^,])/\"\"/g; "$_\n"; } my $csv = Text::xSV->new( filename => "...", filter => \&filter ); </code> <!-- ####################################### --> <h2>Patch [cpan://Text::xSV] - quote all output fields</h2> <code> --- xSV-old.pm 2004-05-26 20:13:12.000000000 -0500 +++ xSV.pm 2004-05-26 20:32:48.000000000 -0500 @@ -172,17 +172,18 @@ } my $sep = $self->{sep}; + my $quote = $self->{always_quote}; my @row; foreach my $value (@_) { if (not defined($value)) { # Empty fields are undef - push @row, ""; + push @row, $quote ? qq("") : ""; } elsif ("" eq $value) { # The empty string has to be quoted. push @row, qq(""); } - elsif ($value =~ /\s|\Q$sep\E|"/) { + elsif ($value =~ /\s|\Q$sep\E|"/ or $quote) { # quote it local $_ = $value; s/"/""/g; @@ -321,7 +322,7 @@ my @normal_accessors = qw( close_fh error_handler warning_handler filename filter fh - row_size row_size_warning + row_size row_size_warning always_quote ); foreach my $accessor (@normal_accessors) { no strict 'refs'; </code> Then activate the "always_quote" option. | http://www.perlmonks.org/index.pl?displaytype=xml;node_id=358374 | CC-MAIN-2015-18 | refinedweb | 3,719 | 58.72 |
Summary
Extracts input features that overlay the clip features.
Use this tool to cut out a piece of one dataset using one or more of the features in another dataset as a cookie cutter. This is particularly useful for creating a new dataset—also referred to as study area or area of interest (AOI)—that contains a geographic subset of the features in another, larger dataset.
An alternate tool is available for clip operations. See the Pairwise Clip tool for details.
Illustration
Usage
The Clip Features parameter values can be points, lines, and polygons, depending on the Input Features or Dataset parameter type.
- When the Input Features or Dataset values are polygons, the Clip Features values must also be polygons.
- When the Input Features or Dataset values are lines, the Clip Features values can be lines or polygons. When clipping line features with line features, only the coincident lines or line segments are written to the output, as shown in the graphic below.
- When the Input Features or Dataset values are points, the Clip Features values.
- When the Input Features or Dataset values are an integrated mesh, 3D object, or point cloud scene layer or scene layer package, the Clip Features values must also be polygons.
The Output Features or Dataset parameter will contain all the attributes of the Input Features or Dataset parameter when the output is a feature class.
Integrated mesh and 3D object scene layer packages must use I3S version 1.6 and later to be used as input. Use the Upgrade Scene Layer tool to upgrade version 1.5 and earlier scene layer packages. The output scene layer package will be in the latest I3S version.: honors the Parallel Processing Factor environment. If the environment is not set (the default) or is set to 0, parallel processing will be disabled. Setting the environment to 100 will enable parallel processing. Up to 10 cores will be used when parallel processing is enabled.
Parameters
arcpy.analysis.Clip(in_features, clip_features, out_feature_class, {cluster_tolerance})
Code sample
The following Python window script demonstrates how to use the Clip function in immediate mode.
import arcpy arcpy.env.workspace = "C:/data" arcpy.Clip_analysis("majorrds.shp", "study_quads.shp", "C:/output/studyarea.shp")
The following Python window script demonstrates how to use the Clip function with a scene layer.
import arcpy arcpy.env.workspace = "C:/data" arcpy.Clip_analysis("campus.slpk", "building_footprint.shp", "C:/output/AreaOfInterest.slpk")
The following Python script demonstrates how to use the Clip function in a stand-alone script.
# Name: Clip_Example2.py # Description: Clip major roads that fall within the study area. # Import system modules import arcpy # Set workspace arcpy.env.workspace = "C:/data" # Set local variables in_features = "majorrds.shp" clip_features = "study_quads.shp" out_feature_class = "C:/output/studyarea.shp" # Execute Clip arcpy.Clip_analysis(in_features, clip_features, out_feature_class)
Environments
Licensing information
- Basic: Yes
- Standard: Yes
- Advanced: Yes | https://pro.arcgis.com/en/pro-app/latest/tool-reference/analysis/clip.htm | CC-MAIN-2022-05 | refinedweb | 471 | 50.53 |
I created a presigned URL for an Amazon Simple Storage Service (Amazon S3) bucket using a temporary token, but the URL expired before the expiration time that I specified. Why did this happen? How can I create a presigned URL that's valid for a longer time?
If you created a presigned URL using a temporary token, then the URL expires when the token expires, even if the URL was created with a later expiration time.
The credentials that you can use to create a presigned URL include:
- AWS Identity and Access Management (IAM) instance profile: Valid up to 6 hours
- AWS Security Token Service (STS): Valid up to 36 hours when signed with permanent credentials, such as the credentials of the AWS account root user or an IAM user
- IAM user: Valid up to 7 days when using AWS Signature Version 4
To create a presigned URL that's valid for up to 7 days, first designate IAM user credentials (the access key and secret access key) to the SDK that you're using. Then, generate a presigned URL using AWS Signature Version 4.
For example, follow these steps to create a presigned URL using Boto 3:
1. Configure your IAM user credentials for use with Boto.
2. Edit and run the following code snippet to create a presigned URL to use with an S3 object:
import boto3 from botocore.client import Config # Get the service client with sigv4 configured s3 = boto3.client('s3', config=Config(signature_version='s3v4')) # Generate the URL to get 'key-name' from 'bucket-name' # URL expires in 604800 seconds (seven days) url = s3.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': 'bucket-name', 'Key': 'key-name' }, ExpiresIn=604800 ) print(url)
Warning: The presigned URL expires prematurely if the IAM user is deleted, or if the access key and secret access key are deactivated.
Did this page help you? Yes | No
Back to the AWS Support Knowledge Center
Need help? Visit the AWS Support Center
Published: 2018-08-06 | https://aws.amazon.com/premiumsupport/knowledge-center/presigned-url-s3-bucket-expiration/ | CC-MAIN-2019-35 | refinedweb | 330 | 58.92 |
I have created a good looking ebook with great content. There are no product promotions or affiliate links in it, but there are some links that lead to my squeeze page I was wondering what the best approach is to get other bloggers to give away my ebook for free to their list? - Can I just ask them to give it to their subscribers or as a bonus to their buyers? - Do I have to do something in return (other then giving the free ebook)? I have no list of my own yet in this niche. Any tips, advice or personal experiences you may have are most welcome! Thank you! | https://www.blackhatworld.com/seo/how-to-get-other-bloggers-to-give-away-my-ebook-for-free-to-their-list.583301/ | CC-MAIN-2017-34 | refinedweb | 110 | 78.28 |
12 September 2012 10:27 [Source: ICIS news]
SINGAPORE (ICIS)--Shanghai Sinopec Mitsui Chemicals plans to shut down its 120,000 tonne/year bisphenol A (BPA) unit for annual maintenance at Caojing in ?xml:namespace>
The turnaround is expected to last for a month, the company source added.
The shutdown is expected to reduce domestic BPA production and tighten supply in the market. This may increase traders’ confidence about the market outlook.
The BPA plant was shut briefly for maintenance work in August after it encountered an equipment issue.
Shanghai Sinopec Mitsui Chemicals is a joint venture between major Chinese producer Sinopec and Japan-based | http://www.icis.com/Articles/2012/09/12/9594704/Shanghai-Sinopec-Mitsui-Chemicals-to-shut-BPA-unit-for.html | CC-MAIN-2014-49 | refinedweb | 105 | 54.73 |
> > ARCH=$(shell dpkg --print-gnu-build-architecture) > > build: > ifeq ($(ARCH),i486) > make linux > else > make linux-$(ARCH) > endif > touch build > > .. and I get the error: > > /bin/sh: -c: line 1: syntax error near unexpected token `(i486,i386)' > /bin/sh: -c: line 1: `ifeq (i486,i386)' > make: *** [build] Error 2 > > Why does make pass the ifeq line to a shell? Hi. Shell commands started with \t in the file - just your case, I guess. To have it interpreted by "make" start them from the beginning of line Alex Y. -- _ _( )_ ( (o___ +-------------------------------------------+ | _ 7 | Alexander Yukhimets | \ (") | | / \ \ +-------------------------------------------+ -- TO UNSUBSCRIBE FROM THIS MAILING LIST: e-mail the word "unsubscribe" to debian-devel-request@lists.debian.org . Trouble? e-mail to templin@bucknell.edu . | https://lists.debian.org/debian-devel/1998/02/msg00444.html | CC-MAIN-2016-44 | refinedweb | 121 | 71.14 |
>
I need to create a circle outline to indicate the "gravity distance" where if you are in a certain range of a circle object (planet), you are in effect of the circle object's gravity.
I have a circle outline sprite that I could put as a child of the circle object that could serve as an indicator. However, I do not know how to scale it properly. If I scale it the same way then, because of the sprite image's different png size, it does not scale properly.
Furthermore, the gravity distance is not strictly determined by the size of the planet. I have a variable called maxGravDist that sets the gravitational range of the planet. I want the circle indicator to change according to this maxGravDist. Here is how I use maxGravDist.
// Used to give gravity to individual planets
if (player.GetComponent<Player>().isJumping)
{
float dist = Vector3.Distance(transform.position, player.transform.position);
if (dist <= maxGravDist)
{
Vector3 v = transform.position - player.transform.position;
player.GetComponent<Rigidbody2D>().AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity);
}
}
Is there a way I can resize the outline according to maxGravDist and the size of the planet so that the player will feel the effect of the gravity as soon as it enters the outer circle? Thank you!
P.S. On the other hand, one other solution that I have come up with is to draw the circle using maxGravDist instead of using the circle outline sprite. However, I do not know how to draw a 2D circle using script. If someone can point me to a tutorial that does that, that would be great! Thank you.
Answer by danii956
·
Jan 10, 2018 at 02:53 AM
Argh.. Why is it so hard to draw a circle in Unity? Well, I found a work around.
[RequireComponent(typeof(LineRenderer))]
public class LineRendererEx : MonoBehaviour
{
public int vertexCount = 40; // 4 vertices == square
public float lineWidth = 0.2f;
public float radius;
private LineRenderer lineRenderer;
private void Awake()
{
lineRenderer = GetComponent<LineRenderer>();
SetupCircle();
}
private void SetupCircle()
{
lineRenderer.widthMultiplier = lineWidth;
float deltaTheta = (2f * Mathf.PI) / vertexCount;
float theta = 0f;
lineRenderer.positionCount = vertexCount;
for (int i=0; i<lineRenderer.positionCount; i++)
{
Vector3 pos = new Vector3(radius * Mathf.Cos(theta), radius * Mathf.Sin(theta), 0f);
lineRenderer.SetPosition(i, pos);
theta += deltaTheta;
}
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
float deltaTheta = (2f * Mathf.PI) / vertexCount;
float theta = 0f;
Vector3 oldPos = Vector3.zero;
for (int i=0; i<vertexCount + 1; i++)
{
Vector3 pos = new Vector3(radius * Mathf.Cos(theta), radius * Mathf.Sin(theta), 0f);
Gizmos.DrawLine(oldPos, transform.position + pos);
oldPos = transform.position + pos;
theta += deltaTheta;
}
}
#endif
}
OnDrawGizmos() function is not really important. It just allows you to see what the circle will look like while in Unity editor. SetupCircle() draws the actual circle. Public float radius determines the circle's radius while you can add/subtract position.x/position.y to Vector3 pos to move the circle around. lineWidth variable is responsible for the width of the circle and vertexCount variable is number of vertices. The more vertices you have, the more "circle" it will look. If you have 3 vertices, you will have a triangle. Also, make sure to check the loop field in LineRenderer component or else you will have a small gap in the circle.
I got this code/tutorial from Krister Cederlund in YouTube if anybody wants to check it out more in.
2D collision without simulating rigid bodies
1
Answer
How to calculate a projectile arc and impact point
0
Answers
How to rotate Bullets alongside Gravity 2D (No RigidBody)
0
Answers
How do you draw 2D circles and primitives
5
Answers
How to Set Gravity for large sprites ?
0
Answers | https://answers.unity.com/questions/1452223/creating-a-dynamic-circle-outline-around-a-circle.html | CC-MAIN-2019-18 | refinedweb | 612 | 58.38 |
***********Updated on 4th October 2017***********
Secure Socket Layer (SSL) and its successor Transport Layer Security (TLS) are protocols which use cryptographic algorithms to secure the communication between 2 entities. It is just a secure layer running on top of HTTP.
Overview of SSL Protocol Stack
Several versions of SSL have been released after its advent in 1995 (SSL 2.0 by Netscape communications, SSL 1.0 was never released). Here is the list:
- SSL 1.0, 2.0 and 3.0
- TLS 1.0 (or SSL 3.1, released in 1999)
- TLS 1.1 (or SSL 3.2, released in 2006)
- TLS 1.2 (or SSL 3.3, released in 2008)
SSL was changed to TLS when it was handed over to IETF for standardizing the security protocol layer in 1999. After making few changes to SSL 3.0, IETF released TLS 1.0. TLS 1.0 is being used by several web servers and browsers till date. What I have never understood, is there have been newer versions released after this, with the latest being TLS 1.2 released in 2008.
On Windows the support for SSL/TLS protocols is tied to the SCHANNEL component. So, if a specific OS version doesn’t support a SSL/TLS version, this means it remains unsupported.
Below table should give you a good understanding of what protocols are supported on Windows OS.
TLS 1.1 & TLS 1.2 are enabled by default on post Windows 8.1 releases. Prior to that they were disabled by default. So the administrators have to enable the settings manually via the registry. Refer this article on how to enable this protocols via registry:
On the client side, you can check this in the browser settings. If you are using IE on any of the supported Windows OS listed above, then in IE, browse to Tools -> Internet Options -> Advanced. Under the Security section, you would see the list of SSL protocols supported by IE. IE supports only those security protocol versions, which is supported by the underlying SCHANNEL component of the OS.
TLS settings in IE on Windows 10
Chrome supports whatever IE supports. If you intend to check the support in Firefox, then enter the text "about:config" in the browser address bar and then enter TLS in the search bar as shown below.
TLS Settings on Firefox v47
The settings security.tls.version.max specifies the maximum supported protocol version and security.tls.version.min specifies the minimum supported protocol version . They can take any of the below 4 values:
- 0 - SSL 3.0
- 1 - TLS 1.0 (This is the current default for the minimum required version.)
- 2 - TLS 1.1
- 3 - TLS 1.2 (This is the current default for the maximum supported version.)
Refer this Mozilla KB for more info:.*
Nice clear information !!! helpful
Excellent!! This was very helpful for me
Hello thanks Much, About TLS 1.2 in windows Seven7, blogs.msdn.com/…/support-for-ssl-tls-protocols-on-windows.aspx, Says you have to Turn On "TLS 1.2", so Where Is The Instruction Setup, if you please ? ? ? Only In internet explorer , and, Or ,What, where, howTo, more, etc. plzz
Hi Calvin,
Sorry for the late reply. I was out on vacation, so couldn't reply to you earlier.
I didn't include the instruction setup because there is a KB article on the same.
Here is the link: support.microsoft.com/…/245030
Basically if you want to disable or enable TLS/SSL on the server side, it has to be done via registry.>
Great article, but I'd appreciate it if you'd put descriptions (altText), under your images so that users reading your information using screen readers have an idea of what you're showing us.
thanks for the feedback Cron. I've included them now. Let me know if this helps.
have a 32 Bit Windows 2008 machine, how do I disable the Ciphers on that server and make it not vulnerable to the BEAST.
Kashif,
There is already a fix for the Beast. Read this article: blogs.msdn.com/…/fixing-the-beast.aspx
Why TLS 1.1 and 1.2 is not turned on by default?
@Ray – Well the reason is that not many existing client browsers don't support TLS 1.1 and later. Even though they are the latest versions of TLS, the problem has been with the adoption of these versions. If they are enabled, there will be additional time spent in re-negotiating these parameters with the server or client. Hence they are always kept disabled.
i m using windows 8. when i open browger its show ssl connection errors. how can i solve
@Arif – Could you provide a snapshot or provide more details on what is being done?
— What site are you browsing?
— What browser are you using?
— What is the actual error?
I have a case where the Win7 clients' SSL3 and TLS1.0 box is checked on IE8. When they try and connect to a Win2008R2 instance of IIS7.5 it refuses to go secure. If the client additionally checks the SSL2.0 checkbox, then the client goes secure with the server. How can that be? The server is default config, so SSL2.0 is turned off by default.
Why Windows Server 2008 (non R2!) do not get new schannel which supports TLS 1.1/1.2 and new ciphers ? It is still in Mainstream Support till 2015.
support.microsoft.com/…/default.aspx
Hello,
I am not sure why it was not added as it would have been really great to add support for latest TLS versions. The only problem I see was the major over-hauling required as the support for SSL is inbuilt into Windows. However you could provide your feedback here:
Hello Kaushal,
I have a few android browers accessing my application which is hosted on iis 7.5 & browsers are throwing a error message saying:
===============================================
Your connection to is encrypted with 256 bit encrption.
The connection uses TLS 1.0
The connection is encrypted using AES_256_CBC…..with sha1 for msg authencation and rsa as the key exchange mechanism.
The server does not support the TLS renegotiation extension
================================================
Need your suggestion on this..do i need to change the TLS to 1.2 in registry? please help.
Could you verify if the necessary updates are installed on the server?
Check this: support.microsoft.com/…/977377.
Please read carefully the instructions on how to fix this. This will affect certain functionality. You may also consider posting this problem on Windows Security Forums to get a quicker and better response: social.technet.microsoft.com/…/home
how to fix internet explorer 10 "this page can't be display" make sure tls and ssl protocols are enabled. but in internet option tls 1.0 and ssl 3.0 box is alreadly selected.
@Deepak, that is a very vague issue description, Have you checked if the issue happens from other clients while accessing the same server?
I had a problem, where TLS states were Grayed out in Win 7 64-bit OS.
Sorry I am facing a problem when checking for a particular website its showing the page cannot be displayed. When moved to IE options , TLS states were Grayed out, How should I proceed further.
Hello Santhosh. Looks like these settings are managed for your computer via group policy or you may want to consider launching IE as an administrator to give it a second try.
hi Kumar, how if i enabling the TLS on Windows Server 2008 R2, is any error in the communication, whereas i enabling both SSL and TLS on IIS Service. can you explain a little bit how SSL and TLS work in encryption before 3-way TCP hanshake key. many thanks and this is a good topic.
How can I enable TLS 1.1, 1.2 for my clients which are using windows application to connect to wcf service?
I think browser specific settings to enable TLS 1.1, 1.2 are not applicable in thi case.
Hello. I am on Windows 7 using wamp and opens SSL. How do i enable TLS 1.1 and 1.2?
@DJ Danni
OpenSSL has its own implementation for SSL/TLS. They don't rely on SCHANNEL.
For OpenSSL I would suggest you to check their documentation on how to enable it. The recent version of OpenSSL does support TLS 1.1 & TLS 1.2.
Here is my OpenSSL Version
OpenSSL/0.9.8k
openssl
OpenSSL support enabled
OpenSSL Library Version OpenSSL 0.9.8k 25 Mar 2009
OpenSSL Header Version OpenSSL 0.9.8r 8 Feb 2011
So is it possabole to use TLS 1.2 on that version?
If so how do i update?
@DJ Danni. From what I read, it is supported on 1.01 and higher versions..…/openssl-1.0.1-notes.html
Not mean to discourage people, but with technology progressing all the time, this article needs update or clearly marked so.
Hi, can any one help me on my below query.
A client has had a security assessment conducted of the web servers in their environment. They want the servers to be configured to disable SSL version 2, and to only accept SSL ciphers greater than, or equal to, 128 bits. The web servers in the environment consist of Apache 2.2 on Red Hat Enterprise Linux 6, IIS 6 on Windows Server 2003, and IIS 7.5 on Windows Server 2008 R2. Please answer the following questions:
1. How do you test the servers to determine which SSL versions and ciphers are
currently supported / accepted? Please describe the process.
2. What changes are needed for each of the web servers / operating systems to meet the client's requirements? Please be specific.
what happens if you create tls 1.0, 1.1 and 1.2 keys in gpo for a mix win2k3, win2k8, win2k8r2, win2k12 environment? the keys for 1.1 and 1.2 would not enable features unsupported on win2k3, however would this cause issues if those keys now existed for gpo or is there a better method similar to enabling IE tls via gpo? (for server/apps/programs like iis)
Hi
We are using IE9 and TLS 1.0 is enable by default, if i will enable TLS 1.2 IT it will impact the other sites…?
@Prashant – It wont!
Hi Kaushal,
Thanks for your prompt replied.. 🙂
TLS 1.2 what exactly its enable and how it is different from TLS 1.0..?
As just want to check the effects before implementing the changes.
There are lots of difference. TLS 1.2 is the latest version while TLS 1.0 is almost obsolete.. Most of the vulnerabilities that we encounter today are related to 1.0
There re several posts describing he differences. you could go through them.
I have a question. With PCI standards dictating now that TLSv1 needs to be disabled on web servers in order to be compliant. Yet many users are still sitting on IE 8-10 which has support for TLSv1.1 and 1.2 disabled by default. Many users simply won't be able to use these PCI compliant sites.
Does Microsoft plan to enable 1.1 and 1.2 in IE 8-10 in a patch?
It has nothing to do with IE. IE supports whatever the underlying OS supports.
Until Windows Server 2012 R2/Windows 8.1 TLS 1.1/1.2 was disabled by default. It is debatable to say whether to enable it or not. However a simple solution is that we can have the registry key switched to enable the support for these protocols.
It has everything to do with IE. Other than IE8-10 every single other browser has TLSv1.1. ans 1.2 enabled by default. IE 8-10 has that support as well but has it turned off by default.
And this has nothing to do with IIS, most web servers are running on apache, tomcat or other linux variants.
As it stands now, in June 2016 when every single web site on the net that has to be PCI compliant will need to disable TLSv1.
Then you will have a significant number of people who are still running IE 8-10 who will not be able to access these sites by default.
@Joe
As I said it depends on the underlying Operating System for most of the Microsoft products. IE supports, whatever the underlying OS supports. IE 8 on windows XP supports only TLS 1.0 as XP has no support for the later versions of TLS.
The component is called SCHANNEL. We have either Client & Server specific registry keys.
We need to understand why this decision was made. When IE came out with support for TLS 1.1 and TLS 1.2, it was the only browser which supported these protocols.
As you mentioned most of the web servers run on Apache and they didn't support these protocols until 2010/2011 I believe. When Windows 8.1 was launched IT industry was slowly shifting to newer versions. FINALLY IT HAPPENED.
So the decision was made to be keep it as disabled by default. Chrome and other major browsers started support for it around the same time (2011).
Instead of waiting for a patch its a simple setting that can be enforced. One can write a script or if the machines are part of a domain, then push it via Group Policy.
I'm not quite certain why we are discussing web servers.
Hi All,
Couple of website is hosted in system (Windows 2008 R2) in IIS7.0 environment and now working with SSL V3.0. I want to move to TLS1.2.
I have setup the the TLS1.2 in registry and disable my existing SSLv2.0,3.0, TLS1.0 & TLS1.1. Also, enable the TLS1.2 in IE and disdable all other type of SSL & TLS.
Now, when I browse the app, i am getting error.
1. Do I need to chnage anything in website configuration for TLS support?
2. The services are currently hosted using a Verisign SSL certificate. Can we use same certificate for TLS?
@ Ambarish
Correction: Windows Server 2008 R2 has IIS 7.5. Could you let me know the registry that you have added? You can email me at kaushalp@microsoft.com.
There is no configuration in IIS to enable/disable a specific SSL protocol version.
Ensure the browser you are using to communicate has TLS 1.2 enabled as well.
Secondly, SSL Certificates are not dependent on the SSL protocol version.
"Ensure the browser you are using to communicate has TLS 1.2 enabled as well."
My point exactly. When every PCI compliant web server switches over to TLSv1.2 in June of next year the entire web will be filled with people running IE 8-10 saying the same thing. It's ridiculous. Only IE 8-10 has support for that protocol off by default. And it's doubly ridiculous that it is still that way if IE had support for those protocols before the other browsers.
I might add as well that while IE 8-10 only use TLSv1 by default that it is a broken protocol and not secure at all anymore.
As if the world needed another reason to get off of IE altogether.
Yes it is absurd that it is switched off by default on earlier OS's.
I am not quite certain of the future updates that will be provided. Rather waiting as I suggested earlier push these settings off to machines via group policies.
You could also submit your feedback to the IE dev team here: connect.microsoft.com/IE
So, we just went under a Scan and now it's complaining that we need to disable TLS 1.0. That throws a couple of quick wrenches. 1st, the back end app talks over TLS 1.0 to SQL Server so we need to keep the client side enabled. Second, if I disable the server side, I can't RDP into the server. I can use weaker RDP encryption, but that's not good either. How are we getting past this aging TLS v1.0? On top of that, there are still a lot of browsers that can't use 1.1 or 1.2. I'm more concerned about RDP. Oh, and I do NOT use RDP over the internet, VPN tunnel only, so I'm guessing you'll say it's ok to use the weaker encryption.
Thanks.
@Kevin. Every single browser currently supports TLS 1.1 & 1.2. The ones that don't support them are IE running on Windows XP/Windows server 2003. The Reason being both the OS don't have native support for TLS 1.1 & TLS 1.2.
If you are using Windows Vista o higher, you shouldn't have any issues. At some point you need to make the transition, it is better you do it now than at a later stage.
I'm not an RDP expert, but check if the RDP client supports TLS 1.1/1.2.
Very helpful! Thanks!
Hi, i'm tying to make a secure connection from a .net 4.5 context with WebRequest over TLS 1.1 / 1.2 for Windows Server 2008 sp2. All goes fine when i run the application from windows 8/8.1 host, but on Windows Server 2008 is fails with: "The underlying connection was closed: An unexpected error occurred on a send." I believe it is due to "Now let’s come to the point, on Windows the support for SSL/TLS protocols is tied to the SCHANNEL component" and "All the windows components/applications abide by this rule and can support only those protocols which are supported at the OS level." If this is true for .net 4.5, could you point me to a reference document confirming the implementation?
Hello, I am trying to make some changes to pass the PCI Compliance Scan. For starters, I was able to disable TLS 1.0 on the Exchange server but now many users outside of the network are having trouble connecting to the server via Outlook, would you happen to know what would be the best way to get them to connect?
Also, I am running a terminal server on Windows Server 2008 (not R2) and I see on the top of the page that the server does not support TLS 1.1 and 1.2. Is there a way around that? I am failing because of TLS 1.0 being enabled.
Thanks,
Saul
@Saul
Windows Server 2008 doesn't support TLS 1.1 & 1.2. The best solution for you is to upgrade to 2008 R2 or higher.
i am currently running windows vista and internet explorer 9, and cannot see support for tls 1.1 or tls 1.2 when i go control panel-advanced internet options. what gives? would like to keep current os and browser. you said vist or higher should have no problems.
@Kaushal – Very useful article – thanks.
In your response of the 8th May, you say "If you are using Windows Vista o higher, you shouldn't have any issues." but the table above says that Vista doesn't support TLS1.1/1.2. Can you say which is correct? (Ron's message of the 22nd suggests the table is correct).
Thanks.
This is a good but very old article. Since some people are still commenting on this article it is worth mentioning a few things. Some things are no longer true. For example all major browsers such as Chrome and Firefox have had support for TLS1.1 and TLS 1.2 for quite some time now.
@Kaushal, when you enable TLS1.1 and TLS1.2 in Schannel through the registry, it is not automatically also enabled in IE settings. While it is true that IE is dependent on whatever your version of Schannel.dll supports, these are two separate settings.
For viewing/changing settings on Microsoft servers without editing the registry manually you can use the free tool IISCrypto that makes the necessary registry settings for you. When disabling older protocols on the server side, such as SSL2.0, SSL3.0 please be aware that many older devices may not support TLS, for example Windows XP, older versions of android and windows mobile etc.
I find it quite shocking that if I set up the browsers on my windows 8.1 client to insist on secure connections (ie no support – not even fall-back – for RC4, and no support for anything earlier than TLS1.2, I can no longer access the MSDN website. That doesn't much matter for pages like this one, but it's a bit of an issue for, for example, downloads.
Hi Kushal,
Can I expect help in resolving this problem : stackoverflow.com/…/ssl-protocol-tweaking-at-operating-system-level-by-editing-registry-on-windows.
Thanks in advance!
Hi Kushal,
Its really a good article and gave me a lot of information about SSL and TLS. I have a problem regarding TLS 1.2. One of the webservice hosted on a customer server is having TLS 1.2, to consume that webservice I was told to use TLS 1.2 in my application hosted in different server. How this can be done. I am using Windows 2008 R2 server. I have enabled tls 1.2 in my server and tried to initiate the requests to consume the customer server's web service. But it is erroring out "could not establish secure channel for SSL/TLS with authority"
I had confirmation that MS are developing a hotfix for Windows 2008R2 to support TLS v1.1 and v1.2. Testing is still underway (90 day test cycles) so it could be soon released.
Tracked down a browser not able to access a web page to the SSL cert used on the web server using TLS 1.0. Similar web server apps, when SSL uses TLS 1.2 can be accessed by browser with no problem. Question: who/how decides what TLS version to use with SSL cert? Is it baked into the SSL cert at the time the SSL cert is created? It's not in the app/web server, because the app/web server code is the same in both cases — only the SSL certs are different.
@Aleks
I have covered your answer in this post here: blogs.msdn.com/…/ssl-handshake-and-https-bindings-on-iis.aspx
To answer your question, both client and server engage into a dialog (SSL Handshake) to decide the SSL protocol version.
Hi Kaushal,
I have a server 2003 machine and I'm researching what I need to do to get it to pass an SSL test (e.g. ssllabs.com). I see a lot of information about how server 2003 does not support TLS 1.1 and 1.2, but I'm also seeing a ton of information online regarding workarounds by editing the registry or various other things. e.g.:
portal.chicagonettech.com/…/maximizing-ssl-security-for-windows-server-2003-ssl-tls.aspx
That article appears to show only registry changes which appear to result in a grade of B from ssllabs.com, and if schannel doesn't support TLS 1.1 to begin with I don't see how any registry tweaks are going to change that.
I'm not clear – is there any way to get server 2003 to disable the older insecure protocols and ciphers and only allow the current ones like TLS 1.1 and 1.2? Is the only option to upgrade the OS to a newer version?
Thanks
Since PCI DSS 3.1 will force retire TLS 1.0 from all e-commerce websites by end of June 2016, what will be Microsoft position regarding IE 9 on Vista?
Will they upgrade SCHANNEL on Vista to add TLS 1.1/1.2 support or urge users to drop IE 9 and use Firefox or Chrome instead?…/Migrating_from_SSL_Early_TLS_Information%20Supplement_v1.pdf
Hi Kaushal,
QQ is TLS1.0 Client & Server side enabled by default on Windows 2003 and 2008? I notice that the key Client with the Dword "Enabled" (with value ffffffff) is not present by default. On Windows 2008R2 and 2012 I was able to find documentation that explicitly say is enabled by default, but for 2003 I found a bunch of kbs and notes on How to disable protocols.
Thanks in advanced!
sorry for the delayed response folks. Been away from blogging for quite some time.
@Steve
Windows Server 2003 and Windows Server 2008 do not have native support for TLS 1.1 and TLS 1.2. Even if you add a registry key it is of no use as the protocol itself is not recognized by the OS. There is also a reason for this. Both the protocols were proposed around 2006 and the industry started adopting this around 2010.
The only solution for you would be to upgrade latest version which is Windows Server 2012 R2.
@Valérie
as I mentioned above TLS 1.1 and TLS 1.2 are not supported on Windows Vista and I don't see any investments being made for them to be made available on Vista. However, I am not on the product team which makes such decisions. I think it would be better if you could post a query for this on UserVoice: windows.uservoice.com/…/265757-windows-feature-suggestions
@Fercha
Yes, TLS 1.0 is enabled by default for client and server side on Windows Server 2003 and Windows Server 2008. You may not see any keyword in the registry for this as they are built-in.
I am using IISCrypto at the last few years and until now all works fine with my sites
Today I was asked by the PCI company to Disable TLS 1.1 AND TLS 1.0 and to enable TLS 1.2
From the moment that I enable only TLS 1.2 nobody from any browser and any pc can login to my site and the error msg is :
Runtime Error
Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
Few months ago I did the same at my other sites and all works fine.
I will really appreciate your help to help me understand what I am doing wrong and what should be done to solve this issue ASAP
Btw- my server is windows server 2008R2 with the last updates.
is this what the end user sees if they are trying to access a LTS1.2 encrypted portal with a browser that does not support TLS1.2?
Hi,
Our application wants to support TLS 1.2. I have configured in registry and also updated my configuration files but I have the IIS version as 7. Our OS is Windows 2008 R2 Enterprise edition.
When I tried to execute my application, it is still taking TLSv1.0 as default. Do I need to upgrade my IIS manager to 7.5? Also am getting error if I tried to upgrade as Microsoft .net framework version 4.0 or greater is required to install 7.5 IIS express.
Helping this issue would be highly appreciated.
Thanks,
Rameez
@Rameez Raja
IIS version is tied to Windows version. You are actually running IIS 7.5 as it is Windows Server 2008 R2. There are 2 things to note, there is a client stack and server stack. IIS consume the server stack configuration.
In this blog when we modify the IE settings it is changing the settings only for IE and not IIS. You will have to modify the
Even if you enable TLS1.2 it depends on the client connecting to the server. Basically you have to do this:
Support article: support.microsoft.com/245030
In order to disable or enable TLS/SSL on the server side, registry has to be modified.>
Any one please tell me how can i enable TLS 1.2 in excel vba to use it for a service call which uses TLS 1.2.
Hi Kaushal,
I have TLS 1.0 , 1.1 , TLS 1.2 enabled on both Client and Server and both have the same cipher order.
So which protocol is agreed by both before exchange of actual messages ?
I have read somewhere they use the highest possible protocol. Is this right ?
Thanks,
Mrunal
How do POSReady OSes line up here?
“It is just a secure layer running on top of HTTP.”
No, it’s a layer on top of TCP.
Any one please tell me how can i enable TLS 1.2 in excel vba to use it for a soap service call which uses TLS 1.2.
Hi,
I have a Windows Server 2003. IIS 6 is running on that and TLS 1.0 is available. I have a classic ASP based web application hosted on that server. It has a payment module that connects to PayPoint payment API via https query string from the server side. I checked the paypoint url in the ssllabs and it supports all transport protocols.
The application stopped working since March 2016. I am not able to figure out the error. I initially thought it could be because of the TLS 1.2 version because most of the industry is heading towards that direction and thought that the issue is because the server is Windows 2003. However, the test payment link from PayPoint worked in FireFox browser and it showed that it used TLS 1.2 for the transaction. For a moment I lost my mind.. Does FireFox has the complete implementation of TLS 1.2 build within? So, if the browser or the client application is going to support TLS 1.2 does it really matter whether the server supports TLS 1.2 or not, windows server 2003 in this case?
On the receiving end of the transport connectivity, PayPoint in this case, is it possible for the PayPoint software to put restrictions on the inbound connections to use only TLS 1.2. The ssllabs says the server supports all protocols.
I am sorry for so many questions, but I no very little about this level of connectivity.
Please provide any thoughts.
Thanks
Pandu
An associated question to my previous question:
Can a browser or a client application fully support or implement a Transport Layer Protocol (either directly or with the help of .NET framework, in the case of applications) even if the underlying Operating System does not support that version of protocol?
Thanks
Pandu
Mozilla just announced plans to enable TLS 1.3 by default in Firefox 52 (currently scheduled for March, 2017). Can you talk about Microsoft’s plans for enabling TLS 1.3 in Schannel (to allow those of us running IIS web sites to use it)? Thanks.
Hi Kaushal,
Why my IE11 shows encrypted in connection properties..?
Supose showing TLS something, right?
Firefox now supports TLS 1.3 with version 49 it will be default on after version 49
0 – SSL 3.0
1 – TLS 1.0 (This is the current default for the minimum required version.)
2 – TLS 1.1
3 – TLS 1.2 (This is the current default setting in version 49)
4 – TLS 1.3 (This is the capable setting for version 49+)
We need to provide https support to Windows XP clients with IE 6.0.
We are using wininet API for internet communication. On XP SP3 after enabling TLS 1.0 https connection is established.
But this doesn’t work on XP SP2 and lower. Is https connection possible on XP SP2 and lower?
How can we find weather the IE and OS support Https connection or not?
Please suggest solution.
Hello,
I want to know what are all the dependencies needed for upgrading TLS v1.0 to v1.2 for various web servers.
Nice 1! Like a breath of fresh air. U turned on the light bulbs for me mate. Thanks
Hi Kaushal,
Due to PCI Compliance we had to upgrade the security certificate from SSL to TLS1.2 on the server. My web service resides on server(Windows 2008 R2) and am trying to connect it from the test client console app.
I can access the web service and get the results through my client app which is in my local machine, which was already built successfully when the security certificate on server was Tls1.0.
In my client console app, when I try to ADD the same ‘service’ or ‘web’ reference, am not able to add the service url to the client test application.
I get the following error.
There was an error downloading ‘’.
The underlying connection was closed: An unexpected error occurred on a send.
Unable to read data from the transport connection: An existing connection was forcibly closed
Note: Both Test Console Application and Web Service are built on .Net 4.5
Any help is appreciated.
Thank You..:)
Does anyone know a way to get server 2008 r2 to be able to do tls 1.2 to paypal on the classic asp server side posts? I haev set the registry and in the code I have set option 9 to 128, etc.
I still get channel error. Same code on my windows 10 pro IIS server works just fine.
Can anyone give me some insight on how to update Openssl on a Windows Server 2012 R2? We are being impacted by the PCI industry changes and have not been able to get much support from our host provider.
It seems we are running 0.9.8c and need to upgrade to 1.1.0c. Any thoughts or insight that you can share will be greatly appreciated.
I tried to look on the consulting boards for a Openssl or TLS expert, but couldn’t find anyone in my query. Been struggling to fix this for 4 weeks now…please hlep. Thanks!
Hi Kaushal,
Nice article. I want to know by default in Internet Explorer TLS 1.0, TLS 1.1, TLS 1.2 is used/enabled.
If i unchecked this all TLS then my website is not displaying giving error like :
“This page can’t be displayed, Turn on SSL 3.0, TLS 1.0, TLS 1.1 and TLS 1.2 in Advanced settings and try connecting to website name”
Can you please suggest why this is happening and other websites are running without TLS checked.
If you can provide any idea then it will be great ASAP.
Thanks
is there any script to get this output of this ( security tab) from multiple servers at once.
Windows Server 2008 SP2 now supports TLS 1.1 and TLS 1.2
It was pending for quite some time now. Thanks! I updated the article.
Do you have any experience or are you aware of any issues for UWP apps?
We have an UWP app running in Windows 10 that stopped working after the service we were connecting to disabled TLS1.0.
We tried several things and we are not sure if the issue is on the app or on the network.
But it seems there are no options for enforcing TLS1.2 on the WEB APIs for UWP,
I am not familiar with UWP as such. But can provide pointers. What namespace are you using to initiate the TLS connection?
The update made to this page today has broken the formatting in the table
Also, does Google Chrome use it’s own built-in support for TLS 1.1 and 1.2, and if so, would this work on XP clients, or does it use the system libraries for this and so wouldn’t?
Thanks
Google chrome seems to use the SSL client stack of internet explorer for this and hence doesn’t support.
Hi Kaushal,
Thanks for sharing knowledge through this article and your support.
Currently we ran through a problem. We updated TLS-1.2 in Windows-2012 Enterprise and we were accessing through RDP session from Windows 2008 R2-SP1. We lost our RDP session W2K8 -R2 throws an error while connecting RDP session. We used KB3080079 ( ).
But still unable to open a RDP session. Any Suggestions?
Its difficult to provide recommendations without much insights into the issue. I would suggest to perform checks on the client and server and ensure that TLS 1.2 is enabled for both Client and Server stacks.
Take a network trace from both client and server to ensure that the SSL handshake is completing. | https://blogs.msdn.microsoft.com/kaushal/2011/10/02/support-for-ssltls-protocols-on-windows/?replytocom=4635 | CC-MAIN-2017-43 | refinedweb | 6,105 | 77.23 |
"Coding ... the boring bit between builds"
As you know, MSBuild in .NET 3.5 adds support for building projects concurrently. MSBuild.exe exposes this support with the new /m switch, and because Team Build uses MSBuild to build projects, it will get a speed up as well. In this release, Visual Studio doesn't use this to build managed projects concurrently, but you can write your own host that can build in parallel.
There are some limitations. In 3.5, you can't build in-memory projects concurrently, only project files. Also, I don't like the API much. Msbuild.exe was the only host we were focusing on in 3.5 and we didn't make it pretty. That will change.
Anyway, here's an example. It assumes you have a sleep.exe in the same directory as the projects. So "sleep 3" will pause for 3 seconds. Our objective here is to run two sleeps concurrently :-)
using System;using Microsoft.Build.BuildEngine;using Microsoft.Build.Framework;using System.Reflection;
namespace HostMsBuildExeTest{ class Program { [STAThread] static void Main(string[] args) { // We need to tell MSBuild where msbuild.exe is, so it can launch child nodes string parameters = @"MSBUILDLOCATION=" + System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\..\Microsoft.NET\Framework\v3.5"; // We need to tell MSBuild whether nodes should hang around for 60 seconds after the build is done in case they are needed again bool nodeReuse = true; // e.g. if (!nodeReuse) { parameters += ";NODEREUSE=false"; }
// We need to tell MSBuild the maximum number of nodes to use. It is usually fastest to pick about the same number as you have CPU cores int maxNodeCount = 3; // e.g.
// Create the engine with this information Engine buildEngine = new Engine(null, ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile, maxNodeCount, parameters);
// Create a file logger with a matching forwarding logger, e.g. FileLogger fileLogger = new FileLogger(); fileLogger.Verbosity = LoggerVerbosity.Detailed; Assembly engineAssembly = Assembly.GetAssembly(typeof(Engine)); string loggerAssemblyName = engineAssembly.GetName().FullName; LoggerDescription fileLoggerForwardingLoggerDescription = new LoggerDescription("Microsoft.Build.BuildEngine.ConfigurableForwardingLogger", loggerAssemblyName, null, String.Empty, LoggerVerbosity.Detailed);
// Create a regular console logger too, e.g. ConsoleLogger logger = new ConsoleLogger(); logger.Verbosity = LoggerVerbosity.Normal;
// Register all of these loggers buildEngine.RegisterDistributedLogger(fileLogger, fileLoggerForwardingLoggerDescription); buildEngine.RegisterLogger(logger);
// Do a build buildEngine.BuildProjectFile("root.proj");
// Finish cleanly buildEngine.Shutdown(); } }}
Now for testing purposes, I created three projects like this:
root.projProject <Target Name="t"> <Message Importance="high" Text="## in root building children ##"/> <MSBuild Projects="1.csproj;2.csproj" BuildInParallel="true"/> <Message Importance="high" Text="## in root done building ##"/> </Target></Project>
1.csproj
<Project xmlns="" ToolsVersion="3.5"> <Target Name="t"> <Message Importance="high" Text="## starting 1 ##"/> <Exec Command="sleep 3"/> <Message Importance="high" Text="## finishing 1 ##"/> </Target></Project>
2.csproj
<Project xmlns="" ToolsVersion="3.5"> <Target Name="t"> <Message Importance="high" Text="## starting 2 ##"/> <Exec Command="sleep 3"/> <Message Importance="high" Text="## finishing 2 ##"/> </Target></Project>
Notice that the root project uses the <MSBuild> task with the parameter BuildInParallel="true". This is where the parallelism starts: you still only invoke the build on a single root project. Without BuildInParallel="true", the <MSBuild> task will build serially. In a tree of projects, you would want every node to build its children with BuildInParallel="true".
Here's the output I get:
c:\test>test.exeBuild started 10/21/2007 5:02:55 PM. 1>Project "c:\test\projects\root.proj" on node 0 (defaul t targets). ## in root building children ## 1>Project "c:\test\projects\root.proj" (1) is building " c:\test\projects\1.csproj" (2) on node 1 (default tar gets). ## starting 1 ## 1>Project "c:\test\projects\root.proj" (1) is building " c:\test\projects\2.csproj" (3) on node 2 (default tar gets). ## starting 2 ## 1>t: ## in root done building ## 1>Done Building Project "c:\test\projects\root.proj" (de fault targets). 3>t: ## finishing 2 ## 3>Done Building Project "c:\test\projects\2.proj" (de fault targets). 2>t: ## finishing 1 ## 2>Done Building Project "c:\test\projects\1.proj" (de fault targets).
Build succeeded. 0 Warning(s) 0 Error(s)
Time Elapsed 00:00:03.21
As you can see, the two 3-second sleeps ran concurrently, so the build took 3.21 seconds overall.
Just to prove it I changed the "3" to "1" and got this:
Time Elapsed 00:00:06.11
There's lots more to say about multiproc support, especially to explain the types of loggers I attached here, and that will be the subject of future posts. Even if you don't host MSBuild, you may want to create "traversal" projects (something like solution files, but nestable) that build their children in parallel. I'll explain that too in due course.
Just to be clear though, for most of us, it isn't necessary to know any of this. We can just point msbuild.exe at our solution file and throw the "/m" switch and our build will be faster.
Dan
If you would like to receive an email when updates are made to this post, please register here
RSS
PingBack from
It looks like I'm not the only one who wanted a debugger for MSBuild projects. When the MSBuild team
Could you set MSBUILDLOCATION as environment variable? Would this be then acknowledged by VS.NET and Team Foundation Build Server?
Basically I would like to redirect VS.NET and Build Server to location fo "my" MSBUILD version so I am sure that 3.5 version is used all the time.
One of the scenarios I like to achieve is to build LINQ code from VS.NET 2005. Because VS.NET uses MSBUILD to complie code abbility to swithc MSBUILD would allow me to "upgrade" BCL without upgradeing VS.NET itself.
So the question is how to tell VS.NET and Team Foundation Server which MSBUILD to use. Could MSBUILDLOCATION environment variable be used for this?
Based on several posts from this blog I put together a simple project to play with a multi-proc build. If you find it relevant: | http://blogs.msdn.com/msbuild/archive/2007/10/22/enabling-multiprocessor-support-in-an-msbuild-host.aspx | crawl-002 | refinedweb | 999 | 52.66 |
Collected lots of little bits and pieces from around the Web to cobble this together.
Resources
Notes taken from the following resources with my own thoughts intermingled:
-
-
-
-
History
From wikipedia history of functional programming:
- 40s? lambda calculus
- 50s: Lisp
- 70s: ML for theorem proving (not pure functional), Scheme (dialect of Lisp)
- 1977 John Backus presents FP about his ideas to get away from imperative programming
- 1987 Haskell (pure functional)
- 1986 Erlang
- 2003 Scala
- 2005 F#
Characteristics
- Functional programs evaluate expressions instead of executing sequences instructions.
- Focused on what to compute not how
- In pure functional languages, there are no variables, just labeled values
val x = 1;
x = 2; // INVALID
- Implies you can't iterate through an array by moving index.
- Can't update data structures as we go along
- There is no predefined order evaluation because it doesn't matter–values can be computed on demand. lazy evaluation supported
- Want functions to operate on parameters and return values. that's it. can only depend on parameters:
- No local state maintained
- Can't change global variables
- y = f(x)
y' = f(x)
=> y = y'
- No side effects such as print statements, writing to the disk, launching missiles. Pure functional languages hide these things in creatures called monads.
- Inverse of OO programming that sends messages (functions) between objects (state). Functional languages send state between functions as parameters and return values
- Functions are first-class objects (C function pointers don't count). First-class objects can capture parameters and other stuff not just a function address. We can create new functions on-the-fly whereas everything is fixed/static in C.
- Support for higher-order functions (functions can take functions as parameters and return functions)
- Reliance on recursion instead of looping
Advantages
While we should right small methods and object ordered languages, I've seen and written functions that are huge. Functional programming makes it more difficult to write very large functions; everything is done with lots of little helper functions and then combining the results.
Because state is not being changed all over the place, it's often easier to debug functional programs. All we care about is the parameters and return values. We can treat each function in isolation. Every function can be a unit test.
Functional programs tend to make it very easy to separate out boilerplate code into utility functions such as map, filter, reduce. To make this happen, we need to be able to pass around functions or other snippets of code.
Functional programs are more abstract; We don't have to worry about null pointers and memory issues etc. The productivity boost of Java over C is an order magnitude. The productivity boost of functional languages over Java his equally large, if you can fit your problem into its world.
Pure functional programming languages easily take advantage of concurrency because no 2 threads can be modifying the same memory. A single thread can't even modify its own memory space.
Disadvantages
Functional programming isn't used by mainstream programmers; harder to hire people, nobody knows it, completely different way of programming
Time/space performance is an issue
Lack of good IDEs as we have for imperative programming
Adding some functional flavor to your imperative programming, though, can be extremely effective. You can gain some of the advantages listed above by incorporating functional ideas.
Lack of side effects makes it pretty hard to do GUI programming.
Summary of functional elements from Python
- lambdas
- iterators
- map, reduce, filter
- list comprehensions
- generator expressions
- generators
- higher-order functions / closures
lambdas
vs
Can't have multi line lambdas in Python
iterators
An iterator is any object that answers next(self), but they don't seem useful unless they also implement __iter__(self). next() "consumes" elements:
Iterators can represent infinite streams.
raise a
StopIteration exception when the sequence has reached its logical conclusion.
some locations automatically convert to iterators like for each loop. Can convert an object to an iterator by calling iter() manually. If that object doesn't iterate, raise TypeError
We can also create tuples, lists, multiple assignments, do mix/max with iterators:
Common: file, set, dict, string, tuples support iteration
Sample iterator:
Map, reduce, filter
Don't you hate doing this in Java?
You could make a function that but the idea of iterating through a list performing operation that gets a value happens constantly and we shouldn't have to make a function for each one of those. This is the boilerplate code talking about. If I want to change that += to *=, I have to make an entirely new loop. These are automated for us with a few keystrokes in an IDE usually but he gives us code bloat and breaks single point change rule.
One of the most common operations for me is to walk a list or other data structure to get a new list where the new elements are a function of the old or I have filtered out some of the elements. Python provides a number of functions from functional programming that make this really easy.
To apply a function to each element of the list or sequence, we use map():
Select values that fit a criterion we use filter():
To combine the elements of a list we use reduce():
We often use the term map-reduced because they are so often used in combination. These are also very easy to parallelize because we can split part the list into n chunks for n processors or machines and do them in parallel. We can reduce the elements within each chunk and then do a final reduce on the partial results from the n processors to get a single value.
list comprehensions and generator expressions
List comprehensions are generally much more efficient than the equivalent for-loops in Python.
Syntax:
[ expr for var in sequence]
[ expr for var in sequence if condition]
They are like a loop that adds to the list:
Filter-like example:
compare to: map(lambda x : len(x), names)
Create list of tuples from a map:
Make 10 0's
[ 0 for i in range(10) ]
Use the IF part to filter
How to run out of memory because list comprehensions are not lazy in Python:
But you can use generator expressions for the same purpose I'm getting lazy version:
Think of list comprehension as generator expressions in list constructors. lets us avoid creating a list and can be used generally where list comprehensions can:
Used xrange() instead of range(), which gives you a list of elements instead of an iterator.
any() returns true if any element of the sequence is true; it returns false if the sequence is empty. all() requires all elements in the sequence to be true.
These are cool because they short-circuit the generator like C && and || operators that avoid evaluating operands unnecessarily. They can cut out of an iteration when they can decide the answer.
generators
Generators are just continuations. Every method call has a stack activation record that holds locals and parameters. Return instruction normally pops this record off the stack but yield does not. Moreover, this makes the method special as the virtual machine recognizes it differently. Entry into this method the next time starts where it left off the last time. in other words, the pc register doesn't start at the first location in the method, it starts where the pc left off the last time. It's like a resume.
java has no capabilities to do this.
Calling a generator function actually returns a generator object implementing the iterator protocol that knows how to jump in and out of the code, treating it like a resume. It's a way to build an iterator implicitly without having to define a class and next(). If this were like an actor in a thread, we would treat it like a thread yield that could continue later.
A return (with no value) means stop the generator. no more in next().
Generators are good for 2 reasons:
- You can avoid constructing a list object to make large or infinite streams.
- It's often much easier to build a generator than an iterator for recursive data structures such as trees. it remembers where in the recursion stack we were and can resume from there.
python doc: "You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables."
From stackoverflow.com answer:
iteratoris a more general concept: any object whose class has a
nextmethod (
__next__in Python 3) and an
__iter__method that does
return self.
Every generator is an iterator, but not vice versa.
Another way to walk a recursive data structure is to pass in the functionality to execute rather turning the data structure into stream. The problem is, sometimes we want to treat the nodes in the tree like a stream because we get to use all of the great Python function such as map, reduce, filter etc. on them.
A recursive generator that generates tree nodes in preorder:
My first attempt look like this:
Then we can create a tree and walked the nodes like this:
higher-order functions / closures
In Java, these are methods wrapped in objects such as anonymous inner classes. We can pass functionality to a function by passing an object wrapped around that method. ugly. ugly. ugly. The advantage is that the function can carry along some data in the wrapper object.
We do this in Java as callbacks for GUIs or for passing in comparator functions to sorting algorithms.
We can return anonymous and class objects from functions in Java, but we never do. In Python we can do this with more utility. For example, here's a function factory that returns functions computing linear curves where 'a' is the slope and 'b' is the offset:
When a function captures some arguments in another function and returns it, we call it currying. Basically, we are taking a function of multiple arguments and breaking it down into functions with fewer arguments. Note that we can fix values in the function using parameters from another function as we've done here in linear(). From the Wikipedia page: Given function f(x,y) = y/x, we can create a new function g(y) = 2/x which is just like calling f(2,y). So g(y)=f(2,y)=y/2. g(y) is a function we can return from f. (Some languages only allow functions with single arguments and so they use currying to create functions with multiple arguments.) In Python, it looks like this
This kind of stuff is great for creating new functionality by composing other functions. For example, imagine that we have a general sort routine that takes a comparator function. We could create another function that return of function with a reverse sort function already put in it. Imagine that we have built-in sort() and reverse_cmp() functions. We get tired of having to combine a manually, which is a bit of boilerplate code. Let's create a function that gives us a handy shortcut function that combines sorted and reverse_cmp:
The key is that we're not statically defining new methods. They get created as needed on the fly.
Function composition
Because Python has higher-order functions, we can compose them to make more complicated functions like we did informally with the function objects in the previous section. Composition just means applying a function to the result of calling another function. Given functions f and g, composing the two means calling f(g(x)) or in sequence y = g(x) then z = f(y). z=f(g(x)). Note that because of the nesting, we actually compute the 2nd function first. we often write in functional stuff new composed function fg as:
fg = f • g
I had to manually install the functional package:
$ pip install functional
But then I can use the compose() method.
From Python functional doc:
compose(outer, inner, unpack=False)
The compose() function implements function composition. In other words, it returns a wrapper around the outerand inner callables, such that the return value from inner is fed directly to outer.
They give this example:
Also note that sequence f(); g(); is the same as compose(g, f) because that's g(f()), which would call f first. Weird but correct.
Computing prime number example
Copied more or less from Byrtek slides with tweaks by me.
Here is the imperative version:
With filter(), we ask whether the list of non-1 divisors is empty.
Using list comprehensions now instead of the built-in operations, we can simplify even more.
Problem is that the is_prime() method does the entire range even if it could stop early. That means that we can replace the comprehension in is_prime() with (n%k==0 for k in xrange(2,n)). It will terminate right away for is_prime(1000000) even though that is a big number; the previous one would take a while. note that we are using xrange() not range() which does not create a list either.
Finally, using any(), we get a very English like saying that says a number, n, is prime if there are not any numbers that divide cleanly from 2..n-1.
Compute phone number word possibilities
A world without statements
Resources:
How are we going to avoid using statements like if-then-else or even sequences of statements? let's start with looping.
Walk a list recursively
Replace if-then-else
if cond1: f1() -> cond1 and f1()
if cond1: f1() else: f2() -> (cond1 and f1()) or f2() # uses short-circuiting of expressions
Loops
for x in seq: f(x) -> map(f, seq)
for x in seq: f(x) -> (f(x) for x in seq) | http://www.antlr.org/wiki/display/CS345/Functional+programming+in+Python | CC-MAIN-2013-20 | refinedweb | 2,295 | 59.64 |
Source code: Lib/gettext.py
The.
The. [1]
Bind the domain to codeset, changing the encoding of strings returned by the gettext() family of functions. If codeset is omitted, then the current binding is returned.
Change or query the current global domain. If domain is None, then the current global domain is returned, otherwise the global domain is set to domain, which is returned.
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).
Equivalent to gettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().
Like gettext(), but look the message up in the specified domain.
Equivalent to dgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codes.
Equivalent to ngettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().
Like ngettext(), but look the message up in the specified domain.
Equivalent to dngettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset()..'))
The strings. Instances of this “translations” class can also install themselves in the built-in namespace as the function _().
This function implements the standard .mo file. in the lgettext() and lngettext() methods..
This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation().ins namespace, so it is easily accessible in all modules of your application..
No-op’d in the base class, this method takes file object fp, and reads the data from the file, initializing its message catalog. If you have an unsupported message catalog file format, you should override this method to parse your format.
Add fallback as the fallback object for the current translation object. A translation object should consult the fallback if it cannot provide a translation for a given message.
If a fallback has been set, forward gettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.
If a fallback has been set, forward lgettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.
If a fallback has been set, forward ngettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.
If a fallback has been set, forward lngettext() to the fallback. Otherwise, return the translated message. Overridden in derived classes.
Return the “protected” _info variable.
Return the “protected” _charset variable, which is the encoding of the message catalog file.
Return the “protected” _output_charset variable, which defines the encoding used to return translated messages in lgettext() and lngettext().
Change the “protected” _output_charset variable, which defines the encoding used to return translated messages.'.
Note that this is only one way, albeit the most convenient way, to make the _() function available to your application. Because it affects the entire application globally, and specifically the built-in namespace, localized modules should never install _(). Instead, they should use this code to make _() available to their module:
import gettext t = gettext.translation('mymodule', ...) _ = t.gettext
This puts _() only in the module’s global namespace and so only affects calls within this module..
Equivalent to gettext(), but the translation is returned as a bytestring encoded in the selected output charset, or in the preferred system encoding if no encoding was explicitly set with set_output_charset().}
Equivalent to gettext(), but the translation is returned as a bytestring encoded in the selected output charset, or in the preferred system encoding if no encoding was explicitly set with set_output_charset().
The Solaris operating system defines its own binary .mo file format, but since no documentation can be found on this format, it is not supported at this time.
If, you can pass these into the install() function:
import gettext gettext.install('myapplication', '/usr/share/locale') one way you can handle this situation:
def _(message): return message animals = [_('mollusk'), _('albatross'), _('rat'), _('penguin'), _('python'), ] del _ # ... for a in animals: print(_(a))
This works because the dummy definition of _() simply returns the string unchanged. And this dummy definition will temporarily override any definition of _() in the built-in namespace (until the del command). Take care, though if you have a previous definition of _() in the local namespace.
Note that the second use of _() will not identify “a” as being translatable to the pygettext program, since it is not a string.
Another way to handle this is with the following example:
def N_(message): return message animals = [N_('mollusk'), N_('albatross'), N_('rat'), N_('penguin'), N_('python'), ] # ... for a in animals: print(_(a))
In this case, you are marking translatable strings with the function N_(), | http://wingware.com/psupport/python-manual/3.2/library/gettext.html | CC-MAIN-2014-52 | refinedweb | 810 | 56.86 |
In this article we are going to discuss about truncating the file name with out hiding its extension. We can truncate file name only using CSS, but in this case, it will truncate extension as well. Check css example first for "angular-training.pdf"
Css
.truncateClass { display: inline-block; width: 30px; // your width white-space: nowrap; overflow: hidden !important; text-overflow: ellipsis; }
Example result: angular...
In the above example it is truncating all the file name including the extension. It is not user friendly; user should know the file extension without hovering or clicking on the file. We can achieve this by using a simple angular pipe.
Example results
angular-[...].pdf
Truncate pipe
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncateName implements PipeTransform{ transform(name: string): string { const ext: string = name.substring(name.lastIndexOf('.') + 1, name.length).toLowerCase(); let newName: string = name.replace('.' + ext, ''); if (name.length <= 8) { // if file name length is less than 8 do not format // return same name return name; } newName = newName.substring(0, 8) + (name.length > 8 ? '[...]' : ''); return newName + '.' + ext; } }
Usage
this.fileName = 'angular-training.pdf'; <p title="{{fileName}}">{{fileName | truncate}}</p>
Result
angular-[...].pdf
Here we have created a simple pipe. You can use this pipe anywhere in your angular application. It will truncate the file name without hiding the extension. You can update […] this to (…) or any other way you want. As we added a title user can hover and see the full file name as well.
In this article we have discussed about creating a simple truncate pipe to truncate the file name without hiding its extension.
Related Info
1. How to solve JavaScript heap out of memory issue in Angular project
2. How to create an Angular application from scratch with simple steps.
3. How to create and use shared module in angular application.
Thank you very much | https://www.angulartutorial.net/2020/02/truncate-file-name-without-hiding.html?showComment=1582341048162 | CC-MAIN-2021-10 | refinedweb | 311 | 60.72 |
Using AJAX In WordPress
Using AJAX In WordPress
Join the DZone community and get the full member experience.Join For Free
In the following tutorial we are going to learn how you can use AJAX in WordPress to run your own functions. The way this works in WordPress is by allowing you to attach your own actions that you can access from an AJAX request to change the content on the page.
What Is AJAX?
Normally on a webpage you have to wait for the server to load the content of the web page, after the load the only way you can change the content on the page is with JavaScript code. JavaScript is a client-side language that will not run any server side tasks, therefore you can not make another request to the server to change the content unless you refresh the page, but this could change the content in other areas of the page.
AJAX stands for Asynchronous JavaScript and XML, allowing you to make asynchronous HTTP requests to the server once the page has already loaded. It will use JavaScript to make a request to a URL allowing you to POST additional data to the server, the output of this server request is then processed and stored in the JavaScript so that you can change the content of the page.
WordPress has AJAX already built into the core and requires you to submit this information to a certain URL in the WordPress application, the reason you can't use any URL with WordPress AJAX is because WordPress needs to be instantiated before you can access data in the WordPress database.
AJAX In The Admin Area
If you have previous experience using AJAX, then using it in the WordPress admin area is relatively straight forward. As AJAX is already built into the core you can simply piggy back on this.
First you need to create a JavaScript file that you will use to make the AJAX request and handle the data returned, then enqueue this in the admin screens. Create a WordPress plugin or add the following to your theme functions.php file.
add_action( 'admin_enqueue_scripts', 'add_ajax_javascript_file' ); function add_ajax_javascript_file() { wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') ); }
This will add our JavaScript file to the admin pages in WordPress admin area, now we can add the jQuery required to submit the ajax request.
jQuery(document).ready(function($) { var data = { 'action': 'get_post_information', 'post_id': 120 }; $.post(ajaxurl, data, function(response) { alert('Server response from the AJAX URL ' + response); }); })
The above JavaScript will be added to our JavaScript file and will use jQuery to post data to the ajaxurl variable. This variable is a global variable setup by WordPress that will post to the admin-ajax.php file. This file instantiates WordPress and will run any actions setup in WordPress.
The data that we are submitting is a JavaScript object with the fields action and post_id in it. The action is the WordPress action code we want to run when submitting this request, the other data is also posted so that we can consume this in the server-side code.
Now we need to setup the WordPress action that will get called on this AJAX request.
<?php add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' ); function ajax_get_post_information() { if(!empty($_POST['post_id'])) { $post = get_post( $_POST['post_id'] ); echo json_encode( $post ); } die(); }
The above code should be added to either the new plugin or to the functions.php file so that the action can be registered. We need to use the action of "wp_ajax_{action}" with {action} being the one defined in the JavaScript file. In the callback function we then get the posted post_id and search for the post using the get_post() function, then we can echo a JSON object of the post data for the JavaScript to pick up the response. On the response of the AJAX we can now add this post information to any part of the page we want.
AJAX In The Frontend
AJAX on the frontend of your website is a bit more complicated but is still do-able if you understand the concepts of the above code.
The first thing you need to be aware of is the ajaxurl JavaScript variable is not defined on the frontend so you need to define this namespace object when you load your JavaScript file by using the function wp_localize_script()
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file' ); function add_frontend_ajax_javascript_file() { wp_localize_script( 'frontend-ajax', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') ); }
In the admin area there is only one AJAX action that you need to use wp_ajax_{action} on the frontend you can use two AJAX actions, wp_ajax_{action} and wp_ajax_nopriv_{action} the difference being that the current user doesn't need to be logged in to run the AJAX action. Therefore if the user isn't logged in it will run the function attached to wp_ajax_nopriv_ but if the user is logged in it will run the function attached to wp_ajax_
<?php add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' ); add_action( 'wp_ajax_nopriv_get_post_information', 'ajax_get_post_information' ); function ajax_get_post_information() { if(!empty($_POST['post_id'])) { $post = get_post( $_POST['post_id'] ); echo json_encode( $post ); } die(); }
AJAX Errors
If the AJAX action fails then it will return one of two values either 0 or -1.
If the action that you are requesting doesn't exist then the AJAX response will return 0. To fix this error you need to make sure that you have defined your wp_ajax_ action correctly.
If the request fails to call the URL correctly it will return with a -1.
Published at DZone with permission of Paul Underwood , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/using-ajax-wordpress | CC-MAIN-2019-26 | refinedweb | 954 | 57.5 |
import motorcycle parts, dirt bike parts CNC alloy red colorf...
US $9.99-19.99
50 Pieces (Min. Order)
advantages low carbon alloy steel precision casting parts for...
US $0.5-100
1 Piece (Min. Order)
aluminum alloy motorcycle wheel rim parts
US $1-10
100 Sets (Min. Order)
Low Price Aluminum Alloy CNC Motorcycle Spare Parts
US $0.02-20
5 Pieces (Min. Order)
ISO/SGS passed cnc machined precision part,cnc alloy triple c...
US $0.01-0.15
1000 Pieces (Min. Order)
Alloy Motorcycle Parts
US $0.1-4.8
5 Pieces (Min. Order)
Karo cnc machining metal alloy motorcycle spare parts
US $0.50-2.00
500 Pieces (Min. Order)
China manufacturer non standard alloy casting small ...
US $1.5-19.35
1 Piece (Min. Order)
alloy casting non standard CNC machining motorcycle parts
US $0-5
100 Pieces (Min. Order)
copper, steel, aluminum alloy cnc motorcycle parts manufactur...
US $1.39-2.43
10 Pieces (Min. Order)
ISO / CE / ROHS Customized Titanium Racing Bike & Motorcycle ...
US $0.2-1.1
1000 Pieces (Min. Order)
China cnc machining metal alloy motorcycle spare parts
US $1-100
10 Pieces (Min. Order)
Customized stainless steel, brass, aluminum alloy cnc ...
US $1-10
1 Piece (Min. Order)
Customized CNC Machining Metal Alloy Motorcycle Spare Parts
US $0.01-60
1 Set (Min. Order)
Steel Alloys cnc motorcycle router press cuting machine ...
US $0.99-100
1 Set (Min. Order)
OEM aluminum alloy die casting motorcycle engine parts, elect...
US $0.1-0.99
1 Piece (Min. Order)
China manufacturing cnc service/High quality cnc machining m...
US $1-10
1 Piece (Min. Order)
CNC machining metal alloy Cars Parts/motorcycle parts auto sp...
US $0.5-10
100 Pieces (Min. Order)
CNC machining metal alloy Cars Parts/motorcycle parts
US $0.15-0.6
10000 Pieces (Min. Order)
Hot sale Motorcycle Aluminum alloy CNC Engine parts
US $2-5
200 Pieces (Min. Order)
alibaba express best price with good service custom CNC mach...
US $0.002-2
1 Piece (Min. Order)
manufacture aluminum alloy die casting motorcycles spare ...
US $0.01-1.2
50 Pieces (Min. Order)
Hot sale factory directly steel alloy cnc motorcycle parts
US $24.51-24.62
2000 Pieces (Min. Order)
CNC Aluminum alloy motorcycle racing parts
US $0.1-39.8
1 Piece (Min. Order)
Precision machining service Aluminum Alloy die casting cnc ...
US $1.0-1.0
10 Pieces (Min. Order)
CNC turning metal alloy motorcycle spare parts
US $1-999
50 Pieces (Min. Order)
6061 aluminum alloy material black anodized motorcycle parts
US $0.1-2
1 Piece (Min. Order)
Metal 6063-T5 aluminium alloy customized cnc motorcycle machi...
US $5-20
20 Pieces (Min. Order)
CNC machining metal alloy motorcycle spare parts with high qu...
US $0.1-10
1 Piece (Min. Order)
Economic promotional alloy motorcycle parts
US $0.05-10
1 Piece (Min. Order)
good quality cnc aluminum alloy motorcycle engine parts
US $0.1-2.5
1 Piece (Min. Order)
Steel alloy cnc motorcycle parts for machining
US $0.21-0.51
1000 Pieces (Min. Order)
alloy casting motorcycle engine parts
US $0.02-0.8
1 Piece (Min. Order)
Customized rapid prototype vacuum casting parts and cnc machi...
US $0.5-300
1 Piece (Min. Order)
cnc machining metal alloy motorcycle spare parts
US $1-100
1 Piece (Min. Order)
high precision Aluminum Alloy CNC Motorcycle Spare Parts, cnc...
US $0.01-5
3000 Pieces (Min. Order)
alloy motorcycle parts cnc machining parts
US $1-20
1 Piece (Min. Order)
aluminum alloy metal machining cnc processing motorcycle ...
US $0.5 | http://www.alibaba.com/showroom/motorcycle-alloy-parts.html | CC-MAIN-2016-07 | refinedweb | 603 | 63.76 |
Micro Magician robot controller - I can finally tick the project complete box!
- Login or register to post comments
- by OddBot
- Collected by 6 users).
The Micro Magician is small (60mm x 30mm) and yet is has many features you won't get on big boards.
Dual FET "H" bridge with charge pump:
- Drives 2x DC motors or 1x stepper motor.
- Low voltage opperation from 2.5V to 9V.
- Low "ON" resistance of just 1.1Ω with a supply voltage of 3V for better motor torque.
- Electronic brake is ideal for small robots that need to stop quickly.
- Current limit set to 910mA to prevent accidental damage due to stalled motors or short circuits.
- Motor stall flags allow your code to determine if a motor has stalled.
- Sleep mode to reduce power consumption when not used. Allows control pins to be re-used.
- Arduino library includes commands to simplify use with DC motors and stepper motor.
3-axis accelerometer:
- Defaults to ±1.5G full range sensitivity. Can be changed to ±6G if required.
- 0G detect can be used with external interrupt pin to shut down servos or motors when the robot falls to protect gears.
- Can measure the angle the robot is sitting at to prevent falling over or aid in self righting manuvers.
- Arduino library includes commands to detect direction / magnitude of an impact, eliminating the need for bumper switches.
IR receiver with status LED:
- 38KHz IR receiver hardwired to digital pin 4 allows low cost remote control using a TV remote.
- Status LED indicates when a signal is received to aid program debugging.
- Arduino library includes Sony IR Code (SIRC) decoder providing 128 virtual buttons.
- Additional IR receivers can be added on other pins and read using library decoder.
Drive up to 8x servos:
- Up to 8x miniature servos can plug directly into the PCB and be powered from the battery.
- Servos protected by reverse polarity diode.
I have attached the instruction manual and library. These will also be available on my product support site:
Can't See Micro Magician on Mac OS X 10.8.5 in Arduino IDE
I have the Micro Magician connected to a MacBook Pro 15" 2013 non-Retina display laptop running Mac OS X 10.8.5. I have it connected to the rearward USB port (there are two). I'm using Arduino IDE 1.0.5.
1. I connect the MM to the Mac. Some LEDs flash momentarily, then a red and green LED stay on.
2. I launch the Arduino IDE.
3. In the IDE, I select Tools>Board>Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328
4. I select Tools>Serial Port>
5. I only see Bluetooth devices in the Serial Port submenu.
6. I exit the IDE, unplug the MM, and connect an Arduino UNO, then follow the above steps for the UNO.
7. I see the UNO in the Serial Port submenu, as expected.
What do I need to do for the Arduino IDE to see the Micro Magician? I'm dead in the water for now. I don't want to buy a motor shield, an accelerometer shield, and an IR receiver shield for the UNO when I already have them on the MM.
Thanks!
Have you installed the
Have you installed the drivers for the cp2102 used as a USB to serial converter?
Yes, I have. Twice, and rebooted twice
Yes, I have. Twice, and rebooted twice. Shouldn't it show in the "Serial Port" list?
Problem Solved
It turned out to be the USB cable. I was using one designed to only provide power and no signal. I swapped it out for a data cable, and I'm in business.
Don't you hate that!
I've had similar problems before all though in my case it was a cheap cable with an internal break. If you hold the cable at a certain angle it stops working but the IDE still see's the port. Some times I get AVRdude complaining about the wrong processor being used and other times I get out of sync error.
Sending to the IR using the IRremote LIbrary for Arduino
I am trying to communicate with the IR using the MicroM library on the receiving end and the IRremote library to send. For the transmitter I am using the following code:
#include <IRremote.h>
IRsend irsend;
void setup(){}
void loop(){
for (int i = 0; i<3; i++){
irsend.sendSony(0xa90, 12); //Sony TV power code
delay(40);
}
delay(500);
}
"IR command:128" is always the output. I understand that only 7 bits are being used in your rx code and so I have tried different variations: irsend.sendSony(data, bits) to (0,7) and (64,7)...and all sorts of others.
Any tips?
I admit, I have never used
I admit, I have never used the IR library to send a signal. I have simply used a TV remote.
The normal SONY IR protocol is 7 bits of data followed by 5 bits of device ID. My library simply waits for the start bit, reads the seven data bits and ignores the rest until a new start bit is recognized.
Some things you should check.
Nice job! I just want find a
Nice job! I just want find a micro controller board and like your design very much!
Xie xie
As you are in China you can buy this directly from DAGU. Contact Claudia: claudiadagu@yahoo.com.cn
ni hao
thank you for replay. I would contact him later! | http://letsmakerobots.com/node/31924 | CC-MAIN-2015-27 | refinedweb | 923 | 76.11 |
API Evolution the Right Way
(Watch videos of me presenting this material at PyCon Canada or PyCon US.)
Imagine you are a creator deity, designing a body for a creature. In your benevolence, you wish for the creature to evolve over time: first, because it must respond to changes in its environment, and second, because your wisdom grows and you think of better designs for the beast. It shouldn’t remain in the same body forever!
The creature, however, might be relying on features of its present anatomy. You can’t add wings or change its scales without warning. It needs an orderly process to adapt its lifestyle to its new body. How can you, as a responsible designer in charge of this creature’s natural history, gently coax it toward ever greater improvements?
It’s the same for responsible library maintainers. We keep our promises to the people who depend on our code: we release bugfixes and useful new features. We sometimes delete features if that’s beneficial for the library’s future. We continue to innovate, but we don’t break the code of people who use our library. How can we fulfill all those goals at once?
Add Useful Features
Your library shouldn’t stay the same for eternity: you should add features that your make your library better for your users. For example, if you have a Reptile class and it would be useful to have wings for flying, go for it.
class Reptile: @property def teeth(self): return 'sharp fangs' # If wings are useful, add them! @property def wings(self): return 'majestic wings'
But beware, features come with risk. Consider the following feature in the Python standard library, and let us see what went wrong with it.
bool(datetime.time(9, 30)) == True bool(datetime.time(0, 0)) == False
This is peculiar: converting any time object to a boolean yields True, except for midnight. (Worse, the rules for timezone-aware times are even stranger.) I’ve been writing Python for more than a decade but I didn’t discover this rule until last week. What kind of bugs can this odd behavior cause in users’ code?
Consider a calendar application with a function that creates events. If an event has an end time, the function requires it to also have a start time:
def create_event(day, start_time=None, end_time=None): if end_time and not start_time: raise ValueError("Can't pass end_time without start_time") # The coven meets from midnight until 4am. create_event(datetime.date.today(), datetime.time(0, 0), datetime.time(4, 0))
Unfortunately for witches, an event starting at midnight fails this validation. A careful programmer who knows about the quirk at midnight can write this function correctly, of course:
def create_event(day, start_time=None, end_time=None): if end_time is not None and start_time is None: raise ValueError("Can't pass end_time without start_time")
But this subtlety is worrisome. If a library creator wanted to make an API that bites users, a “feature” like the boolean conversion of midnight works nicely.
The responsible creator’s goal, however, is to make your library easy to use correctly.
This feature was written by Tim Peters when he first made the datetime module in 2002. Even founding Pythonistas like Tim make mistakes. The quirk was removed, and all times are True now.
# Python 3.5 and later. bool(datetime.time(9, 30)) == True bool(datetime.time(0, 0)) == True
Programmers who didn’t know about the oddity of midnight are saved from obscure bugs, but it makes me nervous to think about any code that actually relies on the weird old behavior and didn’t notice the change. It would have been better if this bad feature were never implemented at all. This leads us to the first promise of any library maintainer:
First Covenant:
Avoid Bad Features
The most painful change to make is when you have to delete a feature. One way to avoid bad features is to add few features in general! Make no public method, class, function, or property without a good reason. Thus:
Second Covenant:
Minimize Features
Features are like children: conceived in a moment of passion, they must be supported for years. Don’t do anything silly just because you can. Don’t add feathers to a snake!
But of course, there are plenty of occasions when users need something from your library that it does not yet offer. How do you choose the right feature to give them? Here’s another cautionary tale.
A Cautionary Tale From asyncio
As you may know, when you call a coroutine function, it returns a coroutine object:
async def my_coroutine(): pass print(my_coroutine())
<coroutine object my_coroutine at 0x10bfcbac8>
Your code must “await” this object to actually run the coroutine. It’s easy to forget this, so the asyncio developers wanted a “debug mode” that catches this mistake. Whenever a coroutine is destroyed without being awaited, the debug mode prints a warning with a traceback to the line where it was created.
When Yury Selivanov implemented the debug mode, he added as its foundation a “coroutine wrapper” feature. The wrapper is a function that takes in a coroutine and returns anything at all. Yury used it to install the warning logic on each coroutine, but someone else could use it to turn coroutines into the string “hi!”:
import sys def my_wrapper(coro): return 'hi!' sys.set_coroutine_wrapper(my_wrapper) async def my_coroutine(): pass print(my_coroutine())
hi!
That is one hell of a customization. It changes the very meaning of “async”. Calling set_coroutine_wrapper once will globally and permanently change all coroutine functions. It is, as Nathaniel Smith wrote, “a problematic API” which is prone to misuse and had to be removed. The asyncio developers could have avoided the pain of deleting the feature if they’d better shaped it to its purpose. Responsible creators must keep this in mind:
Third Covenant:
Keep Features Narrow
Luckily, Yury had the good judgment to mark this feature provisional, so asyncio users knew not to rely on it. Nathaniel was free to replace set_coroutine_wrapper with a narrower feature that only customized the traceback depth:
import sys sys.set_coroutine_origin_tracking_depth(2) async def my_coroutine(): pass print(my_coroutine())
<coroutine object my_coroutine at 0x10bfcbac8> RuntimeWarning:'my_coroutine' was never awaited Coroutine created at (most recent call last) File "script.py", line 8, in <module> print(my_coroutine())
This is much better. There’s no more global setting that can change coroutines’ type, so asyncio users need not code as defensively. Deities should all be as farsighted as Yury:
Fourth Covenant:
Mark Experimental Features "Provisional"
If you have merely a hunch that your creature wants horns and a quadruple-forked tongue, introduce the features but mark them “provisional”.
You might discover that the horns are adventitious but the quadruple-forked tongue is useful after all. In the next release of your library you can delete the former and mark the latter official.
Deleting Features
No matter how wisely we guide our creature’s evolution, there may come a time when it’s best to delete an official feature. For example, you might have created a lizard, and now you choose to delete its legs. Perhaps you want to transform this awkward creature into a sleek and modern python.
There are two main reasons to delete features. First, you might discover a feature was a bad idea, through user feedback or your own growing wisdom. That was the case with the quirky behavior of midnight. Or, the feature might have been well-adapted to your library’s environment at first, but the ecology changes. Perhaps another deity invents mammals. Your creature wants to squeeze into their little burrows and eat the tasty mammal filling, so it has to lose its legs.
Similarly, the Python standard library deletes features in response to changes in the language itself. Consider asyncio’s Lock. It has been awaitable ever since “await” was added as a keyword:
lock = asyncio.Lock() async def critical_section(): await lock try: print('holding lock') finally: lock.release()
But now, we can do “async with lock”:
lock = asyncio.Lock() async def critical_section(): async with lock: print('holding lock')
The new style is much better! It’s short, and less prone to mistakes in a big function with other try-except blocks. Since “there should be one and preferably only one obvious way to do it” the old syntax is deprecated in Python 3.7 and it will be banned soon.
It’s inevitable that ecological change will have this effect on your code too, so learn to delete features gently. Before you do so, consider the cost or benefit of deleting it. Responsible maintainers are reluctant to make their users change a large amount of their code, or change their logic. (Remember how painful it was when Python 3 removed the “u” string prefix, before it was added back.) If the code changes are mechanical, however, like a simple search and replace, or if the feature is dangerous, it may be worth deleting.
Whether to Delete a Feature
In the case of our hungry lizard, we decide to delete its legs so it can slither into a mouse’s hole and eat it. How do we go about this? We could just delete the
walk method, changing code from this:
class Reptile: def walk(self): print('step step step')
To this:
class Reptile: def slither(self): print('slide slide slide')
That’s not a good idea, the creature is used to walking! Or, in terms of a library, your users have code that relies on the existing method. When they upgrade to the latest version of your library, their code will break.
# User's code. Oops! Reptile.walk()
Therefore responsible creators make this promise:
Fifth Covenant:
Delete Features Gently
There’s a few steps involved in deleting a feature gently. Starting with a lizard that walks with its legs, you first add the new method, “slither”. Next, deprecate the old method.
import warnings class Reptile: def walk(self): warnings.warn( "walk is deprecated, use slither", DeprecationWarning, stacklevel=2) print('step step step') def slither(self): print('slide slide slide')
The Python warnings module is quite powerful. By default it prints warnings to stderr, only once per code location, but you can silence warnings or turn them into exceptions, among other options.
As soon as you add this warning to your library, PyCharm and other IDEs render the deprecated method with a strikethrough. Users know right away that the method is due for deletion.
Reptile().walk()
What happens when they run their code with the upgraded library?
> python3 script.py DeprecationWarning: walk is deprecated, use slither script.py:14: Reptile().walk() step step step
By default, they see a warning on stderr, but the script succeeds and prints “step step step”. The warning’s traceback shows what line of the user’s code must be fixed. (That’s what the “stacklevel” argument does: it shows the call site that users need to change, not the line in your library where the warning is generated.) Notice that the error message is instructive, it describes what a library user must do to migrate to the new version.
Your users will want to test their code and prove they call no deprecated library methods. Warnings alone won’t make unittests fail, but exceptions will. Python has a command-line option to turn deprecation warnings into exceptions:
> python3 -Werror::DeprecationWarning script.py Traceback (most recent call last): File "script.py", line 14, in <module> Reptile().walk() File "script.py", line 8, in walk DeprecationWarning, stacklevel=2) DeprecationWarning: walk is deprecated, use slither
Now, “step step step” is not printed, because the script terminates with an error.
So once you’ve released a version of your library that warns about the deprecated “walk” method, you can delete it safely in the next release. Right?
Consider what your library’s users might have in their projects’ requirements:
# User's requirements.txt has a dependency on the reptile package. reptile
The next time they deploy their code, they’ll install the latest version of your library. If they haven’t yet handled all deprecations then their code will break, because it still depends on “walk”. You need to be gentler than this. There are three more promises you must keep to your users: to maintain a changelog, choose a version scheme, and write an upgrade guide.
Sixth Covenant:
Maintain a Changelog
Your library must have a change log; its main purpose is to announce when a feature that your users rely on is deprecated or deleted.
Changes in Version 1.1
New features
- New function Reptile.slither()
Deprecations
- Reptile.walk() is deprecated and will be removed in version 2.0, use slither()
Responsible creators use version numbers to express how a library has changed, so users can make informed decisions about upgrading. A “version scheme” is a language for communicating the pace of change.
Seventh Covenant:
Choose a Version Scheme
There are two schemes in widespread use, semantic versioning and time-based versioning. I recommend semantic versioning for nearly any library. The Python flavor thereof is defined in PEP 440, and tools like “pip” understand semantic version numbers.
If you choose semantic versioning for your library, you can delete its legs gently with version numbers like:
1.0: First “stable” release, with walk()
1.1: Add slither(), deprecate walk()
2.0: Delete walk()
Your users should depend on a range of your library’s versions like so:
# User's requirements.txt. reptile>=1,<2
This allows them to upgrade automatically within a major release, receiving bugfixes and potentially raising some deprecation warnings, but not upgrading to the next major release and risking a change that breaks their code.
If you follow time-based version your releases might be numbered thus:
2017.06.0: A release in June 2017
2018.11.0: Add slither(), deprecate walk()
2019.04.0: Delete walk()
And users can depend on your library like:
# User's requirements.txt for time-based version. reptile==2018.11.*
This is terrific, but how do your users know your versioning scheme and how to test their code for deprecations? You have to advise them how to upgrade.
Eighth Covenant:
Write an Upgrade Guide
Here’s how a responsible library creator might guide users:
Upgrading to 2.0
Migrate from Deprecated APIs
See the changelog for deprecated features.
Enable Deprecation Warnings
Upgrade to 1.1 and test your code with:
python -Werror::DeprecationWarning
Now it's safe to upgrade.
You must teach users how to handle deprecation warnings by showing them the command line options. Not all Python programmers know this—I certainly have to look up the syntax each time. And take note, you must release a version that prints warnings from each deprecated API, so users can test with that version before upgrading again. In this example, version 1.1 is the bridge release. It allows your users to rewrite their code incrementally, fixing each deprecation warning separately until they have entirely migrated to the latest API. They can test changes to their code, and changes in your library, independently from each other, and isolate the cause of bugs.
If you chose semantic versioning, this transitional period lasts until the next major release, from 1.x to 2.0, or from 2.x to 3.0, and so on. The gentle way to delete a creature’s legs is to give it at least one version in which to adjust its lifestyle. Don’t remove the legs all at once!
Version numbers, deprecation warnings, the changelog, and the upgrade guide work together to gently evolve your library without breaking the covenant with your users. The Twisted project’s Compatibility Policy explains this beautifully:
“The First One’s Always Free”
Any application which runs without warnings may be upgraded one minor version of Twisted.
In other words, any application which runs its tests without triggering any warnings from Twisted should be able to have its Twisted version upgraded at least once with no ill effects except the possible production of new warnings.
Now, we creator deities have gained the wisdom and power to add features by adding methods, and to delete them gently. We can also add features by adding parameters, but this brings a new level of difficulty. Are you ready?
Adding Parameters
Imagine that you just gave your snake-like creature a pair of wings. Now you must allow it the choice whether to move by slithering or flying. Currently its “move” function takes one parameter:
# Your library code. def move(direction): print(f'slither {direction}') # A user's application. move('north')
You want to add a “mode” parameter, but this breaks your users’ code if they upgrade, because they pass only one argument:
# Your library code. def move(direction, mode): assert mode in ('slither', 'fly') print(f'{mode} {direction}') # A user's application. Error! move('north')
A truly wise creator promises not to break users’ code this way.
Ninth Covenant:
Add Parameters Compatibly
To keep this covenant, add each new parameter with a default value that preserves the original behavior.
# Your library code. def move(direction, mode='slither'): assert mode in ('slither', 'fly') print(f'{mode} {direction}') # A user's application. move('north')
Over time, parameters are the natural history of your function’s evolution. They’re listed oldest first, each with a default value. Library users can pass keyword arguments to opt in to specific new behaviors, and accept the defaults for all others.
# Your library code. def move(direction, mode='slither', turbo=False, extra_sinuous=False, hail_lyft=False): # ... # A user's application. move('north', extra_sinuous=True)
There is a danger, however, that a user might write code like this:
# A user's application, poorly-written. move('north', 'slither', False, True)
What happens if, in the next major version of your library, you get rid of one of the parameters, like “turbo”?
# Your library code, next major version. "turbo" is deleted. def move(direction, mode='slither', extra_sinuous=False, hail_lyft=False): # ... # A user's application, poorly-written. move('north', 'slither', False, True)
The user’s code still compiles, and this is a bad thing. The code stopped moving extra-sinuously and started hailing a Lyft, which was not the intention. I trust that you can predict what I’ll say next: deleting a parameter requires several steps. First, of course, deprecate the “turbo” parameter. I like a technique like this one that detects whether any user’s code is relying on this parameter:
# Your library code. _turbo_default = object() def move(direction, mode='slither', turbo=_turbo_default, extra_sinuous=False, hail_lyft=False): if turbo is not _turbo_default: warnings.warn( "'turbo' is deprecated", DeprecationWarning, stacklevel=2) else: # The old default. turbo = False
But your users might not notice the warning. Warnings are not very loud: they can be suppressed, or lost in log files. Users might heedlessly upgrade to the next major version of your library, the version that deletes “turbo”. Their code will run without error and silently do the wrong thing! As the Zen of Python says, “Errors should never pass silently.” Indeed, reptiles hear poorly, so you must correct them very loudly when they make mistakes.
The best way to protect your users is with Python 3’s star syntax, which requires callers to pass keyword arguments.
# Your library code. # All arguments after "*" must be passed by keyword. def move(direction, *, mode='slither', turbo=False, extra_sinuous=False, hail_lyft=False): # ... # A user's application, poorly-written. # Error! Can't use positional args, keyword args required. move('north', 'slither', False, True)
With the star in place, this is the only syntax allowed:
# A user's application. move('north', extra_sinuous=True)
Now when you delete “turbo”, you can be certain any user code that relies on it will fail loudly. If your library also supports Python 2, there’s no shame in that, you can simulate the star syntax thus, borrowing from the example in PEP-3102:
# Your library code, Python 2 compatible. def move(direction, *ignore, mode='slither', turbo=False, extra_sinuous=False, hail_lyft=False): if ignore: raise TypeError('Unexpected kwargs: %r' % ignore) # ...
(Previously I’d cited Brett Slatkin’s technique, but this one is simpler and a more accurate simulation of the Python 3 behavior.)
Requiring keyword arguments is a wise choice, but it requires foresight. If you allow an argument to be passed positionally, you cannot convert it to keyword-only in a later release. So, add the star now. You can observe in the asyncio API that it uses the star pervasively in constructors, methods, and functions. Even though “Lock” only takes one optional parameter so far, the asyncio developers added the star right away. This is providential.
# In asyncio. class Lock: def __init__(self, *, loop=None): # ...
Now we’ve gained the wisdom to change methods and parameters while keeping our covenant with users. The time has come to try the most challenging kind of evolution: changing behavior without changing either methods or parameters.
Changing Behavior
Let’s say your creature is a rattlesnake, and you want to teach it a new behavior.
Sidewinding! The creature’s body will appear the same, but its behavior will change. How can we prepare it for this step of its evolution?
A responsible creator can learn from the following example in the Python standard library, when behavior changed without a new function or parameters. Once upon a time, the os.stat function was introduced to get file statistics, like the modification time. At first, times were always integers.
>>> os.stat('file.txt').st_mtime 1540817862
One day, the core developers decided to use floats for os.stat times, to give sub-second precision. But they worried that existing user code wasn’t ready for the change. They created a setting in Python 2.3, “stat_float_times”, that was false by default. A user could set it to True to opt in to floating-point timestamps.
>>> # Python 2.3. >>> os.stat_float_times(True) >>> os.stat('file.txt').st_mtime 1540817862.598021
Starting in Python 2.5, float times became the default, so any new code written for 2.5 and later could ignore the setting and expect floats. Of course, you could set it to False to keep the old behavior, or set it to True to ensure the new behavior in all Python versions, and prepare your code for the day when stat_float_times is deleted.
Ages passed. In Python 3.1 the setting was deprecated to prepare people for the distant future, and finally, after its decades-long journey, the setting was removed. Float times are now the only option. It’s a long road, but responsible deities are patient because we know this gradual process has a good chance of saving users from unexpected behavior changes.
Tenth Covenant:
Change Behavior Gradually
Here are the steps:
- Add a flag to opt in to the new behavior, default False, warn if it’s False
- Change default to True, deprecate flag entirely
- Remove the flag
If you follow semantic versioning, the versions might be like so:
You need two major releases to complete the maneuver. If you had gone straight from “Add flag, default False, warn if it’s False” to “Remove flag” without the intervening release, your users’ code would be unable to upgrade. User code written correctly for 1.1, which sets the flag to True and handles the new behavior, must be able to upgrade to the next release with no ill effect except new warnings, but if the flag were deleted in the next release that code would break. A responsible deity never violates the Twisted policy: “The First One’s Always Free.”
The Responsible Creator
Our ten covenants belong loosely in three categories:
Evolve Cautiously
- Avoid Bad Features
- Minimize Features
- Keep Features Narrow
- Mark Experimental Features “Provisional”
- Delete Features Gently
Record History Rigorously
- Maintain a Changelog
- Choose a Version Scheme
- Write an Upgrade Guide
Change Slowly and Loudly
- Add Parameters Compatibly
- Change Behavior Gradually
If you keep these covenants with your creature, you’ll be a responsible creator deity. Your creature’s body can evolve over time, forever improving and adapting to changes in its environment, but without sudden changes the creature isn’t prepared for. If you maintain a library, keep these promises to your users, and you can innovate your library without breaking the code of the people who rely on you.
Illustrations:
- The World’s Progress, The Delphian Society, 1913
- Essay Towards a Natural History of Serpents, Charles Owen, 1742
- On the batrachia and reptilia of Costa Rica: With notes on the herpetology and ichthyology of Nicaragua and Peru, Edward Drinker Cope, 1875
- Natural History, Richard Lydekker et. al., 1897
- Mes Prisons, Silvio Pellico, 1843
- Tierfotoagentur / m.blue-shadow
- From Los Angeles Public Library, 1930 | https://emptysqua.re/blog/api-evolution-the-right-way/ | CC-MAIN-2020-24 | refinedweb | 4,125 | 64.61 |
Ok, that was fun. Seriously, it was. But let's raise the stakes a bit. When someone calls, we are going to try to greet the caller by name.
from flask import Flask, request, redirect from twilio.twiml.voice_response import VoiceResponse app = Flask(__name__) # Try adding your own number to this list! callers = { "+14158675309": "Curious George", "+14158675310": "Boots", "+14158675311": "Virgil", } @app.route("/", methods=['GET', 'POST']) def hello_monkey(): # Get the caller's phone number from the incoming Twilio request from_number = request.values.get('From', None) resp = VoiceResponse() # if the caller is someone we know: if from_number in callers: # Greet the caller by name resp.say("Hello " + callers[from_number]) else: resp.say("Hello Monkey") return str(resp) if __name__ == "__main__": app.run(debug=True) »
We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow. | https://www.twilio.com/docs/quickstart/python/twiml/greet-caller-by-name | CC-MAIN-2017-47 | refinedweb | 151 | 69.58 |
sanjosBAN USER
private static int findNextInteger(int[] arr) {
if (arr == null || arr.length == 0)
return 0;
int number = 0;
// 10^2*1+10^1*2+10^0*3 = 100+20+3 = 234
for (int i = arr.length - 1, j = 0; i >= 0 && j <= arr.length - 1; i--, j++) {
number = number + (int) (Math.pow(10, i) * arr[j]);
}
return (number+1);
}
ShirleyCWest, Software Engineer at Agilent Technologies
Hello, me Shirley and I from Savage. I am an artist and I love to doing art and I am ...
What's the space complexity of this algo according to you? I was asked to submit something with O(1) space complexity.- sanjos February 11, 2019 | https://careercup.com/user?id=6126891946213376 | CC-MAIN-2019-18 | refinedweb | 112 | 69.58 |
.
What you should already know
You should be familiar with:
- What an activity is, and how to set up an activity with a layout in
onCreate().
- Creating a text view and setting the text that the text view displays.
- Using
findViewById()to get a reference to a view.
- Creating and editing a basic XML layout for a view.
What you'll learn
- How to use the Data Binding Library to eliminate inefficient calls to
findViewById().
- How to access app data directly from XML.
What you'll do
- Modify an app to use data binding instead:
- When the user opens the app, the app shows a name, a field to enter a nickname, a Done button, a star image, and scrollable text.
- The user can enter a nickname and tap the Done button. The editable field and button are replaced by a text view that shows the entered nickname.
.
Data binding has the following benefits:
- Code is shorter, easier to read, and easier to maintain than code that uses
findViewById().
- Data and views are clearly separated. This benefit of data binding becomes increasingly important later in this course.
- The Android system only traverses the view hierarchy once to get each view, and it happens during app startup, not at runtime when the user is interacting with the app.
- You get type safety for accessing views. (Type safety means that the compiler validates types while compiling, and it throws an error if you try to assign the wrong type to a variable.)
In this task, you set up data binding, and you use data binding to replace calls to
findViewById() with calls to the binding object.
Step 1: Enable data binding
To use data binding, you need to enable data binding in your Gradle file, as it's not enabled by default. This is because data binding increases compile time and may affect app startup time.
- If you do not have the AboutMe app from a previous codelab, get the AboutMeDataBinding-Starter code from GitHub. Open it in Android Studio.
- Open the
build.gradle (Module: app)file.
- Inside the
androidsection, before the closing brace, add a
buildFeaturessection and set
dataBindingto
true.
buildFeatures { dataBinding true }
- When prompted, Sync the project. If you're not prompted, select File > Sync Project with Gradle Files.
- You can run the app, but you won't see any changes.
Step 2: Change layout file to be usable with data binding.
- Open the
activity_main.xmlfile.
- Switch to the Text tab.
- Add
<layout></layout>as the outermost tag around the
<LinearLayout>.
<layout> <LinearLayout ... > ... </LinearLayout> </layout>
- Choose Code > Reformat code to fix the code indentation.
The namespace declarations for a layout must be in the outermost tag.
- Cut the namespace declarations from the
<LinearLayout>and paste them into the
<layout>tag. Your opening
<layout>tag should look as shown below, and the
<LinearLayout>tag should only contain view properties.
<layout xmlns:
- Build and run your app to verify that you did this correctly.
Step 3: Create a binding object in the main activity
Add a reference to the binding object to the main activity, so that you can use it to access views:
- Open the
MainActivity.ktfile.
- Before
onCreate(), at the top level, create a variable for the binding object. This variable is customarily called
binding.
The type of
binding, the
ActivityMainBinding class, is created by the compiler specifically for this main activity. The name is derived from the name of the layout file, that is,
activity_main + Binding.
private lateinit var binding: ActivityMainBinding
- If prompted by Android Studio, import
ActivityMainBinding. If you aren't prompted, click on
ActivityMainBindingand press
Alt+Enter(
Option+Enteron a Mac) to import this missing class. (For more keyboard shortcuts, see Keyboard shortcuts.)
The
import statement should look similar to the one shown below.
import com.example.android.aboutme.databinding.ActivityMainBinding
Next, you replace the current
setContentView() function with an instruction that does the following:
- Creates the binding object.
- Uses the
setContentView()function from the
DataBindingUtilclass to associate the
activity_mainlayout with the
MainActivity. This
setContentView()function also takes care of some data binding setup for the views.
- In
onCreate(), replace the
setContentView()call with the following line of code.
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
- Import
DataBindingUtil.
import androidx.databinding.DataBindingUtil
Step 4: Use the binding object to replace all calls to findViewById().
- In
onCreate(), replace the code that uses
findViewById()to find the
done_buttonwith code that references the button in the binding object.
Replace this code:
findViewById<Button>(R.id.done_button) with:
binding.doneButton
Your finished code to set the click listener in
onCreate() should look like this.
binding.doneButton.setOnClickListener { addNickname(it) }
- Do the same for all calls to
findViewById()in the
addNickname()function. Replace all occurrences of
findViewById<View>(R.id.id_view)with
binding.idView. Do this in the following way:
- Delete the definitions for the
editTextand
nicknameTextViewvariables along with their calls to
findViewById(). This will give you errors.
- Fix the errors by getting the
nicknameText,
nicknameEdit, and
doneButtonviews from the
bindingobject instead of the (deleted) variables.
- Replace
view.visibilitywith
binding.doneButton.visibility. Using
binding.doneButtoninstead of the passed-in
viewmakes the code more consistent.
The result is the following code:
binding.nicknameText.text = binding.nicknameEdit.text binding.nicknameEdit.visibility = View.GONE binding.doneButton.visibility = View.GONE binding.nicknameText.visibility = View.VISIBLE
- There is no change in functionality. Optionally, you can now eliminate the
viewparameter and update all uses of
viewto use
binding.doneButtoninside this function.
- The
nicknameTextrequires a
String, and
nicknameEdit.textis an
Editable. When using data binding, it is necessary to explicitly convert the
Editableto a
String.
binding.nicknameText.text = binding.nicknameEdit.text.toString()
- You can delete the grayed out imports.
- Kotlinize the function by using
apply{}.
binding.apply { nicknameText.text = nicknameEdit.text.toString() nicknameEdit.visibility = View.GONE doneButton.visibility = View.GONE nicknameText.visibility = View.VISIBLE }
- Build and run your app...and it should look and work exactly the same as before..
Step 1: Create the MyName data class
- In Android Studio in the
javadirectory, open the
MyName.ktfile. If you don't have this file, create a new Kotlin file and call it
MyName.kt.
- Define a data class for the name and nickname. Use empty strings as the default values.
data class MyName(var name: String = "", var nickname: String = "")
Step 2: Add data to the layout
In the
activity_main.xml file, the name is currently set in a
TextView from a string resource. You need to replace the reference to the name with a reference to data in the data class.
- Open
activity_main.xmlin the Text tab.
- At the top of the layout, between the
<layout>and
<LinearLayout>tags, insert a
<data></data>tag. This is where you will connect the view with the data.
<data> </data>
Inside the data tags, you can declare named variables that hold a reference to a class.
- Inside the
<data>tag, add a
<variable>tag.
- Add a.
- Replace}"
Step 3: Create the data
You now have a reference to the data in your layout file. Next, you create the actual data.
- Open the
MainActivity.ktfile.
- Above
onCreate(), create a private variable, also called
myNameby convention. Assign the variable an instance of the
MyNamedata class, passing in the name.
private val myName: MyName = MyName("Aleks Haecky")
- In
- This may show an error, because you need to refresh the binding object after making changes. Build your app, and the error should go away.
Step 4: Use the data class for the nickname in the TextView
The final step is to also use the data class for the nickname in the
TextView.
- Open
activity_main.xml.
- In the
nickname_texttext view, add a
textproperty. Reference the
nicknamein the data class, as shown below.
android:text="@={myName.nickname}"
- In
MainActivity, replace
nicknameText.text = nicknameEdit.text.toString()with code to set the nickname in the
myNamevariable.
myName?.nickname = nicknameEdit.text.toString()
After the nickname is set, you want your code to refresh the UI with the new data. To do this, you must invalidate all binding expressions so that they are recreated with the correct data.
- Add
invalidateAll()after setting the nickname so that the UI is refreshed with the value in the updated binding object.
binding.apply { myName?.nickname = nicknameEdit.text.toString() invalidateAll() ... }
- Build and run your app, and it should work exactly the same as before.
Android Studio project: AboutMeDataBinding
Steps to use data binding to replace calls to
findViewById():
- Enable data binding in the android section of the
build.gradlefile:
buildFeatures {
dataBinding true
}
- Use
<layout>as the root view in your XML layout.
- Define a binding variable:
private lateinit var binding: ActivityMainBinding
- Create a binding object in
MainActivity, replacing
setContentView:
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
- Replace calls to
findViewById()with references to the view in the binding object. For example:
findViewById<Button>(R.id.done_button)⇒
binding.doneButton(In the example, the name of the view is generated camel case from the view's
idin the XML.)
Steps for binding views to data:
- Create a data class for your data.
- Add a
<data>block inside the
<layout>tag.
- Define a
<variable>with a name, and a type that is the data class.
<data> <variable name="myName" type="com.example.android.aboutme.MyName" /> </data>
- In
MainActivity, create a variable with an instance of the data class. For example:
private val myName: MyName = MyName("Aleks Haecky")
- In the binding object, set the variable to the variable you just created:
binding.myName = myName
- In the XML, set the content of the view to the variable that you defined in the
do you want to minimize explicit and implicit calls to
findViewById()?
- Every time
findViewById()is called, it traverses the view hierarchy.
findViewById()runs on the main or UI thread.
- These calls can slow down the user interface.
- Your app is less likely to crash.
Question 2
How would you describe data binding?
For example, here are some things you could say about data binding:
- The big idea about data binding is to create an object that connects/maps/binds two pieces of distant information together at compile time, so that you don't have to look for the data at runtime.
- The object that surfaces these bindings to you is called the binding object.
- The binding object is created by the compiler.
Question 3
Which of the following is NOT a benefit of data binding?
- Code is shorter, easier to read, and easier to maintain.
- Data and views are clearly separated.
- The Android system only traverses the view hierarchy once to get each view.
- Calling
findViewById()generates a compiler error.
- Type safety for accessing views.
Question 4
What is the function of the
<layout> tag?
- You wrap it around your root view in the layout.
- Bindings are created for all the views in a layout.
- It designates the top-level view in an XML layout that uses data binding.
- You can use the
<data>tag in inside a
<layout>to bind a variable to a data class.
Question 5. | https://codelabs.developers.google.com/codelabs/kotlin-android-training-data-binding-basics?hl=en | CC-MAIN-2020-45 | refinedweb | 1,820 | 50.12 |
On Mon, Dec 29, 2008 at 8:55 PM, Paolo Giarrusso <p.giarrusso at gmail.com> wrote: >> >> Atatched is a small patch for the annotator that makes it treat None >> and NotImplemented alike. This is all that is needed for most cases as >> all NotImplemented are typically removed by the optimisations >> performed by the annotator. > That can be made to work, but if such a method returns None you get > completely different semantics (trying again with something else) from > CPython (which will maybe return a failure, or return None for the > result of such an operation), so you have to restrict the allowed No, the patch do distinguish between None and NotImplemented. What I mean is that NotImplemented is treated in a similar manner as to how None is treated. The following crazy construction do compile and generate the same result as in cpython ('OK', 'String', 'None', 'None'): class mystr: def __init__(self,s): self.s=s def __str__(self): return self.s def __add__(self,other): if isinstance(other,mystr): return NotImplemented s=self.s+other if s=='None': return None else: return s __add__._annspecialcase_ = 'specialize:argtype(1)' def __radd__(self,other): return str(other)+self.s __radd__._annspecialcase_ = 'specialize:argtype(1)' def dotst_nonestr(): s1=mystr('No')+'ne' if s1 is None: s1='OK' s2=mystr('Str')+'ing' s3=mystr('No')+mystr('ne') s4='No'+mystr('ne') return (s1,s2,s3,s4) -- Håkan Ardö | https://mail.python.org/pipermail/pypy-dev/2008-December/004939.html | CC-MAIN-2014-15 | refinedweb | 236 | 55.34 |
Network round trips (query gone for execution to database and result comes to the screen, i.e., one network roundtrip) increases while sending multiple queries as individual queries to the database. It is recommended to combine them into a single unit/batch and send that batch to database only once for execution. This is called batch processing and this reduces network round trips between Java application and the database software.
For example
If ten queries are sent to database. Instead of sending them individual for ten times by having ten network roundtrips with browser window, it is recommended to combine them into single batch and send that batch to database only for one time.
Restriction
We cannot add select queries to the batch processing.
In batch processing java application sends query to database as a batch. Similarly, queries result comes back to application as a batch. All non-select queries executions give numeric results. But the select queries executions give ResultSet object. The executeBatch () method return type is int (), and it cannot store ResultSet object. So
we cannot add select queries to batch.
Batch processing does not perform transaction management on its own. But we can perform transaction management on batch processing by disabling the auto commit mode and by adding additional logics using connection.commit () , connection.rollback () methods.
Example of application batch processing
A table is created on Oracle table as shown below:
Source code for the application:
BatchProcess.java
import java.sql.*;
public class BatchProcess
{
public void main (String args []) throws Exception
{
Class.forName ("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
Statement st = con.createStatement ();
//three queries update ,insert, delete are added to batch
st.addBatch ("update student set address= ‘China’ where no=100");
st.addBatch ("insert into student values (109, ‘rahul’, ‘india’)");
st.addBatch ("delete from student where no=101");
int result [] = st.executeBatch ();
int sum = 0;
for (int i=0; i<result .length; ++i)
{
sum = sum+result [i];
}
System.out.println (sum);
}
}
Code explanation:
st.addBatch (“update student set address= ‘China’ where no=100”);
st.addBatch (“insert into student values (109, ‘rahul’, ‘india’)”);
st.addBatch (“delete from student where no=101”);
In the above statements three different queries are added to a batch.
int result[] = st.executeBatch ();
In this code execution an operation is performed and the result, whose return type is integer, is stored in an array.
The program in the next page shows the number of operations that are done. Data in the database table after the execution of the | http://ecomputernotes.com/java/jdbc/jdbc-batch-processing | CC-MAIN-2018-05 | refinedweb | 424 | 51.34 |
Ralf is principal of PERA Software Solutions and can be contacted at rholly@ pera-software.com.
In embedded programming, especially when developing device driver-level code, performance is often at a premium. One way to improve execution time is to reduce the overhead of looping through the use of an age-old technique known as "loop unrolling."
Tom Duff invented a special kind of loop-unrolling mechanism, known as "Duff's Device," that makes loop unrolling much easier. In this article, I examine the idea behind loop unrolling and explain how to generalize loop unrolling such that it can be put in a reusable library.
Classic Loop Unrolling
When implementing device drivers, you often have to access device registers a certain number of times from within a loop. Imagine a network I/O driver that sends characters to a port:
#define HAL_IO_PORT
*(volatile char*)0xFFFF8000
for (i = 0; i < len; ++i) {
HAL_IO_PORT = *pSource++;
}
For each pass through the loop (that is, for each character copied/sent to the port), three things happen:
- There is a jump to the beginning of the loop.
- Next i, the loop counter, is incremented.
- i is compared against len.
If the output operation itself consumes very little time (as it is normally the case when accessing a device register), these three steps add significant overhead.
Instead of copying the characters in a loop, you can transmit the characters "inline" and thereby save the jump, increment, and comparison:
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
...
However, this approach suffers from two weaknesses. First, it is static, meaning you have to know exactly how many characters you want to transfer; second, it is wasteful in terms of code memory, because the same line of code is repeated len times.
As a result, developers usually implement loop unrolling like this:
int n = len / 8;
for (i = 0; i < n; ++i) {
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
HAL_IO_PORT = *pSource++;
}
This approach processes eight operations in a row, which reduces the looping overhead to one-eighth. To handle cases were len is not evenly divisible by eight, a postprocessing loop is needed to execute the remaining copy operations:
n = len % 8;
for (i = 0; i < n; ++i) {
HAL_IO_PORT = *pSource++;
}
Even though this scheme works well, it is quite "wordy" and definitely not easy to maintain. Further, it cannot be generalized and put in a library.
Duff's Device
In 1983, while working at Lucasfilm, Tom Duff invented some C magic that implements loop unrolling without the need for the second (that is, postprocessing) loop. If you haven't seen it before, you should fasten your seatbelts before reading on:
int n = (len + 8 - 1) / 8;
switch (len % 8) {
case 0: do { HAL_IO_PORT = *pSource++;
case 7: HAL_IO_PORT = *pSource++;
case 6: HAL_IO_PORT = *pSource++;
case 5: HAL_IO_PORT = *pSource++;
case 4: HAL_IO_PORT = *pSource++;
case 3: HAL_IO_PORT = *pSource++;
case 2: HAL_IO_PORT = *pSource++;
case 1: HAL_IO_PORT = *pSource++;
} while (--n > 0);
}
If your first reaction is "But this is not legal C code!", you are not alone. But rest assured, this is legal C/C++. For background information on how this piece of code came about and an historic e-mail by Tom Duff that he wrote to Dennis Ritchie, see duffs-device.html.
Just as before, the device works by unrolling the loop eight times; that is, the copy operation is executed eight times in a row. The only exception is the first time through the do-while loop, where fewer copy operations may be executed, as there is no guarantee that the total number of copy operations (len) is evenly divisible by eight. The postprocessing loop has been effectively turned into an inlined preprocessing loop.
As in the previously shown manual unrolling scheme, the loop overhead is effectively reduced to one-eighth (there is only one loop counter decrement and only one comparison against zero for every eight copy operations). If you think one-eighth is not enough, go ahead and increase the block size until you're happy, but make sure that you increase the number of cases in the switch statement accordingly.
A Reusable Duff Device
Tom Duff's Device is highly useful, technically interesting, but unfortunately, not a pleasant sight to see. This is probably the reason why my mind refuses to memorize it. Therefore, I decided to wrap the nitty-gritty details within a macro:
)
Compared to the original device, I've changed a couple of minor things. First, I put the whole device in a dummy do-while block to get a local namespace to avoid variable name clashes and to enforce a trailing semicolon. Second, I've replaced the multiplication and modulo operations with right-shift and bit-wise AND operations. Even though most contemporary compilers would apply this optimization themselves, it certainly doesn't hurt to be explicit. Third, I've introduced another local variable, count_, to cater for cases where coders pass in complicated (expensive) expressions or function calls.
With a macro like this, the transmitter loop is reduced to a single line of code:
DUFF_DEVICE_8(len, HAL_IO_PORT = *pSource++);
By the way, did you notice that there is a subtle difference between the original for loop and the Duff Device version? Answer: The Duff Device does the wrong thing in case len is zero, because it executes the operation eightnot zerotimes. If you want, you can add support for this special case by adding an if check to the macro; however, I prefer to handle it outside the macro and add the check only if it is really needed:
if (len > 0)
DUFF_DEVICE_8
(len, HAL_IO_PORT = *pSource++);
As another example, consider this simplified version of an EEPROM driver routine that I recently implemented:
int CopyToEEPROM(const void*
pSource, void* pDest, unsigned len) {
// Anything to copy?
if (len > 0) {
const char* s = (const char*)pSource;
char* d = (char*)pDest;
// First, need to copy data to page buffer
DUFF_DEVICE_8(len, *d++ = *s++);
// Start EEPROM write cycle
HAL_EEPROM_WRITE();
// Check if data was transferred correctly
s = (const char*)pSource;
d = (char*)pDest;
DUFF_DEVICE_8(len,
if (*d++ != *s++) return 1; /* Fail */);
}
return 0; // Success
}
There used to be two slow, hand-coded loops in the original driver code: One copied the data to the EEPROM page buffer (as required by the EEPROM hardware), the second checked whether the data was successfully written. By replacing them with two Duff Devices, the code has become both faster and clearer.
DDJ | http://www.drdobbs.com/a-reusable-duff-device/184406208 | CC-MAIN-2013-48 | refinedweb | 1,078 | 52.83 |
I recently discovered that the BMP180 sensor has been discontinued, which is kind of a bummer. I always found it to be a good little sensor for temperature and pressure. So I picked up its replacement, and I found that I didn’t have a lot of good directions on making it work. So, I pieced a few things together, and it seems to work. These instructions will take you through it.
Materials
Enable I2C
You will need to turn on I2C for the Raspberry Pi if you haven’t already. I am working with a July-2017 release of Raspian-Pixel with a desktop. Previously, you could do this through raspi-config, but that doesn’t seem to be the case any more. I found the easiest way to do this was through the actual desktop. Everything else we do can be done through an SSH connection.
Simply click on the Start Menu and to Preferences and Raspberry Pi Configuration.
Enable SPI and I2C. Also, you may want to enable SSH, so you can use a program like Putty to control the Pi. Click OK. Then reboot, for the changes to go through.
Connect the Sensor
When you buy the BMP280 sensor, it comes with some pins that you will need to solder on. There are six pins but you will only make 4 connections. The connections are below.
Test the Sensor
If you have connected the sensor, and everything is working you should be able to detect it. Use the command below, and you will see this result.
sudo i2cdetect -y 1
Load the Libraries
This is where I ran into some problems. There were no libraries specifically for the BMP280 that I could find. There is, however, a BME sensor sold by Adafruit and it comes with a humidity sensor. It turns out that the BME library will work for this sensor. Yeah!
From your home directory
apt-get install build-essential python-pip python-dev python-smbus git git clone sudo python setup.py install
In the folder that was just created
git clone
Everything is loaded now. From the Adafruit_Python_BME280 folder run the example file.
python ./Adafruit_BME280_Example.py
You should see the temperature, pressure, and humidity (which will be 0).
The python code for that file is below:
from Adafruit_BME280 import * sensor = BME280(t_mode=BME280_OSAMPLE_8, p_mode=BME280_OSAMPLE_8, h_mode=BME280_OSAMPLE_8) degrees = sensor.read_temperature() pascals = sensor.read_pressure() hectopascals = pascals / 100 humidity = sensor.read_humidity() print 'Temp = {0:0.3f} deg C'.format(degrees) print 'Pressure = {0:0.2f} hPa'.format(hectopascals) print 'Humidity = {0:0.2f} %'.format(humidity)
With this, you can make all kinds of changes, like uploading to Thingspeak, Google Sheets, or making a CSV file. Happy sensing! | http://faradaysclub.com/?p=1325 | CC-MAIN-2018-17 | refinedweb | 452 | 67.76 |
return to main index
It is useful to think about a shading effect, say making a colored pattern,
as a process of sequentially applying layers of colored foil to a surface.
As each layer of foil is applied it is cut out by a digital "cookie-cutter".
Figure 1
Figure 1 shows a "cookie-cutter" and foreground and background colored "foils". The
cookie-cutter can also be thought of as a mask that allows one layer of color
to be composited onto another layer of color.
The cookie-cutter ie. mask, defines areas of transparency and opacity. Opaque
areas allow parts of a foreground foil to overlay a background foil.
Listing 1 provides the code for a function that returns 0 or 1 depending on whether
an location (x, y) is inside or outside a rectangle defined
by its top, left, bottom
and right edges. The function should be saved in a file called "lib.h".
x
y
top
left
bottom
right
Listing 1
float rectangle(float top, left, bottom, right, x, y)
{
float result = 0;
if(x >= left && x <= right && y >= top && y <= bottom)
result = 1;
return result;
}
The value retured from the function is used
by mix() in listing 2 to overlay or composite the final color.
mix
The source for a simple layered shader is shown below in listing 2.
Listing 2
#include "lib.h"
surface
layering1(float Kfb = 1,
top = 0.4,
left = 0.4,
bottom = 0.6,
right = 0.6;
color foreground = color(1,0.239,0))
{
color surfcolor;
float mask;
/* STEP 1 Set the apparent surface opacity. */
Oi = Os;
/* STEP 2 Composite a foreground color over a */
/* background color - in this instance */
/* Cs is the background color. */
mask = rectangle(top, left, bottom, right, s, t);
surfcolor = mix(Cs, foreground, mask);
/* STEP 3 No need to use Cs again because it was */
/* used it in step 2. */
Ci = Oi * surfcolor * Kfb;
}
If you are using Cutter to compile the RSL source code make sure that
both the "lib.h" and "layering1.sl" are in the shader source code directory
specified in Cutter's Preferences - figure 2. If you are not using Cutter
the full path to the "lib.h" file must be specfied by the #include statement.
Figure 2
By repeating step 2 several times, for example,
mask = rectangle(0.1, 0.3, 0.8, 0.7, s, t);
surfcolor = mix(Cs, color(0,0,1), mask);
mask = circle(0.3, 0.5, 0.25, s, t);
surfcolor = mix(surfcolor, color(1,0.239,0), mask);
a shader can give the illusion the
surface to which it is assigned has multiple colored layers - figure 3.
Figure 3
A function called circle() was implemented in the "lib.h" file as follows,
circle
Listing 3
float circle(float locx, locy, radius, x, y)
{
float result = 0;
float d = distance(point(locx,locy,0), point(x,y,0));
if(d <= radius)
result = 1;
return result;
} | http://www.fundza.com/rman_shaders/layered/index.html | crawl-001 | refinedweb | 487 | 65.62 |
What is Reactive Programming in Javascript
Hey web developers, In today’s AppDividend Tutorial, I have briefly described What is Reactive Programming in Javascript?
If you are taking this article, then Node.js is installed on your machine. It is a basic necessity.
It’s time to rethink the basic Software Architecture because Conventional Programming is not satisfied today’s modern software application requirement.
Reactive Programming
Content Overview
It is a programming of event streams happens in time. Reactive Programming is like a sequence of events occur in time. It is an Asynchronous Programming concept around data streams. There are two types of data streams.
- Static Data Streams (Arrays)
- Dynamic Data Streams (Event Emitters)
In general programming paradigm if z = x + y at the time of declaration then z will be the sum of x and y, but after that statement, if we change the value of x and y then z will be unchanged. So no effects after that sum statement.
Example # 1
//main.js var x = 10; var y = 20; let z = x + y; console.log(z); x = 100; y = 200; console.log(z);
If you directly run above code in the browser, then you might face the following issue.
Possible Errors
- You can get any syntax error.
- If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.
Possible Solutions
- Beginner’s Guide To Setup ES6 Development Environment Follow this article strictly and put above code in the main.js file
In both console report, we will get the same thing, and that is 30 and 30
The value of x and y does not effect in variable z, so in Imperative Programming, The concept of Dynamic Change is missing.
Here in example, we are using ES6 so, we need to download ES6 version of RxJS
npm install rxjs-es --save
import {Observable} from 'rxjs-es'; let streamA = Observable.of(3); let streamB = streamA.map(a => 3 * a); streamB.subscribe(b => console.log(b));
In the console, we can see the output of 9
Now we need to specify the Dynamic Behaviour of the Streams at the Declaration of the time and not after that otherwise It will not work. So dynamic code will look like this.
import {Observable} from 'rxjs-es'; let streamA = Observable.of(3, 4); // At the time of declaration, we need to assign the dynamic behaviour. let streamB = streamA.map(a => 10 * a); streamB.subscribe(b => console.log(b));
Now your new output will be 9 and 12
In Reactive Programming, everything is Streams that occur in time. A stream is a progression(sequence) of ongoing events specific to time.
Example # 2
//main.js let a = [1,2,3,4,5,6,7,8,9]; console.log(a); // [1,2,3,4,5,6,7,8,9]
It logs the array of the values, and it does not relate to kind any of time interference.
//main.js var a = [1,2,3,4,5,6,7,8,9]; var b = a.filter(x => x > 4) .reduce((x,y) => x + y); console.log(b);
Run again, you will see in console 35.
Now above example is simple, we have just taken an array and then filter with some condition and then reduce it to the previous and next value to get the final value of b.
This article uses environment setup of Beginner’s Guide To Setup ES6 Development Environment this article. So, still, do not know then please check out that article and you will up and running. Now we need to add RxJS into the step forward.
Step 1: Check your package.json file, It will look like this.
{ "name": "js6", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "webpack-dev-server", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "KRUNAL LATHIYA", "license": "ISC", "devDependencies": { "babel-core": "^6.24.0", "babel-loader": "^6.4.1", "babel-preset-es2015": "^6.24.0", "webpack": "^2.3.2", "webpack-dev-server": "^2.4.2" }, "dependencies": { "rxjs-es": "^5.0.0-beta.12" } }
Now we have successfully installed RxJS library so we can use it in this example.
Step 2: Replace the following code in main.js
//main.js import {Observable} from 'rxjs-es'; let output = Observable.interval(500) .take(6) .map(i => [1,3,5,7,9,11][i]); let result = output.map(x => x); result.subscribe(x => console.log(x));
Now when you again start your server than in the console, you can see like this in every 5oo milliseconds.
1 3 5 7 9 11
In above code, the values are logged at some time interval in our case 500 milliseconds, which is Asynchronous Paradigm.
When interval event is fire, we got the logged values in our console, and It is awesome right!!
We got the event streams at particular time, and we can also apply map, filter, reduce and other array functions to the events streams
//main.js import {Observable} from 'rxjs-es'; let output = Observable.interval(500) .take(6) .map(i => [1,3,5,7,9,11][i]); let result = output.map(x => x) .filter(x => x > 5) .reduce((x, y) => x + y); result.subscribe(x => console.log(x));
And we get 27 in the console.
Memorable Points
- Reactive Programming allows you to set Dynamic Behaviour only at Declaration Time.
- Reactive Programming is different from Imperative programming because as the name suggests it reacts when something in our application is occurring or done.
- It relies on Asynchronous Nature that happens in time.
- It stays responsive in the case of Failure and Success.
- In the Reactive world, we can not wait on something happen to the program, we need to continue the execution, and if something happens, we need to React to it. That is what Async Pattern is.
If you still have any doubt then ask in a comment below, I am happy to help you out.
Hey thank you for this great article. Make mu mide more clear on javascript reactivity | https://appdividend.com/2017/04/13/what-is-reactive-programming-in-javascript/ | CC-MAIN-2019-47 | refinedweb | 1,002 | 67.96 |
Conflict Resolution with 1.x client
- deprecated
Description — Couchbase Sync Gateway — resolving conflicts
Abstract — This guide relates to handling data conflicts while syncing with Couchbase Lite 1.x clients or syncing with pre 2.8 version of Sync Gateway nodes using SG-Replicate
Introduction
This guide covers handling data conflicts while syncing with Couchbase Lite 1.x clients or syncing with pre 2.8 version of Sync Gateway nodes using SG-Replicate
In these cases, the conflict resolution happens on the server-side using the Sync Gateway Admin REST API. This information does not apply to applications using Couchbase Mobile 2.x only — see Conflict Resolution or inter-Sync Gateway replication with versions of Sync Gateway 2.8 and above — see Conflict Resolution
In Couchbase Lite 1.x, a conflict usually occurs when two writers are offline and save a different revision of the same document. Couchbase Mobile provides features to resolve these conflicts, the resolution rules are written in the application to keep full control over which edit (also called a revision) should be picked.
The revision guide and documents conflicts FAQ are good resources to learn how to resolve conflicts on the devices with Couchbase Lite.
Creating a conflict
During development, the new_edits flag can be used to allow conflicts to be created on demand.
// Persist three revisions of user foo with different statuses // and updated_at dates curl -X POST \ -H "Content-Type: application/json" \ -d '{"new_edits": false, "docs": [{"_id": "foo", "type": "user", "updated_at": "2016-06-24T17:37:49.715Z", "status": "online", "_rev": "1-123"}, {"_id": "foo", "type": "user", "updated_at": "2016-06-26T17:37:49.715Z", "status": "offline", "_rev": "1-456"}, {"_id": "foo", "type": "user", "updated_at": "2016-06-25T17:37:49.715Z", "status": "offline", "_rev": "1-789"}]}' // Persist three revisions of task bar with different names curl -X POST \ -H "Content-Type: application/json" \ -d '{"new_edits": false, "docs": [{"_id": "bar", "type": "task", "name": "aaa", "_rev": "1-123"}, {"_id": "bar", "type": "task", "name": "ccc", "_rev": "1-456"}, {"_id": "bar", "type": "task", "name": "bbb", "_rev": "1-789"}]}'
It can be set in the request body of the POST
/{tkn-db}/_bulk_docs endpoint.
Detecting a conflict
Conflicts are detected on the changes feed with the following query string options.
curl -X GET '' { "results": [ {"seq":1,"id":"_user/","changes":[{"rev":""}]}, {"seq":4,"id":"foo","changes":[{"rev":"1-789"},{"rev":"1-123"},{"rev":"1-456"}]}, {"seq":7,"id":"bar","changes":[{"rev":"1-789"},{"rev":"1-123"},{"rev":"1-456"}]} ], "last_seq":"7" }
With
active_only=true and
style=all_docs set, the changes feed excludes the deletions (also known as tombstones) and channel access removals which are not needed for resolving conflicts.
In this guide, we will write a program in node.js to connect to the changes feed and use the request library to perform operations on the Sync Gateway Admin REST API. The concepts covered below should also apply to other server-side languages, the implementation will differ but the sequence of operations is the same. In a new directory, install the library with npm.
npm install request
Create a new file called index.js with the following.
var request = require('request'); var sync_gateway_url = ''; var seq = process.argv[2]; getChanges(seq); function getChanges(seq) { var querystring = 'style=all_docs&active_only=true&include_docs=true&feed=longpoll&since=' + seq; var options = { url: sync_gateway_url + '_changes?' + querystring }; // 1. GET request to _changes?feed=longpoll&... request(options, function (error, response, body) { if (!error && response.statusCode == 200) { var json = JSON.parse(body); for (var i = 0; i < json.results.length; i++) { var row = json.results[i]; var changes = row.changes; console.log("Document with ID " + row.id + " has " + changes.length + " revisions."); // 2. Detect a conflict. if (changes.length > 1) { console.log("Conflicts exist. Resolving..."); resolveConflicts(row.doc, function() { getChanges(row.seq); }); return; } } // 3. There were no conflicts in this response, get the next change(s). getChanges(json.last_seq); } }); }
Let’s go through this step by step:
GET request to the
_changesendpoint. With the following options:
feed=longpoll&since=<seq>: The response will contain all the changes since the specified
seq. If
seqis the last sequence number (the most recent one) then the connection will remain open until a new document is processed by Sync Gateway and the change event is sent. The
getChangesmethod is called recursively to always have the latest changes.
include_docs:The response will contain the document body (i.e. the current revision for that document).
all_docs&active_only=true:The response will exclude changes that are deletions and channel access removals.
Detect and resolve conflicts. If there are more than one revision then it’s a conflict. Resolve the conflict and return (stop processing this response). Once the conflict is resolve, get the next change(s).
There were no conflicts in this response, get the next change(s).
The program won’t run yet because the
resolveConflicts method isn’t defined, read the next section to learn how to resolve conflicts once they are detected.
Resolving conflicts
To resolve conflicts, the
open_revs=all option on the document endpoint returns all the revisions of a given document.
The Accept: application/json header is used to have a single JSON object in the response (otherwise the response is in multipart format).
curl -X GET -H 'Accept: application/json' ''
From there, the App Server decides how to merge the data and/or elect the winning update operation.
Add the following in
index.js below the getChanges method.
function chooseLatest(revisions) { var winning_rev = null; var latest_time = 0; for (var i = 0; i revisions.length; i++) { var time = new Date(revisions[i].updated_at); if (time latest_time) { latest_time = time; winning_rev = Object.assign({}, revisions[i]); //copy as a new object } } return {revisions: revisions, winning_rev: winning_rev}; } function resolveConflicts(current_rev, callback) { var options = { url: sync_gateway_url + current_rev._id + '?open_revs=all', headers: { 'Accept': 'application/json' } }; // 1. Use open_revs=all to get the properties in each revision. request(options, function (error, response, body) { if (!error response.statusCode == 200) { var json = JSON.parse(body); var revisions = json.map(function(row) {return row.ok;}); var resolved; // 2. Resolve the conflict. switch (current_rev.type) { case user: // Choose the revision with the latest updated_at value // as the winner. resolved = chooseLatest(revisions); break; case list: // Write your own resolution logic for other doc types // following the function definition of chooseLatest. default: // Keep the current revision as the winner. Non-current // revisions must be removed even in this scenario. resolved = {revisions: revisions, winning_rev: current_rev}; } // 3. Prepare the changes for the _bulk_docs request. var bulk_docs = revisions.map(function (revision) { if (revision._rev == current_rev._rev) { delete resolved.winning_rev._rev; revision = Object.assign({_rev: current_rev._rev}, resolved.winning_rev); } else { revision._deleted = true; } return revision }); // 4. Write each change (deletion or update) to the database. var options = {url: sync_gateway_url + '_bulk_docs', body: JSON.stringify({docs: bulk_docs})}; request.post(options, function (error, response, body) { if (!error response.statusCode == 201) { console.log('Conflict resolved for doc ID ' + current_rev._id); callback(); } }); } }) }
So what is this code doing?
Use
open_revs=allto get the properties in each revision.
Resolve the conflict. For user documents, the revision with the latest
updated_atvalue wins. For other document types, the current revision (the one that got picked deterministically by the system) remains the winner. Note that non-current revisions must still be removed otherwise they may be promoted as the current revision at a later time. The resolution logic may be different for each document type.
Prepare the changes for the
_bulk_docsrequest. All non-current revision are marked for deletion with the
_deleted: trueproperty. The current revision properties are replaced with the properties of the winning revision.
Write each change (deletion or update) to the database.
Start the program from sequence 0, the first sequence number in any Couchbase Mobile database.
node index.js 0
The conflicts that were added at the beginning of the guide are detected and resolved.
Document with ID _user/ has 1 revisions. Document with ID foo has 3 revisions. Conflicts exist. Resolving... Conflict resolved for doc ID foo Document with ID bar has 3 revisions. Conflicts exist. Resolving... Conflict resolved for doc ID bar Document with ID foo has 1 revisions. Document with ID bar has 1 revisions.
Add more conflicting revisions from the command-line with a different document ID (baz for example). The conflict is resolved and the program continues to listen for the next change(s). | https://docs.couchbase.com/sync-gateway/current/resolving-conflicts.html | CC-MAIN-2020-45 | refinedweb | 1,373 | 51.85 |
import "go/parser"
Package.
fset := token.NewFileSet() // positions are relative to fset src := `package foo import ( "fmt" "time" ) func bar() { fmt.Println(time.Now()) }` // Parse src but stop after processing the imports. f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly) if err != nil { fmt.Println(err) return } // Print the imports from the file's AST. for _, s := range f.Imports { fmt.Println(s.Path.Value) }
Output:
"fmt" "time"
A Mode value is a set of flags (or 0). They control the amount of source code parsed and other optional parser functionality.) )
Package parser imports 13 packages (graph) and is imported by 3391 packages. Updated 2018-06-08. Refresh now. Tools for package owners. | https://godoc.org/go/parser | CC-MAIN-2018-26 | refinedweb | 114 | 63.36 |
018 Channing Crowdeli will forgo his final two years of eligibility and enter the NFL draft. PAGE IE CRiSTY LoFTrs cloftis@chronicleonline.com Chronicle Just a few days after Gov. Jeb Bush signed a bill that enables children to attend state-funded pre-kinder- garten programs, local > 0 -. - : r -- I- OlNIL -- providers say they have ques- tions with no answers. The Citrus County School Readiness Coalition met Wednesday to discuss the new legislation; however, executive director Sonya Bosanko could provide few details to learning center providers. "I have more questions than. I have answers," Bosanko said. The Voluntary Pre-K edu- cation program begins Sept 1 for Florida's 4-year-olds. Throughout the year, chil- dren may receive 540 hours of pre-K instruction-with-no -. m el cl h p t1 Man jumps into river to avo Deputies wait as suspect swims AMY SHANNON ashannon@ chronicleonline.com Chronicle Faced with a sheriff's deputy on his heels and the Withlacoochee River, an Inglis man chose the river. James Blair Bailey, 23, 11240 Northwood Drive, swam across the Withlacoochee River to evade sheriff deputies. Tierney said depu- Once he reached the ties drove Bailey to Levy County side, he Citrus County. He did saw a Citrus County not swim back deputy waiting for him According to his and surrendered, arrest report, this is "Mr. Bailey swam what happened: across the entire river A deputy on West and got up on the James River Road saw a black embankment where the Blair Bailey two-door Oldsmobile deputy was," Citrus swam to Inglis. approaching his patrol County sheriff's car driving 45 mph in a spokeswoman Gail Tierney 35 mph zone. said. "He was given the option The deputy activated his to be arrested by Levy County emergency lights in order to or by us and he voluntary pull the driver over. The car returned back." turned into the driveway of a JjjjjjmjjLp v-c m -ioniine o FORECAST: Mostly sunny. South winds around 5 mph becom- ing onshore. PAGE 2A Man takes developer to task for trees Resident seeks to revoke exemption TERRY WITT terrywitt@chronicleonline.com Chronicle Les Githens used to walk his dog through a forest in Citrus Hills that he says is now bar- ren. Githens blames the county for adopting a tree ordinance last year that exempted Citrus Hills and other large residen- tial developments from a rule that penalizes individ- ual residents for clear- cutting trees on their home sites. Githens, a Citrus Hills resident, will ask the Planning and Development Review Board today to recom- mend revoking the exemption. He says the Li exemption has allowed Citrus Hills developer prles Steve Tamposi to-clear- -'-- cut acres of trees for homes. "I want to make it clear this is not a vindictive effort," Githens said in a presentation Wednesday to the Chronicle Editorial Board. "Tamposi is doing a great job. He just needs to do it in a different way." The county tree ordinance requires individual lot owners to survey their property and identify trees to save before they can build. The county X h le I SO YOU KNOW The Citrus County Planning and Development Review Board meets at 9 a.m. today in the Lecanto Government Building on I County Road 491. planning staff reviews the sur- vey. If the lot owners choose to clear-cut their lots, they must replant enough trees around the home to replace the ones pro- tected by the ordi- nance. Citrus Hills and other large planned developments are exempt from the es requirement. Githens iens is pressing the county arving to preserve the tree anopy. canopy in these devel- -........ opmentsby eliminating the exemption. Planned developments, or PDs, are guided by master plans. Community Services Direc- tor Chick Dixon said PDs were exempted to give developers the flexibility to create green space by clustering homes and using other land-management. techniques. "The premise is PDs already Please see TREES/Page 4A Trio breaks into home at gunpoint Victims tied up, robbed AMY SHANNON ashannon@ chronicleonline.com Chronicle aore than 18 children in a A woman and two men broke classroom. In the summer, into an Inverness house early children are offered 300 Wednesday, robbed a man and ours with a maximum of 10 woman at gunpoint and bound pupils. them together with tape, Citrus About 160 high-risk chil- County Sheriff's officials reported. Please see LEARNING/Page.5A Spokeswoman Gail Tierney said the incident is listed as a home invasion robbery be- cause the three suspects force- st fully entered the home while it id aest "We don't see too many of them, but they're certainly not house on River Road. Bailey unprecedented," she said got out of the car and walked about the incident "I'm sure away. The deputy approached they'll be doing a lot of ques- Bailey and ordered him to stop. tioning and see what we can do Bailey ran to the edge of an suspect-wise." embankment and jumped into According to a press release, the Withlacoochee River, the this is what happened: report said. At 1 a.m., Joan Jarvis The deputy sent another answered the front door of her deputy to cross over into Ingli house on South Fairway where he was met by a Levy Terrace. The woman at the County sheriffs sergeant door told Jarvis her car broke Bailey reached the Levy down and she asked to use a County sid gae and gave up when telephone. he sawlethe deputy.e ran Jarvis told the woman to Pleae se IE/PAag -meet heraturdgaeg g liistis h Please see RIVER/Page 4A could use the cordless phone she kept there. When Jarvis' acquaintance, Anthony Schoene, 21, of Crystal River, opened the garage door, he found a woman and a man waiting for him. A second man ran into the garage with a rifle in his hands. The first male told Schoene he had a pistol. The three sus- pects demanded entry into the house. The suspects forced the two victims into the master bed- room and demanded money. They taped Jarvis' hands behind her back and hit Schoene with a gun. Schoene gave the suspects expensive jewelry and several hundred dollars. The suspects also took several hundred dol- lars from Jarvis' dresser, a small amount of cash from her purse and an expensive tennis bracelet The three suspects moved the victims into a bathroom, taped them together and fled the scene. Jarvis and Schoene removed the tape and called authorities. Deputies noticed a bump on Schoene's forehead and marks on his arms and legs that appeared to be from tape. He refused medical treatment. Jarvis did not appear to have any injuries. Jarvis' daughter, Jessica, answered.a phone at the house Please see TRIO/Page 5A Annie's Mailbox . 4C Movies ...... . 5C Comics. . . 5C Crossword ....... 4C Editorial ....... 10A Horoscope ...... 5C Obituaries ....... 6A Stocks ......... 8A Three Sections Keep kitchen time to a minimum after the holiday push of elaborate meals./1C Cheaper tickets z 0 Delta Air Lines. . announces it t is cutting its t most z. expensive fares by as much as 50 percent and is eliminating other restric- tions./12A Aid pours In for tsunami victims Some worry about nations engaging in one- - upmanship in pledging relief. /14A Closer look at Closer look at historic buildings * Resources board to advise about preservation./3A M The community is urged to take part in the annual ."Fitness in Citrus" program./3A * Inverness plans for a new sewer system./3A Early learning stumps providers DAVE SIGLER/Chronide Charlotte Eadler, owner of Noah's Ark School Readiness Center In Inverness, works with some of her pupils to teach them about the color blue Wednesday during school. Eadler addressed the School Readiness Coalition about the new pre-K law. Children pictured with Eadler, from left, are: Jeramle Cristello, 4; Destiny Whitten, 5; Alyson GIImour, 5; and Ellie Farnsworth, 3. School Readiness Coalition grapples with pre-K measure A -~ 'ii~'.A *f~*'**~':'**~.***'*' .11' -~-~- *~-~ ... - A iW~2. 22* ............. ~ ~ *~' .2..2 ,. '2~. ~ . ,, fl~2~. / HIGH 80 LOW 55 2A ~uSDkjTNU.R t&20S N KPTITAN --NI TCTU CUT.F) HOIL Florida LOTTERIES -- 2 4 2 Here are the winning numbers selected Wednesday in the Florida Lottery: buns CASH 3 8-2-2 PLAY 4 #5-4-5 LOTTO 2-9-21-22-33-49 FANTASY 5 4-6-16-20-27 .\ TUESDAY, JANUARY 4 Cash 3:9-2-3 Play 4:5- 5- 6-7 Fantasy 5: 6- 10- 16- 18-21 5-of-5 3 winners $70,654.06 4-of-5 372 $91.50 3-of5. Caph3:6-4-7 Play 4:7-6-8-7 Fantasy: 9 24- 26 29 31 5-of-5 1 winner $174,614.32 4-of-5 ,169 $166.50 3-of-5 6,627 $11.50 SATURDAY, JANUARY 1 Cash 3:4 8 9 Play 4:51-7-1-S5 Fantasy 5: 4-7-15-16-23 5-of-5 1 winner $218,093.68 4-of-5 420 $83.50 3-pf-5 11,205 $8.50 Ld6tb:11-21-32-35-42-46 6-of-6 2 winners $20 million 5-of-6 126 $4,646.50 4- f-6 6,727 $70.50 3-of-6 131,613 $5 FRIDAY, DECEMBER 31 Cash 3: 81-4 1 Play 4:9-8- 0 0 Fantasy 5:1 17 18 28 36 5-qf-5 : 3 winners $85,627.99 4 349 $118.50 S "Copyrighted Material .. Syndicated Content e .::. I .. . i*m .. Available from Commer cia News.Providers' a. .....- S ,ia a: .h " . .oma- = 0 S i" I 4 ] ( , .... ,r:::::: : I .. ,t .,^ul .l. . ::. ^B:: >4Ab - 0 - e ,f .. ,,..:x -4llE a' ' I :: x ,,: .. '-'IP"" a" .0 . ram .:: ." .. m .^ ::: *. H I i8E a::*lliT-.nj S sm 4' "" *' H-.. - -a *** sO -n at .:. . h- -is <-( *- - h- -p- -, .- , ..... : N: . volft L 5W to -- e r . - -h w m..-1 e r.au 8 y^- S - SOt adi n .n 4 b1I * a ^~m S--- ,"a am r4iS * Ceo I Q e Cel ,ell,, O .0 S" ' 0EO "-. *A qv.... ... .... n. .. . Ap a. emMilo eaOmw emowsp a a1 <:*.- - ". a e. a a. a . ........., ... .. ... : .. m4 g S. r~ **~r"~ .0~t't i).1~4flfl~%t., a~sd~~Lw '~4p.ini. t4~Z..i%%.44.,;<.~iP>4:w:irF .:Y~,. *4i~ 'k~ ~ -~ out too A w a- ** --am 4mo aMOW g Sw mam a a a4 wsean a ana em.mmom Oman 0' a * flue=.M bslpn Gmumm hmm *e-a.m .-*omm W 4e w-mm ..m w e an enqu ammo m..- ONO ..m INSIDE THE NUMBERS i To,verify the accuracy of winpng lottery numbers, pla-'s l-ould doub-clihck the nurnbes' printed 'boe ' 4fti' rintbers officially posted by"t1,fldrida Lottery On the Web,:go to .com; by telephone, call (850) 487-7777. Ut. e mllo CiTRus CouNTY (FL) CHRoNicLE 2A THURSDAY, JANUARY 6. 2005 ENTERTAINMENT .,. * Ow po. '-5 K :( ~S,%\ \j '\L. _ ~JI S .' 3A THURSDAY JANUARY 6, 2005 I Eyeing area's rich past Advisory board examines buildings' backgrounds TERRY WITT terrywitt@chronicleonline.com Chronicle Citrus County's Historical Resources Board toured some of the oldest buildings in the coun- ty Wednesday to prepare itself for advising the county commission on preserving heritage. Chairman Tom Frafnklin said the board was formed to make recommendations about his- toric sites, and the tour did provide insights into the condition of five historic buildings. The board traveled to the Canning Plant in Lecanto, Historic Hernando School, the old Floral City Fire Department Station, the Historic Old Courthouse in Inverness and the Coastal Museum in Crystal River. One of the board's goals is to apply for status as a "Certified Local Government" Franklin said the title would give the county more credi- ability when it applies for historic state grants. Franklin said the capitol's current attitude is not favorable toward cultural and historic grants, but he said those attitudes tend to come and go in cycles and eventually attitudes will change. The advisory board members are Franklin, David Arthurs, Sandra Noble, Francis Langley, architect Richard Clay and Marilyn Jordan. One of the county's more visible historic treasurers is the Old Courthouse on the square. The 92-year-old building has been converted to the Old Courthouse and Historic Museum and looks exactly as it did when it was in use as -the Citrus County Courthouse. The giant clock in the courthouse steeple keeps perfect time, thanks to electricity being added some years ago. Franklin said the aging building is in good shape, but like many of the county's historical structures, it will need maintenance in a few years. The Historic Hernando School, by contrast, will need quite a bit of work, he said. TERRY WITT/Chronicle Sandra Noble and Tom Franklin examine the interior of the clock tower In the Old Courthouse as part of a tour by the Historical Resources Advisory Board. Franklin is board chairman and Noble Is a historical expert. NANCY KENNEDY nkennedy@chronicleonline.com Chronicle Too many cookies, too much candy. Too many "BLTs" Bites, licks and tastes. Now that the official holiday eating season is over and you officially can- not'breathe because your pants are too snug, it's time to do RESPONSI more than think 2004 FIT about doing some- CITRUS CH thing about it Beginning *68 percent s Monday, Jan. 17 very likely to through Feb. 20, the exercising; 3( community, is urged were somewh to take' part in the N 99 percent se annual "Fitness in fun a fun a Citrus" z program. more likely tc Last year more than nently incorp 600 people joined lifestyle. 52 teams through- 76 percent s out the county and im 76 percent sh walked their way to health and fil better health. However, this 58 percent Ic year more than 35 percent lo walking will count stress levels. "One of the things 31 percent people (noted) in 31 periends their evaluation of - last year's program M Many reported was they wanted to blood press do more than just lesterol, betti walk," said Rebecca improved mo Martin, spokes- Several quit woman for Citrus Memorial Hospital. This year, instead of getting points for walking 10,000 steps a day, partic- ipants will get points for moderate to vigorous exercise 10 points for 10. minutes. Based on the Surgeon General's recommendation that people, get a minimum of 30 minutes of physical activity on most days of the week, the following activities "count": Walking, jogging, running, hiking Bicycling, swimming, horseback riding, kayaking Tennis or similar indoor or out- door sports Exercise at home or a gym, either cardio or weight-bearing Vigorously performed household DAVE PIEKLIK dpieklik@ chronicleonline.com Chronicle The city of Inverness continues working with the county on plans for boosting the city's waste- water treatment plant to coincide with the coun- ty's plan for a business park at the Inverness Airport, City council members decided Tuesday to join the county's efforts In receiving grants to move forward with the projects. The city is looking to upgrade the treatment plant for $6.6 million, The plant's capacity will be boosted to com- pensate for growth and will Include a transmis- sion line to supply treated water to several areas for irrigation. In return for cooperating with the city, the county would be able to build an Industrial park next to the plant, off U.S. 41 near Inverness, County officials are seeking a $4,9 million grant to expand the sewage plant, leaving the city to cover the other $1.6 million, City Manager tasks (yard work, gardening, clean- ing) According to the U.S. Surgeon General's office, it's duration rather than intensity that counts, Martin said. Moderate to vigorous walking counts as much as running when it comes to improving your overall health. This year's chal- ES FROM lenge offers bonus NESS IN points to those who ALU.ENGE: quit smoking during the Fitness aid they were Challenge and stay continue smoke-free. ) percent Other changes: at likely. This year's challenge, aid they had starts earlier and. activity is ends sooner. Martin. be perma- said a shorter time orated into a will help participants stay focused and achieve a sense of id they had accomplishment. If r overall you're bored, you'll quit st weight. "Studies have wered their shown that it takes 21 days to change a ade new habit," she said. So, after five weeks of regular exercise, the d lowered chances of keeping re, lower cho- with it as a lifestyle !r sleep, are high. ods. Also, this year smoking. teams will be able to choose their compet- ing category Jocks (those with an already active lifestyle), Getting There (those con- tinuing to improve) or Just Getting Started based on current fitness level. Here's how to get involved: By Monday, form a team. decide on a category, appoint a leader, choose a team name. Register with Tom O'Brien, the Citrus County Health Department health educator, 527-0068, Ext. 287, or e-mail: Thomas O'Brien@doh.state.fl.us. Send a team representative to the Team Leader Kick-off meeting at 4 or 5 p.m. (choose one), Wednesday, at the Citrus County Health Department DAVE SIGLER/Chronicle Don Stewart talks to Loretta Mazzo and Fred Valentino about his recumbent bicycle Wednesday at the Communitywide Fitness Challenge 2005 kickoff at Citrus Memorial Hospital. Participants In this year's challenge may earn points in a variety of fitness activities. office in Lecanto. weeks run from Monday to Sunday; weekly scores are reported to Tom Get moving, track your activity O'Brien by noon the following and record your points. Challenge Wednesday. Frank DiGiovanni said. "Any time you get government's working together, you should fall to your knees and kiss the ground," DiGiovanni said, "because it does- n't happen often." In other Inverness news: Work continues to repair a section of pro- tective wall at the State Road 44 East boat ramp. Engineers with the state noticed sections of granite missing from the 500-foot wall before they were ready to finish the project. The ramp's expected to open by the end of the, month. Councilwoman Jacquie Hepfer said her plans for a skateboard park are continuing. Hepfer said she hopes to have a skate park in place by the end of the school year. Preliminary plans call for the park to be built near Highland Boulevard and Park Avenue. Construction will soon begin on the Inverness government complex. Workers began arriving Wednesday with steel and other mate- rials, The first phase of the $5.8 million project should be completed by November. Staff report Citrus County Sheriff deputies took into custody an occupant of a small white car fitting the description of the vehicle involved in Tuesday's car burglary and purse snatch- ing. Two females one tall, one short ran into the woods near a stretch of U.S. 19, north of Crystal River, after deputies attempted to stop their car. Aviation units arrived on the scene and deputies set up a perimeter to search for the females. Sheriff's spokeswoman Gail Tierney confirmed the deputies took one of the car's occupants in custody Wednesday evening. At 1:05 p.m. Tuesday, deputies received a call about two young women snatching a purse out of another woman's car while she sat in her car parked outside the Homosassa Winn-Dixie. The woman ran after the women and retrieved her purse. Both women ran away. At 3:41 p.m., deputies received a call about a young woman snatching a purse off an elderly woman's arm as she walked away from an ATM at SunTrust in Beverly Hills. The thief fled the scene. Tierney said the descrip- tions of the suspects and the get-away vehicles contained similarities. Anyone with information about either case should call the Sheriff's Office crime tips line at 1-888-269-8477. County BRIEFS Groups accepting tsunami donations International aid workers say the outpouring of giving follow- ing the disastrous earthquake- caused tsunami in Asia that dev- astated coastal villages and towns has been tremendous .' and in some cases overwhelm- "' ing. If you wish to donate to the work they do, the following are only four of the many intema- tional organizations funneling help to survivors: m CARE Phone: (404) 681-2552. E-mail: info@care.org; www,. careusa.org. Mail to: CARE, 151 Ellis Street NE, Atlanta, GA 30303- 2440. m UNICEF Phone: (800) 4UNICEF. E-mail:. --d Mail to: UNICEF, 333 East , 38th Street, New York, NY 10016. Doctors Without Borders Phone: (800) 392-0392. E-mail:-"' borders-usa.org. Mail to: Doctors Without Borders/USA, P.O. Box 1856, Merrifield, VA 22116-8056. Save the Children Phone: (800) 728-3843. E-mail: www. savethechil- - dren.org. Mail to: Save The Children, Attn: Asian Earthquake/Tsunamil Relief Fund, 54 Wilton Road, .. Westport, CT 06880. Chamber announces' CR 495 closure The Citrus County Chamber ,, of Commerce announces the - closure of County Road 495 (Citrus Avenue) from U.S. 19 to' ' Crystal Street from 3 p.m. Friday until 7 p.m. Sunday in prepara- tion for the Florida Manatee Festival. The following connect- ing roads also will be closed: Northwest First Avenue from U.S. 19 to Crystal Street; . Northwest Second Avenue frorn U.S. 19 to Northwest Seventh - Street; and Northwest Seventh - Street from C.R. 495 to Northwest Third Avenue. Alternate roads available wil -l be Crystal Street and North Turkey Oak Drive. Call the Citrus County Chamber of Commerce at 795-3149 or 726- 2801. Those who attend the Manatee Festival on Saturday ; and Sunday should park at the Crystal River Mall, on the south end near Kmart. A free shuttle service is avail- able for those attending the event. * .a.. M --w.* Cc . -o - o "o 0* S. .E - - V ~ - ~ * ~ a 6 7/, Just in time for new year's resolutions 'Fitness in Citrus' a weighty opportunity . City, county team on upgrade Sheriff's deputies take - - - - 0 - - .L - woman into custody a 0 a a c a i itr e r e s 5 CITRus COUNTY (FL) CHRONICLE 4A THURSDAY, JANUARY 6, 2005 TREES Continued from Page 1A have provisions for creating green space," he said. Dixon said he understands what Githens wants to do with the tree ordinance, and he said the planning staff has no objection to Githens' concept, but planners also could' live with the current exemption for PDs. Avis Craig, Citrus Hills development director, said Githens is misinformed about what is happening in Citrus Hills. She also will speak at the planning board. "We have a strong commit- ment to tree planting and pro- tecting specimen trees," she said. Specimen trees are at least 24 inches in diameter. The trees are often sprawling live oaks and other tall hard- woods. They are protected by the tree ordinance because of their age and the difficulty of replacing them. Craig accused qithens of using inflammatory informa- tion to convince the county to change the tree ordinance, and. she denied Citrus1 Hills clear-cuts trees. Citrus Hills has set aside 500 acres of green space. About half of that green space is clustered in the community golf courses, Craig said. She said the company also has spent a great deal of time designing a nature park with a trail system. RIVER Continued from Page 1A because he has a Citrus County warrant and did not have a driver's license. The nature of Bailey's war- rant is unknown: Deputies charged Bailey with driving with a suspended license and resisting/obstruct- ing a law enforcement officer without violence. His bond was set at $750. Man appealing sentence in lewd conduct case DAVE PIEKLIK dpieklik@chronicleonline.com Chronicle A man seeking an appeal for violating probation after he had sex with two underage girls will stay in prison while his -appeal is pending. Circuit Court Judge Ric Howard blocked a request by Michael Gerard Burlew to be released from prison until his appeal is heard, according to court records. Burlew, 21, of Dunnellon, argues the 10-year sentence he was given for violating probation is unfair. IVI8c! Burl pleadE contest court He pleaded no contest in January 2002 to two counts of attempted lewd and lascivious acts for having sex with two underage girls, An Oct 9, 2001, arrest report says a girl admitted to authori- ties she and Burlew had sex on several occasions when she was 13 and he was 17. The girl and Burlew were dating at the time, the report says. The girl is now Burlew's fiancee and the couple has a 3- year-old child. During a separate taped interview, the report says Burlew admitted he had had sex with another teenage girl. Although he was originally ordered to three years of sex- offender probation, court records say in 2003 he violated proba- tion for not paying for .... 'sex-offender treatment classes, violating a cur- few requirement and not attending treatment sessions. hael He was cleared of lew that violation and again ed no placed on probation, to two but records say he vio- nts. lated probation on sev- eral occasions after Feb. 2003. A warrant issued for his arrest after the latest violation says he failed to make pay- ments for treatment, and was not at his home in Dunnellon when a probation officer made a curfew check Records say Burlew, who was at his dad's home prepar- ing to move in, did not notify his 'probation officer about the move.. He was sentenced to 15 years in prison. Attorney Paul Pedestrian struck by pickup truck AMY SHANNON ashannon@ chronicleonline.com Chronicle A Homosassa man received serious head injuries Wednes- day night after he was struck by a truck while crossing U.S. 19 just north of the Homosassa Wal-Mart, Florida Highway . Patrol officials reported. Clarence Fugate Jr., of Homosassa, was northbound in the outside lane of U.S. 19 when he struck a man who crossed in front of his red Ford F250 truck around 7 p.m., Trooper Jamie Mulverhill said. "He went out in front of me," Fugate said. "I should have stayed home." A witness, who was north- bound in the inside lane, but an unknown distance behind -Building Beautiful Homes & Lasting Relationships S2003 GRAND AURORA AWARD WINNER! 1-800-286-1551 or 527-1988 ": - 4637 W. Pine Ridge Blvd. SPine Rid e Estates SLTUTE CERTIT IFD: CBCf4 - Bridge Lessons Bridge Lessons For Novices/Intermediates Learn and play a relaxed game with your peers. A basic knowledge of bridge Is necessary. Bridge lessons are free. Game play immediately after or $3.50 with a .ighi lunch provided. Lessons and game held Mondays a 11.00 AM at me Italian Social Club on CR48. Partners are available Bridge Basics I Lessons for Beginers Bridge Basics for beginners is a new 4-week course starting Tuesday. January 11. 2005 at 2-00 PM. Bridge Basics H Lessons For Advancing Players who have Knowledge of Bridge Basics. A 4-week course in / -E', \ competitive bidding will be covered standing February 8. 2005 ai : '' 2:00 PM. For Information call Pat Peterson @ 74607835 LENNOX Up to $1600 INDOOR COMFORT SYSTEM A better placeTM In REBATES and 10% DISCOUNT For full payment upon completion >p7174 811 S. Pleasant Grove Rd., Inverness, FL 26-2202 795-8808 LIC #CMC039568 Fugate, said the pedestrian ran right out in front of Fugate, Mulverhill said. A large streetlight a few feet from the accident was not working Wednesday night Nature Coast EMS and Citrus County sheriff's deputies responded to the crash. Fugate was airlifted to Tampa General Hospital, Mulverhill said. The pedestrian's name could not be released Wednesday night, because next of kin needed to be notified. Militello, who represented Burlew at the time, filed a notice in May claiming the sen- tence was improper because state sentencing guidelines mandate a maximum five-year prison term for each count Following a hearing, Howard reduced Burlew's prison term to 10 years. The appeal notice argues that sentence is still unfair and says Burlew, who was 17 when the alleged acts occurred, should have been eligible'for youthful offender status, according to court records. The appeal argues there's insufficient evidence to sug- gest Burlew violated his proba- tion by moving in with his father, who lives in the Dunnellon area. It also argues he will not be able to see his fiance and their child. As part of his sentence, Burlew is not to have any con- tact with her or the child. Contacted by phone Wednesday, the girl said she wanted her child to have con- tact with Burlew, but is upset she can't do anything about it Burlew's case will move on to the Fifth District Court of Appeal in Daytona. A hearing date has not been scheduled.. FREE Verticals FREE, Wood Blinds SIn Home Consulting Shutters "ValancesCy P SInstallation' it 1 Crystal Pleat ,' S. "Silhouette LECANTO -TREETOPS PLAZA 16N7 W. GULF TO LAKE HWY 527-0012 F -' 0 & I IU UrI-^--"--"-'--, HOURS: MON.-FRI. 9 AM 5 PM Evenings and Weekends by Appointment RYWANT ALVAREZ JONES RUSSO & GUYTON CERTIFIED The Florkla Bar cvI.TI IMAL Board Certified Civil Trial Lawyers The hiring of a lawyer is an important decision that should not be based solely upon advertisements. Before you decide, ask us to send you free Information about our qualifications and experience SFor the RECORD Citrus County Sheriff Domestic battery arrest James David Tidwell, 39, at 1:38 a.m. Tuesday on a charge of domestic battery. A deputy responded to a house on Santos Drive in Dunnellon in ref- erence to a 911 hangup. A 41-year- old Dunnellon woman told the deputy Tidwell yelled at her and punched her several times in the face and head with a closed fist, according to the arrest report. She said Tidwell also kicked her on the left side of her head and choked her. The deputy saw redness and swelling on the right side of the woman's face and r6d marks on the right side of her neck. No bond was set. Other arrests Colleen Barlow, 47, 926 Furman Terrace, Inverness, at 5:42 p.m. Tuesday on a charge of petty theft. She was released on her own recognizance. Todd Paul Ketelhut, 39, 321 Imperial Blvd. unit H91, Lakeland, at 10:36 p.m. Tuesday on charges of fleeing/attempting to elude a police officer, driving under the influence and resisting/obstructing an officer without violence. A.deputy saw a white Plymouth pull out in front of him in Homosassa. The car, driven by Ketelhut, almost caused a collision, according to the arrest report. The deputy attempted to stop Ketelhut, but he accelerated south on U.S. 19 toward Grover Cleveland Boulevard. The man eventually stopped in a parking lot after turning east ,. onto, Grover Cleveland Boulevard. Ketelhut pulled away from the deputy who tried to arrest him. He would not comply, so the deputy deployed his Taser on Ketelhut, ON THE NET For information about arrests made by the Citrus County Sheriff's Office, go to- fcitrus.org and click on the link to Daily Reports. then Arrest Reports. according to the report. His bond was set at $15,500. Richard Parrish, 19, 5699 S. Sandlewood Way, Floral City, at 1:02 a.m. Wednesday on a charge of carrying a concealed weapon. He was released on. his own recognizance. Leslie Thifault, 40, 8050 W. Baja Court., Crystal River, at 12:12 a.m. Wednesday, on a charge of aggravated assault with a deadly weapon. A deputy contacted a man at the comer of Baja Court and Elm Drive in Crystal River in reference to a bat- tery. The man said Thifault hit him in the headtwo to three times with an unknown blunt metal object while he was sleeping, according to the arrest report. The deputy made contact with Thifault at a house on Baja Court. Thifault told the deputy she and the man fought earlier, but she didn't know he had injuries. No bond was set. SO YOU KNOW Obituaries must be sub- mitted by licensed funer- al homes. Obituaries and funeral notices are subject to editing. Recent photos are wel- come. Call Linda Johnson at 563-5660 for details. N \ -- Btd. 1624 N. Meadowcrest Blvd. Crystal River, FL 34429 Beverly Hills office: Visitor '-i Trurmai Buulav ird 3603 N. Lecanto Highway Beverly Hills, FL 106 W. Main St., Inverness, FL 34450 Homosassa office: Beacon 3852 S. Suncoast Blvd., 106 W. MAIN ST., INVERNESS, FL 34450 1 S PERIODICAL POSTAGE PAID AT INVERNESS, FL SECOND CLASS PERMIT #114280 FORMS AVAILABLE * The Chronicle has forms available for wedding and engagement announce- ments, anniversaries, birth announcements and first birthdays. * Call Linda Johnson at 563-5660 for copies. FiorSa's Best Commauninty newspaper Serving ori d's Best Communiilty 5636 Advertisng- 563-5665, Newsroom 563-3280 E-MAIL IT TO US Advertising advertlslng@chronicleonline.com Newsroom: newsdesk@chronlcleonline.com Where to find us: Meadowcrest office Invemess office I AIR SERVICES I i A I -,.Ml I im THURSDAY, JANUARY 6, 2005 5A CiTRrrs CouNnY (FL) CHRONICLE Rodb EM cm 10ehxiMedMtn .~uIliIb S i e frm mmelilews ~0 -. LEARNING Continued from Page 1A Idren receive services now from the school district, and the Readiness Coalition pro- vides subsidized childcare and other early childhood services to about 1,600 preschool chil- dren in Citrus and Sumter counties. The state's voluntary pre-K program only pays for the 540 hours, which could mean three hours per day during the 180- day school year, or six hours a day for just one semester. "There are just more ques- tions than answers, and we're - going to have a lot of frustrated parents," said Nancy Haynes, Citrus County School District's pre-K specialist. If the state will compensate for only three hours of instruc- tion, parents with children in private accredited learning centers will have to pay for the rest of the day, Bosanko said. Parents trying to avoid this M may consider placing children in the school district's pro- Igram. The problem is the district has limited space and accepts children designated as high- risk, which is based on a vari- ety of factors including family income level and Department of Children and Family refer- rals, Haynes said. Another obstacle is accredit- ing learning centers to meet pre-K standards. Currently, two learning centers and two homes are pre-K accredited, said Tom Scheffey, of Childhood Development Services. Eleven are in the final stage of accreditation and five more have begun the process. Charlotte Eadler, of Noah's Arc School Readiness Center in Inverness, attended the meeting with other providers in hopes of deciphering what the legislation will mean for parents, but left with even more questions than she start- ed with. "There's so much that we don't know, and Tallahassee doesn't know that we need to get together," Eadler said. She plans to meet with other providers next week to formu- late a list of questions they have, and discuss what little they do know about the pre-K program. Board member Debbie Lattin also believes parents and providers need to discuss questions and concerns at a public workshop that the coali- tion will soon organize to help educate about the pre-K pro- gram, and also educate parents about the high level of service the learning centers currently provide. "I'm not sure that parents know that the centers are dping and teaching the same things that the schools are," Lattin said. SOUND OFF Call the anonymous Sound Off line at 563. 0579. Be prepared to leave a brief message write it out before calling to make sure you remember everything you want to say. Or try the online Sound Off forum available at. The Chronicle reserves the right to edit Sound Off messages. I gu'Y u Ad tt wd TRIO Continued from Page 1A Wednesda2wafternoon, .but :did not want to comment. She said she lives at the house with her two sisters, but was not home during the rob- bery. Sheriff's officials provided no description of the suspects. . Anyone .with; information about this incident is asked to call the sheriff's office crime tips line at (888) 269-8477. 2x2 Rates Statewide $1200 Regional or national Placement also available Regions: North, South, Central Total Circulation: 2.2 Million 2x4 Rates Statewide $2400 - Regional placement also available Regions: North, South, Central Circulation- 2 2 Million .. .. - -- -- - Wealo adl ntonl lceen! 8 6) 42 1 73 Vii Nwx,.lriiicasi* dsAoi S* No Batting Tees No Pitching Machines S* : Certified Coaching .... '-' Everyone Plays S Sign-ups *Tea at the Knowledge Ted Wiliams A Lot of Fun. and Baseball the Museum will be on: Way it Was Intended /r -. .." :,.. 4 .~- j '..- .. . s .OO'Child .. Sat.. Jan. 8,2005 -9:00 AM to 1:00 PM Sat.. Jan. 15.2005 9:00 AM to 1:00 PM S/ SaWed.. Jan. 19, 2005 5:30PM to 7:30 PM Sat., Jan. 22. 2005*9:00 AM to 1:00 PM 5' FFor adaiorna inlcormaionr, please call program directors. .;, Jeff & Mindy Gordon at (352) 527-4204. OFFICIAL I MERCHANDISE *Hats T-shirts * Jackets Sports Plaques - THE RIVER RATS - BACK BY POPULAR DEMAND Citrus Springs Community Center ", .. .- Three talented guys 'who bombard you with western, swing, blues, ragtime, -1 ballads, and old pop tunes topped off with rib splitting humor! The River Rats STues., Jan. 11, 2005 at 7:00 p.m. Tickets $15.00 Available at: First Federal Savings Bank Inverness and Crystal River Offices or Call 746-7364 12/28/04. World symbol are registered marks of GWFC. 2004 World Savings, FSB N4264-471N o'l .1 *Im my' 1 .---7 I 9 K'WA - t ; Wq i GA THURSDAY, JANUARY 6, 2005 CITRUS COUNTY (FL) CHRONICLE Obituaries m~~~ ____* -. umohdwer (a0' -Cu U -< g^m- *1 w 4 :0 iu~ - S *^^ -r l -CO) I- ^^^r*" ^^ 7a. U Lu. 02 > *NAM --GOP WUI- ON - qp. U - - - ~- U. ~ - -. - U. U. -- - w q no.w - - - U * U. - U. efai. 7Zac ii 'unera 'tHome 'With Crcen.7ar William Chalmers View: Sat. 9am Funeral: Sat. I Oam Chapel Burial: Hills of Rest Cemetery George Beckwith Private cremation arrangements Joe Broska Mass: Fri. 10:00 am Our Lady of Fatima Carl Mills Service: Thurs 10:00 am Chapel Burial: Hills of Rest Cemetery Frederick Swanson, Jr. Private cremation arrangements Barbara Green Private cremation arrangements Edward Blando Private-cremation arrangements 726-8323 cc a -- -E cnE *-~- me0 mm"- U. smo -4 0 U. -7 C m - z.,wu Raymond Elliott, 73 CRYSTAL RIVER Raymond C. Elliott, 73, life- long resident of Crystal River, died Monday, Jan. 3, 2005, at the Veterans Administrati- on Medical Center in Gainesville. He was born Sept 18, 1931, in Crystal River, to John and Minnie Elliott. Mr. Elliott was a self- employed nursery owner and a veteran of the U.S. Army. He was Baptist. Survivors include one son, Ray Elliott of Homosassa; three daughters, Shirley Frazier of Dunnellon, Susan Austin of Beverly Hills and Debbie Fax of Crystal River; two sisters, Mary Willis and Dorothy Smith, both of Crystal River; nine grandchildren; and nine great-grandchildren. Brown Funeral Home and Crematory, Crystal River. Barbara Green, 60 DUNNELLON Barbara Sue Green, 60, Dunnellon, died at her home Thursday, Dec. 30,2004. Born Nov. 19, 1944, in Cincinnati, Ohio, to Noah and Nancy (Holliday) Jones, she moved to this area in May 2004 from Valrico. She worked as a waitress and she enjoyed gardening. She was Baptist She was preceded. in death by her husband of 36 years, Howard Robert Green, on Sept 15, 1998. Survivors include two sons, Howard Michael Green and wife, Brenda, of Valrico and Timothy Green of Dunnellon; two brothers, Eugene Jones and James Jones of Hillsborough, Ohio; and three sisters, Mary Conover of Ohio, Marie Cochran of North Fort Myers and Lena Phlum of Rising Sun, Ind. Chas. E. Davis Funeral Home with Crematory, Inverness. Carole Leeper, 59 JACKSONVILLE Carole Leeper, 59, Jacksonville, formerly' of Crystal River, died Wednesday, Dec. 26, 2004, in Jacksonville. Mrs. Leeper was born Nov. 23, 1945, in Council Bluffs, Iowa, to Paul and Ella Leeper. Survivors include her father, Paul Leeper Sr. of Beverly Hills; sister, Paula Conley of Inverness; and son, Paul Leeper of Lecanto. Heinz Funeral Home and Cremation, Inverness. Anthony Marino, 87 OCALA Anthony Arthur Marino, 87, Ocala, formerly of Crystal River, died Tuesday, Jan. 4, 2005, in Ocala. Born in Roosevelt, HEINZ FUNERAL HOME & Cremation Affordably priced for all. Cremation Specialist Rental Casket Balloon Release Service at Sea Florida National Cemetery 341-1288 Family Owned Service Since 1962. etric lan d Funeral Home andCrematory CRYSTAL RIVER, FL 34423 352-795-2678 Serving the needs of Trus County Veterans I for over 50 years N.Y, he moved to Crystal River in 1978 and to Ocala two years ago. Mr. Marino was a retired excavating contractor and a World War II U.S. Army veter- an. He was Catholic. He was preceded in death by his wife, Anita Marino, in 1993. Survivors include six sons, Arthur Anthony Marino of Miamisburg, Ohio, Donald C. Marino of Lindenhurst, N.Y, Stephen Marino of Putnam Valley, N.Y, Kenneth Marino of Ocala, Thomas Marino of Lindenhurst, N.Y, and Lt Col. Daniel Marino of Belair, Md.; five daughters, Dottie Ann Alligood of Panama City, Anita Marino-Swan of Ellicott City, Md., Nancy Allocca of Sayville, N.Y, Teresa Guthrie of East Moriches, N.Y, and Loretta Kristofek of Orlando; sister, Philomena Crocini of Lakeland; 30 grandchildren; and nine great-grandchildren. Forest Lawn Funeral Home, Ocala. Jane Phillips BEVERLY HILLS Jane A. Phillips, of Pine Ridge, Beverly Hills, formerly of Crystal River, died Wednesday, Jan. 5, 2005, at her home under the care of Hospice of Citrus County. She was a loving wife and true friend to many, with a big heart and a loving smile. She was an English teacher in New Mexico and Missouri before moving to Florida in 1972. She was preceded in death by her parents, Cecil and Clara Anderson. Survivors include her hus-. band, David Phillips; her lov- ing pet children, Maggie, Callie, Gizmo and Skidmore; her brother, Tom Anderson and wife, Jean, of Missouri; father and mother in-law, Luther and Ester Phillips; brother-in-law, Jim Phillips; niece and nephew, Whitney and Roby Anderson. Memorial contributions in memory of Jane Phillips to: Simonton Cancer Center, PO. Box 660, Malibu, CA 90264. Cremation arrangements under the direction of Strickland Funeral Home, Crystal River. James Roach, 51. CRYSTAL RIVER' James Edward Roach, 51, Crystal River, died Monday, Jan. 3, 2005, at home under the care of his family and Hospice of Citrus County. Born Aug. 20, 1953, in Hatfield, Pa., to John and Margaret Roach, he moved to Citrus County in 1999 from Redding, Pa. Mr. Roach was a janitor at the Crystal River Mall. Survivors include his wife, Mary A. Roach of Crystal River; son, James E. Roach Jr. of Quakertown, Pa.; daughter, Heather Roach of Quakertown, Pa.; mother, Margaret Roach of CO jv U" '- * (1i4!~) I.., \ ______ Perkasie, Pa.; brother, Ronald B. Roach of New Jersey; and sister, Kimberly G. Orr of Quakertown, Pa. Heinz Funeral Home and Cremation, Inverness. Ellis 'Al' Turner, 93 DUNNELLON Ellis T. "Al" Turner, 93, Dunnellon, died Sunday, Jan. 2, 2005, at Ocala Regional Medical Center. A native of Hagerstown, Md., he moved to Dunnellon in 1989 from Oxford, Wis., and was retired from farming in Ashton, Ill. Mr. Turner was a member of Hope .Evangelical Lutheran Church in Citrus Springs. He was preceded in death by a son, Glen Turner, in 2004, and two brothers, Carl and Leck Turner. Stdrvivors include his wife of 21 years, Noreen Turner of Dunnellon; two daughters, Sharon Lund and husband, Sig, of Dallas, Ga., and Elaine Hutton and husband, John, of Gray's Lake, Ill.; stepchildren, Millie, Karen and John; eight grandchildren; eight great- grandchildren; and several nieces and nephews. Fero Funeral Home, Dunnellon. Alfred 'Bud' Weiss Jr., 73 HOMOSASSA Alfred "Bud" Weiss Jr, 73, Homosassa, died Monday; Jan. 3, 2005, at home under the care of his wife, Sharon, and Hospice of Citrus County after a nine- month battle with cancer. o Born in US McCaysville, - Ga., he gradu- ated from i Brevard' High School, N.C., in 1949. He graduated from Duke University in 1953. He was a member of the ROTC and served his country as a captain in the U.S. Air Force. He was a former owner of Law & Sons Casket Co. in Denver, Colo., and upon retire- ment he enjoyed working as a stockbroker for many years. He was a member of Rotary International and was very proud of his 31 years of perfect attendance. His Rotary mem- bership included the cities of Denver, Colo., Lakeville, Minn., where he served as president, and the Central Citrus Rotary Club of Florida. He enjoyed sailing, golfing, reading, crossword puzzles and monitoring the financial mar- kets each day. He was gifted at building and repairing most everything. He and Sharon enjoyed traveling to a variety of destinations. Survivors include his wife of 15 years, Sharon; daughters, Melinda Skinner and Mimi Weiss of Aurora, Colo.; stepchildren, Todd Thulen and wife, Andrea, of Medina, Minn., Toni Thulen of Champlin, Minn., and Kristyn Zoibi and husband, Ron, and grandsons, San, Noah and Ramsey of Lake Zurich, Ill.; brother, Gerald Weiss and sister-in-law, Martha Weiss of Springfield, Va., and Charles Weiss of North Augusta, S.C. Hooper Funeral Home, Homosassa. Click on- cleonline.com to view archived local obituaries. Funeral NOTICES Raymond C. Elliott Mem- orial services for Raymond C. Elliott, 73, Crystal River, will be at 4 p.m. Friday, Jan. 7,2005, at the Brown Funeral Home with Pastor Lloyd Bertine officiat- ing. Private cremation will take place under the direction of Brown Funeral Home and Crematory In lieu of flowers, donations can be made to the American Cancer Society. Ahthony Arthur Marino. Funeral Mass for Anthony Arthur Marino, 87, Ocala, for- merly of Crystal River, will be conducted at 10 a.m. Friday, Jan. 7,2005, at St Jude Catholic Church in Marion Oaks, Ocala, with the Rev. Palmese officiat- ing. Interment will be at the Fountains Memorial Park, Homosassa, under the direc- tion of Forest Lawn Funeral Home. Family will receive friends from 6 to 9 p.m. Thursday, Jan. 6, at Forest Lawn Funeral Home, 5740 S. Pine Ave., Ocala. In lieu of flowers, the family requests that memorial donations be made to Hospice of Marion County. Alfred "Bud" Weiss Jr. The service of remembrance for Alfred "Bud" Weiss Jr., 73, Homosassa, will be conducted at 11 a.m. Saturday, Jan. 8, 2005. at the Homosassa Chapel of Hooper Funeral Homes. In lieu of flowers, memorials may be made to Hospice of -Citrus County or Rotaryc hiitern- ational. ,'" V". GO ONLINE Visit to read today's headlines, add your thoughts to the weekly opinion poll. To see manatees at Homosassa Springs Wildlife State Park, go to. Have friends visit the cam- era at while you're out at the springs in King's Bay. 108-0106-THCRN CITRUS COUNTY PLANNING AND DEVELOPMENT REVIEW BOARD THURSDAY JANUARY 13,. APPLICATIONS PUBLIC HEARING ORDINANCE AMENDMENTS (OA) - LAND DEVELOPMENT CODE OA-04-04 Department of Development Services Impact Fee Update REQUEST: An Ordinance of Citrus County, Florida amending Ordinance No. 2001- A06 by providing for updates, as required to the Transportation, Schools, Public Buildings, and Library Elements of the Impact Fee Ordinance; by providing for codification, severability, and an effective date. The County has hired Tindale Oliver Associates, Inc. of Tampa, Florida to prepare a detailed fiscal analysis and technical report to update the fee schedule. The consultants will present their report and be available to answer questions. STAFF CONTACT: Kevin A. Smith, AICP; Assistant Director E. ADDITIONAL ITEMS. 2005 GA THURSDAY, JANUARY 6, ; CiTRus CouNTY (FL) CHRoNicLE f .Mwm ..db- 6 4 0) I CrJFRUS CO.UNTY I (PL) CHRONIC'LEt THURSDAY, JANUARY 6, 2005 7A I, -! ,_.-. --- ME' MR 0o- GP- do% A-Vailab( AvYailabI 1C 0-016 .6 - OPY righntea a v ialle -- Syndicated Content* from Commercial News Providers" o p omoa ~ 4=P - am-nw 0 a-m - -wow *al- o 4 4p 4WD ENNO 4w t mo I -0 AD Ri. so.m- Gap -4b 4w .w -"mom 4w am mm 0 do -own I ft ammp E-maw - m -mom 00 -Of 41t A -4 ob I mom411W -o n Je SAALL OTHER S200 OFF PLASMA TVs LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 --------------------- RI lI &SAF1 LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 I. if Sill"----------- 4 0 a - THIS COUPON EXTENDS THE MANUFACTURER'S WARRANTY (Usually 90 Days) TO A FULL 2 YEARS FROM ORIGINAL DATE OF PURCHASE SPur d0hai ofN99 Or JAf.r, For iewm Ar R ired 4I- ,b-;iaO O ri ife.ims In A Factor, S Sealed Box W Not SuD ecr to Pror Sale Oner ia For inal.dual s Not us'ner:ies See SStore for Detris EXPIRES 1131105 Lmi--m-m ---m--m-m-m--I----- 7 .COUPONS VALID THROUGH .. S CHOOSE FROM RCA, HITACHI, TOSHIBA, JANUARY 8 2005 SONY, PANASONIC & PHILIPS 1 COUPON PER ITEM NOT SUBJECT TO PRIOR SALE -----------------COUPONS CANNOT BE COMBINED WITH ANY OTHER MERCHANDISE COUPON tNO INTEREST FOR 24 MONTHS ON ALL HITACHI BIG SCREEN TV'S NO INTEREST FOR 12 MONTHS ON ALL OTHER PRODUCTS Financing is subject to credit approval. Financing prOvided by CitlFnancial Retail Services Division of CitiCorp Trust Bank, fsb. No Interest for 12 months offer applies to purchase of $799 or more. Fninace Charges begin to accrue at time of purchase. In order for finance charges to be waived, minimum monthly payments of the greater of,$15 or 3% of the amount financed must be made and payment in full required within 12 months. No interest for 24 months offer applies to Hitachi Big Screen TV's purchased by January 31, 2005;,1/24 of purchase price required to be paid monthly for 24 months, oth- | I lMI 'T rrONE COII ON p ER I EM* EX P i s '-erwlise'standard rates and charges apply. Standard rate 23.99% APR. Default rate 26.99% APR. Minimum monthly finance charge $.50. Offer isor individuals, not businesses. Other financing plans avail- "m' LIMIT OeN CmP E xr mIE1i/ able. See store for complete details, " I IY CHOOSE FROM SHARP, JVC, TOSHIBA, I I CHOOSE FROM SONY, TOSHIBA, ,SONY, PANASONIC & APEX A MAGNAVOX & APEX LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 M --- ---- ---- -- ---- a --- ---- --- -----16 E S a V, CHOOSE FROM JVC, SHARP, SONY, RS S CHOOSE FROM SHARP, SONY, JVC, CHOOSE FROM KLH, PIONEER, SONY, \I ANONHITACHI&PANASOnN~ICI~ 1 PANASONIC, MAGNAVOX & PIONEER i ICERWIN-VEGA, PANASONIC & JENSEN CANON, HITACHI & PANASONIC I C LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 ... ..I I I I CHOOSE FROM JVC, PIONEER, CHOOSE FROM SONY, PANASONIC, RCA, CHOOSE FROM AUDIOVOX, JVC, DUAL, fPANASONIC & SONY I PIONEER, PHILIPS, TOSHIBA & APEX PIONEER, JENSEN, SONY & PANASONIC MT ONEmOUPON ERITEEXPRES LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 - - -- -0 CHOOSE FROM I !J/0 y CHOOSE FROM PANASONIC, I Jl 4 CHOOSE FROM BUSH, GUSDORF, OAK WEST, SONY, JVC &MAGNAVOX | SHARP & SAMSU ,OSULLIVAN, TECHCRA & SOUTH SHORE SONY, JVC & MAGNAVOX-SHARP& SAMSUNG LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 R----cm--- U--010- --to-------- a-- C10010------ I W----. II I ISSSS J CHOOSE FROM SHARP, I R| Cl d7s% PANASONIC & DIRT DEVIL I ---- ------------------I SUNDAY 12 PM TO 6 PM MON. T RIVER MALL Ar % N ; I .. ...." I I I V SAVE ON WASHERS, DRYERS, RANGES, DEHUMIDIFIERS,I REFRIGERATORS, DISHWASHERS & FREEZERS I* f fT LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 --- -------------------..aumm a HRU SAT. 10 AM TO 9 PM CRYSTAL RIVER 2061 NW HWY. 19 1/2 Mile North Of Crystal River Mall 795-3400 I I WW LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 L--------------------- VISA BUSINESSES, CONTRACTORS OR SCHOOLS CALL: 1-800-528-9739 IN WRITING. IF YOU FIND ANY OTHER LOCAL STORE (EXCEPT INTERNET) STOCKING AND OFFERING TO SELL FOR LESS THE IDENTICAL ITEM IN A FACTORY , SEALED BOX WITHIN 30 DAYS AFTER YOUR REX PURCHASE, WE'LL REFUND THE DIFFERENCE PLUS AN ADDITIONAL 25% OF THE DIFFERENCE. 012 .,- T~TQr )T1 lT. TR ii1 STATE 41 bW m-M sm- .- - mb q 'WI, CHOOSE FROM SONY, RCA, TOSHIBA, PANASONIC, JVC AND SHARP I R Eff -Ay LIMIT ONE COUPON PER ITEM EXPIRES 1/8/2005 - - - - - - - - - - STOCKS SA THURSDAY, JANUARY 6, 2005 CITRUS COUNTY (FL) CHRONICLE TH ARE I EVE Mo*T ACTIVE ($1 OR MORE) Name Vol (00) Last Chg Lucent 449894 3.64 -.08 Pfizer 274314 26.27 -.18 AMD 191282 19.75 -.46 GenElec 189075 35.93 -.22 Citigrp 187345 48.46 +.60 GAINERS ($2 OR MORE) Name Last Chg %Chg Too inc 27.71 +3.48 +14.4 LSI Log 5.73 +.71 +14.1 UniFirst 31.96 +3.15 +10.9 Salesforc n 17.95 +1.59 +9.7 Cryolite 6.90 +.35 +5.3 LOSERS ($2 OR MORE) Name Last Chg %Chg InputOut 6.90 -1.41 -17.0 . AmWest 5.59 -.66 -10.6 Bluegreen 16.49 -1.91 -10.4 AMR 9.05 -.96 -9.6 RegisCp 41.10 -4.10 -9.1 DIARY Advanced 916 Declined 2,391 Unchanged 144 Total issues 3,451 New Highs 32 New Lows 14 Volume 2,129,814,490 MOST ACTIVE ($1 OR MORE) Name Vol (00) Last Chg SPDR 630013 118.01 -.72 SemiHTr 358663 31.35 -.55 iShRs2000 147317 122.58 -2.50 DJIA Diam 107550 105.71 -.59 iShJapan 58980 10.60 -.01 GAINERS ($2 OR MORE) Name Last Chg %Chg FmkCap 18.42 +4.17 +29.3 Calcasieu 12.25 +1.95 +18.9 TriValley 9.84 +1.11 +12.7 NevGCas 13.73 +1.32 +10.6 VKCal 11.00 +.90 +8.9 LOSERS (52 OR MORE) Name Last Chg %Chg Webcolnd 9.26 -1.72 -15.7 GmbriCp 3.79 -.48 -11.2 Arhyth 17.81 -2.19 -11.0 TitanPhm 2.70 -.32 -10.6 Drydean 3.06 -.35 -10.3 DIARY Advanced 303 Declined 630 Unchanged 87 Total issues 1,020 New Highs 17 New Lows 10 Volume 271,779,690 MOST ACTIVE ($1 OR MORE) Name Vol (00) Last Chg Nasd100Tr 1246522 38.54 -.24 SiriusS 1038000 7.64 +.13 StemCells 805417 5.56 -.41 Intel 728432 22.39. -.22 Microsoft 703557 26.78 -.06 GAINERS ($2 OR MORE) Name Last Chg %Chg RickCab 3.78 +.93 +32.6 IsonicswtC 4.11 +.86 +26.5 KeryxBio 14.18 +2.95 +26.3 EducLend 18.94 +3.52 +22.8 Tarragon s 22.00 +3.90 +21.5 LOSERS (S2 OR MORE) Name Last Chg %Chg Innodata 6.87 -2.42 -26.0 WoidGate 4.81 -1.54 Trmfrd 5.10 -1.50 Phazar 35.22 -10.23 Chindexs 8.25 -1.75 DIARY Advanced Declined Unchanged Total issues . New Highs New Lows Volume -24.3 -22.7 -22.5 -17.5 910 2,250 111 3,271 39 19 2,359,097,013 Ies Tables show name. price and nel change. and one to two ariditiOnal [ehld roialed througri ihe week as lollows DIv: Current annual dividend rale paid on stock, Dased on latest quanerly or serniannual declaration, unless otherwise footnoted Name: Stocks appear alpnabelically Dy Ine company's fult name (not its atbreviatiop) Names conisiting or inlitals appear at the beginning of each letter s list. Last: Price stock was trading at when exchange closed for the day Chg: Loss or gain for me clay No change indicated by . L.. ri.., ujm ,r.. ! .44 ACELId :w 1 10 ACM I 1 ir ACMOP . r ACMSo. Stock Footnotes. cc PE grealr ian 99' :.. I u6 h.A be ar, i.allfd itC redemptionl by -. N e Lat Ch c.,rlp.any ,. d rNe 52 sek I.:.w ad LCss Irn lils 12 n'm l Ci,,,T.parey Irrreiy 1,3 i Ed 24.8 .13 on Ir,. Amrr.rcan E vcn3rrqe Emerging Cornmpran Ma3.eipla.a g D d oena ana eanu . I ,r,. Car.a rJhor, >.i'la h le lr ly E.m prl rojm jNaid, apial .and .urpjlu Ilting quoii..icn ., Si.i u, r.ew iEU r, Ira s I arre a .i3j- n rir3.1 1, Ag ule-0 datla 6l-r ir:.mra c5 tg.rir.rij ul rr.sirg p. Prtlrd iut s. pr Flai'vsrn. e. pp HoI-.r one. in:ialSerit5 1 p .ufr.a e price q Cros5d-erid Tiualual uri no PE cal cZaulaid n Rignt To ibuy 0-:urlv at a 6peaolie,2 prrn. . Sl'tk r.: 'rilbl ya 61 lea ..20 pFrcent lflrin ir- Iiil 41.3r Trae. a lill be Ei.d wher. [tI4r -.:i I u J Isued .d - Wher- adii:r.utrJ tl Wair,ar,. .h .r9rig a rurns5 6 :.Il 6C.: u i rija w .s.,k eh gh u.' Suit inCludlnr.] marl rr3.x One -Curry vi CTiprrv in birarinkruipy or rCen.6ar'lip, or ,, . t,i.n r-rg ari:ed under rhe bar.kruprcy law Apa drs ir front l irin ame ' Dividend Footnotes a. Elira dldfenL2s ere p iJ bul aie rt included' b Ar r.al rate plul sik.k ULiquidatig n ivdieind ? Anour.n a ,ciared or [ aid in lasI 12 nr:.nltrr i . Curntl annual rala el.l:r, Wa. h',rrs.ai dj Dy rnr.il r.:rnl diUid'rd onr,.urlCtelni I Sum c.t l Id ndi paid ller siOC spiln ro e ,iular rail Sum ul dl ldan ls paid INSI r = Mosi recent dividend wea orriilead cor Ocfatrad I k ere or pinta irisi yea as cumulia Id 24 -1 nrie i':ua wmn aii..rmNI ir. arnreara m Curratfl annual rate .wn.Ch wa O.acreasO25 b i.up 7 .1 . rc. l i.1intrliiaenrd a'irun.Larr,ient p. Inlial dividend anrnual rle inot ncr-, 'ivld noI t 'M 0-12. srcrn r Dl&rea >orr pall in pra:ading 12 ronlflhapiilSl ch aI, lvidnrd I P Fd iln alok approliallm cCash ialuje on X-di]nulbionldai1 Source: The Associated Press. Sales figures are unofficial. ISTOC S O LCL NERS YTD Name Div YId PE Last Chg %Chg Name Div YId PE Last AT&T .95 5.1 ... 18.49 AmSouth 1.00 3.9 15 25.73 BkofAm s 1.80 4.0 12 45.25 BellSouth 1.08 4.0 12 27.27 CapCtyBk .76 1.9 19 40.62 Citigrp 1.60 3.3 15 48.46 Disney .24 .9 24 27.40 EKodak .50 1.5 14 32.35 ExxonMbI 1.08 2.2 14 49.49 FPLGp 2.72 3.8 15 72.06 FlaRock s .80 1.4 22 55.80 FordM .40 2.8 12 14.43 GenElec .88 2.4 23 35.93 GnMotr 2.00 5.1 5 39.12 HomeDp .34 .8 19 42.16 Intel .32 1.4 18 22.39 IBM .72 .7 21 96.50 YTD Chg %Chg LowesCos .16 .3' 21 56.27 -.48 -2.3 McDnlds .55 1.7 20 31.83 -.25 -.7 Microsoft .32 1.2 34 26.78 -.06 +.2 Motorola .16 1.0 30 16.52 -.20 -4.0 Penney .50 1.2 ... 40.80 +.22 -1.4 ProgrssEn2.36 5.3 16 44.23 -.12 -2.2 Sears .92 1.8 24 50.40 -1.40 -1.2 SpmtFON .50 2.1 ... 24.16 +.11 -2.8 TimeWarn ... ...31 18.91 -.19 -2.8 UniFirst .15 .5 18 31.96 +3.15 +13.0 VerizonCml.54 3.8 34 40.02 -.06 -1.2 Wachovia 1.84 3.5 14 52.21 +.56 -.7 WalMart .52 1.0 23 53.29 +.07 +.9 Walgrn .21 .5 30 41.12 +1.03 +7.2 INEE 52-Week High Low Name Net % YTD 52-WK Last Chg Chg % Chg % Chg NE OKSTOCKEXCANG Tkr "Name Last Chg ABB ABB Lid 5.66 +.06 A ACE Lid 42.19 -.03 ACG ACMInco 8.18 +.02 AES1,AESCp 13.02 -.03 AFL AFLAC 39.38 -.29 AG JiAGCO 20.78 -.04 ATG AGL Res 32.46 -.05 AKS -AKSteel 12.93 -.36" AML-AMULRs 29.70 -1.30 AMR AMR 9.05 -.96 ASA ASALtd 38.27 -.08 T AT&T 18.49 +.16 AUC UOptron 13.35 +.03 AXA AXA, 23.99 -.09 ABT tLab 45.67 -.53 ANF rFitc u47.47 +.19 AC l nature 25.65 -.10. ADX daEx 12.80 -.04 KAR desan 19.90 -.60 AM MD 19.75 -.46 ARC ropsi s 28.57 -.93 AET Aetna 121.83 +1.18 ACS AffCmpS 58.25 -.01 0AGF Aqere 1.44 +.04 AGF AgereB 1.44 +.08 A Agilent 2324 -.01 AES Agnicog 12.98 -.20 AGL iAgrumg 14.75 -1.19 AH old 7.85 -20 APD rProd 56.99 +.05 SAAI irTran 9.47 -.45 ALK IskAir 30.55 -.71 ABS bertsn 23.28 +.03 ABS Abrtsnun 24.90 +.01 AL Alcan 46.82 -.83 ALA Acatel 14.84 -.13 AA 'lcoa 30.25 -.18 AYE IllgEngy 18.82 -.21 ATI AllegTch 19.25 -.56 ALE Alleles 36.74 +.89 AC liCap 40.79 -.13 AGI liGam 12.50 -.45 AWI 'lWri2 12.30 -.04 AW dWaste 8.85 -.23 AFC IlmrFn 31.75 -.58 ALL slate 50.65 -.40 AT hlel 58.00 -20 ALO Iphamla 15.84 -32 SMO .da 60.94 -.11 DOX Amdocs 25.50. +.04 AHC 'mAnHess 79.00 -.50 AEE Ameren 48.38 -.44 AMX AMovilL 49.94 -1.13 AWAVAmWest 5.59 -.66 AEP AEP 33.49 -.40 AEL .AEqlnvU 10.54 -.05 AXP 'AmExp 54.44 -.51 'AFR AFnclRT, 15.17 -63 AM /AGreel 24.25 -.10 AIG -AmlntGp 67.35 +1.10 ASD AmSds 40.29 -.56 CSP KAmSiP3 12.23 -.10 AMT AmTower 17.76 -.16 ACF, A.neicidt 23.53 -.17 ABC ''AmedsBrg 57.58 -.11 ASO AinSouth 25.73 +.03 APCA Anadrk 60.40 -1.02 ADI AnalogDev 35.56 +.16 AU AnglogldA 34.27 +.24 BUD Anheusr, 49.95 -.53 ANN AnnTaylr.s 20.59 +.02 NLY iAnnaly 18.15 -.86 ANH 'Anworth ,d10.04 -.33 AOC AonCorp 22.73 -.63 APA "'Apache s 47.73 -.16 AIV Aptlnv 36.25 -1.60 ABI pApplBio 20.22 +.02 WTR AquaAm 23.96 +.15 ILA Aquila 3.52 -.04 ACI ArchCoal 33.63 -.17 ADM ArchDan 21.35 -.37 ASN ArchstlnSm 35.20 -1.44 AH ArmlorH 45.56 +2.05 ARW AnowEl 23.81 +.28 ASH Ashland 55.22 -.69 AEC AsdEstat 9.75 -.29 ATO TMOS 26.50 -.18 AN gAutoNatn 19.00 +.05 ADP AutoData 42.97 -.18 AZO FAutoZone 90.29 +.59 AVB iAvalonBay 70.02 -3.55 AV Avaya 17.00 -.03 AVL Aviall 22.32 +.15 AVP IAvons 37.45 -.19 BBT BB&TCp 42.05 +.25 BHP BHP BilILt 2272 +.07 BJS BJSvcIf 43.66 -.59 BJBJJsWhIs 27.51 -.29 BMC BMCSit 17.00 -.07 BP BPPLC 56.70 +.09 BRT BRT 24.30 +.05 BHI BakrHu 41.32 -.14 BLL BalICps 42.35 -1.03 BBD BcoBrads 23.30 -.19 BAC BkofAms 4525 -.57 BK BkNY 32.65 +.05 BNK Banknorth 36.40 -.08 BN Banta 43.21 -.99 BRL BarrPhms 45.31 +1.31 ABX BarickG 22.59 -.30 OL BauschL 62.00 -1.40 BAX Baxter u34.92 +.37 BSC BearSt 102.31 +.96 BE BearingPt 7.64 -.05 BZH BeazrHm 135.92 -.86 BEC BeckCoul 65.00 -.18 BOX BectDck 55.05 -.31 BLS BellSouth 2727 BBY BestBuy 58.05 +,35 BLI BigLots 11,33 BDK BlackD 85.35 -1.25 BKH BIkHICp 29.99' -.12 BRF BIkFL08 15.90 -.14 HRB BiockHR 46.91 -1.19 BBI Blockbstr 9.45 +.32 BLU BlueChp 6,49 XG Bluegreen 16.9 -1.91 BA Boeing 50.81 +.83 BGP Borders 24.06 -.27 SAM BostBeer 21.49 +:18 BXP BostProp 60.10 -2.46 BSX BostonSci 34.70 +.53 BOW Bowatr 41.78 -1.24 BDY BradPhm 15.15 -.60 EAT Brinker 34.50 -.17 BMY BrMySq 24.79 -.08 BG BungeLt 53.94 -1.39 BNI BudNSF 44.83 -.30 BR BuriRscs 40.55 -.33 CBG CBREilisn 31.82 -94 CHG CH Engy 47.38 -.07 Cl CIGNA 78.92 -.50 CIT CIT Gp 42.75 -2.04 CKR CKERst 14.11 -.03 CMS CMSEng 10.11 -.14 CSS CSS Inds 3152 -.08 CSX CSX 38.83 -.15 CVS CVS Cp 45.25 +.76 CVC CabivsnNY24'92 -.73 CAI CACI 63.20 +.28 CDN Cadence 13.31 +.01 CZR Caesars 19.70 +.11 ELY CallGolf 12.23 -44 CPN Calpine 3.44 -.11 CPB CampSp 29.66 -.23 COF CapOne 81.43 -.62. CMOpB CapMpfB 13.40 -19 CAH CardnlHih 55.43 -.13 CMX CaremkRxu40.75 +1.30 CCL Carnival 56.95 -.10 POS CatalMktg 27.11 -1.57 CAT Caterpilhr 92.22 -1.80 CLS Celesticg 13.07 -.42 CX Cemex 34.91 -.91 CD Cendant 22.54 -.24 CNP CenterPnt 10.75 -.20 CTX Centexs 54.74 -.86 CTL CntryTel 33.65 -.64 CEN Ceridian 17.64 -.05 CHB ChmpE 11.78 -25 CKP Checkpnt 16.56 -.90 CHK ChesEng 15.22 -.12 CVX ChevTexs 50.88 +.33 CME ChiMerc 217.50 +3.00 CHS ChicosFAS 44.31 +.41 CHL ChinaMble 15.70 -.49 CHU ChinaUni, 7.37 -.20 CB Chubb 75.16 -.09 CBB CinciBell 3.95 -.24 CIN CINergy 40.00 -.40 CC CircCtty 13.71 -1.25 C Citigro 48.46 +.60 CZN CizComm 13.40 +.07 CLE ClaJresStrs 20.67 +.07 CCU ClearChan 31.80 -.75 CLX Clorox 57.46 -.29 COH Coach 53.90 +.05 KO CocaCl 40.77 -.19 CCE CocaCE 20.65 -.15 CDE Coeur 3.59 -.02 CL ColgPal 48.55 -1.12 CMK CcIIntln 9.25 +.09 CBH CmcSNJ 61.62 -.72 CMC CmclMtl 48.18 -1.51 CTV ComScop 18.00 -.17 RIO CVRDas 26.05 -.63 RIOp CVRDpts 22,06 -.26 CA CompAs 29.34 -.41 CSC CompSci 54.32 -.24 CAG ConAgra 28.84 -.29 COP ConocPhil 84.18 +.62 CNX ConsolEgy 37.90 -.75 ED ConEd 42.70 -.47 CEG ConstellEn 43.20 +..04 CAL CtlAirB 11,21 -.99 CVG Cnvrgys 14.66 +.19 COO CooperCo 72.51 +1.45 GLW Comrna 11.40 -.13 CFC CntwdFns 35.54 -.68 CVH Coventry 52.50 +.69 CEI CresRE 17.40 -.41 CK Crompton 10.87 -.47 CCI CwnCstle 16.55 +.40 CCK CrownHold 13.15 -.30 CMI Cummins 76.87 -3.50 CY CypSem 10.60 -.22 DNP DNPSeIct 11.48 -.19 DPL DPL 24.37 -.25 DHI DR Hortn 36.80 -.81 DST DSTSys 49.77 -.52 DTE DTE 42.50 -.25 DCN DanaCp 16.83 -.17 DHR Danahers 55.37 -.28 DRI Darden 26.37 -.78 DF DeanFds 31.74 -.57 DE Deere 70.51 -.69 DLM DelMnte 11.00 -.05 DPH Delphi 8.40 -.15 DAL DeltaAIr 6.80 -.51 DNR Denbury 24.89 -.93 DT DeutTel. 22.14 -.04 DDR DevDV 41.20 -1.70 DVN DevonEs 36.60 -.51 DO DiaOffs 38.25 -.04 DDS Dillards 26.18 -.13 DTV DirecTV 16.00 -.05 DIS Disney 27.40 -.15 DG DollarG 20.94 +.13 D DomRes 66.70 -.47 RRD DonlleyRR 33.90 -.45 DOV Dover 40.19 -.80 DOW DowChm 47.90 -.49 DD DuPont 47.42 -.64 DUK DukeEgy 24.61 -.19 DRE DukeRlty 32.00 -1.18 DQE DuqUght 18.26 -.13 DY Dycom 27.75 -.68 DYN Dynegy 4.39 -.03 ET ETrade 13.85 -.25 EMC EMCCp 14.05 -.26 EOG EOGRes 64.95 -55 EMN EastChm 51.61 -.5B EK EKodak 32.35 -.14 ETN Eatons 68.20 -1.01 ECL EcOlab 33.83 -.33 EIX Edisonlnt 31.17 -.51 .AGE Edwards 42.40 +.03 EP ElPasoCo 10.07 -.09 ELN Elan 27.45 +.05 EDS EDS 22.09 -.40 EMR EmrsnEI 67.29 -.61 EDE EmpDIst 22.00 -.15 ELX Emulex 16.41 -.12 EEP EnbrEPtrs 49.91 -.44 ECA EnCanag 53.23 -1.20 EAS EgyEast 26.55 -.11 'EC EnglCp 29.49 -.32 NPO EnPro 27.91 -.65 ESV ENSCO 30.50 +.15 ETR Entergy 64.88 -1.06 EPD EntPrPI 24.95 -.35 ENN Eqtyinn 11.20 -.31 EOP EqOffPT 27.69 -.86 EQR EqtyRsd 34.10 -1.13 EL EsteeLdr 43.82 -.85 EXC Exelons 42.30 -.64 XOM ExxonMbl 49.49 -.26 FPL FPLGp 72.06 -.94 FCS FairchldS 14.55 -.55 FDO FamDIr 30.21 +.04 FNM FannIMae 69.80 -.11 FDX FedExCp 95.54 -.12 FSS FedSIgnI 17.25 -.02 FD FedrDS 57.22 -.32 FMP Feldmann 13.00 FGP' Ferreligs 20.40 FOE Ferro 21.60 -1.37 FNF FIdelFin 45.00 -.34. FDC FrslData 41.86 +.42 FF FFinFds 19,80 -.21 FHN FslHorizon 42.54 -.04 FE FirslEngy 38,90 -.32 FSH FishrSci 60.29 -.43 FRK FlaRocks 55.80 -.55 F FordM 14.43 -23, FpS FordC pIS 52.35 -49 FRX ForestLab 41.70 -1.22 FST ForestOlI 29.50 -1.03 FO FortuneBr 75.13 -,.70 FOX FoxEnt 30.96 -.37 BEN FrankRes 68.08 -.99 FRE FredMac 71.28 -.57 FCX FMCG 35.33 -.41 FSL Freescale n 16.52 -.44 FSUB FreescBn 16.87 -.38 FMT Fremont 23.47 -.76 FBR FriedBR 18.32 -.36 FRO Frontline s 43.10 +1.86 GMT GATX 27.30 -.85 GAE" GabelliET 8.82 -.11 GC .Gannett 80.30 -.50 GPS Gap 20.74 +.09 GTW Gateway 5.50 -.14, GY' GenCorp 17.47 -.36 DNA Genentchs 53.15 +1.40 GD GenDyn 99.27 -.10 GE GenElec 35.93 -.22 GGP GnGrthPrp 33.54 -1.19 GMR GnMarit 35.95 -.05 GIS GenMills 49.75 +1.00 GM GnMotr 39.12 -.77 GPM GMdb33 26.17 -.30 GP GaPacil 36.01 -.09 G Gillette 43.87 -.48 GLG Glamls 15.74 -.38 GSK GlaxoSKIn 46.41 -.19 GSF GlobalSFe 32.41 -.01 GFI GoldFLtd 12.25 +.21 GG Goldorp g 13.86 -.19 GDW GoldWFs 59.57'-1.21 GS GoldmanS 103.80 -.47 GR Goodrich 30.88 -.61 GT Goodyear 14.34 -.12 GRA viGrace 12.84 -.56 GTI GrafTech 8.71 -.30 GRP GranlPrae 18.29 -.62, GXP GtPlalnEn 29.80 -.13 GMP GMP 28.56 -.01 GFF Griffon 26.15 -.65 GTK Gtechs 24.90 -.47 GSH GuangRy 19.90 GDT Guidant 71.77 -.11 HCA HCAInc 39.33 -.46 HRPT Prp 12.08 Hallibtn 37.58 HanJS 15.65 HanPtDlIv 9.96 HanPtDv2 11.65 HarleyD 59.78 HarmonyG 9.02 HarrahE 65.23 Harris 56.85 HartfdFn 67.75 Hasbro 18.90 HattSe 14.58 HawaliEl s 28.05 HItCrREIT 35.33 HiMgt 22.46 HNthcrRlty 37.40 HL HeclaM 5.55 -.04 HNZ Heinz 38.23 -.16 OTE HellnTel 8.46 -.11 HPC Hercules 14.19 -.20 HSY Heisheys 53.61 -1.33 HPQ HewlettP 21.00 +.09 HIW HIghwdP 25.39 -1.26 HLT Hion 22.15 -.09 HD HomeDo 42.16 -.39 HON Honwilinl 34.57 -.10 HPT HospPT 42.67 -1.66 HMT HostMan 16.27 -.58 HOV HovnanE s 45.51 -36 HUG HughSups 30.84 -.47 HUM Humana 29.70 +.60 IBN ICICIBk 18.35 -1.42 RX IMS Hih 22.22 -.28 DVY iShDJDv 59.68 -.47 IDA Idacorp 29.36 -.3B ITW ITW 92.12 +.54 IMN Imatuon 30.80 -.71 IMH ImpacMtg 20.92 -.97 N INCO 33.94 -1.07 IR IngerRd 75.55 -1.74 IM IngrmM 19.34 -.17 10 InputOut 6.90 -1.41 IBM IBM 96.50 -.20 IGT IntlGame 33.59 -.21 IP IntPap 41.59 +.59 IRF IntRect 40.18 -.72 ISG IntSteel 39.30 -.44 IPG Interpublic 13.19 -.02 ION Ionics 43.30 +.03 IRM IronMIns 29.32 +.36 JPM JPMorCh 38,49 +.08 JBL Jabil 23,57 -.50 JNJ JohnJn 62.66 -.04 JCI JohnsnCti 61.44 -.54 KBH KB Home 98.65 -.49 KCS KCSEn 13.54 -.02 KDN Kaydon 31,37 -.55 K Kellogg 44,47 +.27 KWD Kellwood 31.85 -.76 KEM KemetCp 8.35 -.04 KMG KerrMc 55.47 -.26 KEG KeyEng I '10.76 -.27 KEY Keycorp 33,08 -.22 KSE KeySpan 38.51 -.49 KMB KImbClk 63.47 -1.11 KMI KIndMorg 69.85 -.50 KCI KineticC n 70.10 -2.10 KG KingPhrm 12.25 +.02 KGC Kinrossg 6.67 -.12 KSS Kohls 48.08 +.38 KEP KoreaEIc 12.76 -.29 KFT Kraft 34.46 -.28 KKD KrspKrmn 9.70 -.78 KR Kroger 16,55 -.14 LLL L-3 Com 68.97 +.91 LRT LLE Ry 6.30 +.23 LSI LSI Loa 5.73 +.71 LTC LTCPrp 18.99 -.98 LZB LaZBoy 14.38 -.50 LQI LaQulnta 8.99 LH LabCp 47.88 -.61 LG Laclede 29.72 -.35 LM LeggMass 69.55 -.63 LEH LehmBr 86.35 +.50 LEN LennarAs 52.93 .50 LXK Lexmark. 84.40 +.88 ASG LbtyASG 6.40 -.08 L UbtvMA 10.51 -.18 LLY UllyEli 56.08 +.58 LTD. Limited 22.62 +.26 LNC UncNat 46.20 -.10 LNN Undsay 23.95 -1.28 LGF UonsGtg 9.96 -.24 LMT LockhdM 54.63 +1.34 LPX LaPac 25.07 -.70 LOW LowesCos 56.27 -.48 LU Lucent 3.64 -.08 LYO Lyondell 27.46 -.64 MTB M&TBk 105.26 -.16 KRB MBNA 27.60 -.09 MDU MDU Res 25.77 -.45 WFR MEMC 11.87 -24 MCR MCR 8.78 -.06 MGG MGMMr 72.40 +1.28 MPS MPSGrp 11.44 -.12 MAC Macerich 58.2Q -2.95 MAD Madeco 10.03 -.10 MGA Magnalg 79.05 -1.06 MHR MagnHunt 11.65 -.45 MHY MgdHi 6.49 -.02 MFC Manulifg 45.08 -.60 MRO Marathon 35.73 -.44 MAR MarinIA 61.62 +.04 MMC MarshM 32.70 -.30 MI Marshils 43,53 +.35 MSO MStewrt .27.91 -.86 MVL MarvelEs 19.12 -.61 MAS Masco 35.10 -.51 MEE MasseyEn 32.19 -1.07 MSC MatScI 16.90 +.10 MAT Mattel 18.89 -.30 MXO Maxtor 4.98 -.01 MAY MayDS 29.14 +.08 MYG Maylag 19.29 -.75 MCD McDnlds 31.83 -.25 MCK McKesson 30,66 -.01 MFE McAfee 26.63 -.55 MWV MeadWvco 32,55 -25 MHS MedcoHIth u42.35 +.55 MDT Medimic 48.75 -.36 MEL MellonFnc 30,05 -.13 MRK Merck 31.34 +.21 TMR MeridRes 5.52 -.12 MHX MerStHsp 7.77 -.33 MER MerdllLyn 58.09 -.21 MET MetUfe 39.65 -.26 MU MicronT 11.53 -.13 MAA MIdAApt 39.20 -1.51 MDS Midas 19.51 -.28 MZ Mllacron 3.19 -.01 MIL MIllpore 47.94 -.50 MLS MillsCp 59.60 -1.90 MSA MineSafs 46.71 -1.99 MEpA MisplAcld 25.14 MTF MtsuTkyo 9.96 +.18 MBT MobileTel s 32.80 -.34 MON Monsnlo 51.00 -1 34 MWD MorgStan 54.98 -.32 MSF MSEmMkt 16.75 -.41 MOS Mosaic 14.95 -.36 MOT Motorola 16.52 -.20 MEN MunlenhFd 10.85 +.05 MYL Mylanlab 17.03 -.16 NTY NBTY 23.47 +.06 NCR NCRCp 66.72 .-18 NRG NRG Egy n 34.28 -.43 NLC NalcoHidn 19.52 +.01 NCC NatlCiy 36.34 -.39 NFG NatFuGas 26.86 -29 NGG NatGrid 47.38 +.30 NOI NatOIlwl 33.60 -.33 NSM NatSemis 16.88 -.03 NAV Navistar 41.30 -1.49 HYB NewAm 2.19 NEW NwCentFn 58.55 -2.93 NJR NJRscs 4227 -.18 NXL NPlanExl 25.64 -.84 NYB NYCmtys 19.39 -.74 NWL NewellRub 23.15 -.49 NEM NewmtM 41.67 +.10 NR NwpkRs 4.93 -.04 NWS/ANewsCoAn 18.14 -.17 NWS NewsCpBn18.62 -18 NI NISource 21,89 -.13 GAS Nicor 35.77 -.24 NKE NikeB 88.33 -1.07 NE NobleCoip 47.31 NBL NobleEngy 56.11 -1.28 NOK NoklaCp 15.52 JWN Nordstr 47.06 +1.44 NSC NorlkSo 35.89 +.65 NT NrtelN II 3.36 +.01 NFB NoFrkBcs 28.21 -.51 NU NoestUt 18.15 -.17 NBP NoBordr 47.26 +.08 NOC NorthrpGs 53.30 +.80 NVS Noarls 48.86 -.19 NFI NovaSlar 45.70 -1.03 NST NSTAR 53.24 -.34 NUS NuSkin 22.98 -1.61 NUE Nucors 49.68 -.44 NQF NvFL 15.35 +.09 NIO NvIMO 15.87 +.08 OCA OCAInc 5.90 -.19 OGE OGE Engy 25.32 -.34 OMG OMGrplf 30,08 -.79 OMM OMI Cp 15.71 +21 OXY OcclPet 55.61 -.31 ODP OffcDpt 16.61 -.21 OMX OfficeMax 29.91 -1.77 OLN Olin 20.43 -.42 OMC 'Omnicom 84.15 -.40 ORB OrbitalSc o10.85 -.10 OSK OshkshTk 64.44 -.70 OSI OulbkStk 43.99 -.86 OSG OvShip 52.30 +.06 OI Owensill 21.41 -.59 OXM Oxfordinds 37.31 -2.45 PCG PG&ECp 32.37 -.40 PNC PNC 55.67 -.50 PNM PNM Res s 24.21 -.36 PKX POSCO% 41.94 -.84 PPG PPG 64.80 -.93 PPL PPLCorp. 51.69 -.75 PHS PacrfCres 56.55 +1.91 PTV Pactiv 24.65 -.34 PRX ParPharm 42.20 -.83 PH ParkHan 71.81 -1.30 POG Patinas 35.40 -.46 PSS PaylShoe 11.95 +.16 BTU PeabdyE 74.31 -2.05 PGH Pengrthg 20.22 +.68 PVR PenVaRs 48.48 -.68 JCP Penney 40.80 +.22 PNR Pentairs 40.80 -125 PBY PepBoy 15.89 -.05 PBG PepsiBoxt 26.35 -.32 PEP PepsiCo 51.63 +.06 PAS PepslAmlr 20.44 -29 PKI PerkElm 21.17 -.65 PBT Prmian 13.22 -.28 PBR Petrobrs 37.41 -.33 PBR/A PetrrsA 33,95 .-.35 PFE Pfier 26.27 -.16 PD PhelpD 92.76 +.71 PHG PhllipsEl 25.16 -.42 PNY PiedNGs 22.52 -.17 PIR Pier 1 18.75 -.35 PPC PilgrirsPr 29.36 RCS PimcoStrat 11.86 -.15 PNW PinWst 43.09 -.98 PXD PioNtd 33.15 -.76 PBI PimnyBw 44.12 -.77 PDG PlacerD 17.51 -.23 PCL PlumCrk 36.05 -1.59 POL PolyOne 8.85 +.02 PPS PostPrp 32.80 -.96 POT Potash s 75.25 -3.58 PX Praxair 42.47 -.88 PR PriceCm 18.09 -.19 PDE Pridelnt 19.72 -29 PRM Prmedia 3.60 -.05 PG ProctGs 55.07 +.57 PGN ProgrssEn 44.23 -.12 PLD Prologis 40.90 -1.42 PHY ProsStHiln 3.54 -.02 PVN Providlan 15.70 -.44 PRU Prudent 52.94 -.53 PEG PSEG 49.85 -.67 PSD PugetEngy 23.80 -.24 PHM PulteHm 60.34 -.50 PYM PHYM 6.66 +.01 PGM PIGM 9.55 +.04 PPT PPlT 6.52 -.02 NX Quanexs 42.55 -1.35 PWR QuantaSvc 7.80 +.10 Q QwestCm 4.38 -.01 RPM RPM 18.37 -.62 RSH RadioShk 32.22 +.64 RAH Ralcorp 41.58 -.03 RRC RangeRsc 18.90 -.33 RJF RJamesFs 29.39 -.69 RYN Rayonier 45.81 -1.71 ROV Rayovac 34.85 +.20 RTN Raytheon 36.88 +.30 RDA ReaderDig 15.10 -.13 0 Rtylncos 23.53 -1.26 RWT RedwdTr 58.75 -3.70 RBK Reebok 43.12 -.31 RF RegionsF n 34.92 -.21 RGS ReglsCp 41.10 -4.10 RRI RellantEn 13.02 -.29 REP Repsol 24.95 -.32 RVI RetalVent 7.06 -.11 REV Revlon 2.24 -.04 RAI ReynIdsAm 77.50 -.25 RHA Rhodia 2.63 -.02 RAD RlfeAld 3.48 -.02 RHI RobtHalf 28.09 -.59 ROK RockwiAut 46.99 -1.01 ROH RoHaas 41.41 -.59 RDC Rowan 24.89 +.06 RCL RylCarb 52.85 -.76 RD RoylDul 55.76 +.01 RVT Royce 19.00 -50 R Ryder 46.50 +25 RYL Rylands 53.7 -.54 SAP SAPAG 4221 -.12 SBC SBCCom 25.44 +.12 SCG SCANA 38.55 -.36 SKM SKTIcm 21.64 -21 SLM SLM Cp 53.76 +.09 SPW SPXCp 38.30 -.70 STM STMicro 18.51 -.17 SFE SfgdSci 1.69 -.10 SWY Safeway 18.66 -.21 JOE SLUoe 60,56 -1.39 STJ SUudes 40.14 -.66 STA StPaulTrav 36.98 -.06 SKS Saks 14.07 -.38 CRM Salesfore n17.95 +1.59 EDF SalEMInc2 16.37 -.06 SBF SalmSBF 12.59 -.08 SJT SJuanB 27.83 -.25 SLE SaraLee 23.86 -.45 SGP ScherqPI 20.36 -.12 SGPpM SchrPpfM 55.05 -.07 SLB Schimb 63.96 +.20 SCH Schwab 11.32 -.07 SFA SciAulanta 30.92 -.53 SPI ScottPw 31.10 +.16 STX SeagateT 16.90 -.17 SEE SealAir 50.62 -1.32 S Sears 50.40 -1.40 SRE SempmEn 35.75 -.46 SNH SenHous 17.43 -.55 SXT Sensient 22.66 -.05 SCI SvceCp. 7.30 -.01 SGR ShawGp 16.01 -.68 SKO ShopKo 18.73 +.03 SHU Shurgard 42.25 -.90 SRP SierrPac 9.70 -.15 0SGI SilenGph 1.61 -.06 SPG SirnmonPmp 60.45 -2.80 PKS SixFags 5.24 -.13 AOS SmnthAO 27.72 -.94 SII Smffilntl 51.91 -.46 'SOL Sola 27.18 SLR Solectm 5.06 -.06 SO SouthnCo 32.84 -.20 LUV SwstAiri 15.61 . SWN SwnEnig 44.67 -.68 SOV SovrgnBcp 22.30 -.31 TSA SplAuth 24.55 +.24 FON SpmtFON 24.16 +.11 SPF StdPac 60.43 -.35 SXI Standex 27.00 -.90 HOT StarwdH0t 56.34 -.48 STT StateStr 48.19 -.32 STE Steris 22.50 -.15 STK StorTch u32.57 +1.00 GLD sTGoldn 42.67 -.07 SYK Strykers 48.95 +.06 RGR SturmR 8.62 -.17 SUI SunCmts 38.80 -.68 SU Suncorg 32.19 -.60 SDS- SunGard 27.62 +.32 SUNM Sunoco 76.65 -1.10 STI SunTrst 71.42 -.52 SVU Supvalu 33.11 -.15 SBL SymblT 16.24 -26 SYT Syngenta 20.60 -.07 SYY Sysoo 36.55 +.05 TCB TCFFncds 31.01 -.12 TE TECO 15.04 -.13 TJX TJX 24.66 -.10 'TZA TVAzteca 9.25 +.11 IN SA Q ATION AL M R EII Tkr !Name Last Chg ADBL Audble n 22.86 +.71 AUDC AudCodes 15.09 -.29 VOXX Audvox 15.33 -.33 ADC81 ADCTel 2.53 -.05 ADSK AutodsRs 35.27 +.27 ASTS ASETst 5.65 -55 ,AVNX Avanex 2.91 +.04 ASML~ ASMLHId 14.99 -.22 AVID AvidTch 58.45 -.89 ATYT ATITech 18.49 -.33 AWRE Aware 4.73 -.11 ATPG ATPO&G 16,84 -.81 ACLS Axcells 6.96 -.43 ATSr ATS Med 4.40 -.08 XEDA AxedaSys .98 +.01 AAI aalPharma 3.42 -.39 AXYX Axonyx 5.46 -.15 ASTtg Aastrom 1.56 -.07 BEAV BEAero 10.30 -.33 ABG n1 Abgenix 9,73 -.09 BEAS BEASys 8.42 -.22 LEND H AccHme 45.45 -2.00 BLDP BallardPw 6.06 -.20 ACK Acc Aredo 26.56 -.52 BCON BeaconP .83 -.02 ATVI AclMsns 19.40 +.28 BBGI BeagleyB" 17.27 -.25 ACTU Actuate 2.28 -.08 BEBE BebeSrss 26.24 +.08 ACXi Acxdom 24.70 -.68 BBBY BedBath 40.01 +.35 ADPTg Adaplec 7.11 -.03 BIVN Boenvisn 8.18 -.17 ADBE AdobeSy 59.73 -.33 BIIB Blogenldc 64.84 +.08 ADLRi AdolorCp 9.78 +.02 BMRN BloMarin 6.08 -.09 ADTN Ad4ran d17.78 -,40 BMET Blomel 41.83 -.11 ADIC AdvDiglnl 9.33 +.01 BIOM Boma 2.25 -.04 AEIS AdvEnd 8.20 +.15 BPUR Biopure .54 -.08 AERT AdvEnv 1.42 +.03 BSTE Biosite 57.96 -.67 ADVN Advanta 22.00 -.12 BOBE BobEvn 25.11 -.60 ADVN AdvantB 23.74 +.01 BKHM Bookham 4.26 -.21 ARXX Aeroflex 11.16 -.13 BORL Borland 10.40 -.50 AFFX Affymet 35.95 +2.01 BPFH BostPrv 27.11 -.79 AGIL AgieS t 7.50 -.30 BRCM Brdcom 31.01 -.55 AIRN4 AirepanNet 4.85 -.17 BWNG Broadwing 7.76 -.32 AKA M AkamaiT 12.00 -.20 BRCD BrcdeCm 7.00 -.14 AKZO Akzo 41.95 +.15 BRKS BrooksAut 15.68 -.59 APCS Alamosan 12.08 -.04 BSQR Bsquare 1.29 -.00 ALDAr Adilars 14.04 -.25 BMHC BidgMat 34.67 -2.35 ALXN8 Alexion 23.37 -.07 BO30J BusnObj 24.12 -.04 ALGN0 AgnTech 10.40 -.01 CCBL C-COR 8.58 -.63 ALKS Alkenm 13.01 -.60 CBRL CBRLGrp 40.32 '-.18 ALTH AlMosThera 2.52 +.26 CDWC CDWCorp 64.63 +.19 ALOY Alloync 7.65 -.29 CHRW CH Robn 55.16 +.49 ALNY AJnylamrn 8.05 +50 CMGI CMGI 2.23 -.09 ALTI AltairNano 2.45 -.13 CNET CNET 10.05 -.34 ALTR AlteraCp 18.86 -.33 CSGSS GSGSys 18.00 +.20 ALVR Alvarion 13.24 -.25 CVTX CVThera 21.51 AMZ Amazon 41.77 -37 CCMP CabotMic 36.95 -.88 ABMC AmerBio 1.30 +.20 CALM CalManes 10.67 -.33 ABMC 8 AmrBlowt .25 .:. CARS CapAuto 33.49 -1.41 ACAS AmCapSir 32.50 +.45 CCBG CapClyBk 40.62 .+.32 AEOS AEagleO 47.92 +1.00 CPST CpstnTrb 1.66 -.05 AMMI AmrMed 38.75 -1.06 DFIB CardlacSc 2.04 -.03 APPX AmPharm 32.66 -.61 CRDM Cardima .52 -.01 APCC APwCnv 20.51 -.16 CECO CareerEd 40.22 +.67 AMTD AmrTrde 13.07 -.20 CMRG CasualMal 5.77 +AO AMG Amqen 62.26 -140 CLTK Celerileks 1.15 -.13 AMK AmkorT 5.57 -.41 CELG Celgene s 25.55 +.38 AMSC Amsurg 27.49 -1.62 CEGE CellGens 7.13 -.31 AMLN Amylin 22.81 -.02 CTIC CelThera 7.75 +.24 ALOG Anlogic 42.66 -1,32 CENX CentAl 24.71 -.69 ANLY Analysts 3.83 +.11 CNTY CentCas 8.26 +.26 ANLT AnlySur 2.69 -.19 CEPH Cephln 48.39 -.69 ANDW Andrew 13.02 -.03 CRDN Ceradynes 52.01 -1.04 ADRX AndrxGp 22.45 +.26 CERN Cemer 50.71 -.97 ANGO AngloDynn21.67 +18AB CHRS ChnnmSh 924 -.01 ANPI rAnglotchgs 18.18 +.12 CHTR ChartCm 2.25 -.05 AGEN 8 Anfgncs 9.40 +.13 CHKP ChkPolnt 24.18 +.13 APOL "ApoloG 81.18 -1.03 CKFR ChkFree 35.74 -.36 AAPL- ApoeC 64.50 +.56 CHKR Checkers 13.41 +.01 APPB Applebeess25.85 -.21 CAKE Cheesecks 31.19 -.56 ADSX- ApplDIgIrs 6.60 -.55 PLCE ChildPc 35.82 +.72 AINN Apdlinov 3.32 -.13 CHINA chndlcm 4.15 -.02 AMAT- ApldMall 16.22 -.28 IMOS ChipMOS 5.89 -.16 AMCC AMCC 3.95 ... CHIR Chiron 34.80 +.12 AQNT aOuantve 8.60 -.14 CHRD Chordnt 2.08 -.04 ARDM Aradigm 1.53 -.08 CHDN ChrchllD 40.00 -1,50 ARIA AiladP 6.70 -.17 ClEN ClenaCi 3.03 -.03 ARBA Arlbars 14.01 -.73 CINF CIlnFIn 44,60 +.82 ARMHY ArmHId 6.16 -.03 CTAS Cintas 42.44 -.11 ARTX Arotech 1.47 -.05 CRUS Cirus 499 -.09 ARRS Arris 6.69 -.17 CSCO CIco 18657 '+.01 ARTG ArtTech 1.34 -.04 CTXS CtlqxSy 22.96 -.80 ATSN Anesyn 10,45 -.28 CLHB CleanH 1409 -.31 ASCL AscentSoft 14.93 +.05 CKCM CIlckCm 15.00 +.17 ASKJ AskJvs 26.60 -.41 COGT Cogent n 30.63 +.06 ASPT AspectCm 10.70 -.16 CTSH' CogTechs 40.98 -.38 ASBC AsdBncs 32.59 -.12 COGN Cognosg 42.05 +.33 ASYTE AsystTchIf 4,78 -.17 CWTR CIdwlrCrs 28.55 +.21 AGIX AthrGnc 18.13 -.11 CFSI CollgFdSvnl4.70 +.98 ATML Atmel 3,45 -.16 CMRO Comarco 631 -.29 CMCSA Comcast 3233 +.30. CMCSK Comcso 31.72 -.06 CCBI CmrdCaps 21.82 -.83 CBSS CompsBc 46.59 -.69 CPWR Compwme 6.04 -.17 CMTL Comtech 3524 +.58 CMVT Comvers 23.03 +.22 CCUR ConcCm 2.49 -.04 CNXT Conexant 1.81 -.03 CNCT Connelcs 23.32 -.68 CPRT Copart 23.62 -.52' CGTK Corgentchn 8.09 +.10 COCO CodrnthCs 17.77 -.25 CRXA CorixaCp 3.73 +.17 COST Coslco 47.22 +,t0 CRAY Crayinc 4.13 -.21 CMOS CredSys 8.18 -.38 CREE Cree Inc 33.84 -1.70 CBST CubistPh 11.12 -.26 CMLS CumMed 14.03 -.36 CRIS Cusri .4.50 -.35 CURN CuronMed 1.98 +,29 CYMI Cymer 25.7Q -.66 CYTC Cytyc 25.29 -,24 -1 DOVP DOVPh 16.80 -.36 DPAC DPACTc .79 -.07 DROOY DRDGOLD 1.44 -.02 DADE DadeBeh 56.09 -.29 DANKY Danka 3.07 -.01 DECK DeckOut 44.75 -.66 DCGN decdGenet 7.85 +.09 DELL Dellnc 40.25 -.27 ONDN Dndreon 10.11 -.13 OCAI DIalCpAs 25.14 +.94 DIGL DIgLght 123 -.06 DRIV D5River 36.36 -.06 DTAS Dilas 9.10 -.08 DSCO DiscvLabs 7.51 -.03 DESC DistEnSy 2.73 +.28 DITC DItechCo 13.90 -.22 DCEL DobsonCm 1.68 -.10 DLTR DIIrTree 28.30 +.67 HILL DotHIU 6.85 -26 DCLK DbleCIck, 7.57 -.09 DRAX Draxisg 4.26 -.04 DSCM dmrgstre 3,45 +.04 DRRX DurectCp 2.76 -.28 EELN E-loan 3.21 +.08 EBAY eBay 110.90 -.41 EAGL EGLInc 27.55 -.15 ERES eResrch 13.55 -.36 ESST ESSTech 6.41 -.17 ELNK' ErthUnk 10.83 -.19 DISH EchoStar 3229 -.01 ECLP Eclipsys 18.87 -.21 ECST eCost.cmn 1342 -.07 EDLG EducLend u18.94 +3.52 EDMC EducMgt 31.78 -.16 EDUC EduDv 10.10 EGHT 8x8 Inc 3.88 +.05 ESIO ElecSci 17,82 -.31 ERTS ElectArts 59.71 +.57" ELBO ElecBIq 40.41 +.37 EFII EFII 16.91 -.25 EMRG eMrgelnt 1.55 -.03 EMMS EmmisC 18,49 -.30 ENMC EncrMed 6.08 -35 ENCY EncysveP 9.87 -.02 ENDP EndoPhcm 20.00 -35 ENMD EntreMd 3.77 +.61 ENTU Entrust 3.85 +.15 ECGI EnvoyCm .58 -.02 ENZN EnzonPhar 13.08 -.10 ELAB EonLabss 2630 +.27 EPNY Epiphany 4.65 -.09 ERICY EricsnTI 30.90 -.75 ESPD eSpeed 9.74 -1.22 KEYW EssexCp 17.78 +.82 EEFT Euronelt 25.41 +.01 ESLR EvrgrSIr 4.58 -.10 EVOL EvolSys 4.05 -.27 EXAR Exar 13.30 +.03 EXPD Expdlntil 55.63 +1.70 ESRX ExpScript 76.20 +.57 EXTR ExtNetw 5.98 Eyetechn 42.63 F5 Nelw 44.48 FFLC Bcp 35.00 FX Ener u13.50 FalconStor 8.25 Fastenal 59.16 RFfthThird 46.45 Fnisar 1,99 FnLnUnes 18.76 FsIHithGp 18.56 FrstHrz 19.93 FstMerit 27,72 FIsew 39.71 Flextm 13.00 FLY1 1,71 FocusEn 1.07 Fonr; 1.46 ForbesMd 2.45 FonrFac 2.378 Fossils 24.50 Foundry 11.58 Fredsnc 15.56 FmlrAir 10.07 FueiCell 9.42 Ftrmdia .83 -.02 GRMN Garmin 53.56 -3.07 GMST Gemstar 5.59 -.12 GENR Genaera 3.29 -.21 GNLB GeneLTc 1.13 -.04 GNSS GenesMcr 15.23 -.31 GNTA Genta 1.65 -.04 GNTX Gentex 34.76 +.27 GENZ Genzyme 56.91 +.21 GORX GeoPharm 4.99 -.15 GERN GeronCp 7.99 -.23 GILD GilleadSds 33.41 -.47 GLBL Glolind 7.60 -.17 GLOW Glowpoint 1,61 +.11 GOOG Gooedon 193.51 -.99 GRIC GoRemote 1.38 -.03 GBBK GrrBay 28.73 +.01 GYMB Gymbree 12.29 -.04 HMNF HMNFn 32.35 +.10 HANS Hansen 33.51 -1.70 HARB HarbrFL 33.63 -.45 HLIT Harmonic 7.99 -.39 TINY HarisHa 14.02 -.50 HDWR Headwairs 27.71 +.72 HMSL Hemosolwl .93 +.13 HSIC HSchein 68.23 -.07 HLYW HlywdE 13.08 +.19 HOLX Hologic 25.66 -.13 HOMS HomeSlore 2.59 -.12 HOFF HrznOf 1.37 -.35 HOTT HotTopic 16.50 -.16 HGSI HumGen 11.72 -.18 JBHT HunUB 42.08 -.98 HBAN HuntBnk 2434 -.16 HYSL HyperSolu 46.18 +1.04 IMNY I-Many 1.49 +.01 IACI IACInteiac 25.43 -.20 ICOS ICOS 26.92 -.78 IDBE ID80o 14.13 -.12 IPIX IPIXCp 5.34 -.03 IPAS iPass 6.53 -.33 ICOR Icoda .60 -.02 IDNX Identix 6.94 -.11 [MAX IrnmaxCp 7.84 IMCL Imdone 44.06 -1.26 BLUD Immucors 22.98 +.14 IMMU Imunmd 3.28 +.21 IPXL ImpaxLab 16.42 +.53 INCY Incye 9.25 -.02 ICSC IndpCmly 40.46 -.95 IDEV IndevusPh 539 -.22 INSP InfoSpce 44.25 +.23 INFS InFocua 8.27 -.77 INFA Inlonnmat 755 +.07 INOD Innodata 6.87 -2.42 ICCl InslhtCm 9.35 NSIT Insight 20,08 +.30 INSM Insmed 2,00 -21 ISPH InspPhar 15.65 -.21 INGP Instinet 5.58 -.19 INMD IntegMed u12.04 -.96 ICST IntgCIrc d19.92 -.29 IDTI InlgDv 10.31 -.18 ISSI ISSI 7.26 -23 INTC Intel 22.39 -.22 INCX Interchgn 16.98 -.22 IDCC InterDig 20.50 -.22 ITMN InterMune 12.42 -.28 ISCA InlSpdw 51.71 -.25 ICGE ItmtCprs 8.29 -.66 ISSX IntntSec 21.09 -.30 ISIL Intersil dl5.18 -.41 INTV Intervoice 12.90 +.33 IWOV Inlerwovn 9.71 -.18 INTZ Intrusnhrs 3.80 -.58 INTU Inluit 41.02 -.47 ISRG IntSurg 36.09 -.32 IFIN InvFnSv 47.13 -.53 IVGN Invirogn 65.14 -.32 ISIS sis 5.36 -.05 ISON Isonics 5.65 +.77 IVAN IvanhoeEn 2.26 -.16 IVIL IVillage 5.84 -.10 XXIA .Mxia 1486 +.66 JCOM j2GIob 31.38 -1.25 JDSU JDS Uniph 298 -.07 JKHY JackHenry 20.29 +.11 JAKK JkksPac 20.51 -.57 JBLU JetBlue 21.22 -.43 JOSB JosBnkrs 28.17 -.74 JOYG JoyGlbI 39.91 -.84 JNPR JnliNtw 25.64 -.16 JUPM Jupltrmed 20.15 -1.71 KSWS K Swiss 28.90 +.05 KLAC KLATnc 43.12 -.71 KVHI KVHInd 11.43 +.29 KERX KeryxBlo 14.18 +2.95 KNTA Kintera 8.17 -.25 KMRT Kmaot 96.57 -3.78 NITE KnghtTrd 10.36 +.02 VLCCF KnighIT 29.26 +.61 KONG KongZhgn 8.40 -.01 KOPN KopinCp 3.38 -.21 KOSP Kos Phr 34.93 -.79 KRON Kronos 48.05 -.73 KLIC Kulicke 7.55 -.20 LKOX LKQCp 18.15 -.85 LYTS LSIInds 11.35 -.22 LTXX LTX 6.72 -.29 LJPC LaJoIPh 1.73 +.01 LABS LabOre 32.22 +.91 LRCX LamRsch 25.88 -.91 LAMR LamarAdv 41.76 -.65 LCRD LasrCard 1125 +1.14 LSCP Lasoscp 31.42 -.13 LSCC Latice 501 -.15 LAUR Laureate u44.79 +.08 LWSN Law w Sft 6.10 -.50 LVLT Level3 3.17 -.05 LEXR LexarMd 7.16 -.03 LBTYA UbMIntAn 43.69 -1.20 LPNT UIoePH 34.26 -1.26 LGND UgandB 10.54 -.48 LNCR Uncare 40.98 +11 LLTC UnearTch 36,81 -.39 LNET LodgEnt 18.01 +.06 LOOK LookSmarl 205 +.05 LOUD Loudeye 1.79 -.13 FLSH M-SysFD 18.65 -.07 MCIP MCIImnn 19.37 -.60 MOGN MGIPhrs 2645 +40 MKSI MKSInst 16.71 -.62 MRVC MRVCm 3.24 -.21 MTSC MTS 31.43 -.90 MACR Macmndia 27.42 -.05 MVSN Macrsn 2371 -46 LAVA Magma d10.50 -.88 MANH ManhAssc 22.85 +.57 MTEX Manntch 18.58 -.47 MANU Manugist 2.65 +.01 MATK Martek 48.50 +.59 MRVL Mavellrs 32.90 +.12 MXIM Maxm d39,38 -.81 MXWL MaxwifT 9.14 -.13 MCLD McLeoA 82 -10 MCDT 'McData 5.21 -.18 MCDTA McDataA 5.58 -.18 MEDI Medlmun 25.25 -1.12 MEDX Medarex 10.04 -.51 MBAY MediaBay 1.15 .-.10 MCCC Mediacm 6.10 -.16 MDCI MedAct 18.70 -.05 MDCO MedCo 27.80 +.07 MDKI Mdcomre 10.95 +.17 MENT MentGr 13.66, -.25 MRCY MrcCmp 27.29 -1,00 MERQ Mercintr 42.62 +.09 MESA MesaAIr 7.03 -.17 MTLM MalalMgs 25.23 +.13 MEOH Mlhanx 16.90 -.60 MCRL Micrel 9.50 -.37 MCHP Microchp d24.77 -.78 MUSE Mcromnse 5.19 +.13 MSCC MicSemis 15.59 -.42 MSFT Microsoft 26.78 -.06 MSTR McroStr 56.44 -.39 TUNE Mlcmtunen 5.36 -.08' MIKR Mlkron 9.23 -.67 MCEL MillCell 1.15 -.04 MLNM MillPhar 11.44 +.07 MICC Millcmlnts 20.50 -.80 MSPD Mindspeed 2.52 -.02 MSON Misonix 6.03 -.27 MODT ModtcH 7.36 +.07 MOLXE Molex I 28.11 -.61 MNST MnsltrWw 28.63 -1.17 MGAM MulimGas 14.41 +.16 MYGN MyriadGn 21.82 +.38 NNDS NDS Grp 30.84 -2.79 NTGR NETgear 16.39 +.09 EGOV NIC Inc 4.57 -.43 NIHD NIIHkIdgs 49.02 +1.08 NPSP NPSPhm 17.75 +.14 NTLI NTL Inc 69.18 -.95 NGEN Nanogen 6.21 -.43 NANO Nanornt 13.92 -.20 NAPS Napster 8.75 +.24 QQQQ Nasd100Tr 38.54 -.24 NSDA Nassda 6.85 -.01 NSTK Nastech 10.84 -.20 NAVR Navarre u17.66 -.08 NCRX NelghCar 30.55 -.24 NKTR NektarTh 18.80 -.43 NMGC NeoMgc 1.00 -.04 NTBK NetBank 10.12 -.13 NTOP Net2Phn 3.20 -.07 NTIQ NellQ 11.62 NTES Nelease 51.25 -.60 NFLX Nelflixs 11.20 -.46 WOLV NetWolv 122 -.12 NTAP NetwkAp 31.45 +.05 NENG NtwrEng 2.63 -,22 NEWP Newport 13.11 -.14 NXTL NextleC 29.56 -.02 NXTP NextlPrt 19.30 +.22 NTMD NitroMed 25.00 +.22 NOBH NobftyH 22.20 -.10 NTRS NorTrst 46.94 -.18 NWAC NwetAld 8.60 -1.04 NOVA NpvaMed 6.03 -.62 NGPS Novatel 31.00 -4.91 NVTL NvtWds 16.15 -.05 NOVL Novell 6.36 +.04 NVLS Novlus 25.79 -.33 NUHC NuHorz 7.48 -.46 NUAN NuanceC 3.78 -.01 NVDA Nvida 2268 +.21 OiIM o2MIcro 1000 -.27 OSIP OSIPhrm 69.56 -1.43 OCLR OculrScd 50.16 +.98 ODSY OdysseyHIt 12.81 -.65 OVTI OmniVsns 1684 -.39 ASGN OnAssign 516 -.11 ONNN OnSmInd 4500 -.13 FLWS 1800Fowrs 8.07 +.02 ONXX OnyxPh 31.13 +07 OTEX OpenTxt 19.71 +.09 OPTV OpenTV 3.58 -03 OPWV Opnw.Sy 13.73 -45 OPLK OplinkC 1.67 -11 OPSW Opsware 6.72 -.24 ORCL Oracle 130 OFIX OrOfx 38.57 +.17 OSCI Osenti 3.41 -.11 OTTR OrterTal 24:60 -.40 OSTK Overstk 63.32 -.68 PFCB PFChng 53.68 -1.34 PMCS PMCSra 10.07 -.33 PPTV PPTVis 1.05 +.03 PSSI PSSWrid 11.84 -.42 PCAR Paccars 73.77 -2.46 PSUN Pac.unwr 22.94 +.44 PACT PaclficNet 835 -.79 PSRC PalmSrce 12.02 -.22 PLMO palmOne 29.62 -.49 PMTI PalmrM 23.63 -.07- PAAS PanASN 14.75 -.21 PNRA PaneraBrd 39.41 +.05 PMTC ParmTc 5.35 -.12 PTMK Pathmrk 4.95 -.41 PDCO Pattersons 42.59 -.04 PTEN PattUTIs 18.02 -.10 PAYX Paychex 32.50 -23 PENN PennNGm 58.44 -M05 PSFT Peoplesoft u26,48 -.01 PPHM Peregrine 1.12 -.06 PRFT Perficent 7.80 -.38 PRGO Pernigo 16.42 -.13 PETD PetDv 36.05 -.43 PETM PetsMart 33.84 -.52 PFSW PFSweb 2.75 +.22 PARS Phannos 1.23 -.04 PHRM Pharmion 40.70 -1.19 ANTP Phazar 35.22-10.23 PHTN Phoon1 23.73 POLE PInnSyst 5.20 -.18 PIXR PIxar 84.43 -.04 PXLW Pxlwrks 11,53 -.11 PLNR PlanrSy 10.08 -28 PLXS Plexus 10.93 -26 PLUG PlugPower 5.42 -.23 PLCM Polycom 20.00 -2.16 PLAY PortPlayn 22.98 -1.13 POW1 Powrlnig 17.14 -.67 PWER Power-One 8.18 -24 PWAV Powrwa 7.98 +.07 PRCS PraecisP 1.99 -M06 PRST Prestek 9.99 +.15 TROW PrceTR 59.69 -.25 PCLN pipeline 23.59 -29 PRTL PrimusT 2.86 -.08 POSO Prosoft .40 -.02 PDLI ProtDsg 19.92 +.15 QLTI OLT 16.39 +28 QLGC Ilogic 35.50 QalC Oaloms 42.31 +.18 QSFT QuestSftw 15.15 -.11 RFM RFMIcO 6.12 -.17 TISAS RSASec 18.37 +.20 ROLAK ROneD 15.65 -.19 RMBS Rambus 22.06 +.58 RNWK RealNwk 6.13 -.02 RHAT RedHat 1246 -.17 RBAK Redback 4.92 -.12 REMC Remec 6.86 -.10 RCII RentACt 2700 +.19 RBNC RepBcp 14.89 -20 RIMM RschMols 76.91 +.05 RECN ResConn 51.76 -.11 RSTO RestHrd 533 -.22 RETK Retek 5.35 +.09 RICK RickCab u3.78 +93 RIGS RigsNt 21.60 +.01 ROST RoseSSra 27.59 -.24 RURL Rudr/Mron 5.26 +.00 RYAAY Ryanair 40.80 +.01 SFLK SAFLINK 260 +.05 SBAC SBACom 8.88 -.24 SAFC Saeco 49.97 -.20 SLXP SalixPh s 15.43 -.73 SNDK SanDLsks 23.17 -20 SANM Sarnmina 7.72 -.07 SAPE Sapient 8.00 -.26 SATC Satcon 1.74 -.05 SWS SvisCm 1.10 -.07 SAXN SaxonCpn 23.02 -.73 SCHN Schnlters 32.31 +.31 SGMS SdGames 22.52 -.48 SEAC SeaChng 16.40 -.47 SBYN SeeBeyond 3.77 +.27 SCSS SelCmsit 16.89 -26 SIGI Selcin 43.82 +.02 SMTC Semtech 19.78 -.74 SNMX Senomyxn 8.50 +.29 SEPR Seprecor 58.10 -.01 SQNM Sequenm 1.39 +.14 SRNA SerenaSt 20.22 -.49 SERO Serolog 20.78 -.07 SNDA Shanda n 39.36 +28 SHRP Shrplm 17.89 -.17 SHPGY ShIrePh 32.31 -.48 SHFL ShufflMsts 43.82 -.31 SEBL SlebelSys 9.61 -.27 SWIR SlenaWr 16.24 +.56 SIAL SgkmAI 58.38 -.32 SGTL SgmaTel 31.57 -.19 SIMG Silmnlmg 15.51 +.03 SLAB SllcnLab 32.26 -1.00 SSTI SST 5.38 -.14 SIVB SiicVyB 43.9,1 -29 SSRI SilvStdg 11.01 +.01 SINA Sina 30.39 -.11 SBGI Sinclair 8.86 +.05 SIRI SidusS 7.64 +.13 SKYF SkyFnd 28.32 -.04 SKYW SkyWest 18.01 -1.46 SWKS SkywksSi 8.79 -.02 SMSI SmlthMIcro 7.35 -.73 SSCC SmurStne 17.47 -.39 SOHU Sohu.cm 16.67 -29 SONC SoricCps 30.89 -.55 SNIC SonicSol 20.15 +.15 SNWL SncWall 5.76 -.03 SONS Sonusn 5.61 -.11 SMBC SouMoBc 18.48 TSFG SouthFnd 31.55 -.47 HDTV SpataLt 7.78 -.56 SPLS Staples 32.14 -.04 STSI StarScien 4.58 +.11 SBUX Starbudcks 61.60 +.50 STLD SUDyna 35.98 -30 STEM StemCels u5.856 -Al STEI StewEnt 6.85 -.05 STXN Stratex 2.11 -.04 SUNW SunMicmo 4.70 +.07 STKL SunOpta 6.63 -.45 SCON SupTech 1.11 -22 SUPG SuperGen 5.70 -.14 SPRT SupportSft 5.91 +.12 SUSQ SusqBtc 24.59 -.18 SWFT SwilTm 20.00 -.43 SCMR Sycanmr 3.72 -05 SYMC Symantec s 25.04 -37 SYMM Synmelc 8.96 -26 SYNA Synaptics 29.00 -.70 ELOS Syneronn 26.33 -1.87 SNPS Synopsys 18.07 -.51 SYNO Synovis 10.08 -37 THQI THQOInc 21.08 -.63 TLCV TLC Msion 9.94 -.15 TOPT TOPTankn 14.98 +.29 TrMI TTMTch 10.32 -.58 TTWO TakeTwo 3360 -.30 TGEN TargGene 1.70 +.03 TARO TaroPh 31.86 -1.20 TARR Tarragon s 22.00 +390 TAGS Trrant 2.48 +.10 TASR TASERs 28.6 +.17 TAYD TayrDv 6.30 -43 TECD TechData 42.85 +39 TICCR Techlnvrt .17 -.08 TCNO Tecnmtx 16.69 -.01 TGAL Tegal 1.43 -.05 TKLC Tekelec 19.02 -27 TIWI Telesys 11.14 +06 TLWT TelwestGIn 1676 -.48 TELK Teliknc 18.01 -.45 TLAB Teliabs 8.70 +.01 TERN Terayon 2.61 +.01 TSRA TesseraT 34.05 -.84 TEVA TevaPh s 27.80 -56 THOR Thoratc 9.75 -.64' COMS 3Com 3.93 -.08 TXU TXUCorp 62.90 -.08 TSM TaIwSemi 7.92 -.16 TGT Target 5128 +.04 TK" Teekays 40.45 +.33 TNE TelNorL 15.25 -.01 TMX TelMexL 36.58 -.92 TIN Templelnl 65.85 -1.00 TPX TempurP 20.98 -.37 THC TenltHIt 10.48 -.13 TPP Teppco 38.65 -.05 TER Teradyn 15.36 -.21 TEX Terex 44.35 -.32 TRA Terra 8.17 -.74 TNH TerraNitro 20.65 +.44 TSO Tesoro 29.25 -.26 TT11 TetraTech 25.78 -1.47 TXN Texinst 22.89 -.71 TGX Theragen 4.05 +.04 TMO ThermoEl 29.23 -.08 TNB ThmBet 28.56 -.59 TMA Thombg 27.21 -1.11 MMM 3MCo 80.73 -1.00 TIF Tiffany 3066 -.57 TWX TimeWam 18.91 -.19 TKR Timken 23.63 -.94 TTN TitanCp 15.43 -.29 TOD ToddShp 17.59 +.09 TOL TollBros .65.70 -.40 TOO Toolnc u27.71 +3.48 jTRU TorchEn 6.46 +.01 TMK Trchmrk 56.20 -.01 TOT Total SA 105.26 -.50 TSS TotalSys 23.36 -.42 TWR TwrAuto 2.47 -22 TCT TwnCtry 26.65 -.67 TOY ToyRU 20.42 -,01 RIG Transocn 39.80 -20 TG Tredgar 19.21 -.68 TY TriContl 17.90 -.05 TRI TriadH 36.01 -.54 TRB Tribune 41.53 +.06 TRZ TrizecPr 17.74 -.81 TUP Tuppwre 19.79 -.07 TYC Tycolni 35.49 -.16 TSN Tyson 17.82 -20 UIL UIL Hold 48.87 -.93 USG vjUSG 37.50 -.77 UST USTInc 48.04 +.09 UNS UniSrcEn 24.95 -.25 UBB UUniao 30.53 -.57 UNF UnlFirst u31.96 +3.15 UNP UnionPac 65.20 -.60 UIS Unisys 9.76 -.06 UDR UDomR 23.29 -.61 UMC UtdMicro 3.30 -.08 UPS UPSB 83.75 -.17 USB USBancrp 31.06 +16 X USSteel 48.84 +.09 UTX UltdTech 101.05 -.76 UNH UtdhithGp 86.03 +.30 UHS UnvHih 44.00 +28 UVN Unlision 27.62 -.68 UCL. Unocal 41.19 -.57 UNA Unova 22.94 -25 UNM UnumProv 17.22 -.28 VRX ValeantPh 25.25 -20 VLO ValeroEs 42.16 -.91 VIT VKHiincT 4.14 +.02 WPI WOISflPS 3112 -.50 WPI WatsnPh 31.12 -.50 WFT Weathflnt 49.37 -34 WLM Wellmn 9.71 -28 WLP WellPoint 115.22 +4.22 WFC WellsFrgo 62.03 +.07 WEN Wendys 38.11 -.84 WR WeslarEn 2220 -.18 WIW WAstTIP2n 13.20 WDC WDIgiti 10.23 -24 WON WestwOne 25.77 -.80 WY Weyerh 66.25 +28 WHR Whrpl 67.92 +.06 WTU WilmCS 16.50 +25 WMB WmsCos 15.29 -.11 WSM WmsSon 35.00 -.07 WIN WinDix 4.41 -.04 WGO Winnbgos 36.11 -.99 WIT Wipros 21.76 -1.39 WEC WiscEn 33.45 -.24 WOR Worthgtn 19.74 +.37 WWY Wdigley 67.50 -28 WYE Wyeth 41.35 -.92 XL XL Cap 75.95 -.73 XTO XTOEgyr s 31.92 -.94 XEL XcelEngy 17.55 -20 XRX Xerox 16.39 -.33 YCC YankCdl 31.42 +.20 YUM YumBrds 46.09 -.11 ZMH Zmmer 78.73 -.62ibCosf 12.55 +.30 Yesterday Pvs Day T iVoInc 5.48 -.20 T .n00 iY -4 A Australia 1.065 1.3014 TXCC TmSwtc 1.39 -.01 TZOO Travelzo 90.59 -2.11 TRMB Trimbles 31.85 -.27 TRIN Trinsncrs 1.50 -20 TRPH TripathT 1.33 -.06 TQNT TriQuint 3.89 -.08 TRST TrstNY 13.16 -.35 TRMK Trusmk 29.83 -.04 TWTR Tweeter 7.03 +.13 TFSM 24/7Realrs 4.04 -27 UAPH UAPHIdgn 16,08 -.46 XPRSA USXprss 27.10 -1.41 USIH USIHkidg 11.30 -.11 UTIW UTiWrd 67.85 -.32 UTSI UTStrcm 20.71 -.65 UPCS Ubiquy 6.75 -.01 ULTEE UItEIctf 1.51 +.11 ULTI ULimSo8l 12.16 -.02 ULBI Ultralie 17.90 -.54 UTEK Uifratech 16.71 -25 UNTO UtdOnIn 10.95 -20 USEG US Enr 2.88 -.03 UCOMA UtdGIblCm 9.05 -.20 UFPI UnivFor 42.19 -.65 URBN UrblOuts 42.78 -.53 LNUX VASftwr 2.17 -.09 WOOF VCAAnts 18.91 -.10 VITX VI Tech .69 -.08 VCLK ValueClik 12.62 -.50 VSEA VarlanS 32.02 -1.51 VDSI VascoDta 6.09 -41 VASO Vasomed 1.08 -.05 VECO Veeconst 18.79 -.62 VTIV Venlv 20.14 +.67 VRSN VeriOign 30.64 -.83 VRTS Verilas 27.46 -31 VRTY Verity 11.94 -.44 VRSO VersoTch .69 -.06 VRTX VeitxPh. 9.90 -.19 VERT VerclNet 1.46 -.10 VNWI ViaNet .75 -,03 VWFT VewtCp 2.81 -.10 VIGN VIgnete 1.25 -.06 VISG Wage .8X -.44 VION VionPhm 4.42 +.10 VTSS Vlesse 3.48 +.05 WRNC Wamaco 20.69 -.77 WAVX WaveSys 1.12 --03 HLTH WebMD 7.80 +.05 WEBX WebEx 2128 -.77 WEBME webMeth f 6.52 -08 WBSN Websense 46.57 -126 WERN WenerEnt 21.63 -.03 WSTL Westel 6.07 -29 WWCA WWreIss u31.00 +.22 WTSLA WetSeal 201 -.09 WFMI WholeFd 93.25 -.14 OATS WklOats 8.00 -39 WIND WindRWr 12.58 +.38 WFII WrissFac 9.18 +10 WSTM Wrkstrean 3.64 +10 WLDA WorldAir 6.25 +.18 WHRT WHeartgn -1.95 -14 WGAT WoridGate 4.81 -154 WMGI WrightM 26.30 -37 WYNN Wynn 66.15 +.74 XMSR XMSat 4.56 -.79 XOMA XOMA 229 -.11 XLNX XMinx 27.54 -90 XYBR Xybmautl 1.17 -02 YDIW YDIWissn 4.60 -.11 YHOO Yahoos 36.13 -.45 YELL YellowRd 53.60 -122 ZBRA ZebraTs 5257 -190 ZICA ZICorp 5.97 -.44 ZION ZJonBcp 66.23 -24 ZIXI ZixCorp 4.75 -08 ZOLL ZollMed 30.94 -.85 ZRAN Zoran 10.67 -.38 IRrail 9 7170 9 R670 Britain 1.8850 1.8804 Canada 1.2264 1.2226 China 8.2781 8.2781 Euro .7542 .7534 Honq Kong 7.7887 7.7852 Hungary 185.15. 182.15 India 43.690 43.380 Indnsia 9305.00 9280.00 Israel 4.3879 4.3668 Japan 104.09 104.50 Jordan .70907 .70907. Malaysia 3.7995 3.7995 Mexico 11.3600 11.3690 Pakistan 59.56 59.45 Poland 3.10 3.03 Russia 27.8520 27.7100 SDR .6551 .6509 Singapore 1.6451 1.6384 Slovak Rep 29.06 28.69 So. Africa 5.8900 5.8150 So. Korea 1046.30 1038.50 Sweden 6.7981 6.8051 Switzerlnd 1.1693 1.1697 Taiwan 32.05 31.84 U.A.E. 3.6724 3.6724 British pound expressed in U.S. dollars. All others show dollar in foreign currency. Yesterday Pvs Day Prime Rate 5.25 5.25 Discount Rate 3.25 3.25 Federal Funds Rate 2.25 2.25 Treasuries 3-month 2.29 2.18 6-month 2.55 2.52 5-year 3.72 3.69 10-year 4.29 4.33 30-year 4.85 4.95 FUTURES Exch Contract Settle Chg Lt Sweet Crude NYMX Feb05 43.39 -.52 Corn CBOT Mar 05 2011/2 +1/2 Wheat CBOT Mar 05 2993/4 +3/4 Soybeans CBOT Mar 05 527 +2 Cattle CME Feb05 89.40 -1.07 Pork Bellies CME Feb05 93.95 -.87 Sugar (world) NYBT Mar05 8.98 -.05 Orange Juice NYBT Mar05 86.20 -.35 SPOT Yesterday Pvs Day Gold (troy oz., spot) $426.60 $436.00 Silver (troy oz., spot) $6.512 $6.797 Copper (pound) l .4220 $1.4825 NMER = New York Mercantile Exchange. CBOT = Chicago Board of Trade. CMER = Chicago Mercantile Exchange. NCSE = New York Cotton, Sugar & Cocoa Exchange. NCTN = New York Cotton Exchange. 10,868.07 9,708.40 Dow Jones industrials 10,597.83 -32.95 -.31 -1.72 +.65 3,823.96 2,743.46 Dow Jones Transportation 3,653.29 -25.04 -.68 -3.81 +20.41 337.79 259.08 Dow Jones Utilities 325.44 -3.02 -.92 -2.84 +21.57 7,273.18 6,211.33 NYSE Composite 7,055.21 -35.31 -.50 -2.69 +8.12 1,435.04 1,150.74 Amex Index 1,385.85 -13.20 -.94 -3.38 +16.89 2,191.60 1,750.82 Nasdaq Composite 2,091.24 -16.62 -.79 -3.87 +.65 1,217.90 1,060.72 S&P 500 1,183.74 -4.31 -.36 -2.33 +5.10 656.11 515.90 Russell 2000 617.48 -11.06 -1.76 -5.23 +7.46 12,024.36 10,268.52 DJ Wilshire 5000 11,632.58 -67.99 -.58 -2.83 +6.16 I I oil lic-F II CITRUS COUNTY (FL) CHRONICLED IMTALFN3 3-Yr. Name NAV Chg %Rtn AARP Invst: Balanced 17.20 -.05 +2.9 CapGr 42.48 -.09 -8.5 GNMA 15.12 ... +14.8 Glba. 25.90 -.10 +20.6 Gthinc 21.42 -.08 +2.3 Intl 43.13 -.09 +19.0 PthwyCn 11.53 -.03 +12.9 PtIwyGr 12.82 -.05 +8.3 ShTrmBd 10.19 ... +9.2 AIM Investments A: Agrsvp 10.05-.09 +4.4 BalAp 24.88 -.05 +1.0 BasValAp31.54 -.16 +9.9 ChartAp 12.47 -.06 +7.2 Constp 22.08 -.11 -2.3 HYdAp 4.55 -.01 +27.6 IntlGrow 19.58 -.15 +29.3 MuBp 8.18 ... +18.5 PrernEqty 9.62 -.04 -12.0 SelEqty 17.10 -.11 -0.6 SumilS 10.48 -.05 -0.1 WeingAp 12.68 -.04 -7.6 AIM Investments B: CapDvBt 16.52 -.13 +14.3 PremEqty 8.92 -.03 -14.0 AIM Investor Cl: Dynm 15.94 -.09 -4.6 Energy 26.40 -27 +54.4 HtlSci 49.84 -.25 +1.8 SmCoGIp 12.04-.13 -3.3 ToRtn 24.13 -.05 +2.5 Ufifs 11.67 -.09 +10.0 AIM/INVESCO Invstr: CoreStk 10.53 -.04 -1.9 AMF Funds: AdjMtg 9.82 ... +6.6 Advance Capital I: Balancpn17.61 -.05 +18.8 Retlncn 10.14 +.01 +27.5 Alger Funds B: SmCapGrt 4.14 -.05 +10.4 AllianceBem A: AmGvlncA 7.43 +.01 +36.1 BalanAp 16.91 ... +18.2 GIbTchAp 54.72 -.36 -23.1 GrincAp 3.68 ... +5.1 SmCpGrA22.15 -.23 +7.4 AllianceBem Adv: LgCpGrAd 1824 -.06 -13.0 AllianceBem B: AmGvIncB 7.43 +.02 +33.3 CorpBdBp 12.33 ... +20.2 GIbTchBt 49.63 -.31 -24.9 GrowthBt 22.69 -.07 +2.7 SCpGrBt 18.73 -.20 +4.8 USGovtB p 7.05 ... +11.4 AllianceBem C: SCpGrCt 18.77 -.20 +4.9 AmSouth Fds CII: Value 16.41 -.06 -1.9 Amer Century Adv: EqGropn21.41 -.14 +12.1, Amer Century Inv: Balancedn16.19 -.06 +15.5 Eqlncn 7.93 -.05 +28.6 Growthin 19.15 -.11 -5.0 -feritageln11.36 -.08. +5.3 IncGron 29.82 -.19 +12.7 IntDiscrn 13.08 -.11 +44.2 IntGroln 8.85 -.04 +12.6 LfeScin 4.78 -.03 -0.8 NewOpptrn5.20 -.10 -1.0 RealEsi n 23.40 -.83 +79.6 Selectln 37.08 -.19 -1.2 Ultran 28.62 -.11 +3.3 UtLIn 11.73 -.09 +7.1 Valuelnvn 7.23 -.04 +24.8 Amer Express A: Cal 5.21 ... +16.7 Discover 8.33 -.12 +23.2 BEI 10.78 -.07 +31.2 DivrBd 4.88 ... +15.4 DvOppA 6.97 -.04 +0,8 EqSel 12.46 -.10 +9.4 Growth 25.93 -.08 -6.0 HiYId 4.46 ... +17.1 Insr 5.47 ... +1.9 MgdAlp 9.31 -.04 +13.8 Mass 5.41 ... +15.2 Mich 5.32 ... +16.8 Minn 5.33 ... +17.0 Mutual p 9.60 -.02 +7.4 NwD 23.59 -.05 -3.3 NY 5.14 ... +17.2 Ohio 5.31 ... +14.7 PreMt 8.82 -.07+100.4 Sel 8.67 ... +9.6 SDGovI 4.79 ... +7.6 Stockp 18.87 -.07 +1.0 TEBd 3.90 +.01 +16.4 TIndlnti 5.47 -.01 +6.7 Thdllnl 7.08 -.01 +14.5 Amer Express B: EqValp 9.93 -.05 +5.4 Nwet 22.36 -.05 -5,5 Amer Express Y: NwD n 23.70 -.04 -2.9 American Funds A: AmcpAp 17.87 -.06 +11:2 AMultAp 25.91 -.10 +16.0 BalAp 17.74 -.03 +22.1 BondAp 13.60 -.01 +25.4 CaplBA p 52.35 -29 +40.2 CapWAp 19.80 -.01 +51.4 CapWGAp33.10 -.13 +48.3 EupacAp 34.76 -.11 +32.0 FdinvAp 31.27 -.21 +18.3 GwIhAp 26.58 -.13 +10.7 HITrAp 12.58 -.03 +34.6 IncoAp 18.23 -.09 +31,4 IntBdAp 13.68 ... +12.2 ICAAp 30.11 -.08 +14.7 NEcoAp 20.41 -.13 +9.2 N PerAp 26.99 -.08 +25.6 SmCpAp 30.09 -.21 +28.9 TxExAp 12.54 +.01 +18.8 WshAp 30.14 -.09 +13.7 American Funds B: BalBt 17.69 -.03 +19.4 CapBBt 52.35 -.29 +37.0 GrwthBt 25.83 -,13 +8.1 IncoBt 18.14 -.09 +28.4 ICABt 30.00 -.08 +12.0 WashBt 29.99 -.09 +11.3 Ariel Mutual Fds: Apprec 46.46 -.26 +28.2 Adiel 51.54 -.51 +43.1 Artisan Funds: Ins 21.51 -.12 +19.2 MiCap 28.43 -.20 +8.6 Baron Funds: Asset 51.06 -.20 +23.9 Growth 43.37 -.36.+41.2 Bernstein Fds: InOur 13.38 ... +17.2 D/vMu 14.25 ... +13.6 TxMlglntV 22.08 -.11 +43.7 Bramwell Funds: Growthp 19.27 -.12 -3.7 Brandywine Fds: Brmdywnn25.96 -.25 +11.9 Brinson Funds Y: HIYlalYn 7.48 -.02 +37.0 CGM Funds: CapDv 26.07 -.42 +33.5 Mu 24.31 -.14 +24.8 Calamos Funds: GaelA p 50.78 -.32 +36.2 GrwthCt 48.93 -.31 +33.1 Calvert Group: Incop 16.98 ... +25.8 InlEqAp 1t.71 -.04 +26.3 MBCAI 10.41 ... +11.4 Munln 4 10.95 +01 +16.5 SocalAp 27.05 -.07 +7.1 Socgdp 15.93 ... +21.9 SocEqAp 33.57 -.15 +68.7 TxFL 10.02 +.01 +5.7 TxFLgp 16.66 +.02 +18.5 TxFVT 15.99 +.01 +16.9 Clipper 87.94 -.48+16.9 Cohen & Steers: RlyShrs 65.56 -2.40 +83.7 Columbia Class A: Acosm 24.93 -.26 +43.6 Columbia Class Z: AcomZ 25.43 -27 +45.8 AcomlntZ 28.43 -.19 +52.9 LargeCo 27.22 -.09 +5.3 SmalICo 20.25 -.33 +32.5 Columbia Funds: ReEsEqZ 25.35 -.76 +71.9 Davis Funds A: NYVenA 30.08 -.12 +19.4 Davis Funds B: NYVenB 28.87 -.11 +16.6 Davis Funds C & Y: NYVenC 29.05 -.12 +16.6 Delaware Invest A: TxUSAp. 11.57 +.01 +21.8 Delaware Invest B: DelchB 3.38 -.01 +44.9 SelGrBt 20.04 -.15 -6.2 Dimensional Fds: IntSmVan 15.13 -.04+129.7 USLgVan 19.49 -.08 +28.7 US Micro n14.38 -.22 +54.5 USSmalln18.56 -.31 +33.9 USSmVa 25.50 -.42 +08.0 EmgMktn 15.06 -.17 +75.0 tnlVan 16.01 -.07 +70.0 OFARIEn 21.57 -.81 +74.7 Dodge&Cox: Baanced 77.99 -.25 +33.4 I 4or .12.82 ... +21.6 In0Sk 29,87 -.07 +63.0 Stock 126.78 -.63 +35.5 Dreyfus: Aprec 38.06 -.05 +2.0 Discp 31.17 -.11 -1.5 Dreyl 10.02 -.03 +0.5 DrSOOlnt 34.45 -.13 +4.8 EmgLd 42.15 -.56 +18.8 FLIntr 13.44 +.01 +15.6 InsMutn 17.98 +.02 +16,5 StrValAr 27.83 -.16 +15.3 Dreyfus Founders: GrowthBn 9.86 -.05 -8.4 GrwthFpnlO.29 -.05 -5.7 Dreyfus Premier: CoreEqAI 14.25 -.01 -3,0 CorVIvp 29.70 -.07 +3.7 LtdHYdAp 7.63 -.02 +24.3 TxMgGCt 15.20 -.01 -4.3 TciGroA 22.11 -.15 -18.5 Eaton Vance Cl A: ChinaAp 13,33 -.23 +38.3 GrwthA 7.15 -.05 +7.8 InBosA '6.58 -.01 +41.2 SpEqtA 4.49 -.06 -15.3 MunBdl 10.70 +.01 +23.2 TradGvA 8.83 ... +9.4 Eaton Vance Cl B: FLMBI 10.89 +.02 +15.8 HIthSBt 10.93 -.06 -0.6 NatlMBt 10.35 +.02 +27.4 Eaton Vance Cl C: GovtCp 7.60 ... +6.8 NaflMCI 9.86 +.02 +263 Evergreen B: BalanBt 8.31 -.01 +6.7 BtuChpB 23.45 -.04 -2.8 DvrBdBt 15.01 ... +173 FoundB 1671 -.04 +4.2 MuBdBt 7.49 ... +17.4 Evergreen I: CorBdl 10.68 ... +19.7 AdjRatel 9.40 +.01 +8.7 Evrgml 12.77 -04 +1.3 Foundl 16.80 -.03 +7.4 SlMunil 10.11 ... +12.4 Excelsior Funds: Energy 18.85 -.25 +51.2 HiYielkp 4.80 -.01 +19.7 ValRestr 41.33 +.15 +29.4 FPA Funds: NwInc- 11.19 ... +16.1 Federated A: AmLdrA 24.35 -.07 +7.4 CapApA 24.79 -.09 +3.9 MidGrStA 28.92 -.27 +9.5 MuSecA 10.79 +.01 +19.4 Federated B: StIncB 8.84 -.03 +34.1 Federated Instl: Kaufmn 5.17 -.04 +27.1 Fidelity Adv Foc T: HICarT 19.79 -.03 +1.3 NatResT 30.93 -.26 +35.3 Fidelity Advisor I: EqGrln 46.57 -.21 -10.2 Eqlnin 27.99 -.08 +18.2 IntBdln 11.12 -.01 +19.6 Fidelity Advisor T: BalancT 16.16 -.03 +9.5 DivGrTp 11,48 -.03 -1.8 DynCATp12.79 -.10 +1.0 EqGrTp 44.30 -.21 -11.8 EqlnT 27.68 -.08 +16.2 GovInT 10.06 ... +16.9 GrOppT 29.74 -.14 +2.8 HilnAdTp 9.97 -.05 +56.2 IntBdI 11.11 ... +18,7 MidCpTp 24.14 -.27 +29.2 MulncTp 13.17 +.01 +21.2 OvrseaT 17.23 -.06 +21.9 STFiT 9.52 ... +11.4 Fidelity Freedom: FF2010n 13.44 -.02 +14.4 FF2020n 13.69 -.04 +14.1 FF2030n 13.77 -.05 +12.7 Fidelity Invest: AggrGrrn 15.095 -.09 -16.8 AMgrn 16.01 -.03 +11.1 AMgrGrn 14.57 -.04 +7.7 AMgrlnn 12.50 -.04 +19.1 Balancn 17.33 -.11 +25.3 BlueChGrn40.71 -.16 -5.5 Canadan 32.48 -.44 +73.5 CapApn 24.99 -.18 +24.7 Cpincrn 8.43 -.02 +52.8 ChinaRgn 16.55 -.14'/+30.9 CngSn 387.49-1.05 +5.6 Contra n 54,82 -.31 +28.7 CnvScn 21.05 -.10 +17.2 Destl 12.49 -.05 -1.6 Destll 1160 -.06 +7.7 DisEqn 24.68 -.07 +11.8 Divlntin 27.89 -.08 +47.7 DivGthn 27.92 -.09 0.0 EmrMkn 12.50 -.12 +56.8 Eqlncn 51.54 -.17 +15.1 EQIIn 23.37 -.11 +16.1 ECapAp 20.99 -.08 +28.4 Europe 33.62 -.01 +35.5 Exchn 262.51 -.97 +12.9 Exportn 19.10 -.09 +18.5 Fideln 29.24 -.11 +3.4 Fifty rn 1986 -.14 +25.1 FrInOnen 24.57 -.10 +16.2 GNMAn 11.07 ... +15.9 Govtlncn 10.20 ... +17.5 GroCon 53.88 -.31 -1.3 Grolnen 37.56 -.08 +4.5 Grolnclln 9.53 -.02 +4.4 Highlncrn 9.08 -.02 +40.2 Indepn n 17.21 -.12 +08.1 IntBdn 10.49 ... +18.2 InlGovn 10.21 ... +15.0 InflDiscn 27.50 -.05.+45.7 IntSCprn 22.80 +.01 NS InvGBn 7.51 ... +19.8 Japann 12.55 +.05 +34.8 JpnSmn 1236 +.11 +92.7 LatAmn 19.97 -.25 +68.6 LowPr n 38.89 -.38 +53.9 Magellnno101.67 -.25 -1.1 MidCapn 22.49 -.15 -0.4 MtgSecn 11.22 ... +18.0 NwMktrn 14.13 -.09 +60.0 NwMilln 30.22 -.32 I51 OTC n 33.32 -.27 ,rI Ovrsean 34:35 -.13 -".- PcBaSn 19.35 -.05 +37.2 PudEtnn 18.64 -.05 +19.8 RealEn 27.84 -.95 +78.1 STBFn 8.97 ... +125 SmCaplndn19.06-.19 +18.4 SmIlCpSrn17.45 -.19 +32.4 SEAsian 16.10 -.06 +42.9 SikStcn 22.27 -.09 +5.4 Stratlncn 10.71 -.02 +40.3 Trend n 52.37 -.18 +7.0 USBIn 11.11 ... +203 UltRiyn 13.28 -.03 +2.4 ValStrtn 35.30 -.65 +24.8 Valuen 68.66 -.72 +40.2 Wrldwn 17.74 -.08 +20.8 Fidelity Selects: Airrn 32.11 -.14 +3.4 Autlonn 33.59 -.29 +37.3 Bankng n 38.91 -.09 +32.3 Blotchn 55.50 -.09 -12.1 Brokrn 54.26 -.37 +19.2 Chemn 64.84 -1.29 +53.3 Compn 33.36 -.23 -18.5 Conlndn 24.04 -.18 +9.7 CstHon 41.68 -.53 +01.9 DfAern 62.17 i.11 +45.1 DvCmn 18.40 -.11 -4.8 Elecrn 35.64 -.31 -34.6 Enrgyn 30.91 -.30' +37.8 EngSvn 40.52 -.36 +40.9 Envirn 13.64 -.18 +12.1 FinSvn 114.94 -.47 +24.7 Foodtn 49.44 -.42 +21.3 Goldrn 25.46 -.04 +2.4 Healthn 125..11 -.19 +3.0 HomFn 61.41 -.74 +47.0 IndMtn 37,93 .-.51 +59.3 Insurn 60.90 -.19 +35.4 Leisr n 76.22 -.62 +26.4 MedDIn 44.23 +.34 +66.0 MdEqSysn22.78 -.13 +47.0 Muirmd n 44.03 -.34 +24.6 NItGasn 28.13 -.34 +56,.0 Papern 31.86 -.47 +16,8 Pharmn 8.75 -.07 -6.4 Retailn 50,64 +.11 +21.2 Softwrn 50.36 =.52 +2.9 Techn 57.38 -.41 -10.6 Telmn 36.51 +.02 -1.1 Transn 40.63 -.39 +33.7 USilGrn 39.36 -.09 +4.2 Wirelassn 5.8 ... +2.3 Fidelity Spartan: CAMunn 12.56 +.01 +19,4 CTMo unrnll.71 +.01 +19.1 Eqidxn 41.87"-.15 +5.3 500M1nrn 81.44 -.29 +5.9 FLMurn 11.73 ... +19.3 Govont 11.02 ... +18.9 InvGrBdn 10.64 ... +20.9 MDMurn11.05 +,01 +18.3 MAMunn 12.12 +.01 +20.5 MIMunn 12.11 +.01 +20.4 MNMunn 11.62 ... +18,4 Munilncn 13.09 ... +22.0 NJMunrn11.70 +.01 +19.9 NY Munn 13.07 .. +21.9 OrMunn 11.98 ... +20.7 PAMunrnll.03 +.01 +19.4 StInltMun 10.38 ... +11.1 TotMklnn32.12 -.18 +10.7 First Eagle: Gibla 38.06 -.25 +73.7 OverseasA21.38 -.12 +86.8 First Investors A BIChpAp 19.87 -.08 -5.8 GabblAp 6.46 -.05 +8.8 GovlAp 11.06 -.01 +13.7 GrolnAp 12.81 -.07 +6.1 IncoAp 3.25 -.01 +36.4 InvGrAp 10.04 ... +21.3 MATFAp 12.10 ... +18.5 MITFAp 12,78 ... +17.3 MkiCpAp 24.38 -.20 +17.8 NJTFAp 13.11 ... +16.0 NYTFAp 14.60 ... +17.7 PATFAp 13.32 ... +17,8 SpSitAp 18.64 -.27 +6.0 TxExAp 1025 .. +17.6 TotRtAp 13.42 -.05 +10.6 ValueBp 6.24 -.03 +10.1 Firsthand Funds: GIbTech 4.05 -.08 -27.0 Tech Val 27.61 -.20 -37.6 Frank/Temp Fimk A: AGEAp 2.15 -.01 +43.3 AdjUSp 9.02 ... +6.5 ALTFAp 11.62 ... +20.4 AZTFAp 11.16 ... +21.1 Ballnvp 56.14 -.61 +45.3 CallnsAp 1268 +.01 +18.4 CAIntAp 11.66 ... +16.2 CalTFAp 7.27 +.01 +17.9 CapGrA 10.75 -.05 -1.5 COTFAp 12.03 +.01 +19.0, CTTFAp 11.08 +.01 +18.8 CvlScAp 15.91 -.08 +28.0 DblTFA 11.93 +.01 +19.5 DynTchA 23.54 -.10 +12.1 EqlncAp 20.32 -.07 +13.4 Fedlntp 11.57 ... +18.7 FedTFAp 12.13 +.01 +19.4 FLTFAp 12.00 +.01 +19.6 GATFAp 12.14 +.01 +19.1 GoldPrMA17.33 -.09 +83.0 GMlhAp 32.72 -.15 +2.2 HYTFAp 10.77 +.01 +21.3 IncomA9 2.47 -.01 +42.2 I HW ST RAD HE UTALFND ABLS: Here are the 1 000 Diggest mutual lundis lisled on Nasdaq Tables snoW the lund name sell price or Nei Asset Value INAV) and daily nel change. as well as one tolal return Ilgure as lollowos. Tues: 4 wK total rleurn ("4. Wed: 12-mo total return |'l| Thu: 3-yr cumulative total return (,,i FrI: 5-yr cumulative total return ~.ol Name: Name of01 nmulual fund and larrmly. NAV: Nei asset value Chg: iet change in price ol NAV Total return: Perceni change ,rin NAV for the time period shown. with diidendas reinvested II period longer than 1 year return is cumula- live Data r3sea on NA'I4s reported to Lipper b) 6 p m. Eastern Footnotes: e E%-capilal gari.s ditribuiian I Previous day's quote n No-load lund p Fund assets used to pay distrioulion cosis r Redemption tee or contingent delerred sales load may apply s SItock dividend or split I Boih p and r x Ex cash divi dena. NA ti mniormarionr available NE Data in question NN - Fund does not wish to be tracked. NS Fund did nol exist at starl date Source: Lipper, Inc. and The Associated Press InsTFAp 12.38 ... +19.1 NYITFp 11.12 +.01 +18.0 LATFAp 11.68 ... +19.7 LMGvScA 10.15 -.01 +10.4 MDTFAp 11.77 +.01 +18.8 MATFAp 11.96 +.01 +19.3 MITFAp 12.33 ... +18.5 MNInsA 12.22 +.01 +18.1 MOTFAp 12.27 ... +19.5 NJTFAp 12.13, +.01 +19.5 NYInsAp 11.69 ... +19.0 NYTFAp 11.90 ... +18.9 NCTFAp 12,32 +.01 +20.3 OhiolAp 12.60 ... +18.3 ORTFAp 11,86 +.01 +20.0 PATFAp 10.45 ... +18.7 ReEScAp25.08 -.77 +75.1 RisDvAp 31.43 -.15 +29.6 SMCpGrA 32.63 -.31 +2.2 USGovAp 6.63 ... +14.8 UlilsAp 10.81 -09 +27.9 VATFAp 11.87 ... +19.7 Frank/Temp Frnk B: IncomBI p 2.47 -.02 +40.1 IncomeBt 2.46 -.02 +39.0 Frank/Temp Frnk C:' IncomCt 2.49 -.01 +40.5 Frank/Temp Mtl A&B: QualfdAt 18.98 -.15 +27.9 SharesA 22.45 -.17 +24.0 FrankrrTemp Temp A: DvMktAp 18.00 -.26 +83.7 ForgnAp 12.03 -.11 +34.6 GIBdAp 10.93 -.03 +62.2 GrwthAp 22.36 -.14 +35.1 IntxEMp 14.48 -.11 +33,2 WorkdAp 17.32 -.15 +29.7 Frank/Temp Tmp &C: DevMktC 17.70 -.26 +80.2 ForgnCp 11.90 -.10 +31.6 Fremont Funds: Bond 10.43 ... +21.7 USMicro 30.80 -.39 +0.8 GE Elfun S&S: S&Slnc 11.49 ... +19,9 S&SPM 44.29 -.16 +5.2 GMO Trust III: . EmMkr 16.64 -.14+102.5 For 14.62 -.06 +56,0 GMO Trust IV: EmrMkt 16.60 -.15+101.8 Gabelli Funds: Asset 40.15 -.33 +25.1 Gartmore Fds D: Bond 9.71 ... +22.0 GvtBdD 10.29 ... +17.2 GrowthD 6.50 -.03 -3.3 NatonwD 19.74 -.08 +10.0 TxFrr 10.64 ... +18.8 Goldman Sachs A: GrlncA 24.54 -.12 +25.2 SmCapA 40.69 -.67 +47.2 Guardian Funds: GBG IntA 13.01 -.02 +15.9 ParkA A 30.67 -.11 -3.3 Harbor Funds: Bond 11.79 -01 +22.6 CapApnst 27.89 -03 -5.7 Intlr 41.65 -19 +49.2 Hartford Fds A: AdvrsAp 14.87 -02 +2,8 CpAppAp 32.71 -35 +21.2 DivGthAp 18.41 -10 +15.5 SmlCoAp 15,80 -.20 +11.9 Hartford HLS IA: CapApp 51.14 -.56 +29.4 Di&Gr 20.27 -.11, +17.0 Advisers 22.72 -.03 +3.1 . W:... Ju 2 -.10 -4.2 H,:,IelFar .i, 4i -.02 +2.2 ISl Funds. NoAmp 7.34 +.01 +16.8 JPMorgan A Class: CapGro 37.00 -.32 +9.5 GroTnc 32.28 -.13 +13.5 Janus : Balanced 20.89 -05 +13.0 Contraian 12.80 -14 +35.8 CoreEq 19.84 -.08 +10.8 Enterprn 36.10 -.31 +12.4 FedTEn 7.08 ... +16.0 Ftxlncn 9.67 ... +21.4 Fundtn 23.84 -11 -5.3 GIUfeScirn17.50-.03 +2.0 GITech rn 10.22 -10 -19.9 Gdin 31.22 -.16 +4.9 Mercury 20.94 11 -,11 -1.3 MdCpVal 21.26 -.24 +35.6 Olyrpusn27.59 -.17 -3.1 Orionn 6.63 -06 +9.0 Ovrseasr 23.44 -.22 +17.4 ShTmBd 2.91 ... +9.7 Twenty 43.56 -.03 +12.8 Venturn 55.36 -.70 +24.9 WridWr 40.56 -.20 -6.0 Janus Aspen Instp: Balanced 23.98 -.06 +13.3 WridwGr 26.26 -.12 -6.0 JennisonDryden A: HiYIdAp 5.92 -.01 +35.0 InsuredA 11.01 +.01 +17.2 UtIityA 11.27 -.09 +22.2 JennisonDryden B: GrowthB 12,81 -.01 -9.1 HiYIdBt 5.91 -.01 +33.0 InsuredB 11.03 +.01 +16.4 John Hancock A: BondAp 15,30 +.01 +20.9 HiYldAp 5,28 -.02 +49.8 StlnAp 7.12 ... +34.8 John Hancock B: SwncB 7.12 ... +32.1 Julius Baer Funds: IntlEqA 30,94 -.15 +54.3 InlEqlr 31.46 -.16.+56.2 Legg Mason: Fd OpporTrt 15.01 -.16 +47.7 Splnvp 44.96 -23 +49.2 ValTrhp 63.44 -20 +23.6 Legg Mason InstI: ValTrInsl 69.17 -.21 +27.4 Longleaf Partners: Partners 30.74 -21 +28.2 SmCap 29.13 -.32 +50.8 Loomis Sayles: LSBondl' 13.68 -.03 +60.4 Lord Abbett A: AlitAp '14.40 -.07 +14.4 BdDebAp 8.16 -.02 +27.5 . GIIncAp 7.55 .... +38.2 MidCpAp 21.67 -26 +35.3 MFS Funds A: MITAp 16.84 -.05 +2.2 MIGAp 12,02 -.05 -7.7 GrOpAp 8.61 -.04 -4.2 HilnAp 4.01 -.01 +34.2 MFLAp 10.19 ... +19.5 TotRAp 15.72 -.05 +20.2 ValueAp 22.60 -.08 +19.8 MFS Funds B: MIGB 11.05 -.04 -9.5 GvScBt 9,68 ... +13.0 HilnBt 4.02 -.01 +31.2 MulnBt 8,68 +,01 +17.4 TotRBt 15.72 -.04 +18.0 MalnStay Funds B: BIChGBp 9.19 -.02 -17.1 CapApBI 26.29 -.08 -16.1 ConvBt 12.66 -.08 +11.3 GovtBt 8.33 +.01 +11.9 HYIdBBt 6.50 -.01 +48.7 InlEqB 12.49 -.02 +41.0 ResValBt 11.09 -.03 -2.6 SrnCGBp 13.66 -.19 -1.7 TolRIBt 18.26 -.04 -1.0 Mairs & Power: Growth 68.35 -.45 +32.9 Managers Funds: SpdEqn 86.14 -1.15 +19.9 Marsico Funds: Focusp. 16.26 ... +17.5 Merrill Lynch A: GLAIAp 16.21 -.04 +38.0" HealthAp 6.15 +.01 +3.2 NJMunBd 10.55 +.01 +19.4 Merrill Lynch B: BalCapBt NA BaVIBt 30.51 -.03 +13.3 BdHilnc 5.35 -.01 +39.5 CalnsMB 11,76 +.01 +16.5 CiEPt8t NA CpTrBt 11.95 ".. +17.7 EquityDiv 13.93 -.07 +21.0 EuroBt 14.37 -.04 +33.9 FocValI 12.26 ... +9.2 FndlGBt 15.36 -.10 -8.6 FLMet 10:34 ... +18,9 GIAIBt 15.91 -.05 +34.7 HeatrBt 4,66 .. +0.7 LatABt 22.08 -.18 +76.4 MnlnBt 7.92 +.01 +17.4 ShTUSG t 9.26 ,.. +6.6 MLtdBI 10.03 ... +4.8 MulntBI 10.67 +.01 +17.8 MNtIBI 10.54 +,01 +19.8 NJMBt 10.55 +.21 +18.1 NYMBI 11.10 +.21 +16.0 NatRsTBt30,41 -.36 +62.2 PacBt 18.73 +.04 +27.3 PAMBt 11.33 +.01 +18.1 ValueOppt23.57 -.30 +12.6 USGvMItg t .25 ... +12.5 Utircmrt 10.42 -.06 +15.5 WidlnBt 6.55 -.01 +46.6 Merrill Lynch I: BalCapl .. .. NA BaVll 31.16 -.03 +16.9 BdHilnc 5.34 -.02 +42,5 CalnsMB 11.76 +.01 +18.4 CrBPIIt ... ... NA CplTI 11.95 ... +19.6 DvCapp 16.47 -.18 +54.2 EquityDv 13.88 -.07 +24.7 Eurolt 16.68 -.04 +3B.2 FocVall 13.40 ... +12.6 FLMI 10.34 ... +20.7 GIAIIt 16.25 -.04 +38.9 Healhl 6.65 ... +3.9 LatAt 23.08 -.19 +82.1 Mnlnl 7.92 +.01 +20.1 MLtdl 10.03 ... +5,9 MulTI 10.67 ,, +18,9 MNaIll 10.54 +.01 +22.5 NatRsTrt 31,99 -.38 +67.2 Pad 20.35 +.06 +31.4 ValueOpp 26.12 -33 +16.2 USGvtMIg 10,25 ... +15.0 UlIcmlt 10.44 -.06 +18.2 WldlncI 6.55 -.02 +50.1 Midas Funds: Midas Fd NA Monetta Funds: Moneltan 10.01 -.06 +3.5 Morgan Stanley B: AmOppB 22.40 -.11 -6.4 DivGtB 36.20'-.15 +6.8 GIbDivB 13.63 -.03 +23.4 GrwthB 11.79 -.05 -7.8 StratB 17.33 -.09 +10.1 USGVtB 9.15 ... +15.6 MorganStanley Inst: GIVaIEqAn17.47 -.04 +18.0 IntlEqn 20.57 -.06 +47.8 Munder Funds: NetNetAp 17.99 -.20 -6.4 Mutual Series: BeacnZ 15,58 -.11 +28.2 QualfdZ 19,06 -.15 +29.2 SharesZ 22.56 -.17 +25.3 Nations Funds Inv B: FOcEqBt 17.22 ... +15.3 MarsGrBt,16,52 ... +18.6 Nations Funds Pri A: IntVIPrAn 22.31 -.07 +46.1 Neuberger&Berm Inv: Focus 36.17 -.22 -0.7 Intlr 17.92 -.07 +58.3 Neuberger&Berm tr: Genesis 40.83 -.47 +44.0 Nicholas Applegate: EmgGroln 9.62 -.15 -3.3 Nicholas Group: Nich n 59.02 -.24 +8.9 NchIntn 2.23 ... +19.9 Northern Funds: SmCpldxn 9.73 -.18 +25.7 Technlyn 11,31 -.09 -15.3 Nuveen Cl R: InMunR 11.02 +.01 +18.5 Oak Assoc Fds: WhiteOkG 2.82 -.21 -20.5 Oakmark Funds I; Eqtylncrn22.96 -.08 +30.6 Global n 21.30 -.07 +0.5 Intllrn 20.86 -.06 442,9 Oanmarkrn40.88 -.10 +16.6 Selectrn 32.40 -27 +198 One Group I: Bondl In 10.89 ... +19.7 Oppenheimer A: AMTFMu 9.92 +.01 +26.3 AMTFrNY 12.53 +.02 +18.9 CAMuniAp 10.91 +.01 +24.1 CapApAp40.25 -.16 -22 CaplcAp 12.25 -.05 420.5 ChlncAp 9.69 -.03 +30.8 Discp 41.25 -.33 +2.0 EquayA .10.51 -.06 +11.4 GlobAp 58.97 -.28 +25.7 GIbOppA 31.94 -.33 +39.9 Goldp 17.30 -.14 +98.0 HiYdAp 9.77 -.02 +30.7 LtdTmMu 15.41 ... +24.8 MnSIFdA 34.61 -.12 +7.5 MidCapA 15.88 -.02 +5.7 PAMuniAp12.29 +.01 +30.3 StlnAp 4.29 -.01 +37.3 USGvp 9.71 +.01 +18.0 Oppenheimer B: AMTFMu 9.88 ... +23.4 AMTFrNY 12.53 +.01 +16.0 CplncBt 12.14, -.05 +17.6 ChlncBt 9.68 -.03 +27.9 EquityB 10.18 -.06 +8.4 HiYIdBt 9.62 -.02 +27.8 StrlncBt 4.31 -.01 +34.5 Oppenhelm Quest: OBaA 17.62 -.08 +10.6 OQBalB 17.41 -.07 +82 Oppenheimer Roch: RoMu A p17.76 +.02 +22.2 PBHG Funds: . SelGrwthrn21.56 -.11 -13.0 PIMCO Admin PIMS: TotRIAd 10.63 -.01 +21.3 PIMCO Instl PIMS: AIIAsset 12,52 -.07 NS ComodRR 14.39 -.07 NS HiYId 9.95 -.02 +33.6 LowDu 10.17 -.01 +13.1 RealRtnl 11.39 -.04 +37.5- ShortT 10.03 ... +7.4 TotRI 10.63 -.01 +22.2 PIMCO Funds A: RenaisA 25.54 -.33 +27,4 RealRtAp11.39 -.04 +35.7 TotRtA 10.63 -.01 +20.5 PIMCO Funds C: GwthCt 17.44 -.04 -8.2 TargtCt 15.29 -.09 +0.5 ToIRICI 10.63 -.01 +17.8 Phoenix-Aberdeen: InItA 9.96 -.06 +25.4 WldOpp 8.33 -.04 +15.1 Phoenix-Engemann : SCapGrA 14.75 -.06 -7.3 Phoenix-Oakhurst: BalanA 14.73 -.05 +9.6 StrAIIAp 15.55 -.04 +10.0 Pioneer Funds A: BalanA p 9.57 -.01 +5.0 BondA p 9.36 ... +25.0 EqlncAp 27.98 -.18 +14.4 EuropAp 29.57 -.10 +21.6 GrwthAp 11.81 -.06 -16.7 HiYIdAp 11.49 -.04 +34.5 IntValA 17.03 -.06 +23.5 MdCpGrA 14.47 -.12 -0.7 MdCVAp 24.01 -.20'+39.8 PionFdAp 40.92 -.14 +5.4 TxFreAp 11.67 +.01 +18.4 ValueAp 17.29 -.06 +12.6 Pioneer Funds B: HiYldBt 11.54 -.03 +31.6 MdCpVB 21.57 -.18 +36.2 PIoneer Funds C: HiYldCt 11.64 -.04 +31.6 Price Funds: Balance n 19.38 -.04 +19.3 BIChipn 30.19 -.07 +3.8 CABondn 11.09 +.01 +18.0 CapAppn 19.08 -.08 +41.9 DiGron 22.41 -.09 +10.5 Eqlncn 25.98 -.10 +21.2 Eqlndexn 31.81 -.12 +5.5 Europe n 19.53 -.07 +25.0 Fttnrrnn 11.02 +,01 +15.1. GNMAhn 9.64 .. +15.7 Growthn 26.08 -.05 +7.9 Gr&ln 21.92 -.09 +42 HlthSdcn 22.34 -.10 +13.7 HiYieldn 7.20 ... +38.5 ForEqn 15.11 -.05 +19.1 IntlBondn 10.53 +.01 +58.1 IntDssn 32.04 -.18 +65.3 Intls0fn 12.66 -.05 +17.3 Japan n 8,33 ... +35.0 LatAmn 15.13 -.16 +63.8 MDSlrtn 5.19 ... +6.5 MDBondnl0.80 +.01 +18.7 MidCapn 47.73 -.44 +23.5 MCapValn22.25 -.18 +47.3 NAmern 32.14 -.12 +2.4 NAsian 9,86 -.13 +54.2 New Eran31,99 -.37 +54.3 N Hoans 28.05 -.24 +22.9 Nlncn 9,08 ... +18.7 NYBondn 11.42 +.01 +19.3 PSIncn 14.64 -.03 +23.8 ShIBdn 4.75 ... +10.8 SmCpStkn30.32 -.45 +26.8 Specinn 12.01 ... +31.4 TFIncn 10.06 +.01 +19.5 TxFrHn 11.79 +.01 +21.5 TFIntmn 11.31 +.01 +15.6 TxFrSIn 5.43 ... +10.4 USTIntn 5.43 ... +15.8 USTLg n 11.82 +.02 +25.8 VABondn 11.75 +.01 +19.6 Valuen 22.35 -.11 +19.9 Putnam Funds A: AmGvAp 9.05 ... +13.4 AZTE 9.33 .. +17.4 CiscEqAp 12.48 -.04 +5,4 Conv p 17.28 -.09 +34.0 .DiscGr 16.60 -.11 -5.8 DvrlnAp 10.30 ... +37.9 EuEq 20.51 -.06 +21.2 FLTxA 9.29 ... +16.9 GeoAp 17.81 -.03 +13.6 GIGvAp 13.08 +.01 +44.5 GbEqtyp 8.24 -.03 +13.0 GrInA/p 18.98 -.07 +9.8 HIthAp 57.63 -.30 +0.7 HiYdAp 8.24 -.02 +39.3 HYAdAp 6.20 -.01 +39.5 IncmAp 6.83 ... +18.3 IntUSAp 5.12 -.01 +11.2 IntlEqp 23.13 -.08 +18.4 IntGrlnp 11.61 -.04 +37.8 InvAp 12.29 -.04 +5.0 MITxp' 9.06 ... +16.0 MNTxp 9.09 ... +17.9 MuniAp 8.75 ... +16.4 NJTxAp 9.24 ... +16.6 NwOpAp 40.06 -.21 -4.9 OTC A p 7.01 -.06 -9.5 PATE 9.17 ... +18.6 TxExAp 8.88 ... +18.1 TFInAp 15.11 +.01 +18.5 TFHYA 12.81 ... +17.1 USGvAp 13.24 ... +13.3 UIlAp 10.02 -.06 +11.1 VstaAp 9.12 -.05 +3.6 VoyAp 16.19 -.06 -8.3 Putnam Funds B: CapAprt. 17.19 -.14 +3.4 CiscEqBt 12.38 -.04 +3.0 DiscGr 15.41 -.10 -7,9 DvrinBt 10.22 ... +34.5 Eqlnct 16.91 -.07 +16.4 EuEq 19.84 -.06 +18.4 FLTxBO 9.29 ... +14.7 GeoBt 17.63 -.04.+11.0 GIIncBt 13.04 +.02 +41.3 GIbEqt 7.54 -.02 +10.7 GINtRst 21.62 -.13 +42.3 GrInBt 18.70 -.07 +7.3 HIlNBt 52.72 -.27, -1.6 HiYIdBt 8.20 -.02 +36.2 HYAdBt 6.12 -.01 +36.2 IncmBnt 6.79 ... +15.8 InGrint 11.42 -.05 +34.5 IntNopt 10.65 -.07 +21.9 InvBt 11.31 -.04 +2.6 MuniBt 8.75 +.01 +14.5 NJTxBt 9.23 ... +14.3 NwOpBt 36.19 -.19 -7.0 NwValp 17.24 -.09 +20.7 NYTxBt 8.80 ... +15.6 OTCBt 6.23 -.05 -11.5 TxExBt 8.89 +.01 +15.9 TFHYBt 12.83 ... +15.1 TFInBt 15.13 ... +16.2 USGvBt 13.16 -.01 +10.7 UtilBt 9.96 -.07 +8.5 VistaBt 8.01 -.04 -1.4 VoyBt 14.17 -.05 -10.4 Putnam Funds M: Dvrlncp 10.21 -.01 +36.6 RS Funds: RSVaGtr 15.97 -.12 +10.9 Royce Funds: LwPrStkr 14.49 -.24 +26.3 MicroCap 15.08 -.18 +44.8 Premier r 14.41 -.21 +46.6 TotRetlr 11.82 -.14 +42.3 Rydex Advisor: OTCn 10.16 -.05 -11.9 SEI Portfolios: CoreFxA n 10.54 ... +20.3 InlEqAn 10.80 -.02 +24.7 LgCGroAn18.10 -.02 -9.2 LgCValAn20.80 -.09 +16.9 STI Classic: CpAppLp 11.26 -.02 -7.6 CpAppAp11.90 -.02 -.3 TxSnGrTp24.23' -.08 -3.4 TxSnGrLt 22.77 -.07 -6.4 VIInStkA 12.28 -.06 +14.6 Salomon Brothers: BalancBp 12.81 -.06 +16.0 Opporl 45.92 -.22 +12.3 Schviab Funds: 10001nvrn33.71 -.16 +7.3 S&Plnvn 18.20 -.07 +5.3 S&PSeln 18.26 -.06 +5.9 YIdPlsSI 9.69 ... +8.4 Scudder Funds A: DrHiRA 41.77 -.17 +17.6 FIgComAp 16.38 -.12 -14.2 USGovA 8.61 ... +14.3 Scudder Funds S: BalnS 17.19 -.05 +2.9 EmMkln 10.63 -.08 +62.7 EmMkGfr 16.90 -.10 +68.1 GIbBdSr 10.37 ... +31.1 GbDis 33.83 -.17 +43.2 GlobalS 25.86 -.10 +20.6 Gold&FPr 16.32 -.11+175,2 GrEuGr 26.55 -.13 +17.6 GrolncS 21.39 -.08 +2.1 HiYklTrrx 12.80 +.01 +21.5 IncomeS 12.97 .. +19,0 InITxAMT 11.45 +.01 +15.,9 IntlFdS 43.15 -.10 +19,4 LgCoGro 22.98 -.06 -12.2 LatAmr 0.36 -.35 +56,0 MgdMuniS 9.21 +.01 +19.1 MATFS 14.67 +.02 +19.9 -i ,,12+t 7.1 -.04 +42.3 iiii.': 11, '; . +9.2 SrmCoVlSr 25.42 -.56 +46.4 Selected Funds: AmShSp 36.11 -.15 +17.8 Seligman Group: FronlrAl 12.85 -.14 +8.1 FronIrOt 11.38 -.13 +5.7 GIbSmA 14.79 -.14 +22.5 GIbTchA 12.15 -.09 -12.3 HYdBAp 3.51 ... +22.7 Sentinel Group: ComSv A p 28.66 -.10 +13.2 Sequoia n152.22 -.30+18.1 Sit Funds: LrgCpGr 33.08 -.08 -5.3 Smith Barney A: AgGrAp 91.90 -.66 -2.2 ApprAp 14.35 -.06 +9.6 FdValAp 14.61 -.08 +3.9 HilncAt 7.07 -.01 +34.0 InAICGAp 1338 -.03 +10.3 LgCpGAp21.21-.11 +2.7 Smith Barney B&P: FValBt 13.79 -.08 +1.5 LgCpGBI 20.09 -.10 +0.5 SeCplnct 16.05 -.11 +23.7 Smith Barney 1: DvStrl 17.14 -.10 -9.2 GrIndc 14.96 -.06 +4.3 St FarmAssoc: GwthE 47.07 -.13 +9.7 State Str Resrch A: AuroraA 38.30 -.64 +27.4 HilncA p 3.58 -.01 +34.2 InvTrAp 9.83 -.04 +0.5 LegcyAp 13.22 -.04 +3.5 MCpGrAp 6.43 -.05 +5.1 State Str Resrch B: HilncB 3.58 -.01 +33.8 Strategic Partners: EquityA 14.91 -.05 +0.0 Stratton Funds: Dividend 34.52 -1.30 +5009 Growth 38088 -.44 +30.6 SmCap 38020 -.54 +51.1 Strong Funds: CmStk 21.72 -.24 +15.9 Discov 20.39 -.23 +30.2 GrCmlnv 18.58 -.16 +3.1 HiVMu ... ... NA LgCapGr 22.04 -.13 -9.4 Opplylnv 44.72 -.28 +11.9 . UtStlnov 9.20 ... +5.0 SunAmerdca Funds: USGivt 9.44 ... +17.0 SunAmerica Focus: FLgCpAp 17.21 -.04 +4.8 TCW Galileo Fda: SelEqty 19.02 -.07 +8.4 TD Waterhouse Fds: Dow30n 10.62 -.04 .+9.2 TIAA-CREF Funds: BdPlus 10.31 ... +20.4 Eqlndex 8.35 -.05 +8.9 Groenc 11.90 -.04 +0.4 GroEq 8.93 -.03 -9.8 HiYIdBd 9.49 -.01 +34.8 IntlEq 10.47 -.07 +34.5 MgdAlc 10.95 -.04 +15.8 ShtTrBd 10.53 ... +13.5 IngeM hr A. SocChEq 8.93 -.05 +10.1 TxExBd 10.94 +.01 +22.2 Tamarack Funds: EntSmCp 32.39 -.53 +44.8 Value 44.70 -.10 +20.7 Templeton Instit: ForEqS 19.80 -.16 +40.5 Third Avenue Fds: RIEslVIr 26.17 -.42 +78.6 Value 50.48 -.44 +40.2 Thrivent Fds A: HiYld 5.26 -.01 +28.4 Incomrn 8.80 ... +18.2 LgCpStk 24.97 -.08 -2.5 TA IDEX A: FdTEAp 11.88 +.01 +18.7 JanGrowp 23.08 -.13 -2.9 GCGlob p 23.97 -.11 -7.8 TrCHYBp 9.35 -.02 +26.1 TAFIxInp 9.65 ... +21.5 Turner Funds: SmlCpGrn22.62-.30 +8.8 Tweedy Browne: GlobVal 23.11 -.14 +30.6 US Glbbal Investors: AIIAmn '22.98 -.11 -3.6 GlbRs 9.92 -.16+189.3 GIdShr 7.61 -.02+160.2 USChina 6.39 -.16 +52.9 WIdPrcMn 15.34 -.10+229.8 USAA Group: AgvGt 28.56 -.03 -1.1 CABd 11.25 +.02 +19.4 CmstStr 26.09 -.13 +21.8 GNMA 9.80 ... +15.2 GrTxStr 14.40 -.01 +11.6 Grwth 13.48. -.02 -10.2 Gr&Inc 17:87 -.11 +6.7 IncStk 16.24 -.09 +9.2 Inco 12.39 ... +19.1 Intl 21.42 -.10 +36.5 NYBd 12.05 +.02 +20.8 PrecMM 14.49 -.05+138.4 SaTech 9.13 -.07 -12.5 ShtTBnd 8.95 ... +6.0 SmCpStk 13.00 -.18 +26.6 TxElt 13.34 +.01 +17.9 TxELT 14.17 +.02 +23.7 TxESh 10.76 ... +9.6 VABd- 11.76 +.01 +20.4 WIdGr 17.52 -.08 +21.9 Value Line Fd: LevGtn 24.17 -.21 -13.6 Van Kamp Funds A: CATFAp 18.91 +.03 +18.6 CmslAp 18.09 -.07 +19.8 CpBdAp 6.75 ... +192 EGAp 37.31 -.23 -13.6 EqincAp 8.44 -.03 +21.9 Exch 335.45-1.83 -6.0 GdnAp 19.66 -.08 +19.6 HarbAp 14,65 -.06 +14.3 HiYldA 3.73 -.01 +22.9 HYMuAp 10.72 +.01 +22.3 InTFAp -18.93 +.03 +19.3 MunlAp 14.81 +.02 +19.4 PATFAp 17.45 +.02 +17.3 StrMunlnc 13.13 +.01 +19.7 USGvAP'13.92 ... +13.8 LMIAp 16.30 -15 +11.1 Van Kamp Funds B: EGBt 32.04 -.20-15.5 EnterpBt 10.98 -.04 -14.2 EqlncBt 8.32 -.03 +19.2 HYMuBt 10.72 +.01 +19.6 MulB 14.79 +.02 +16.7 PATFBI 17.40 +.02 +14.6 StMunlnc 13.13 +.01 +17.1 USGvBt 13.86 -.01 +11.1 U/lB 16.28 -.16 +8.5 Vanguard Admiral: 500Admln109.07 -.39 +6.2 GNMAAdn1lO.42 ... +17.1 HlhCrn 52.23 -.22 +21.6 ITAdrr n 13.58 +.01 +16.3 UdTrAdn 10,91 +.01 +10.7 PrmCaprn62.49 -.38 +15.6 STsyAdmlnlO.45 ... +12.1 STIGrAdn 10.63 -.01 +12.0 TStkAdrmn27.96 -.6 +11.4 WeltAdmnn51.16 -.16 +21.3 Windsorn 59.20 -.39 +15.4 WdsrllAdn53.40 -.18 +24.6 Vanguard Fds: AssetAn 24.04 -.07 +15.4 CALTn 11.81 +.01 +19.5 CapOppn 29.44 -.19 +21.4 Convtn 12.99 -.06 +23.6 DivdGron 11.88 -.05 +7.3 Energy 38.20 -.28 +76.3 Eqlncn 22.88 -.13 +15.4 Explrn 70.98 -.88 +15.9 FLLTn 11.89 +.01 +21.6 GNMAn 10.42 ... +16.9 Grolncn 29.82 -.13 +6.2 GrahEqn 9.31 -.05 -6.1 HYCorpn 6.43 -.01 +28.5 HthCre'n123.78, -.53 +21.3 InflaPron 12.47 -.03 +35.1 InMlExpirn 16.04 -.09 +72.1 IntlGrn 18.45 -.14 +25.7 IntlVaIn 30.25 -.25 +40.3 ITIGrade n 10.03 ... +22.6 ITrsiyn 11.22 ... +21.2 UifeConn 15.06 -.03 +16.8 UfeGron 19.58 -.10 +17.2 Ufelncn 13.42 -.01 +16.3 UfeModn 17.59 -.06 +17.9 LTIGraden 9.51 +.02 +311 LTTsryn 11.48 +.03 +29.7 Morgn 15.78 -.09 +7.3 MuHYn 10.83 +.01 +19.7 MulnsLgn 12.81 +.01 +20.6 Mulntn 13.58 +.01 +16.1 MuLtdn 10.91 +.01 +10.5 MuLongn 11.48 +.02 +20.3 MuShnn 15.63 +.01 +602 NJLTn 12.08 +.01 +19.8 NYLTn 11.52 +.01 +21.2 OHLTTEn12.26 +.01 +21.0 PALTn 11.60 +.02 +20.6 PrecMtlsrn15.83 -.22+114.7 Pmscprn 60.25 -.36 +15.1 SelValurn17.59 -.15 +41.6 STARn 18.40 -.06 +20.0 STIGradenlO.863 -.01 +11.7 STFedn 10.39 ... +11.3 SnIatEqn 20.42 -.25 +42.0 USGron 15.71 -.05 -18.0 USValuen13.38 -.07 +19.8 Wellslyn 21.33 -.04 +21.7 CWellnn 29.61 -.10 +20.8 Wndsrn 17.54 -.12 +15.1 Wndslln 30.08 -.10 +24.2 Vanguard Idx Fds: 500 n 109.06 -.39 +6.0 Balancedn19.10 -.07 +15.1 EMktn 14.18 -.23 +69.7 Europe n 25.45 -.21 +33.1 Extendn 30.00 -.38 +31.2 Growth n 25.72 -.09 -1.7 ITBndn 10.64 ... +23.4 MidCapo 14.98 -.16 +29.5 Pacific 9.18 -.05 +42.7 REITrn 17.65 -.67 +71.9 SmCapn 25.48 -.40 +29.7 SmlCpVln13.29 -.24 +34.4 STBndn 10.11 -.01 +11.4 TolBndn 10.24 ... +17.3 Totllntln 12.31 -.11"+38.3 TotStkn 27.96 -.16 +11.2 Valuen 20.84 -.10 +152 Vanguard Instl Fds: Instldxn 108.15 -.39 +6.4 InsPIn 108.16 -.38 +6.5 TBIstn 10.24 .., +17.7 TSInstn 27.97 -.16 +11.6 Vantagepoint Fds: Growth 8.10 -.03 -5.0 Waddell & Reed Adv: CorelnvA 5.49 -.02 -3.9 Wasatch: SmCpGr 37.63 -.53 +12.8 Weltz Funds: PariVal 23.35 -.16 +14.3 Value 36.82 -.27 +18.0 Wells Fargo Insl: IndexI 47.42 -.17 +5.8 Western Asset: CorePlus 10.63 -.01 +27.4 Core 11.44 ... +23.4 William Blair N: GrowthN 10.35 -.05 -6.5 Yacktman Funds: Fundp 15.04 -.09 +58.6 -w-qp.0-4- a& w ____ am& - m dim "a oss "a a ft -a 4 m d *111m 4 a 0 --ow Goom-owdw m --ft 4mq- -m a m r"sg doe% ,mm ft 4 .0 - lwomo 4 a aWOEIM ---d=% I -o a -"pw. "a 4N.d --Ma MINW * -ow do-o a 4 mms a.---a mow b 4wasa a- 4-. 4 4 w f- a - 41 40 a.0 do-- --IS p a- a- ft~mb a * * -a -A SmallPid. VERTICL BLIN OUTLE 'A `A :A A ;A ^A ASAT. EJan.8-_ SGunter's Farm Paul's Parrots Inc. Feed & Nursery 7231 W. Grover Cleveland Blvd, S 3187 E Dunnelloni ld., -LHomnosassa, FL Dunnellon, FL 10:00 A.M.-11:30 A.M. 8:00 A.M.- 9:00 A.M. 10 A.M-1130A.M. Dog Pack 1 Dog Pack 2 Hr Dog Pack 3 Puppy Pack .* Rate .7in1 I Rabies,7ion1I . "I Rabies ,, S Borderna, Le Brdeela revention lea 7in 1 B i A \ Heartwomitest Heartwonntest IContProl d P uctjs Bordetella tewoii"ilg (0~1) $5700 $41oo AvailaleAtClinic. ,t.' $3000 s3000 Ferret Pack Rabies LowCost Cat Pack 1 Cat Pack 2 Kitten Pack Diem r Heartworm 4in V RFIP 4 in'Fle r1 9 e $50 Sa Leukemiairg,(St 111 . $ '2700 500 Prevention $41! $28"6 $3000 k Ple e..A Cats Fet tsMustBe Bn Canilers aild AltDogsMut BeOnLeashes. Ifapp9cablle, tag, fees are separate 4 The paer & an y otT r person msponsrie r'vlen has airglvorefuse to pay cancel paymenior A d State \ mbe mtnursedir the lee. discounted fe .e...r u f.d fe .. payment fot any oth.re .ia l 0 .... ... .... >..... \ ,f, 315-8100 A i N. w441 o M -IWM iShRs2000122.58 - IYR 1ShREst 115.51 SUR IShSPSm 154.50 - 2.51 INS InligSys 2.08 +.06 -IBD IntactBdn ,60 +.07 -"A -IIP IntrNAP 94 - HHH IntntHTr 6800 -0 .62 .' - IIH Inelnfra 4 24 .12 -IVX IvaxCps 1500 - ' .34 -KFX KFXCInc 12.81r-e - LFP LifePoln .27 - .01 - MRM Memmac 9.13 +09 Now 2 Locations FREE DEU VERY Quality & Value Since 1974 AMERICAN STOCKShXHANEmM EEM iShEmMkt 191.23 2.37 - TLT iSh20 TB 88.28 +.47 - IEF iSh7-10TB 84.73 +.14 SHY iShl-3TB 81.28 +.02 - EFA iShEAFE 155.95 .10 - IGW iShGSSem 50.49 .81 - IBB iShNqBo 71.75 .50 ICF iShC&SRIt128.15 5.45 - IWO iShROO0V 64.71 .41 - IWF iShR1000G 47 69 .32 IWN iShR2000V183.51 3.74 - IWO ShR2000G 63.50 1.12 629-0984 State Rd 200 > SouthTrust SW 17th St. I 2002 &KW 17th St. Ocala Tkr Name Last C FAX AbdAsPac 6.18 .01 AAC Ableaucn .79 .01 AE AdmnRsC 17.10 .25 SIL ApexSihl 16.03 AGT ApolloG g .74 .02 AVR Avrtar .15 .01 BGO BemaGold 2.89 .03 BBH BIotechT 148.50 .70 HIV CalypteB n .35 .02 CBJ Camblorg 2.49 .02 SNG CdnSEng 1.75 +.10 Chg CNY CarverBcp 2000 EAG EagleBbnd .66 -HEC Harken .51 - ... 03 +.O . CVM CtelS .63 -EGO EdorGid g 2.76 IGR ING GREn 14.36 .06 +.02 .47 CLN CetsionCp .58 EU EftePh 3.50 ISO ISCO Int .36 +.06 .02 CHC ChartMac 22.95 ECF Elwh 8.00 EWA iShAsta 16.24 .83 .05 +.06 JCS ComSys 11.80 EMA eMagin 1.06 -EWZ iShBrazl 20.55 .18 .02 .18 KRY Cryslallxg 3.41 FVD FTrVLDv 14.61 EWH IShHK 11.45 +.01 .26 .26 DHBl DHB Inds 16.70 FPU FaPUtil 18.55 EWJ iShJapan 10.60 +17 20 .01 DIA DJIA Diam 105.71 FRD FrIedmind 9.43 EWY iSh Kor 28.25 1.07 +.19 DOR DORBo .55 GSX GascoEnn 3.83 EWW IShMexico 23.93 .03 .02 23 - BIZ DSL.net h .30 GSS GoldStrg 3.55 EWT IShTawan 11 55 .04 .03 .05 DOC DIgtAngel 7.60 -GW GreyWol 4.75 -EWU iShUK 17.66 .61 10 +.01 EZM EZEM u14.85 -SIM GpoSlmec 6.35 -IW iShSP500 118.29 30 .63 .72 ra *LEISURE I LIVING "FURNITURE FOR FLORIDA" INVENTORY CLEARANCE SALE Large Selection a of Quality SIndoor & Outdoor I Furniture & Accessories On Sale Now! THURSDAY, JANUARY 6, 2o005 SbA --.""Copygighted Material.1 . .. _- y rIgr e * ia Syndicaed Coniaene r' Po e AvilIable from Commercial News Providers" m I qp 74W t ,/ 10A THURSDAY JANUARY 6, 2005 0- "Happiness is not a state to arrive at, but a manner of traveling." Margaret Lee Runbeck; CITRUS COUNTY CHRONICLE EDITORIAL BOARD Gerry Mulligan ... I...................... publisher Charlie Brennan ........................... editor Neale Brennan ..... promotions/community affairs Kathle Stewart ....... advertising services director Steve Arthur ............... Chronicle columnist Mike Arnold .....................m.... managing editor Jim Hunter ......................... senior reporter by Albert M.91 Curt Ebitz .......................... citizen member Williamson Mike Moberley ...................guest member 'You may differ with my choice, but not my right to choose." David S. Arthurs publisher emeritus COMMUNITY EVENT Celebrate our sea cows this weekend Downtown Crystal River is preparing for the annual hoopla that brings not only a heightened awareness to the celebrated manatee, but gathers residents and visitors togeth- er for a weekend of THE IS fun, food and enter- Manatee tainment. The Florida OUR OP Manatee Festival began in honor of It's a cele Wte endangered mammal that has, become the poster WHEN: 1 child of Citrus 5 p.m. Sa County. This year's and noon event will again Sunday. offer the most coml- E WHERE: prehensive as well. Crystal RI as entertaining 0 COST: $2 exhibits dedicated for guests to the manatee, older. highlighting the importance of pro- ..... tection and the impact on our community. J Each winter, the Crystal River and Kings Bay welcome the largest herd of the West'Indian manatees in the world. While we continue to struggle to maintain A balance between the protected animal and the unavoidable growth along this coastline, we qan be pleased with the harmo- ny we've found. Visitors come to witness this unique environment and we can extend that welcome Not just Southern C 0O I'm reading Sunday's paper and I'm reading Sound Off and I'm reading .. "Elder respect"... I real- ly, really and truly resent going into a doctor's office or a dentist's office or any I other office to do business CALL and they call you by your first name. .563 I mean, I'm old enough to be their great-great- grandmother and they're calling me by my first name. So I suggest to this caller who said "elder respect." that it isn't just because you were born in the South. You don't have to be born in the South to be respect- ful of your elders. Stop the sprawl I'm calling about the urban sprawl editorial. Citrus County's not the only place with the problem; the entire state of Florida is filling with urban sprawl. In another 50 years, the state will be completely paved over, with houses 3 feet apart and shopping centers every three blocks. It's getting tQ be ridiculous. A lot more has to be done to control it, otherwise we'll have no trees, no wildlife, no place to even turn around. Sticker shock Handicapped stickers should not be given to a person just because they are overweight or just plumb lazy. I think there ought to be a greater review of the stickers hand- ed out. Give it to the real people that really need it. Global Warming You see that Arctic air dipping all the way down into southern Texas and snow in New Orleans? Wow, talk about global warming. You know-it's here. F Ic at C :s 10' I I ,I mat with pride. This year's two-day festival comes with a reputation of past accomplishments as well as a promise of more crafters and fine arts exhibitors from across the SUE: nation, expanded Festival. children's games and activities, increased INION: vendors for all tastes, and even better bration. Jimmy Buffett imita- tors to highlight the ongoing entertain- 0 a.m. to ment turday A large portion of to 4 p.m. the festival is dedi- cated to educational Downtown booths and displays ver. that will tell the story donation of these passive, 12 and portly mammals. Skilled boat captains will again maneuver their vessels in the waterways to give hundreds the opportunity of seeing manatees in their native habitat. Children's posters illustrating the tales of.the manatee will be on display. It's time -to show off, to appre- ciate, to browse, to purchase, to taste, to applaud and to learn. With the manatee taking center stage, volunteers and businesses work together to give thousands the opportunity to have a good time. Don't miss it! Pedestrian risk I just finished reading the article in the Chronicle this morning about the sheriff's plans to boost manpower. I'm just wondering if, by charice, they never men- tion anything about traffic, 0579 which is normal for the 057 sheriff's (office) since I've lived here in 20 years. Traffic is a bad name, I guess, because they don't enforce it... So I was just wondering if Dawsy just might find a few deputies to enforce traffic, especial- ly in Beverly Hills. We have them running through the stop sign at Barber and New York Boulevard. We have them running up and own New York Boulevard at speeds you wouldn't believe. And th6 poor peo- ple that walk. I don't walk, but the people that walk are really pushing their luck. Have a good, happy New Year. Plane chutes I see I am not the only person who thought of parachutes to lower small planes in trouble or out of gas. (Someone) used it on his Cessna to land it safely. As soon as I saw the chute to slow down the space plane landing at Cape Canaveral, my first words to my husband was, "Stan, why don't they use chutes on commercial planes in trouble?" Stop the engine and release a chute to lower planes safe- ly. It would need an ejection chute similar to ejection chutes on mili- tary planes. I'm quite sure we will have it soon. Santa letter My favorite "Dear Santa" letter from the children was from Ashley. She was a real sweet girl and she didn't ask for much at all. She was lovely. ACWUVisdeM" piimp.-WI, u q -- ,- --- 111al ..W .0 qm Iu -als _P -- i .. .. .._ o- ---- on rl ll M tr l --- .-- T -m -/I l I " ____-_ AA - -aft -0.0II Il- Mi,"CIylgldara ~ -0- --0.. 0-00 ___ 1111111a-. snow.na -m A Dablae from Cimmeift. Ne Prv 41,411- -ano miiW 11M.0 411411 41F401 m -A 40alolms 0 dmm - o.mo-w 0odb qm ft- -MO - m 6 ft d-O mo -lmmbdm 4-0 4140 0 qb -am *bm qr 0 -1 w dmism 4wmfi Gb- bmw m - ompam V q am Vm 410 r a- b 0 q q dom4W 40-wM oso w a- ~- 4b~ o- mmama Naob mlom 4bi- w 4o im- 40 b-- s qmp. 0 ob. ft- -do -m *bm 4a -m. lb -00 40 n 0 -low--ow qb- 0 amS mm Amk -or ql 0 f -o f 4hmoa 0- Q* 41M S 40090M w 411ONM w" -00 -meow 0---wm q- dho o up 41b40boqD bm w- SW UTTERS^ to Elementary lofts have greater meaning The Chronicle had a great article about the reading lofts at Hernando Elementary School, but one must wonder if these new teachers know the story and the legacy behind these lofts. Seven or eight years ago, the kindergarten teachers at Hernando organized a Dads Club to repair, repaint, etc., all the toys for the kids. Then the teachers showed an ad for reading lofts to the Dads Club and asked if we could build them. We were fortunate to have several dads who were excellent woodworkers and the most experienced of all was Maurice Hammond, a grandfather of one of the students, who had a fan- tastic wood- shop. Six lofts were made as more or less an assembly line so that all parts were interchangeable, and one was put up at Hernando Elementary School. Everyone in the community thought it was fantastic except for one guy in the school administration who did everything he could to block this project Finally, we had Gov. Lawton Chiles step in, and he actual- ly came to our community to cut the ribbons to officially, open all the reading lofts. We put the remaining five together@chronIclinllne.com, in one evening one long evening. One dad was a sergeant in the National Guard and his unit was shipping out the next morning for Desert Storm, but he was there until past midnight. Sam Himmel, our new school superintendent, was there for many hours working a power drill. School administrator Jimmy Hughes was there for hours. The lofts were ready for the kids on the Editor -- schedule and they are a wonderful aid to the teachers. These reading lofts are more than that they are an example of inno- vative thinking by our teachers, together with dedicated dads, a trib- ute to the American tradition of sticking to your guns to get a. worth- while project done. But most impor- tant of all, these reading-lofts are a tribute to a kindly man, Maurice Hammond, who was taken by cancer less than a year after the lofts he worked so hard on were up and ready for the kids. Harry Cooper Hernando Thanks to community service, pests are gone Thanks to the efforts of Aero Termite and Pest Control, the Annie Johnson Senior Center at 1991 W. Test Court in Dunnellon is now free of pests and termites, which were causing a multitude of structure problems to the old building. The staff and seniors appreciated the fact that Richard Mell and crew provided this service at their cost in the true spirit of community service. Our many thanks to Aero Termite and Pest Control. Barbara McKinnon Annie Johnson Senior Center! !URSDAY, JANUARY 6, 2005 11A CITRusi CoINTiY (FL) CHRONICLE GOLD ANY TYPE NEW OR OLD 10K 14K 18K 22K 24K WE BUY ALL SOLID GOLD ITEMS - NEW USED OR BROKEN High School Rings up to............... CA$H prices by these designers. lA IJ FOR ANTIQUES All Diamond Engagement Rings All Diamond & Art Deco Jewelry ALL DIAMOND & ART DECO JEWELRY ALL TYPES & SIZES We will pay you CA$H so we can quote you an accurate price on your items. Silver Coins Gold Coins *Silver Coins We ill Buy 1A U.S. Minted Coins $1.00 Gold Coins (US) $2.50 Gold Coins (US) $3.00 Gold Coins (US) $5.00 Gold Coins (US) $10.00 Gold Coins (US) $20.00 Gold Coins (US) $70.00 to $70.00 to $85.00 to $80.00 to $150.00 to $400.00 to $2,500.00 $2,500.00 $3,500.00 $2,500.00 $2,500.00 $4,200.00 Also Buying Foreign Gold Coins. Prices are subject to change due to fluctuations in precious metals market. Silver Dollars (before 1936) Half Dollars (before 1965) Quarters (before 1965) Dimes (before 1965) Nickels (before 1938) War Nickels (1942-1945) Indian Head Pennies $4.00 to $50.00 o $1.25 to $10.003 $.55 to $5.00 $.25 to $3.00 a Bring for Offer: Bring for Offer Bring for Offer , -' These prices listed are for U.S. coins only, -We also buy ProofSets, Commemoratives, SMint$,ts k %Silver Coins. 9 kLGN' OLD WATCHE WOR'I IIIII~'UTH A FORKS]TUNEM INWUA$H Ii WE BUY PARTIAL OR ENTIRE INVENTORIES FOR CASH r .. .. Pt e r ' i .^":" .. '.P- ,,, * CHECK TO SEE IF You HAVE ANY OF THESE ITEMS WE ARE BUYING? 0 Rare & Important Jewelry D Diamond Earrings Q Diamond Bar Pins L Hamilton Watches Q Antique Bracelets D R. Lalique Glass o Diamond Bow Pins OU Rolex Watches L Pocket Watches 1 Diamonds from 1 to 20 CTS. O Sapphire & Diamond Jewelry L Antique Lockets Q Patek Phillipe Watches 0 Lladro O Ruby & Diamond Jewelry 0 Victorian Jewelry O Emerald & Diamond Jewelry L Cartier & Tiffany Items 0 Vacheron & Constantin Watches 0 Gold or Silver Mesh Purses O Jewelry from the 20's, 30's, & 40'sO Art Deco Jewelry L Silver & Gold Boxes U Railroad Watches O Nicely Carved Old Cameos o R. Chaarus Statues 1. Blackthorn Estate Buyers specializes in, appraising and buying New and Antiques jewelry. Our generations of experience qualify us to evaluate everything from:4 small pieces to the finest and most valuable estate jewelry. 2. Blackthornm Estate Buyers has an undisput-. ed reputation. We are authorized and' regulated by your local and State Government 3. Owners of rare pieces say that it isc extremely difficult to find buyers who have: the experience and knowledge to pay tops market prices most jewelry stores wont, even make you an offer. 4. This is an ideal opportunity to have your valuables appraised (especially if you: inherited them) by experts right here in' this area. Come in for a free appraisal and cash offer NO APPOINTMENT' NECESSARY. 5. If you are not wearing or enjoying these items that you have, then this is a great chance for you to convert them to CASH. This is much better than hard to sell diamonds, jewelry & coins. Prices quoted are for actual watches pictured. All prices are based on condition of watch. FREE PARKING HOUSE AND/OR BANK CALLS AVAILABLE BY APPOINTMENT SECURITY PROVIDED 2004 BIAcK7tORN ESTATE BVUYFS. INC" *RFPROUjCT'oN OR US NE OF THIS ANNOUNCEMENT IN ANY IW' IS PROTECTED UNDER FEDERAl COPYRIGHT LAWS AND ANY RE-CREATION, IN WHOLE OR IN P4RT BY ANY MEANS ELECTRONIC OR PHOTOGRAPHIC IS STRIl77.Y PROfHlBITED AND 1 Ll BE CRIMIMALL Y PROSECUTFED T THE FULI EXTF.NT OF THE 1AW CONSIDER BRINGING EVERYTHING We have surprised many people who thought their items were not valuable enough to consider. The expert appraisers advice.. PLANTATION INN & GOLF RESORT 9301 W Fort Island Trail Crystal River (800) 246-0876 (Hwy. 19 to Fort Island Trail, 1/8 mile on Rt. Across from the Kash & Karry For further directions call 800-632-6262) Blackthorn Estate Buyers "Over 30 years of experience with integrity" Wed. Thurs. Fri. Sat. Jan 5th Jan 6th Jan 7th Jan 8th 10AM-6PM 10 AM-7PM 10AM-6PM I10AM-4PM Lots of Free Parking %,I I Rua k .,j k L' GOLD COINS I I SILVER COINS I I2A Nation THURSDAY JANUARY 6, 2005 ', www chronlcleonline com r up rsC.& Oe 0 S rmm we a % ,m, -: .. : S/J t t. .. -"S as *I n|||| aglp a. -gii -ii aS " lllll mli m all lIIIb S ri- e ......a..... :z, ,u. ., - Lnveling a Ia~a, a =W ai- In icate Onten.f IIU~ lcU*rtofll a mwaa- omo winmie 4aw fl 40 aiH a MHI a a aue mew t am a " a." 4 A* **:: .... :: 4M::** ..n m1s"H -mob& 1 @No own Q&* *. * -tb ::-ff it - a .. a e. .A.ommmercia iews ProvIe r" 'I- lv 1l fu l Av al a- - a,..** 0: ..." .w .4 - e.** ...:: .. .:: eii . ., . 1f I-. - a -klllk **-a- -- ... .*,, ad - "a .- -e m- a 4.:e. ... . ..... .. a .:me,* ". , .." ... *. --. Jalt a ~- - 0-. *.euugo v IMW n,,m mLm* fl mn ,l .* n.. f lm a asawda ena aa Me OEM nt4nll nu *s . 40 g f- ' anu oam am a a eb IW MO A p4WM MNAI or smrsw a & am ,, em. " *am Alqdoi SM I ~ A, TI a. ~ A" A 11 ,b, Ah. 49ers clean house after disappointing season PAGE SB THURSDAY JANUARY 6, 2005 .... .... .... ... Sports BRIEFS Lecanto grapplers beat Nature Coast Senior heavyweight Lucas Williams pinned Nature Coast's Kyle Saverese in 1:23 to give I the Lecanto wrestling team a S39-36 victory on Wednesday. The Panthers (2-1) also got wins from sophomore Brian Jackson (103-pounds, 11-5 ; decision), sophomore Corey L Wheeler (140, 1:59 pin), junior Dustin Whitelaw (160, 1:09) and junior Mike Musto (171, 2:20). Lecanto also won the 145 and 152 weight classes by forfeit. Lecanto hosts The Villages at 6:30 tonight. Panthers get first weight lifting win The Lecanto girls weight lift- ing team won its first match, 56- 20, against Hemando on Wednesday. The Panthers (1-2) took first place in eight of the ten weight classes, with sophomore Christian Holbeck and freshman Bryenna Edwards tying with a combined weight of 200 pounds in the 199-pound class. Other winners included junior Jen Corriveau (185 pounds in 101 class), sophomore Kelly Butler (180, 110), freshman Nichole Whitelaw (150, 119), junior Christine Flores (190, 129), senior Tanya Spencer (200, 139), freshman Victoria Mele (205, 154) and sophomore Shaneatha Gates (230,183). Citrus boys soccer ends in stalemate Despite two goals apiece from Matt Steelfox and Bodee Wright, the Citrus boys soccer team failed to win Wednesday. The Hurricanes, however, did manage a 4-4 tie with Ocala Vanguard. Citrus hosts South Lake on Friday. m e. :: .11w 0 ... ..: r ... . ... U . . . low* IM -NAM U .j if *> * Ross Rnundbnll 101 Laternm m Iulw ,w m ----m mm ---mmmm ,q mm -mmm -mm Senior forward powers Citrus JON STYF jstyf@chronicleonline.com Chronicle R.J. Cobb dribbled up the court and' drove toward the lane. As the senior point guard approached the hoop for what appeared to be a contested lay- up in Wednesday's Citrus bas- ketball practice, he pulled up and blindly tossed the ball one- handed behind his head. He didn't look because he didn't need to. Cobb knew his trailer was coming and he knew who it would be - Donnie Ross running the court to finish the score. "We don't even have to talk, its just eye contact," Ross said. "I feel when he's around me and he feels when I'm around him." After playing in an offense designed around Jamaal Galloway for most of their var- sity careers, Ross and Cobb have taken over, running the Hurricanes to an 8-3 (4-1 dis- trict) record. The offense now runs through Ross, a 6-foot-2 power forward, and depends on his ability to score near the basket or kick the ball out to the open shooter. "He's everything," Cobb said. "If he's not in the game we're struggling offensively because we don't have anybody to free our shooters up and we don't have anyone else besides me that can create a shot for them- selves." Citrus won its first eight games, but have lost three in a row to Eustis and Leesburg in a holiday tournament, and then against Leesburg again Tuesday night in overtime after Ross fouled out "He fouls out and we can't get a shot," Cobb said. "We have to keep him out of foul trouble and keep him' on the court. If we can't do that, we're going to lose more games like that" Please see ROSS/Page 3B Citrus senior forward Donnie Ross elevates to the basket during the Hurricanes' 80-54 win again Lecanto on Dec. 10, Ross finished with 20 points and 15 rebounds. Cr 1.0114 -Urn propels Pirates ANDY MARKS amarks@chronicleonline.corn Chronicle SPRING HILL J.Q Livingston's third-quarte' scoring outburst of 14 points was more than his entire Crystal River team scored ii any other quarter Wednesday at Nature Coast. It couldn't have come at A better time. Livingston's sudden hot shooting pulled his team out 6t a game-long slump and sparked a 7-0 run early in the fourth quarter that propelled the Pirates to a 42-37 win. "We opened it up, gave it to him on the wing and let him create a little bit, and he did,'I Crystal River coach Tony Stukes said. "He's capable of doing that He sat out most of the second quarter with his second foul, but he came on in the third to do a real good jobl for us." With the game knotted in a stagnant 15-15 tie three mini utes into the third quarter, Livingston came alive by scored ing three straight buckets -- the third was a breakaway dunk after a mid-court steal, The 6-foot-5 junior went on tq connect on two 3s and a mid, range bank shot in the last three minutes of the frame as " the Pirates carried a 31-27 lead into the fourth. Eric Nowak's back-to-bacl baskets and Brett Miller's fred throw opened a nine-point lead, 36-27, with three minutes left in the game. The misfiring Sharks weren't able to over, come the deficit despite horrid Crystal River fdul shooting down the stretch. The Pirates shot just 6-of-15 from the line for the game, including a rud of six consecutive misses igr the fourth. iclie It was par for the course on a ist Please see PIRATES/Page 3B -. at ri l .. - .~ m u. a - sSS"- xy...xWx *^. ... ... -elltt *sis- .....i.. ..... ..e.n................. - : Syndicated Content .4. .. .. ... 4. A% d -w Jl ft , .. Available from Commercial News Providers" From staff, wire reports Mertd&As kxkka (f* R A Tour .a'*m 4. . Ulow .4m -W z-bmM4o-o 4- 4- - mm*w0 Mum4-avp WN, I Citrus wrestling falls .to West Port, again JON-MICHAEL SORACCHI West Port was 16 points, but For the Chronicle this time, the meet came down to the last two matches. In the win-loss column, the After losing the first three outcome was exactly the same matches and finding them- as the two teams' previous selves down 14-0, Citrus turned meeting. to senior grappler But when Citrus Marlin Dimitrion to hosted West Port in a '~ get things started. wrestling dual meet Dimitrion defeated at home Wednesday Kevin Jagnamdan 16- night, the result was a little 1 to earn a technical fall in the closer. 125-pound match. Still, the Hurricanes The Hurricanes eventually dropped a 41-33 decision to the took a 33-29 lead after Tommy . .. visiting Wolfpack Newman earned a 13-4 deci- S The first time the two teams met, the margin of victory for Please see CITRUS/Page 3B / San Francisco sweep N SIP'. 0.. r Ls, - -- .......... 1::::... .0 *Wx: ............. - CITRus COUNTY (FL) CHRONICLE NBA SCOREBOARD Magic shock Superonics a I "Copyrighted MIt M : era Sy Available from 'Mom ndicated iCo tet Commercia News Providers I ,, jifiij-dlM ^ -ifNM New York Boston Philadelphia Toronto New Jersey Miami Washington Orlando Charlotte Atlanta Cleveland Detroit Indiana Chicago Milwaukee San Antonio Dallas Houston Memphis New Orleans Seattle Minnesota Portland Denver Utah Phoenix Sacramento L.A. Lakers L.A. Clippers Golden State EASTERN CONFERENCE Atlantic Division L Pct GB L10 16 .500 5-5 17 .469 1 5-5 16 .467 1 6-4 21 .364 41/2 5-5 20 .355 41A 4-6 Southeast Division L Pct GB L10 8 .765 9-1 13 .567 7 5-5 14 .533 8 3-7 21 .276 15Y2 3-7 25 .167 19 1-9 Central Division L Pct GB L10 12 .613 6-4 13 .567 1Y2 7-3 13 .552 2 6-4 18 .379 7 7-3 19 .345 8 4-6 WESTERN CONFERENCE Southwest Division L Pct GB L10 7 .788 8-2 10 .677 4 8-2 15 .516 9 7-3 17 .485 10 7-3 28 .067 221/2 1-9 Northwest Division L Pct GB L10 7 .767 6-4 14 .533 7 3-7 15 .483 8 4-6 17 .452 9 2-8 21 .344 13 1-9 Pacific Division L Pct GB L10 4 .871 9-1 10 .667 6 6-4 14 .533 10 4-6 15 .500 11 4-6 21 .344 161/2 4-6 - SmU 40 4 m m - -OAI 1- * Heat ride 'Diesel' to win J*0 Av siftI- wowm"_ m-400 mo w f w4msom w -wm *oeftl a m ama l -'q -~ .~ S ~ - w - a -~ .~ rn - w. *-.. - - ~ ~ *SB. .& .M -. ..- -o.- *.. . ....... . -a?- .. l--- ,---am - 0 -- :. H .* W 40 - U * - --. .: .- '. admp 4b00015b A Tuesday s Games Indiana 116, Milwaukee 99 Washington 112, New Jersey 88 Sacramento 105, New York 98 Phoenix 122, Minnesota 115 San Antonio 100, L.A. Lakers 83 Wed. Friday. Magic 105, SuperSonics 87 GOLDEN STATE (83) Murphy 6-16 3-6 15, Dunleavy 5-9 3-4 SEATTLE (87) 14, Robinson 8-17 1-4 18, Claxton 3-9 0-0 Lewis 8-16 0-0 20, Collison 3-5 1-1 7, 6, Cheaney 5-10 0-0 10, Fisher 2-9 4-6 10, James 0-4 6-6 6, Allen 9-19 9-11 30, Foyle 3-5 0-0 6, Flores 2-2 0-0 4, Ridnour 5-10 0-0 11, Fortson 0-0 4-4 4, Cabarkapa 0-1 0-0 0. Totals 34-78 11-20 Daniels 0-7 2-2 2, Radmanovic 3-16 0-0 7, 83. Murray 0-3 0-0 0, Kutluay 0-0 0-0 0, BOSTON (84) Potapenko 0-0 0-0 0. Totals 28-80 22-24 Welsch 0-3 1-2 1, LaFrentz 4-7 1-3 9, 87. Blount 4-9 0-0 8, Payton 6-7 0-0 13, Pierce ORLANDO (105) 7-20 5-7 19, Jefferson 5-7 0-2 10, R.Davis Hill 9-11 3-3 21, Howard 5-6 0-0 10, 3-11 0-0 7, Banks 2-5 2-2 8, McCarty 3-7 Battle 1-7 4-5 6, Mobley 6-14 0-0 13, 0-0 7, Allen 1-4 0-0 2. Totals 35-80 9-16 84. Francis 14-24 4-4 35, Augmon 2-6 2-4 6, Golden State 23 20 211 9 83 Turkoglu 5-12 0-0 12, Kasun 0-1 0-0 0, Boston 25 20 271 2 84 Garrity 0-0 0-0 0, Nelson 1-3 0-0 2. Totals 3-Point Goals-Golden State 4-14 43-841316 105 26 23 12 0 7 (Fisher 2-4, Dunleavy 1-2, Robinson 1-5, Seattle 26 23 182 0 87 Murphy 0-1, Claxton 0-2), Boston 5-14 Orlando 15 31 302 9 105 (Banks 2-3, Payton 1-1, R.Davis 1-2, 3-Point Goals-Seattle 9-31 (Lewis 4-9, McCarty 1-4, LaFrentz 0-1, Pierce 0-3). Allen 3-8, Ridnour 1-4, Radmanovic 1-7, Fouled out-None. Rebounds-Golden Daniels 0-1, Murray 0-2), Orlando 6-12 State 53 (Murphy 16), Boston 52 (Jefferson (Francis 3-3, Turkoglu 2-5, Mobley 1-3, 11). Assists-Golden State 22 (Claxton, Nelson 0-1). Fouled out-None. Robinson, Fisher 6), Boston 24-(Piree' 8). Rebounds-Seattle 39 (Lewis .11),. Orlandq Total fouls-Golden State 18-, Btbn62. 59 (Battle 12). Assists-Seattle 12 Technicals-Golden State .DefehsiVe (Ridnour 5), Orlando 21 (Hill, Francis 6). Three Second 2. A-13,078 (18,624). Total fouls-Seattle 20, Orlando 18. A- 13,035 (17,248). Raptors 96, Kings 93 Heat 102, Knicks 94 SACRAMENTO (93) Stojakovic 2-11 5-7 10, Webber 6-21 0-0 NEW YORK (94) 13, Miller 6-10 2-3 14, Christie 2-9 4-4 8, K.Thomas 11-15 1-1 23, T.Thomas 3-9 2- Bibby 12-20 6-10 32, Evans 4-5 1-3 9, 2 9, Mohammed 3-7 5-8 11, Marbury 11-20 Songaila 2-7 2-2 6, Martin 0-3 1-4 1. Totals 6-9 28, Houston 4-9 0-0 10, Baker 1-5 1-2 34-86 21-33 93. 3, Williams 3-4 0-0 6, Ariza 2-5 0-0 4, TORONTO (96) Norris 0-1 0-0 0. Totals 38-75 15-22 94. E.Williams 3-7 2-2 10, Bosh 11-16 1-4 MIAMI (102) 23, Araujo 2-9 0-0 4, Peterson 5-16 7-7 19, E.Jones 4-8 1-1 9, Haslem 5-7 0-0 10, -Alston 2-13 0-0 5, Rose 6-13 7-9 20, O'Neal 14-21 5-9 33, D.Jones 3-10 1-1 9, Marshall 1-8 0-0 3, Bonner 5-8 0-0 10, Wade 8-19 5-8 21, Doleac 0-1 0-0 0, Murray 0-1 0-00, Palacio 1-1 0-0 2. Totals Dooling 2-8 0-0 4, Anderson 4-8 4-4 12, 36-92 17-22 96. Laettner 2-4 0-0 4. Totals 42-86 16-23 102. Sacramento 23 17 163 7 93 New York 19 20 2332 94 Toronto 29 20 2225 96 Miami 24 26 242 8 102 3-Point Goals-Sacramento 4-12 (Bibby 3-Point Goals-New York 3-8 (Houston 2-5, Webber 1-1, Stojakovic 1-3, Martin 0- 2-4, T.Thomas 1-2, Marbury 0-2), Miami 2- 1, Miller 0-2), Toronto 7-24 (E.Williams 2-3, 13 (D.Jones 2-9, Anderson 0-1, Laettner 0- Peterson 2-8, Rose 1-3, Marshall 1-5, 1, E.Jones 0-2). Fouled out-None. Alston 1-5). Fouled out-Webber. Rebounds-New York 41 (K.Thomas 12), Rebounds-Sacramento 64 (Miller 19), Miami 54 (O'Neal 18). Assists-New York Toronto 61 (Araujo 14). Assists- 15 (Marbury 8), Miami 25 (Wade 9). Total Sacramento 21 (Webber 6), Toronto 22 fouls-New York 20, Miami 18. (Alston 10). Total fouls-Sacramento 21, Technicals-Mohammed. A-20,275 Toronto 24. Technicals-Bibby. A-18,288 (19,600). (19,800). Cavaliers 101, Hawks 85 Bucks 97, Nets 74 ATLANTA (85) NEW JERSEY (74) Walker 9-20 4-8 26, Harrington 5-12 6-8 Collins 2-3 0-1 4, Jefferson 6-19 4-4 16, 16, Collier 3-5 0-0 6, Lue 5-12 0-0 10, Krstic 0-3 0-0 0, Carter 6-14 3-415, Kidd 5- J.Smith 5-7 1-1 11, Childress 2-11 0-2 4, 140-0 12, Ja.Smith 7-13 5-5 19, Buford 2- Drobnjak 3-8 4-4 10, Ivey 0-1 2-22, Delk 0- 11 0-0 4, Best 0-3 2-2 2, Moiso 0-1 0-0 0, 2 0-0 0, Willis 0-0 0-0 0, Diaw 0-0 0-0 0. Vaughn 1-2 0-0 2. Totals 29-83 14-16 74. Totals 32-78 17-25 85. MILWAUKEE (97) CLEVELAND (101) Mason 5-12 6-7 16, Jo.Smith 7-9 3-3 17, James 7-14 4-6 20, Gooden 3-4 4-4 10, Pachulia 4-7 1-3 9, Redd 4-11 5-5 13, Ilgauskas 11-19 6-6 28, Mclnnis 7-15 0-0 M.Williams 1-2 2-2 5, Kukoc 1-3 0-2 2, 16, Newble 5-9 0-0 10, Traylor 3-4 0-0 6, James 7-12 1-2 17, Strickland 3-5 4-4 10, Harris 2-6 2-2 6, Varejao 0-2 0-0 0, Snow Fizer 3-4 2-6 8, Hamilton 0-0 0-0 0, 0-5 0-0 0, Pavlovic 2-3 0-0 5. Totals 40-81 Santiago 0-0 0-0 0. Totals 35-65 24-34 97. 16-18 101. New Jersey 21 23 1911 74 Atlanta 29 20 28 8 85 Milwaukee 22 31 212 3 97 Cleveland 29 19 302 3 101 3-Point Goals-New Jersey 2-14 (Kidd 3-Point Goals-Atlanta 4-16 (Walker 4-9, 2-6, Carter 0-2, Jefferson 0-2, Buford 0-4), Drobnjak 0-1, Childress 0-3, Lue 0-3), Milwaukee 3-9 (James 2-5, M.Williams 1- Cleveland 5-15 (James 2-5, McInnis 2-5, 1, Strickland 0-1, Redd 0-2). Fouled out- Pavlovic 1-1, Newble 0-1, Snow 0-1, Harris None. Rebounds-New Jersey 48 0-2). Fouled out-None. Rebounds- (Jefferson 11), Milwaukee 48 (Pachulia 8). Atlanta 49 (Walker 10), Cleveland 48 Assists-New Jersey 18 (Ja.Smith 6), (Varejao 11). Assists-Atlanta 18 (Walker Milwaukee 28 (Redd 8). Total fouls-New 5), Cleveland 26 (James, Mclnnis 9). Total Jersey 23, Milwaukee 19. A-13,081 fouls-Atlanta 22, Cleveland 21. A- (18,717). 17,881 (20,562). . Bobcats 102, Timberwolves 84 MINNESOTA (84) Szczerbiak 5-12 2-2 13, Garnett 9-18 5- 5 23, Olowokandi 3-5 1-2 7, Cassell 8-18 3-5 20, Sprewell 1-6 2-2 4, Hassell 2-7 1-1 5, Madsen 1-3 0-0 2, Hoiberg 0-1 0-0 0, Griffin 3-10 0-0 8, Hudson 1-4 0-0 2, Johnson 0-0 0-0 0. Totals 33-84 14-17 84. CHARLOTTE (102) Wallace 7-10 6-8 21, Okafor 5-16 8-10 18, Brezec 2-7 1-2 5, Knight 0-4 2-2 2, Rush 3-8 4-4 11, Bogans 7-13 1-2 16, Ely 6-11 0-0 12, T.Smith 0-2 0-0 0, Hart 5-7 2- 2 13, White 2-5 0-0 4, Kapono 0-1 0-0 0. Totals 37-84 24-30 102. Minnesota 24 16 251 9 84 Charlotte 21 22 243 5 102 3-Point Goals-Minnesota 4-19 (Griffin 2-7, Cassell 1-2, Szczerbiak 1-4, Sprewell 0-1, Garnett 0-1, Hoiberg 0-1, Hassell 0-1, Hudson 0-2), Charlotte 4-10 (Hart 1-1, Wallace 1-2, Rush 1-3, Bogans 1-4). Fouled out-None. Rebounds-Minnesota 54 (Gamett 20), Charlotte 53 (Wallace 12). Assists-Minnesota 22 (Cassell 6), Charlotte 23 (Knight 8). Total fouls- Minnesota 25, Charlotte 17. A-12,037 (23,319). Celtics 84, Warriors 83 Bulls 95, Homets 89 CHICAGO (95) Deng 5-14 4-6 14, A.Davis 3-4 2-2 8, Curry 4-13 9-10 17, Hinrich 8-14 2-2 19,: Duhon 1-5 0-0 3, Gordon 4-6 3-3 11, Chandler 2-2 2-4 6, Piatkowski 3-7 1-2 8, Nbcioni 1-5 0-0 2, O.Harrington 1-2 3-3 5, Griffin 0-0 2-2 2. Totals 32-72 28-34 95. NEW ORLEANS (89) Nailon 7-12 0-2 14, Rogers 7-17 1-2 19, Brown 3-11 0-0 6, B.Davis 6-19 7-12 21,. J.Smith 1-3 1-2 4, Dickau 1-5 2-2 4, Andersen 3-4 4-4 10, Nachbar 2-8 4-4 10, J.Harrington 0-3 1-2 1. Totals 30-82 20-30, 89. Chicago 25 28 222 0 95 New Orleans 18 30 1625 89 3-Point Goals-Chicago 3-14 (Duhon 1- 2, Piatkowski 1-3, Hinrich 1-6, Nocioni 0-1, Deng 0-2), New Orleans 9-27 (Rogers 4- 11, Nachbar 2-5, B.Davis 2-7, J.Smith 1-2, J.Harrington 0-1, Dickau 0-1). Fouled out-None. Rebounds-Chicago 59 (Curry, A.Davis 9), New Orleans 49 (Rogers 8). Assists-Chicago 16 (Duhon 6), New Orleans 19 (B.Davis 5). Total fouls-Chicago 21, New Orleans 24.. Technicals-Chicago Defensive Three- Second. Flagrant fouls-B.Davis. A- 13,369 (17,200). SmPORrs Home 10-6 10-5 7-6 10-4 6-8 Home 14-4 10-5 10-4 7-8 3-13 Home 12-3 9-5 9-6 7-9 8-7 Home 15-1 11-6 11-7 10-7 1-12 Home 11-3 8-5 8-5 10-7 6-8 Home 14-2 12-4 11-6 10-8 8-9 Away Conf 6-10 9-10 5-12 8-9 7-10 10-6 2-17 5-10 5-12 9-11 Away Conf 12-4 20-2 7-8 13-8 6-10 6-9 1-13 4-14 2-12 2-15 Away Conf 7-9 12-8 8-8 11-8 7-7 13-7 4-9 5-9 2-12 8-9 Away Conf 11-6 14-5 10-4 12-7 5-8 10-7 6-10 10-11 1-16 2-16 Away Conf 12-4 13-3 8-9 12-6 6-10 5-9 4-10 4-12 5-13 7-12 Away Conf 13-2 16-3 8-6 10-8 5-8 10-10 5-7 7-12 3-12 5-16 M-Ol - -, , .H * &IM I HURSDAY, JANUARY 0, :ZUU> !!ill THURSDAY YANUARY A *>nnS i *..* .. ::" m .-- a ==, """ * . . ... ,. ..::: l .t- ,W < *. --'W .S.r f tp, MP-* ..... ....... .... "::" 4m .. . CTARUS, LOUNTY (JIL) CAMI'L SE STUSDY AURY6 05 FOOTBALL NFL Playoff Glance Wild-card Playoffs Saturday, Jan. 8 St. Louis at Seattle, 4:30 p.m. (ABC) N.Y. Jets at San Diego, 8 p.m. (ABC) Sunday, Jan. 9) AP NFL Offensive Player Voting NEW YORK Voting for the 2004 NFL Offensive Player of the Year selected by The Associated Press in balloting by a nationwide panel of the media: Peyton Manning, Indianapolis 35 Terrell Owens, Philadelphia 4 Daunte Culpepper, Minnesota 4 Curtis Martin, NY Jets 2 Michael Vick, Atlanta 1 Drew Brees, San Diego 1 LaDainian Tomlinson, San Diego 1 AP NFL Offensive Player History 2004- Peyton Manning, Indianapolis, QB 2003- Jamal Lewis, Baltimore, RB 2002 Priest Holmes, Kansas City, RB 2001 marshalll Faulk, St. Louis, RB 2000 Marshall Faulk, St. Louis, RB 1999 Marshall Faulk, St. Louis, RB 1998- Terrell Davis, Denver, RB 1997 Barry Sanders, Detroit, RB 1996- Terrell Davis, Denver, RB 1995 Brett Favre, Green Bay, QB 1994- Barry Sanders, Detroit, RB 1993- Jerry Rice, San Francisco, WR 1992- Steve Young, San Francisco, QB 1991 Thurman Thomas, Buffalo, RB 1990- Warren Moon, Houston, QB 1989-Joe Montana, San Francisco, QB 1988- Roger Craig, San Francisco, RB 1987 Jerry Rice, San Francisco, WR 1986-Eric Dickerson, LosAngeles Rams, RB 1985- MarcusAlen, LosAngeles Raiders, RB 1984 Dan Marino, Miami, QB 1983 -Joe Theismann, Washington, QB 1982 Dan Fouts, San Diego, QB 1981 Ken Anderson, Cincinnati, QB 1980 Earl Campbell, Houston, RB 1979 Earl Campbell, Houston, RB 1978 Earl Campbell, Houston, RB 1977 Walter Payton, Chicago, RB 1976 Bert Jones, Baltimore, QB 1975 Fran Tarkenton, Minnesota, QB 1974 Ken Stabler, Oakland, QB 1973 Chuck Foreman,. Minnesota, RB AP NFL Offensive Rookie Voting NEW YORK Voting for the 2004 NFL Offensive Rookie of the Year selected by TheAsspciated Press in balloting by a nationwjcd. panel of the,media: Ben Roethlisberger, Pittsburgh 48 NFL Offensive Rookie Of The Year History Preseason Baseball America Top 25 DURHAM, N.C. (AP) The top 25 teams in the Baseball America preseason poll with 2004 final records'and 2004 final ranking (voting by the staff of Baseball America): 1. Tulane 2. Louisiana State 3. Cal State Fullerton 4. Texas 5. Miami 6. Stanford 7. South Carolina 8. Washington 9. Arizona State 10. Georgia 11. Baylor 12. Arizona 13. Texas A&M 14. North Carolina 15. Florida 16. Mississippi 17. Vanderbilt 18. Rice 19. Georgia Tech 20. Notre Dame 21. Texas Christian 22. Long Beach State 23. Oklahoma State 24. Oral Roberts 25. Winthrop Record 41-21 46-19 47-22 58-15 50-13 46-14 53-17 39-20 41-18 45-23 29-31 36-27 42-22 43-21 43-22 39-21 45-19 46-14 44-21 51-12 39-26 40-21 38-24 50-11 37-23 On the AIR TODAY'S BASKE 7 p.m. (ESPN2) College Basketb (CC) (SUN) College Basketball Miami (TNT) NBA Basketball Seattle So From MCI Center in Washington, D 9 p.m. (ESPN2) College Basketb (CC) 9:30 p.m. (TNT) NBA Basketball Spurs. From the SBC Center in Sai 10:30 p.m. (FSNFL) College Bas (Live) 11 p.m. (ESPN2) College Basket (Live) (CC) BILLI 4:30 p.m. (ESPN2) Billiards 2004 Classic Semifinal. From Hollywood 5:30 p.m. (ESPN2) Billiards 2004 Classic Semifinal. From Hollywood GO 7 p.m. (ESPN) PGA Golf Merced Round. From the Plantation Course (Live) (CC) WINTER 3 p.m. (OUTDOOR) Snowboardi From Breckenridge, Colo. (Taped) 4 p.m. (OUTDOOR) Skiing USS Aspen, Colo. (Taped) 10 p.m. (OUTDOOR) Skiing USS Aspen, Colo. (Taped) LO' 7:30 p.m. (WYKE) Sports Talk Li' Cathy Pearson will have a live call- 795-4919. Sports Talk can be seen Adelphia Citrus, Dunnellon or Inglis Prep CAL TODAY'S PR BOYS BAS 7:30 p.m. Westwood Hills at Sev GIRLS BA 4:30 p.m. Citrus Park Christian a '7 p.m. Hernando at Crystal River 7 p.m. Citrus at Leesburg BOYS S 8 p.m. Citrus at Springstead GIRLS 7 p.m. Central at Crystal River NCAA HOOPS The AP Top 25 The top 25 teams in The Associated Press' men's college basketball poll, with first-place votes in parentheses, records through Jan. 2, total points based on, 25 points for a first-place vote through orne point for a 25th-place vote and last week's ranking: Record Pts Pvs 1. Illinois (62) 14-01,787 1 2. Kansas (10) 9-01,724 2 3. North Carolina 12-11,614 4 4. Wake Forest 12-11,539 5 5. Duke ,9-01,492 6 6: Syracuse 13-11,380 7 7. Oklahoma St. 9-11,368 3 8. Kentucky 9-11,317 8 9. Georgia Tech 9-21,173 9 10. Connecticut 8-11,058 11 11. Gonzaga 10-21,014 12 12. Washington 12-1 934 13 13. Arizona 11-2 865 14 14. Iowa 12-1 845 16 15. Texas 10-2 81,9 15 16. Pittsburgh 10-1 727 10 17. Louisville 11-2 694 19 18. Mississippi St. 12-2 538 21 19. Alabama 11-2 378 18 20. Michigan St. 8-2 339 23 S21. West Virginia 10-0 310 - 22. Maryland 8-2 309 24 23. Cincinnati 11-1 216 22 24. George Washington 8-2 198 20 25. Boston College 11-0 156 - Others receiving votes: Marquette 154, Wisconsin 150, N.C. State 115, Virginia 51, Oklahoma 35, Arkansas 30, Wichita St. 25, Oregon 16, Notre Dame 13, Bucknell 4, Miami 3, Old Dominion 3, W. Kentucky 3, Hofstra 2, UTEP 2. USA Today/ESPN Top 25 Poll The top 25 teams in the USA Today- ESPN men's college basketball poll, with first-place votes in parentheses, records through Jan. 2, points based on 25 points for a first-place vote, through one point for a 25th-place vote and previous ranking: Record Pts Pvs 1. Illinois (27) 14-0 771 1 2. Kansas (4) 9-0 742 2 3. Wake Forest 12-1 689 4 4. North Carolina 12-1 672 5 5. Duke 9-0 660 6 6. Oklahoma State 9-1 574 3 7. Syracuse 13-1 568 8 8. Kentucky 9-1 557 10 9. Connecticut 8-1 493 11 10. Georgia Tech 9-2 477 9 11. Texas 10-2 439 12 12. Pittsburgh 10-1 390 7 13. Arizona 11-2 389 14 14. Washington 12-1 385 16 15. Iowa 12-1 343 18 16. Louisville 11-2 277 19 17. Gonzaga 10-2 240 21 18. Alabama 11-2 239 13 19. Michigan State 8-2 227 20 20. Cincinnati 11-1 202 17 21. Maryland 8-2 143 23 22. Mississippi State 12-2 131 24 23. West Virginia 10-0 98 NR 24. N.C. State 10-3 59 15 25. George Washington 8-2 55 22 Others receiving votes: Boston College 49; Wisconsin 49; Oklahoma 44; Marquette 41; Virginia 12; Wichita State 10; UAB 8; New Mexico 8; Iowa State 7; Southern Illinois 7; Florida 6; Notre Dame 6; Providence 3; LSU 2; Arkansas 1; Oregon 1; Texas A&M 1. Top 25 Glance Wednesday 1. Illinois (15-0) beat Ohio State 84-65. Next: at Purdue, Saturday. 2. Kansas (10-0) beat Texas A&M 65-60. Next: at No. 8 Kentucky, Sunday. 3. North Carolina (12-1) did not play. Next: vs. No. 22 Maryland, Saturday. 4. Wake Forest (12-1) did not play. Next: at Clemson, Saturday. 5. Duke (10-0) beat Princeton 59-46. Next: vs. Temple, Saturday. 6. Syracuse (14-1) beat St. John's 79-65. Next: vs. Seton Hall, Saturday. 7. Oklahoma State (10-1) did not play. Sparks 3-9 3-6 10, Moss 0-2 1-2 1, Bradley 1-5 0-0 2, Carrier 0-0 0-0 0, Perry 1-1 0-0 2, Alleyne 1-2 5-7 7, Thomas 0-0 0-0 0, (. I Crawford 0-1 0-2 0. Totals 28-57 17-29 79. S',> I Halftime-South Carolina 41-35. 3-Point Goals-South Carolina 8-22 (Kelley 3-7, Gonner 3-7, Powell 2-3, Balkman 0-1, SW AVES ...Wallace 0-2, Kinsey 0-2), Kentucky 6-17 WA a(Azubuike 4-6, Rondo 1-1, Sparks 1-6, Moss 0-1, Crawford 0-1, Bradley 0-2). Fouled out-None. Rebounds-South i SPORTS Carolina 30 (Balkman 7), Kentucky 31 ETBALL (Hayes 10). Assists-South Carolina 14 )all DePaul at Cincinnati. (Live) (Powell, Kelley, Gonner 3), Kentucky 17 (Sparks 7). Total fouls-South Carolina 22, Kentucky 13. A-22,782. at Georgia Tech. (Live) No. 25 BOSTON COLLEGE 75, inics at Washington Wizards. No. 10 CONNECTICUT 70 .C. (Live) (CC) BOSTON COLLEGE (12-0) .C. (Live) (CC) Smith 7-13 2-2 16, Dudley 5-14 5-6 17, )all Memphis at Texas. (Live) Doomekamp 3-6 0-0 6, Hinnant 2-5 4-5 8, Marshall 3-9 0-0 7, Watson 4-6 2-2 10, Indiana Pacers at San Antonio Halley 0-4 3-5 3, S.Williams 3-8 2-4 8. Totals 27-65 18-24 75. n Antonio. (Live) (CC) CONNECTICUT (8-2) ,ketball Arizona at California. Villanueva 4-8 0-1 8, Gay 5-10 2-4 13, Boone 4-8 10-11 18, M.Williams 3-9 1-1 7, ball Gonzaga at Santa Clara. Anderson 5-15 2-3 15, Armstrong 0-2 0-0 0, Kellogg 0-5 2-2 2, Nelson 2-4 0-0 4, Brown 1-4 0-0 3. Totals 24-65 17-22 70. ARDS Halftime-Connecticut 37-30. 3-Point WPBA Classic Tour Florida goals-Boston College 3-14 (Dudley 2-5, (Taped)Marshall 1-6, Doornekamp 0-1, Hinnant 0- (Taped) 1, Halley 0-1), Connecticut 5-19 (Anderson WPBA Classic Tour Florida 3-10, Gay 1-2, Brown 1-2, M.Williams 0-1, (Taped) Kellogg ,0-4). Fouled out-None. (LF Rebounds-Boston College 40 LF (Doornekamp 8), Connecticut 44 (Boone les Championships First 15). Assists-Boston College 17 (Dudley, at Kapalua in Kapalua, Hawaii. Doornekamp, Hinnant, Marshall 3), Connecticut 12 (M.Williams 7). Total Sfouls-Boston College 21, Connecticut 19. SPORTS A-16,294. ng USSA Snowboard Exhibit. No. 18 MISSISSIPPI STATE 90, AUBURN 53 A- Women's Slalom. From AUBURN (9-5) Brown 4-11 0-0 8, Hayles 1-2 2-2 5, Young 3-17 2-2 10, Douglas 5-16 0-0 14, SA Women's Slalom. From Watson 2-8 0-0 4, Tolbert 0-2 2-2 2, Gaines 2-6 1-2 7, Edun 0-3 0-0 0, Howell 1-2 0-0 CAL 3, Campbell 0-0 0-0 0, Daniel 0-1 0-0 0. ICAL Totals 18-68 7-8 53. ve, hosted by Stan Solovich and MISSISSIPPI ST. (13-2) in show. To ask questions call Roberts 5-14 9-11 19, Power 3-7 2-2 9, on Bright House Citrtis 16, Morgan 1-2 0-0 2, Ervin 5-10 0-2 11, Frazier 5-11 0-0 12, Begley 0-0 0-0 0, 16 and Broadcast 49. Edmonson 4-7 0-0 12, Cannon 0-1 0-0 0, Boler 1-2 1-2 3, Slater 3-4 2-2 8, Harper 3- 5 0-0 6, Stelmach 1-2 0-0 2, Sharpe 3-3 0- 0 6. Totals 34-68 14-19 90. ENDAR Halftime-Mississippi St. 37-25. 3-Point goals-Auburn 10-38 (Douglas 4-11, Gaines 2-4, Young 2-9, Hayles 1-2, Howell 1-2, Tolbert 0-1, Brown 0-5, Watson 0-4), REP SPORTS Mississippi St. 8-17 (Edmonson 4-6, SKETBALL Frazier 2-5, Ervin 1-1, Power 1-3, Roberts Rivers 0-1, Boler 0-1). Fouled out-None. en Rivers Rebounds-Auburn 33 (Young 8), SKETBALL Mississippi St. 53 (Roberts 15). Assists- it Seven Rivers Auburn 11 (Young 5), Mississippi St. 16 r (Ervin 6). Total fouls-Auburn 17, Mississippi St. 11. A-8;746. No. 20 MICHIGAN STATE 84, PENN STATE 58 SOCCER MICHIGAN STATE (9-2) Anderson 6-13 4-4 17, Davis 2-5 4-4 8, Brown 7-12 0-0 16, Hill 3-7 1-1 9, Ager-4-8 SOCCER 3-4 12, Neitzel 1-3 0-0 3, Trannon 2-2 0-0 4, Torbert 4-6 2-2 11, Bograkos 0-0 2-2 2, Naymick 0-1 0-0 0, Harvey 0-0 0-0 0, Rowley 1-2 0-0 2. Totals 30-59 16-17 84. PENN STATE (6-8) Next: at Texas Tech, Saturday. Johnson 5-10 3-4 13, Claxtort 5-9 10-14 8. Kentucky (10-1) beat South Carolina 20, Parker 2-4 1-2 6, Luber 0-2 2-2 2, 79-75. Next: vs. No. 2 Kansas, Sunday. Smith 2-8 2-2 7, Walker 2-5 0-0 5, Hassell 9. Georgia Tech (9-2) did not play. Next: 2-4 1-2 5, Fellows 0-1 0-0 0, Morrissey 0-2 vs. Miami, Thursday. 0-0 0, McDougald 0-1 0-0 0. Totals 18-46 10. Connecticut (8-2) lost to No. 25 19-2658. Boston. College 75-70., Next: at Halftime-Michigan St. 40-30. 3-Point Georgetown, Saturday. -. goals-Michigan St 8-23 (Brown 2-4, Hill" ... 1.JGonzg4Q0-.2.) cad.toL.play. Next .at 2-6; Ager 1 3, Nedize~l 1..Tortba.l,3.. Santa Clara. Thursday. ". Anderson 1-4). Penn St. 3-15 (Parker 1.3, 12 Washington 12-1) d1i not play. Next: Hassell 1-4, SmiIn 1.5. Claxton 0-1. at Southern California, Thursday. Morrissey 0-2). Fouled out-None. 13. Arizona (11-2) did not play. Next: at Rebounds-Michigan St. 33 (Davis 8), California, Thursday. Penn St. 28 (Johnson 9). Assists- 14. lova (12-2) lost to Michigan 65-63. Michigan St. 19 (Hill 6), Penn St. 10 Next: at Ohio State, Saturday. (Parker 3, Luber 3). Total fouls-Michigan 15. Texas (10-2) did not play. Next: vs. St. 22, Penn St. 28. A-5,637. Memphis, Thursday. VILLANOVA 84, 16. Pittsburgh (10-2) beat Georgetown No. 21 WEST VIRGINIA 46 67-64. Next: at Rutgers, Saturday. WEST VIRGINIA (10-1) 17. Louisville (11-3) lost to Houston 70- Sally 3-9 2-3 10, Gansey 1-8 0-1 3, 67. Next: vs. Texas Christian, Saturday. Fischer 5-7 4-4 14, Collins 0-0 0-0 0, 18. Mississippi State (13-2) beat Aubum Herber 0-3 0-0 0, Byerson 0-1 0-0 0, 90-53. Next: at Mississippi, Saturday. Beilein 1-8 2-2 5, Price 1-1 0-0 3, Nichols 19. Alabama (11-2) at Vanderbilt. Next: 1-5 2-2 4, Young 3-6 0-0 7, Bonner 0-2 0-0 vs. LSU, Saturday., 0, Pittsnogle 0-5 0-0 0. Totals 15-55 10-12 20. Michigan State (9-2) beat Penn State 46. 84-58. Next: vs. Northwestern, Saturday. VILLANOVA (8-1) 21. West Virginia (10-1) lost to Villanova Sumpter 3-7 7-11 13, Sheridan 0-0 0-0 0, 84-46. Next: vs. St. John's, Saturday. Foye 5-10 0-0 11, Nardi 7-14 0-0 18, Ray 22. Maryland (9-2) did not play. Next: at 10-16 1-1 26, Condonr 0-0 0-0 0, Grace 0- No. 3 North Carolina, Saturday. 0 0-0 0, Lowry 1-5 4-6 6, Fraser 1-1 1-2 3, 23. Cincinnati (11-1) did not play. Next: Charles 1-1 1-2'3, Dunleavy 1-1 0-0 2, vs. DePaul, Thursday. Austin 1-1 0-0 2. Totals 30-56 14-22 84. 24. George Washington (9-2) beat La Halftime-Villanova 38-18. 3-Point Salle 71-42. Next: at Duquesne, Saturday. goals-West Virginia 6-29 (Sally 2-6, Price 25. Boston College (12-0) beat No. 10 1-1, Young 1-4, Beilein 1-5, Gansey 1-6, Connecticut 75-70. Next: vs. Providence,. Nichols 0-1, Bonner 0-1, Herber 0-2, Saturday. Pittsnogle 0-3), Villanova 10-24 (Ray 5-9, No. 5 DUKE 59, PRINCETON 46 Nardi 4-8, Foye 1-4, Sumpter 0-1, Lowry 0- PRINCETON (8-5) 2). Fouled out-None. Rebounds-West Wallace 6-16 0-0 12, Savage 1-2 0-0 2, Virginia 26 (Gansey 9), Villanova 43 Greenman 2-7 0-0 4, Sergeant 0-6 0-0 0, (Fraser 9). Assists-West Virginia 10 Venable 8-13 5-6 21, Schafer 0-0 0-0 0, (Nichols 4), Villanova 15 (Foye 4). Total Buffmlre 0-0 0-0 0, Owlngs 2-3 0-0 5, fouls-West Virginia 16, Villanova 15. A- Logan 1-3 0-0 2, Stephens 0-3 0-0 0. 6,500. Totals 20-53 5-6 46. No. 24 GEORGE WASHINGTON 71, DUKE (10-0) LA SALLE 42 Melchionni 2-5 2-2 6, Williams 3-7 1-2 7, LA SALLE (3-8) Redick 3-10 14-14 21, Ewing 3-10 3-5 9, Smith 8-18 5-6 23, St. John 1-5 0-0 3, Dockery 3-7 0-0 7, McClure .0-2 0-0 0, Harris 1-10 0-0 2, Cunningham 1-2 0-0 2, Nelson 2-5 2-2 7, Davidson 0-0 0-0 0, Thomas 4-15 0-0 12, Diaz 0-2 0-0 0, Lewis Johnson 1-1 0-0 2. Totals 17-47 22-25 59. 0-0 0-0 0, Neal 0-3 0-0 0, Sullivan 0-1 0-0 Halftime-Duke 33-18. 3-Point goals- 0, Narmbaye 0-0 0-0 0. Totals 15-56 5-6 Princeton 1-17 (Owings 1-2, Savage 0-1, 42. Venable 0-1, Stephens 0-1, Sargeant 0-2, GEORGE WASHINGTON (9-2) Logan 0-2, Wallace 0-4, Greenman 0-4), Williams 3-10 1-2 7, Hall 3-10 2-3 9, Duke 3-12 (Nelson 1-1, Redick 1-3, Mensah-Bonsu 5-9 4-8 14, Thompson 6- Dockery 1-4, Melchionni 0-1, Ewing 0-3). 14 0-0 16, Elliott 3-6 0-0 6, Lucas 2-6 0-2 Fouled out-None. Rebounds-Princeton 5, Johnson 1-3 0-0 3, Kireev 1-2 2-2 4, 26 (Wallace 10), Duke 41 (Williams 14). Battistoni 0-1 0-0 0, Rice 3-6 0-0 7, Assists-Princeton 10 (Venable 3), Duke 8 Akingbade 0-1 0-0 0. Totals 27-68 9-17 71. (Ewing 3). Total fouls-Princeton 19, Duke Halftime-George Washington 41-21. 3- 13. Technical-Princeton bench. A- Point goals-La Salle 7-27 (Thomas 4-9, 9,314. Smith 2-4, St. John 1-3, Sullivan 0-1, Diaz No. 6 SYRACUSE 79, ST. JOHN'S 65 0-2, Neal 0-2, Harris 0-6), George SYRACUSE (14-1) Washington 8-24 (Thompson 4-8, Hall 1-3, McCroskey 4-7 1-2 11, Warrick 8-15 6-8 Lucas 1-5, Johnson 1-3, Rice 1-4, Elliott 0- 22, Forth 2-6 0-0 4, McNamara 6-13 2-2 1). Fouled out-St. John. Rebounds-La 19, Pace 6-8 0-0 12, Roberts 3-3 0-2 7, Salle 26 (St. John 5), George Washington Edelin 0-0 1-2 1, Nichols 1-1 0-0 3, 60 (Hall 17). Assists-La Salle 9 J.Wright 0-0 0-0 0, D.Wright 0-0 0-0 0. (Cunningham 3), George Washington 13 Totals 30-53 10-16 79. (Thompson, Elliott 4). Total fouls-La Salle ST. JOHN'S (6-5) 15, George Washington 14. A-2,836. Gray 2-7 2-2 6, Lawrence 2-7 0-0 5, Houston 70, No. 17 Louisville 67 Hamilton 7-12 6-10 20, Hill 7-19 6-6 23, LOUISVILLE (11-3) Jackson 2-4 0-0 4, Jones 0-2 0-0 0, Myles 1-3 6-13 8, Garcia 4-7 3-4 13, Williams 3-3 0-0 7. Totals 23-54 14-18 65. Dean 0-3 0-0 0, Johnson 0-0 0-0 0, Halftime-Syracuse 37-28. 3-Point O'Bannon 2-7 4-4 10, Wade 3-7 0-0 6, goals-Syracuse 9-18 (McNamara 5-11, Palacios 7-11 3-6 20, Jenkins 3-6 2-3 10, McCroskey 2-4, Roberts 1-1, Nichols 1-1, Gianiny 0-1 0-0 0, Current 0-0 0-00. Totals Warrick 0-1), St. John's 5-14 (Hill 3-7, 20-45 18-30 67. Williams 1-1, Lawrence 1-4, Jackson 0-1, HOUSTON (9-5) Jones 0-1). Fouled out-Hamilton. Cherrington 1-20-0 2, Dyer 3-11 3-4 10, Rebounds-Syracuse 28 (Forth 7), St. Latham 2-4 2-2 7, Owens 10-25 0-1 27, John's 31 (Gray 6). Assists-Syracuse 14 Smith 3-12 4-4 12, Francis 0-0 0-0 0, (McNamara 5), St. John's 12 (Lawrence 4). Lawson 0-2 0-0 0, Jones 1-2 1-1 3, Shelton Total fouls-Syracuse 13, St. John's 16. 0-0 0-0 0, Hensley 1-2 1-1 3, Hannah 3-6 A-9,596. 0-0 6. Totals 24-66 11-13 70. No. 8 KENTUCKY 79, Halftime-Houston 34-30. 3-Point SOUTH CAROLINA 75 goals-Louisville 9-22 (Palacios 3-4, +SOUTH CAROLINA+ (8-4, 0-1) Jenkins 2-4, Garcia 2-4, O'Bannon 2-5, Powell 6-8 1-1 15, Kinsey 1-4 0-0 2, Dean 0-2, Wade 0-3), Houston 11-31 Wallace 3-6 0-0 6, Kelley 7-16 2-3 19, (Owens 7-16, Smith 2-5, Latham 1-1, Dyer Trice 3-5 2-2 8, Tisby 3-4 0-0 6, Gonner 4- 1-6, Hensley 0-1, Jones 0-1, Lawson 0-1). 8 2-3 13, Balkman 3-5 0-0 6, Chappell 0-0 Fouled out-Garcia. Rebounds-Louisville 0-0 0. Totals 30-56 7-9 75. 38 (Myles 11), Houston 37 (Hannah 16). +KENTUCKY+ (10-1, 1-0) Assists-Louisville 12 (Myles 4), Houston Azubuike 8-13 1-1 21, Hayes 4-10 7-8 11 (Smith 4). Tot fouls-Louisville 17, 15, Morris 5-6 0-2 10, Rondo 5-8 0-1 11, Houston 27. A-4 '92. ROSS Continued from Page 1B The Hurricanes will try to turn around their recent for- tunes when they travel to face South Sumter at 7 p.m. Friday before a tough district matchup with Brooksville Central next Tuesday. One of coach Tom Densmore's concerns during the recent skid is that his team has gotten B away from the transition he's 6-2, game and is waiting to pres- always sure on defense until inside, h the fourth. He hopes hard for v that Ross and Cobb can help got. the team get more involved Tom early to avoid going to over- time, like they did in both loss- es to Leesburg. "Last night, I don't think we got anything in transition and we lost in overtime," Densmore said. "That means if just one time we got a long rebound and turned it into a fast break that would have been the difference." During the offseason, Ross worked on extending his shooting range, along with bulking up in the weight room. The extra effort has paid off with more rebounds, and a more dominant presence inside. "Donnie works hard on offense to get the ball, and works :hard on defense to rebound," Densmore said. "Because he's 6-2, and he's always played inside, he works hard for what he's got" Along with Walter Howard, who has grown into a solid rebounder and role scorer, the Hurricanes have one of the most imposing interior duos in the area. PIRATES Continued from Page 1B night when the Pirates and Sharks combined for six total points in the second quarter Sand.carried a 14-11 score into ther.in mission. - ',.,.Shot very poorly toi ght,"Stukes said. "'We v been shooting 45 percent for the year and at halftime tonight we were at 28. We made a couple right at the end, but we've got to shoot better. It wasn't like we missed wild shots tonight, we missed a bunch of easy CITRUS Continued from Page 1B sion over Charles Huxoll in the 189-pound class. "I was just thinking about last year when he took my chance of winning districts," Newman said. "I wanted to show him that I had gotten better." But Citrus couldn't hold its lead as West Port's Brian Farker pinned Eric Vega in 1:40 at 215 and Chris Carter scored a pinfall over Robert Severin at 5:03 to close out their victory. Other winners for Citrus were Billy Laflamme (135), Darrell Prior (140) and Josh Walters (171), who each won by pin. LaFlamme's win over West Port's Drake Raulerson "Me and Walter have to body, up and play down low against 200-and-some pound people,": Ross said. "It's hard, but some- body's got to do it." The Citrus guards are plenty thankful for the help, because when Ross gets double- teamed, they are the benefici- aries of open shots. "That's how I get all my shots, he gets me open," Cobb said. "If we can't get into our: offensive set, he sets me a pick becausee and he's played ie works what he's Densmore Citrus coach so we can get going. If he's not there, nobody else is really mature enough to know to do that" Despite con- centrating more on bas- ketball, Ross' also decided to. give a shot at football in the; fall. After his father talked him out of playing because of the risk of injury in the past,; the senior finally got the clear-i ance to play, and excelled. He acknowledges that the; sport made him tougher and; the success that the' Hurricanes had making the: playoffs for the first time in seven seasons gave many of the players' confidence head- ing into the basketball season.: "I never thought football had; an impact on basketball; before," Ross said. "But play- ing football makes you tougher because it's a more aggressive; game. When you play more: aggressive teams it makes the- game easier for you." When basketball season; ends, he'll be looking for a col- lege next season. His heart is with basketball but he would-; n't mind playing football .too.; The senior. has seen interest' from several colleges, includ-, ing Jacksonville University: and Tuskegee University; (Ala.), but his main priority is: getting a degree in law. shots." Livingston finished with148 points and nine rebounds -to lead Crystal River (6-5). Sn Walker also grabbed nine boards for the Pirates. "I thought we played good defensively and we rebounWl- ed well,".Stukes said. " "We played very hard, bit again, we've got to shoot bet- ter than that to beat 'most teams." Nature Coast (2-6) was paced by Jonathan Woodbury's 13 points. The Pirates return to the court Friday with a 7 p.m. disL trict road matchup at first- place Central. came just 1:43 into the first period. Another Citrus grappler looking to avenge an earlier season loss was Prior Although it took Prior just inside the allotted time to win his match against the Wolfpack's Tom Semidey, it was easily one of the most exciting efforts of the night-,n Semidey scored a tak-, down and a near fall late in the first period to take a-5-0 lead after one. But Prior went on the offensive and outscored Semidey 11-4 the rest of the way, earning his last points on a reversal that set up his pin. "It was the best match .of my life," said Prior. "I waA just happy because he (Semidey) was the one keep- ing me from being district champ." 'Tle Sports showt"iV rowiin/ LUNCH DAILY. Restaurant Dining Room Wed. Sun. OTB Parimutuel Wagering From All Major Racetracks. 0 Greyhound Racing. Night Racing Wed Sat.1 11:00 AM Daily Except Tues. T 2 Adm. $1.00. Free after 6 p.m. n yr b ITW Teletheatre (352) 237-4144 Acrossfrom Ocala Airport on SW 60th Avenue , k., THURSDAY, JANuARY 6, 2005 39 SPORTS fI'- IPT ( ) ,.,uvnmrt .. ... Tlor -1.nasU'RS TJANAR n-(, ZU05 )flflC CimJ- I--(FL)-HRONICL Ohio S 1%r ft 0a-- - iahted'MateriaI' clown -Q. at~e -- doew- Aifaila a - aMP i.Syndicated Contet .- -. ..-. - a. - S ~. -.~ . blefrom Commercial Ne 0 - 4D-- -. - Al Ab - manmiwuni w - a - -MP a -apo qbw mvo maS 40 -ft 41 M - ammo lk-- O- h 0 0 a40 o 1ops a go S 40 4b. *AN G am *.-0 a a.M omo q= 4D Sama4 On aw 40 ba0 %ONO I -m-0 -o 4w OP 4m d - a ~.a. Noa. - o-mmas oa o -Now 0-lo-mom um ID 4boo -a Sm Ua 4-D UP 40 -med andbo -moo4b - sm MNII'sGm =f- g-Io. .oft. - -a - a. NM- quo ap- ft- a- 4l -.M h w - 4b 0MMMOa *adom ND a.OM a.. 41 4M doO - Imoma om- b" 4 f- n o ftm: L 1 am 40o__m 400 aw -Mw-a lp-n Ow - w-wm amp tmq- 4w ow a.i Ip0- a.m 0 a.- - a.4 40-a ow41. 40M 0 o ~0* -4m 4b.- - a 4b.- a 40 -.- a --40. - -a a. a- --a. a - a a a - aaa - -~ ~-a. a - - -~ a. -0 -a a. a - a- a- aa 0 - -a. - a a . - otani. ammm -w a. so -000990 g -Nam 0 . -40 -00 a- 4-. a. * - a - * - -a.. a~-a a. - a- - S ~0~ - 'Canes come up short at home JON-MICHAEL SORACCHI For the Chronicle The Hurricanes hit their high point during the 61st minute of their District 4A-9 girls soccer match against Springstead on Wednesday. Kaela Fitzpatrick had just scored a breakaway equalizer, shooting past Springstead keeper Amber Collard who had come off her line on the play and the crowd roared its approval. But defensive miscues after that goal did Citrus in and they eventually lost 5-3 to the visit- ing Eagles at the Citrus Bowl. "We played well," said Citrus coach Charlie Gatto, whose team fell to 5-5-5 overall and 4-4-4 in district. "We played much better in the first half, though." Fitzpatrick's goal was a great individual effort that helped Citrus back into a game they had been out of just six minutes earlier, when Eagles' midfielder Nicholynn Faulkner flicked a shot past the outstretched hands of Citrus keeper Ashley Christensen to give Springstead a 2-1 lead. But moments after Fitzpatrick's score, the game got away again. Citrus was called for a handball infrac- tion in its own box, setting up a Angela Passafaro goal on the ensuing penalty kick. Then, in the 71st minute, Citrus let another goal in when Faulkner hit a hard shot from 18 yards out that rang hard off the crossbar, and then collect- ed her own rebound and rico- cheted it off the inside of the crossbar and past the line for a 4-2 Eagles lead. After Springstead's Taylor McKinney scored to make it 5- 2, Citrus cut the gap when freshman Kaitlyn Clark scored her first career varsity goal. Clark shot from the right side past Collard and the ball bounced off the left post right m a. WA. -a S. ~@ a = ~ - S 0 -.00 a.- mob-aNg -ft 4- .% m_ d * .. ana. -40a. -* a - a. a.a a.-.~ .-ft -aa. a S4w -4b. S a. 0~~ ~- fa 0000% 00m -41 "Rlm w 4 D4 -=I- - -- 4b 4m qb ql 4b 41 4w -om. 0 Q 40 a am 4o 4b m OEW qw* ame -% 4 0m- ao f bam m a t0p 0-gab 41b uo 1- -4- -wpm a d- p. - 41000"m 0 -0 0.-1W ....... z 0 - qw4w-M mom 4 w G--N Se . a a 5 back to her. With Collard turned around, Clark shot the ball back to the left, just inside the net to reduce the Eagles' lead to 5-3 in the 78th minute. "I'm pleased with the way my midfield and forwards played," said Springstead coach Randy Strat, whose team improved to 11-1-2 and 9- 1-2. "Defensively ... I was a bit upset. Sometimes we looked good but other times, we looked horrible." The score was 1-1 at half- time behind goals from Springstead's McKinney and Citrus' Marcy Mills. Citrus next plays 7:30 p.m. Friday at Nature Coast Trojans loaded for N5 u &Iad (An ~dwrpm -- a a. a. - - -a -a S - a.- a. -~ - S-a a - a. a. -a. a -F a 0 - qft a. a CiTRus CouNTY (FL) CHRoNicLE AIR -ri4l IRSDAY. TANUARY A ?.On'q 0 s1>oli1tys -Now do-- -ddm m Q O Rrr US OUNTY ( ) HRO 49er dismiss coach Erickson, GM Donahue .. Co frih ed aeria vUUYIUI~lU li~ll~I) Offensive IliC Avai m M a. *.=. OI ru hhia 4tr 'Luum- ,.r ,fi Coie E h WnW- abl e romiil News Providefs - e n4iigil t n al ib.no* a l I -. . U '1 4 e. --* * 0 Ir PA THURSDAY, JANUARY 6, 2005 514 SPOnTS C C FL C NICLE 4 eSn an. k 6B THURSDAY JANUARY 6, 2005 U T I I I I 1 I I 1 I I I I I I~r l' I I I I I I I ... .... ... ... '""0 Outdoor BRIEFS Floral City Anglers to meet on Jan. 27 Floral City Anglers' monthly meeting will be held at 7 p.m. on Thursday, Jan. 27. The meeting will take place at the Floral City Community Building, downtown Floral City. This months meeting will fea- ture guest speaker Kurt Derdorff, owner and operator of River Sport Kayaks in Homosassa. He will bring in some models, and demonstrate the mobility, and diversity of the vessel. ie, outfitted for fishing. As well as answer any ques- tions regarding the sport. As always, the meetings are open to guests and new mem- bers. Door prizes. Refreshments served. And fishing reports will be shared. Pine Ridge Fishing Club seeks members The reorganized Pine Ridge Fishing Club is seeking new members who are interested in fun and fellowship through fish- ing. The club meets at 7 p.m. on the second Tuesday of each month at the Pine Ridge Community Center. The speaker on Jan. 11 will be fishing guide Capt. Rick Bums with his presentation on fishing local waters. For further information or to join, contact Phil at 249-1187 or by email at phillipd@atlantic.net. Boating safety in Crystal River The Crystal River Power Squadron is conducting a two session boating safety course in Crystal River on Jan. 22 and 29 from 9 a.m. to 1 p.m. at 845 NE 3rd Avenue. Topics include Coast Guard and Florida state regulations, equipment requirements, rules of the road, boat handling, jet ski handling, trailer handling and others to help you operate your vessel safely. Upon completion of both ses- sions and the final exam, you may.eam your "Boat Smart Certificate of Completion." This certificate qualifies you for mem- bership in the Crystal River Power Squadron and for the Florida Boat Operators License required by all under 22 years of age and others. For more information and to register, call Bill Foster on 352- 563-2114 or Jack Flynn on 352- 527-8038. 154 boating safety program under way The U.S. Coast Guard Auxiliary Flotilla 15-4, as a public service is offering a Boating Skills and Seamanship program. The program will be at the West Citrus Community Center, 8940 W. Veterans Drive, Homosassa, beginning Jan. 3, on Monday and Thursday evening from 7p.m. to 9p.m. through Jan. 27. This pro- gram fulfills the state require- ments for Florida's Boater Card. This program has been pro- duced for the boating public by the U.S. Coast Guard Auxiliary to provide a unique and excel- lent combination of boating techniques, legal responsibili- ties, personal safety for crew and passengers, boat handling, rules of the road, the latest fed- eral boating regulations and other subjects which will help you to become a more proficient boater. For additional information call 564-2521. Flotilla 15-1 conducts free safety checks The U.S. Coast Guard Auxiliary Flotilla 15-1 is conduct- ing free vessel safety checks. This free courtesy examination is a check of safety equipment carried or installed on a vessel and certain aspects of the ves- sel. From staff reports Anglers spring to life Gary Moore MOORE WILDLIFE Warmer air leads to fishingfrenzy We are on the verge of a fishing explosion. The sun is climbing slightly higher in the sky, each day lasts a little bit longer, and that equals warmer water temperatures and aquatic spawning activities. Enjoy it while it lasts because Mother Nature is not finished with us just yet and will more than likely throw us a handful of cold fronts just for fun. In the gulf, colder tempera- tures normally mean that the, sport fish are moving closer to the shoreline or into the rivers for warmer water temperatures. The reports on trout and redfish have been, to say the least, a bit of a roller coaster ride. One week, the trout are in the rivers and fishermen are catching them, the next week they are few and far between. Last month, we had a cold spell where the large trout and redfish came alive and took up residence in both Crystal River and the Homosassa. Anglers were taking them on practically anything that took up space in the tackle box, but to be a bit more specific, a V -ounce jig under a Cajun Thunder was a winning combination. This week, I am getting mixed reports. The guides out of McRae's are doing really well on redfish and trout and they are catching them in large numbers. The average angler, however, is not Smaller fish have taken the place of larger fish and the num- bers are not as great Nobody can predict what this prolonged warm spell will do to the trophy GANY MOuuI ,''L ro,,.: I, Though the mercury has been on the rise and fall, grouper have remained a constant in our area. Pictured from left to right: Danny Trabue, Kevin Jackson, Kenny Richards and Robert Eadle. The group were fishing with Captain Phil Muldrow out of "Sandy Gale". trout and redfish only time will tell. One species that has remained a constant has been the grouper. During all of last month and even through the current warm spell, anglers have been catching red and gag grouper in pretty good numbers and better than average size. Distance has not seemed to be a big problem. Most anglers I have talked with are getting limits of gag grouper up to 16 pounds and not traveling much more than 11 miles off- shore. I have it from a reliable source that the water temperature remains a bit more constant in depths beyond 12 feet and there- fore, the grouper are not experi- encing temperature fluctuations to a degree that would put them in lockjaw mode. On the freshwater side, the bass and specs are being fooled into an early spring pattern and are beginning to make a move towards the shallows. During the next few weeks, (weather permitting), we should start to see fish take up residence in shallow water area's in prepara- tion for the spawn. As cold fronts come and go, so do the fish. Once an area is found to hold pre- spawn fish, they won't travel far away. One of the Florida Fish & Wildlife officers turned me onto some excellent spec fishing on Orange Lake on the southern border of Alachua County. He told me that the action was fast * and furious and he was right I took a trip there and found that the spec fishing was really doing quite good. Of course, it had slowed a bit during my visit but asking around the bait houses brought the same response: "You should have been here Sheephead success, For the Chronicle Bernie VanBoken, of Kentucky, shows off a good haul of Sheephead caught between Crystal River and Cedar Key in Capt. John Bedingham's Whopper Stopper late last month. C I T R U a COUNTY IM Tide charts Chassahowitzka High/L THURS 12:39 a.m. 1/6 3:12 p.m. FRI 1/7 SAT 1/8 SUN 1/9 MON 1/10 TUES 1/11 Crystal River Homosassa -ow High/Low High/Low 10:02 a.m. 1:33 p.m. 7:24 a.m. 2:24 p.m. 9:01 a.m. 9:41 p.m. 11:58 p.m. 7:03 p.m. 8:40 p.m. Withlacoochee High/Low 11:20 a.m. 5:12 a.m. 9:45 p.m. 4:51 p.m. 1:37 a.m. 11:08 a.m. 2:47 p.m. 8:30 a.m. 12:49 a.m. 10:07 a.m. 12:34 p.m. 6:18 a.m. 4:26 p.m. 10:50 p.m. 8:12 p.m. 3:38 p.m. 9:49 p.m. 10:43 p.m. 6:00 p.m. 2:35 a.m. 12:07 p.m. 12:56 a.m. 9:29 a.m. 1:47 a.m. 11:06 a.m. 1:33 p.m. 7:17 a.m. 5:25 p.m. 11:50 p.m. 3:46 p.m. 9:12 p.m. 4:37 p.m. 10:49 p.m. 11:39 p.m. 7:00 p.m. 3:31 a.m. 1:00 p.m. 1:52 a.m. 10:22 a.m. 2:43 a.m. 11:59 a.m. 2:22 a.m. 8:10 a.m. 6:14 p.m. 4:35 p.m. 10:05 p.m. 5:26 p.m. 11:42 p.m. 7:53 p.m. 4:27 a.m. 12:43 a.m. 2:48 a.m. 11:11 a.m. 3:39 a.m. 12:48 p.m. 12:35 a.m. 8:59 a.m. 6:57 p.m. 1:49 p.m. 5:18 p.m. 10:55 p.m. 6:09 p.m. 3:05 p.m. 8:43 p.m. 5:21 a.m. 1:33 a.m. 3:42 a.m. 11:58 a.m. 4:33 a.m. 12:32 a.m. 1:29 a.m. 9:46 a.m. 7:34 p.m. 2:36 p.m. 5:55 p.m. 11:44 p.m. 6:46 p.m. 1:35 p.m. 3:42 p.m. 9:32 p.m. last week" How many times have you heard that one? Orange Lake has changed a bit since I was last there and I had heard rumor that it had all but dried up during the droughts, so I wondered just how smart it was to go fishing there. I fished in and around Redbird Island, Sampson's Point and on the northeast side of McCormick Island, which looks more like an extended point. I caught several specs drifting a chub minnow and then I found a few hard-bot- tom areas and slow rolled 1/16- ounce tube jigs. The fish either hit the minnow or totally turned away from it. When the fish went off the min- now, I caught them on the jig. When I say slow rolling- I mean S-L-O-W rolling. I use six- or eight-pound test line and cast the jig out without a floater, straight to the bottom. I then turn the handle as painfully slow as possible it is the only way I could get the non-active fish to bite. By the way, the colors of the jig had to be a red, green or yel- low combination or they would look away. As you can see, the fishing in our area is doing pretty good right now and is only going to get better, Plan a trip to The Homosassa or Crystal River for some trout and redfish and if you want to take a walk offrthe beat- en path, take a little trip to Orange Lake in Alachua County and get involved in some of the good spec fishing they are expe- riencing. Good luck and good fishing. Gary Moore, Chronicle out- doors correspondent, can be reached at grygsm@aol.com. FWC reveals top striped b For the Chronicle Bass anglers don't have to hang up their fishing rods for the winter just because Florida's leg- endary largemouths pretty much come down with lockjaw when the weather gets too cool. Fall and winter months offer the best striped bass arid hybrid bass fish- ing scientific family name, "Moronidae"). Striped bass stripers for short can get huge. The state record is a 42.25 pounder, bagged in the Apalachicola River in 1993. Anglers catch stripers on heavy bait-casting or open-faced spinning tackle with 12- to 25- pound test line. For big stripers, live shad or small eels are the best baits. For smaller stripers, yellow or white 1/8- to 1-ounce jigs are good, and so are plastic twitch baits and poppers for sur- face fishing and also spoons. FWC fisheries biologist said the most productive morone fish- ing in Florida in 2005 will be: 1. The Apalachicola River/Lake Seminole This is the home of all three state record morones. In the lake, stripers and sunshine bass con- gregate ass spots: bass feed in schools, and they like live crayfish and freshwater shrimp. 2. Lake Talquin and the. 3. St. Johns River Eight- to 1,2 pound fish showing up regularly. Striped bass move throughout the - river in fall and winter. The best sp64s- to catch them are around jetties, th&.. bombing ranges in Lake George, thf. 4. Blackwater/Yellow rivers In this northwest Florida area, the FWQC stocks these waters with stripers '- every year. The best fishing is in the upper Blackwater Bay, near the riveJr mouths in the fall and winter and - upstream in the summer. Sometimes, the best time to go is at night. Be pre pared to bag 10-, 20- or even 30- pound striped bass. Use live mullet, menhaden or shrimp for bait. Shad- imitating lures also work. 'i- tating lures to bag fish from surface- feeding schools. During summertime, the fish seek out cool-water tributar- ies. WED 6:14 a.m. 2:22 a.m. 4:35 a.m. 12:41 p.m. 5:26 a.m. 1:21 a.m. 2:22 a.m. 10:29 a.m. 1/12 8:08 p.m. 3:19 p.m. 6:29 p.m. 7:20 p.m. 2:18 p.m. 4:16 p.m. 10:20 p.m. Tide readings taken from mouths of rivers ffa-- I Amish holiday The Amish Cook celebrates Christmas with ^ family. r PAGE 2C Fooi) ... .. ........ .... 1 is h wonP, neor hte ateriaers ~I- Ron Drinkhouse WINES & SUCH r^ S sl i I ' I if ^ I ^ I s' Availab e from Comm al News Providers 11 domwiilmmmm b a4m4ammomm ai m am d ,d -,ame * w lc ... 4vo.*. 0mmo.* S1b- H141 i:AN- *- f -m a - * 4 w m -mqfp bamm 'i promise you, I am not mak- ing this up. The prestigious British Medical Journal (Dec. 18-25, 2004; vol. 329, pp. S1447-1450)describes a new diet for the prevention of heart disease dubbed the "Poly- meal." It consists of dark K chocolate, almonds, fruits and . vegetables, and garlic, Those on panied by a the plan glass of, you guessed it increased red wine. It is re- their total ported that these foods, life spans eaten on a i| daily basis, by more 1, plus fish at -least four than six times a week "sig- yeas. nificantly in- creases the life expectancy of people over 50 and reduces heart events by more than two- thirds." 'If you happen to be a teeto- taler, and leave out the wine, the impact of this regimen will be reduced by 10 percent. It seems men benefit the most. Those who followed the plan increased their total life spans by some six-and-a-half years | compared with those not on the "Polymeal" diet. Heart dis- eases were delayed by some nine years, this stat versus the general population. While women "would live about five years longer than women not eatingit." And they kept heart disease at bay by eight years more than their non-regimen sisters. As an aside, it seems a team of scientists in 2003 developed a kind of "Polypill" combining common medications used | against different risk factors for heart disease. The pill they i demonstrated reduced cardio- vascular disease by "more than 80 percent" In the Netherlands, a group of experimenters wanted to do the same thing without resort- ing to prescription medica- tions. A panel led by Oscar Franco wanted to invent a non- pharmacological alternative. The news report went on to say: "Following the Polymeal promises to be an effective (drug-free), safe, and tasty Means to reduce heart disease across the populations." As Mel Allen used to say, "How about that!" | You may ask what about Please see /Page 2C .XI. Tk4;-t ,RSDAY JANUARY 6, 2005 CITRUS COUNn' (FL) CHRONICLE 2C 'Iliiuim "10,ANU AN I I\6, 2005 Lovina shares her mother's ice cream recipe 40O 4M T w Co f io II eri a - - * m - ~- - a _--. -- - onen-NNO h.-~ ~ a. a qmImh - -a a a - - a. - a ~- -a a. - * 'a -~ - 4f from om N Pr"des e romr ommerclal News lfovaers 2, -a 0 a a -~ - - - a - - * a - - * * a1 -D * --a - a - w -40 a.- a - - - a - a.. - a. - a - ~- a - W pv - a. mmu -.0 o.- 4a. 4w 4ab a-0 - - a - a a -. - *1muo m SWOO* - - a a. - 0-~ a - O - - a a. a - a a-a. - - a. a -a.- - - a - ~a. m - 'a a - , WINE I Continued from Page 1C the negatives? It seems there O)- are none reported so far. The researchers report, "No adverse effects ... except in people who are allergic to the components." They say further, -* "... ingredients can be taken r combined as a meal or individ- S - ually at different times of the . day." And go on to add, "... the regime would be enhanced by a -2 specific recipes using the - i Polymeal ingredients." - V So knowing what we know s now from reading the above, how about sitting down to a a 2 dinner of fresh broiled grouper - * -- slathered in garlic sauce, with roast potatoes and spinach, washed down by two glasses of Pinot Noir. And for dessert some nice dark chocolate-cov- ered almonds. WINES OF THE WEEK - To accompany our four-times- a-week fish dinners, Pinot Noir is an ideal red wine. Several highly recommended super values from the QPR (Quality to Price Ratio) Web site, are Echelon '01 at about $12, La Crema '01 at about $16, and Fess Parker '01 for $15. Oak Ridge resident Ron Drinkhouse was a buyer and seller of wines in his native Connecticut He welcomes inquiries, and can be reached via e-mail at ronoct9@aol.com or via telephone at (352) 489-8952 W~ sopr r @be* hw~k A - - - - a. * 40 .AD - a quo-No ~ a a ~ - -a. - 0 I -1 * a. g r2 *700% Growth Award Winning Same Local Owner/Publisher r52.344.1184 Altrusa International of Citrus County Presents 3R ANNUAL MONTE CARLO NIGHT ;eJ Bk~ A'. Gaming, prizes, entertainment, W l refreshments WHEN: Saturday, February 5th, 2005 6 p.m. 10 p.m. W H ERE Beverly Hills Recreation Center 77 Civic Circle, Beverly Hills Benefit: Family Visitation Center, High School Scholarships Tickets: $20 per person or $36 for two. Call Vicki Humphrey 341-3449 or Judi VanDermark 726-59(X) "'if Aval - 4b - 0.. ~- a - ~ m a* 0 - - - a a GOT A NEWS TIP? * The Chronicle welcomes tips from readers about breaking news. Call the newsroom at 563-5660, and be prepared to give your name, phone number, and the address of the news event. CELEBREX, VIOXX, BEXTRA or HORMONE THERAPY If you or a loved one has taken CELEBREX, VIOXX or BEXTRA and suffered death, a heart attack, a stroke, blood clots or other serious injuries or have taken Hormone Therapy drugs such as PREMPRO, PREMARIN, or PREMPHASE or PROVERA and developed breast cancer, you may be entitled to compensation. Contact the Law Offices of Nikki M. Kavouklis for a free consultation. ( ikki K AV 0 U KILI S I\'w OCS oi NIKKI M. KAVOUKIIS, P.A. U I . ..... .... .... .... .. CALL NOW FOR A FREE CONSULTATION 1-(877)944-LAWS(5297) Serving: Tarpon Springs, New Port Richey, Spring Hill, Brooksville, and Tampa THE HIRING OFA LAWYER IS AN IMPORTANT DECISION THAI SHOULD NOT BE BASED SOLELY UPON ADVERTISEMENTS BEFORE YOU DECIDE, ASK THE LAWYER TO SEND FREE WRITTEN INFORMATION ABOUT THEIR QUALIFICATIONS AND EXPERIENCE. 6 o g o r o . - * * - * THURSDAY, JANUARY 6, 2005 3C C...."..., -C ,,..., JtrS C.,Imno rrlr CLIIMUS COUNTY i (PL) CIIRONICL CHARLENE ANDERSON LUCY, LEX &NATHAN BARNES Multi-Million $ Producer Multi-Million $ Producer JENNEY MORELLI Realtor SCOTf BENDER JOY BILY JUDY BLACKSTOCK Multi-Million $ Producer Multi-Million $ Producer Multi-Million $ Producer MIKE BLACKSTOCK Realtor ERMA & WALTER BRADY JODY BROOM Multi-Million $ Producers Multi-Million $ Producer JOHN CAREY TIM COUNTS Million $ Producer Multi-Million $ Producer KAREN CUNNINGHAM Realtor PAT WALMSLEY Multi-Million $ Producer RICHARD VENTICINQUE Multi-Million $ Producer STEVE VARNADOE Broker ELLIE SUTTON Multi-Million $ Producer MARK STONE Multi-Million $ Producer JENNIFER STOLZ Multi-MilBlion $ Producer LARRY SCINTA Multi-MilBon $ Producer DEBBIE RECTOR Multi-Million $ Producer If You're Planning On Selling Or Buying Real Estate In 2005, Contact A RE/MAX Professional. The Proof Is In The Numbers! Citrus County's #1 Company, Year After Year.. '245,000,000 Closed Sales Volume Nobody Sells More Real Estate Than VWAMWL Realty One 618 KEVIN CUNNINGHAM Broker SCOTT FILLBACH Multi-Million $ Producer KELLY GODDARD Multi-Million $ Producer ALEX GRIFFIN Multi-Million $ Producer JERRY HARTMAN Multi-Million $ Producer WAYNE HEMMERICH Multi-Million $ Producer DEBRA PILNY Multi-Million $ Producer PAT & JIM PHILLIPS Multi-Million $ Producers LEN PALMER Multi-Million $ Producer Residential Listings Sold Top 6 Offices, 2004 JOHN HOLLOWAY Multi-Million $ Producer 361 320 304 205 174 This representation is based on whole or in part on data supplied by the Realtors Association of Citrus County and its Multiple listing Service. Neither the association nor its MLS guarantees nor is in any way responsible for its accuracy. Data maintained by the association may not reflect all real estate activity in the area. This bar graph reflects the residential listings sold (homes listed by each office that sold) as reported to the Association or its MLS for 1/1/04 thru 12/30/04 as of 12/30/04. RVMR1 Realty One CRYSTAL RIVER OFFICE 504 NE Hwy. 19 Crystal River, FL 34429 352-795-2441 CENTRAL RIDGE OFFICE 2421 N. Lecanto Hwy. Lecanto, FL 34461 352-527-7842 INVERNESS OFFICE 1100 W. Main St. Inverness, FL 34450 352-637-6200 SUSAN KNOWLES Multi-Million $ Producer KAREN OGBURN Multi-Million $ Producer LORENE LOGAN Multi-Million $ Producer MARIA O'BRIEN CHERYL NADAL BRIAN MURRAY Million $ Producer Multi-Million $ Producer Multi-Million $ Producer TONY MOUDIS BARBARA MILLS LINDA MEAIIL VIC McDONALD DIANNE MacDONALD TOM MAYBERRY Multi-Million $ Producer Multi-Million $ Producer Multi-Million $ Producer Multi-Million $ Producer Multi-Million $ Producer Multi-Million $ Producer BARBARA MALZ VICKI LOVE Million $ Producer Multi-Million $ Producer Realty One JIM CURTIS Million $ Producer 4C WFi1NESDAY, JANUARY 6, 2005 S m- -a m o * t *** S... * d - S * * * - ^ 0** * * *S- * *^ ENTERTAINMENT - *---_ - *a $a *a a 00 00 S*a@olls0 sow oil 'p * *~- b turn (q% ift di WI' I0-w a -0 qw 0 . 6r ~mI 0 a C *' . . U *1*t J'J1d~~U~d a *a a Ei - -5--- * .. p es i % - - * Q a asa 0 *. * *. 0@ a a a 0 - - . A~a a a. * a-a so da * U. lit-f 'Coopyrl hted Material .* *." * Iablefrom Com S.. a 4 do dln - - I = $ *am am *M 0 rwl Pt 1-40e . 10 1". O & 0* -A 0 ft 4b f aS - ~ a * 0 * 0 * 0 0 a 3 0 0 ,. . -- -.- -- * merciai News Providers , . . t 1- 8 4m- - 4 b pow%,~I - -a Ipwns mw - * * C * = -a C - C ~5 - Ilk Am .mt a 0,4 - --Now--Nu a. a -' ~ - wa0 ~ C S a. a S V * a ' a - a I ~ a. w - * * * O00 * o * 0 e * * *0 * * 0 a - T uf-cr -yin w" *h f p4fW - W~ w - 0 a - S - C o a * a i_%I - *II - .- IE - * ** 9 -w -- -mi UT- a- 01T qdlm a m q . 4 p S I S 0 *-o -p - o - ~~ -W obaow a CIRUS COUNTY (FL) CHRONICLE 0 a - 3ted Content7 aw qm - C - m 4b aqwmq p * ^ * * - 49p- ILI ** T. . . ,'CrIRUS Courn~ (FL) CuRoNIcIE Cc~Ics TIJumDAY, JANIIAiV~ 6, 2005 5C a a -0 A 9 I' a 4 W D 4m40, 40A ti oil LfA I ~am~ Ihb a C quo -as D - ~ ,qr *~i: .'1. * a S do - L-adW 5 I h &7 Oh - 0 ' A' a #a S0ontent - ~ 9 ommercia NEws Pfrvi ers 'I 0~ i a V no- - - ~ - o* - mum -M ~ 0 -41b am MOWNE - qw 4w ah 01 aiA Citrus Cinemas 6 Inverness Box Office 637-3377 "Meet the Fockers" (PG-13) 1:10 p.m., 4:10 p.m., 7:15 p.m. "Lemony Snicket's A Series of Unfortunate Events" (PG) -1:15 p.m., 4:15 p.m., 7:20 p.m. "Fat Albert" (PG) 1:25 p.m., 4:30 p.m., 7:25 p.m. . "Spanglish" (PG-13) 12: 45 p.m., 3:45 p.m., 7 p.m. "Christmas with the Kranks" (PG) 12:50 p.m., 3:50 p.m., 7:30 p.m. "Ocean's Twelve" (PG-13) 4 p.m., 7:05 p.m. "Polar Express" (G) 1:30 p.m. Crystal River Mall 9; 564-6864 "Darkness" (PG-13) 4:10 p.m., 10:05 p.m. "Fat Albert" (PG) 1:20 p.m., 4:35 p.m., 7:40 p.m., 9:40 p.m. "The Aviator" (PG-13) 12:55 0 h* 74,.'a. p.m., 4:25 p.m., 8 p.m. "Meet the Fockers" (PG-13) 1:10 p.m., 4:20 p.m., 7:20 p.m., 9:55p.m. "Flight of the Phoenix" (PG- 13) 1:25 p.m., 4 p.m., 7:30 p.m., 10:10 p.m. "Lemony Snicket's A Series of Unfortunate Events" (PG) 1:35 p.m., 4:30 p.m., 7:20 p.m., 9:50 p.m. "Spanglish" (PG-13) 1:15 p.m., 4:05 p.m., 7:05 p.m., 9:50 p.m. "Ocean's Twelve" (PG-13) 1:30 p.m., 4:15 p.m., 7 p.m., 9:45 p.m. "Christmas with the Kranks" (PG) 7:50 p.m., 10 p.m. "National Treasure" (PG) 1:05 p.m., 7:10 p.m. "Polar Express" (G) 1 p.m., 2:25p.m., 4:40 p.m. Times subject to change; call ahead. a S. do* fit I& L4 .5% -Am 49 4w a- 4w Mil dS IV Am qqpm' - .lw A ND.-- 0 dm 40000M* a dub a-Nb - - o ..o . - -n, an fA X a --a a - a __ ~ a -~ - 4t - w '% a- 0 I" 1-0 0 T 4Esl.. Today's MOVIES V ci doo sommlme q .0 4b M -,n. : dib w 6eq, "I CITRUS COUN7Y (FL) CHRONICLE COMICS ,rILJRSDAY, JANIJMy 6, 2005 SC oo - Q O ID . . - . fs, rli io . in 'o i CITRUS COUNTY (FL) CHIRONICLi 6C T!iltlRSDAY, JANUARY 6, 2005 Property TRANSACTIONS Property transaction infor- mation is supplied to the Chronicle by the Citrus County Property Appraiser's Office. Call 341-6600 with questions. Seller: Meyer Frank E & Geraldine J Buyer: Johnson Eric Price: $4200 Addr: East County: 04510 E Bahia Ln Description: River Lakes Manor Unit 1 Pb 3 Pg 96 Lot 4 BIk 32 Seller: Padilla Ricardo & Elba Buyer: Kersey William T II & Tammy L Price: $12000 Addr: East County: Description: Inverness Hglds South Pb 3 Pg 51 Lot 1 BIk 297 Seller: Dean Ronald S Jr & Leslie B Buyer: Kulper Paul B Price: $110000 Addr: East County: 01092 S Chateau Pt Description: Henderson Pt Unrec Sub Lot 11: Coam At Se Car Of Nel/4 Of Swl/4 On Pb 3 Pg 113 Bel Air Being S Ln Of BIk A, Th S 89 Deg 2 Seller: Hewitt Bertram & Freda L Buyer:.Lapointe Armand B & Lena Price: $3500 Addr: East County: 06632 E Glencoe St Description: Inverness Hglds West Pb 5 Pg 19 Lot 5 BIk 335 Seller: Edwards Barbara A Buyer: Lateef Ahmad Hosan & Shazia Price: $21500 Addr: East County: 00381 E Dusty Ct Description: Casa De Sol Pb 12 Pg 24 Lot 30c: Coam At The Nw Car Of Lot 30, Th S Od 03m 24s E Al The W Ln Of Sd Lot 30, 304.95 Ft To T Seller: Rinehart Lowell E & Alberta L Buyer: Mathewson Wilfred & Dorothy Price: $45000 Addr: East County: 10135 E Bass Cir Description: East Cove Unit 1 Pb 4 Pg 82 Lots 41 & 42 Bik D Seller: Lee Peter Y & Julie W Buyer: Mc Coy Douglas R Price: $36000 Addr: East County: 03872 N Baywood Dr Description: Fairview Estates Pb 12 Pg 49 Lot 27 BIk J Seller: Hall Michael L Buyer: Melnyk Stephen T Price: $92900 Addr: East County: 00175 E Hartford St Description: Greenbriar Of Citrus Hills Consolidated Condominium Bldg 8 Unit 2a Desc In Or Bk 834 Pg 1262 Seller: Massey Arthur G Trustee Buyer: Messer Charles L & Cynthia L Price: $4000 Addr: East County: 09064 S Spoonbill Ave Description: Pine Lake Pb 4 Pg 67 Lot 45 & N1/2 Of Lot 44 BIk E Seller: Keener Glen L & Peggy Buyer: Mills Jeffrey Wayne Price: $2500 Addr: East County: 03315 E Paula Ln Description: Inverness Hglds Unit 8 Pb 2 Pg 166 Lots 46, 47, 48 & 49 BIk 18 Seller: Kopp Clyde Trustee Buyer: Negro Heriberto Price: $15000 Addr: East County: 09118 E Island Dr Description: Barnette Ests Unrec Sub Lot 12 Desc As: Coam At Sw Cor Of Sw 1/4 Of Nw 1/4 Of Sec 2-19-20 Th N 88deg 43m E Al S Ln Of Sd Seller: Kopp Clyde Trustee Buyer: Negron Heriberto Price: $15000 Addr: East County: 09023 E Island Dr Description: Barnette Ests Unrec Sub Lot 9 Desc As Follows: Comm At Sw Cm Of Sw 1/4 Of Nw 1/4 Of Sec 2-19-20 Thn N 88deg 43m E Alg S Seller: Mansfield Maria Buyer: Newco Homes Of Ocala Inc Price: $15500 Addr: East County: 01604 N Baltic Ter Description: Cambridge Greens Of Citrus Hills Pb 13 Pg 119 Lot 28 Blk 2 Seller: Thomas Antonina Milazzo Buyer: Oliver Dorothy J Price: $610DO Addr: East County: 09751 S Florida Ave Description: N 100 Ft Of Pt Of Swl/4 Of Ne1/4 E Of Sec 28-20-20 Lylilng E Of Us Hwy 41 R/W Desc In Desc In Or Bk 1292 Pg 1186 & Or B Seller: Meyer Frank E & Geraldine Buyer: Paulson Gregory Price: $840D Addr: East County: 07230 N Comanche Ter Description: Comanche Village Unrec Sub Lots 17 & 18: From Sw Car Of Nwl/4 Of Nwl/4 Of Swl/4 Of Sec 32 & 33-17-20, S 89 Deg 34 M 29s Seller: Kartagener Armin & Or Buyer: Schurich Richard Price: $4400 Addr: East County: Description: Inverness Hgids South Pb 3 Pg 51 Lots 49 & 50 Blk 248 Seller: Ambrosino Geraldlne Buyer: Segarra Victor I Price: $73000 Addr: East County: 00405 W Harvard St Description: Inverness Hglds South Pb 3 Pg 51 Lots 21 & 22 Blk 271 Seller: Carpenter Susan E Buyer: Sisk Pierrepont F & Sharon K Price: $24000 Addr: East County: 00628 N Seton Ave Description: Kensington Ests Unit 2 Pb 11 Pg 66 Lot 27 Blk J Seller: Secretary Of Housing & Urban Buyer: Stephenson Peter D & Frances K Price: $49200 Addr: East County: 01492 N Lagoon Pt Description: Coam At Sw Car Of Nw1/4 Of Nel/4, Th N Al W Ln Of Nwl/4 Of Nel/4 426,79 Ft To Pob. Th N Al W Ln 23.21 Ft, Th S 89 Deg 20m Seller: Pochlntesta Louis & Marie Buyer: Tessmer Robert H Sr & Janette Price: $5500 Addr: East County: Description: Inverness Hglds South Pb 3 Pg 51 Lots 51 & 52 BIk 266 Seller: Finnan Marion E Trustee Buyer: Vet Marinus & Jean Price: $79000 Addr: East County: 06832 E Royal Cres St Description: Royal Oaks Pb 13 Pg 51 Lot 11 Blk 2 Seller: Thompson Milton E Jr Buyer: Vincent George & Susanne Price: $15000 Addr: East County: Description: Oakwood Island Pb 8 Pg 74 Lot 48 Blk A Title In Or Bk 599 Pg 2004 Seller: Vreeland Norman C Jr & Buyer: Vreeland Norman C Sr Price: $22700 Addr: East County: 13213 S Oakview Ave Description: Whispering Oaks Pb 7 Pg 24 Lot 8 BIk F Seller: Barbin Thelma Buyer: Wall Ricky & Nancy Lee Price: $22000 Addr: East County: 01155 N Beach Park Dr Description: Magnolia Beach Park Unit 1 Pb 3 Pg 38 Lots 2 & 3 Bl1k C Seller: Barbin Thelma Buyer: Wall Ricky & Nancy Lee Price: $22000 Addr: East County: 01139 N Beach Park Dr Description: Magnolia Beach Park Unit 1 Pb 3 Pg 38 Lots 2 & 3 BIk C Seller: Youmans Evelyn Buyer: Williams Kellis L & Denise Price: $6000 Addr: East County: 12460 S Aster Pt Description: Oak Forest Pb 11 Pg 84 Lot 3 BIk A Seller: Hoppough John Buyer: Anselmo Paul J & Virginia Price: $22500 Addr: Sugarmill Woods: 00009 Milbark Ct Description: Sugarmilll Woods Cypress VIg Pb 9 Pg 86 Lot 12 Blk 43 Seller: Cates Richard B 2nd Buyer: Closi Victor & Phyllis Price: $28000 Addr: Sugarmlll Woods: 00014 Sweet Peas Ct Description: Sugarmill Woods Oak VIg Pb 10 Pg 10 Lot 7 Blk 211 Seller: Schiering Irene B Buyer: Lfc Asset Recovery Corporation Price: $27800 Addr: Sugarmill Woods: 00012 Mimosa Ct Description: Sugarmill Woods Oak VIg Pb 10 Pg 10 Lot 42 Blk 148 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00078 Whitewood St Description: Sugarmill Woods Cypress Vig. Pb 9 Pg 86 Lot 2 BIk 45 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00014 Pagoda Ct Description: Sugarmill Woods Cypress Vig Pb 9 Pg 86 Lot 27 Blk 46 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00004 Cactus St Description: Sugarmlll Woods Oak VIg Pb 10 Pg 10 Lot 2 BIk 157 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 06370 W Oak Park Blvd Description: Sugarrilll Woods Oak VIg Pb 10 Pg 10 Lot 4 BIk 146 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00076 Whitewood St Description: Sugarmill Woods Cypress VIg Pb 9 Pg 86 Lot 1 BIk 45 Seller: Burt Donald M & Betty J Buyer: National Recreational Price: $8000 Addr: Sugarmill Woods: 00034 Village Center Dr Description: Sugarmill Woods Oak VIg Pb 10 Pg 10 Lot 5 Blk 156 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00016 Eugenia Ct Description: Sugarmill Woods Cypress VIg Pb 9 Pg 86lot 19 Blk 54 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00001 Cleome Ct Description: Sugarmill Woods Oak VIg Pb 10 Pg 10 Lot 16 Blk 159 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00019 Mimosa Ct Description: Sugarmill Woods Oak VIg Pb 10 Pg 10 Lot 14 Blk 148 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00023 Lysiloma Ct Description: Sugarmill Woods Cypress VIg Pb 9 Pg 86 Lot 10 Blk 9 Seller; Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 06425 W Oak Park Blvd Description: Sugarmill Woods Cypress VIg Pb 9 Pg 86 Lot 22 Blk 111 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00034 Cherrypalm Ct Description: Sugarmill Woods Cypress Vig Pb 9 Pg 86 Lot 25 Blk 49 Seller: Lfc Asset Recovery Corporatlon Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00174 Linder Dr Description: Sugarmill Woods Cypress Vig Pb 9 Pg 86 Lot 14 Blk 38 Seller: Lfc Asset Recovery Corporation Buyer: National Recreational Price: $110500 Addr: Sugarmill Woods: 00010 Cassla Ct Description: Sugarmill Woods Oak Vig Pb 10 Pg 10 Lot 5 BIk 149 Seller: Palmer Unda Freeland & Buyer: Possidente Anthony Price: $57500 Addr: Sugarmill Woods: 00011 Beech Ct Description: Sugarmill Woods Cypress VIg , Pb 9 Pg 86 Lot 9 BIk J Seller: Mc MInn Robert J & Evelyn M Buyer: Welsh John & Dorothy Price: $140500 Addr: Sugarmill Woods: 00058 Douglas St Description: Sugarmill Woods Cypress Village Pb 9 Pg 86 Lot 2 BIk 12 Seller: Costa Alexander & Anita M Buyer: Zebrowski Bernard L & Marilyn Price: $180000 Addr: Sugarmill Woods: 00029 W Byrsonima Loop Description: The Hammocks Of Sugarmill Woods Pb 14 Pg 6 Lot 79 Seller: Herbert Lloyd S & Evelyn K Buyer: Andrews Gregory T & Elaine A Price: $6000 Addr: West County: Description: Unit 4 Of Homosassa Pb 1 Pg 46 Lots 5 & 6 Unrec Of Lots 1 Thru 24 Incl Blk 189 Lot 5-Lot 19 & W 20ft Of Lot 18 & E 0lqft Seller: Vascimini Michael & Julia Buyer: Beller Richard G Price: $47000 Addr: West County: 06340 S Tex Pt Description: Servos Commercial Center Condo Decl In Or Bk 762 Pg 191 Unit 7 Bldg B Seller: Tucker Annie M Buyer: Brunca Inc Price: $11000 Addr: West County: 06190 S Esmeralda Ter Description: El Dorado Ests Pb 11 Pg 35 Lot 12 Blk F Seller: Gelsinger J M Trustee Buyer: Daiello Martha L Trustee Price: $60000 Addr: West County: 05337 N Mallows CIr Description: Pine Ridge Unit 3 Pb 8 Pg 51 Lot 2 Bik 47 Seller: Tidey Donald Allen Buyer: Feola Alexander Price: $24000 Addr: West County: 08806 N Cacalla Dr Description: Crystal Manor Unit 2 Pb 8 Pg 112 Lt 1 BIk 70 Seller: Smith Roger K Buyer: Flynn Brandon W Price: $3500 Addr: West County: 08463 N Hatfield Ter Description: Holiday Hts Unit 1 Pb 4 Pg 61 Lot 51 Blk 15 Seller: Hayn Raymond W & Helen S Buyer: Gajadhar Sean Price: $14500 Addr: West County: 00925 N Conant Ave Description: Pine Tree Homesites Pb 3 Pg 2 Lots 16 & 17 Seller: Balerlein John 0 Sr &Geraldine Buyer: Geskie Robert & Valerie Susan 'Price: $56500 Addr: West County: 01515 N Killebrew Pt Description: Hillside South Pb 16 Pg 56 Lot 49 BIk D Seller: Blackburn Charles'D & Theresa Buyer: Giordano Thomas & Aleta Price: $150000 Addr: West County: 02840 N Brentwood Cir Description: Brentwood Pb 12 Pg 70 Lot 2 Tract 6 Seller: Mathews Edward W & Shirley C Buyer: Goldman Michael M & Charlotte Price: $8500 Addr: West County: 12668 W Rosemary PI Description: Crystal Manor Unit 3 Pb 8 Pg 136 Lot 6 Bik 173 Seller: Crask Garnett E & Marcia T Buyer: Grizzle Michael & Shella Price: $20000 Addr: West County: 09899 N Marigold Pt Description: Crystal Manor Unit 3 Pb 8 Pg 136 Lot 8 Blk 147 Seller: Crask Garnett E & Marcia T Buyer: Grizzle Michael & Shella- Price: $20000 Addr: West County: 12580 W Baltic Ivy St Description: Crystal Manor Unit 3 Pb 8 Pg 136 Lot 2 Blk 167 Seller: Carillot Lucy G Trustee Buyer: Hedick Robert W Jr & Dawnya Price: $475000 Addr: West County: 03296 N Spyglass Village Path Description: Spyglass Village Pb 16 Pg 69 Lot 23 Seller: Litchfleld Financial Corp Buyer: High Card Inc Price: $40000 Addr: West County: Description: River Cove Landings Condominium II Bldg 200 Unit 201 Seller: Litchfield Financial Corp Buyer: High Card Inc Price: $40000 Addr: West County: Description: River Cove Landings Condominium li Bldg 200 Unit 204 Seller: Breakey Fred A & Buyer: Jalramsingh Dan Price:$14000 Addr: West County: 09124 N Husky Ave Description: Eighteen Oaks Unrec Sub Lot 50 Desc As Follows: S 258.27ft Of N 805.04ft Of W 1/2 Of Se 1/4 Of Se 1/4 Of Sec 18 Less & E Seller: Sacchetti Nicholas & Rose Buyer: Johnson David & Cynthia J Price: $16000 Addr: West County: 00830 S Rosemary Pt Description: Cinnamon Ridge Unit 2 Pb 12 Pg 65 Lot 18 Blk A Seller: Sacchetti Nicholas & Rose Buyer: Johnson David & Cynthia J Price: $16000 Addr: West County: 00820 S Rosemary Pt Description: Cinnamon Ridge Unit 2 Pb 12 Pg 65 Lot 19 BIk A Seller: Tullos Don W Buyer: Mac Rae Phillip R & Marian H .Price: $50000. Addr: West County: 06218 S Candice Path Description: Rooks Add To Homosassa Unrec Sub Lot 13: Coam At S 1/4 Sec Car Of Sec 31-19-17, Tn N 88 Deg 25m 24s E Al N Ln Of Frac Se Seller: Veccia James V & Judy 0 Buyer: Macaluso Paul & Kathleen I Price: $20000 Addr: West County: 11512 W Cornflower Dr Description: Crystal Manor Unit 3 Pb 8 Pg 136 Lot 3 Blk 137 Seller: Tuckfield William J Buyer: Malone Richard F Sr & Ursula G Price: $180000, Addr: West County: 05885 N Lamp Post Dr Description: Pine Ridge Unit 3 Pb 8 Pg 51 Lot 17 BIk 36 Seller: Kaufman Suzie K Buyer: Maloney Mark & Price: $4700 Addr: West County: 08126 W Fern PI Description: Unit 5 Of Homosassa Pb 1 Pg 47 Lots 11 & 12 BIk 201 Seller: Mc Guire Robert L & Shirley A Buyer: Nettles David Allen & Gall Price: $11000 Addr: West County: 04532 N Mitchum Pt Description: Liv Acres Unrec Sub Lot 25 Desc As Follows: W 1/2 Of E 1/2 Of Sw 1/4 Of Nw 1/4 Less N 4/5 Thereof Subj Ot 25ft Wide Estm Seller: Ruggiero Patrick Michael Buyer: Onbey Doug Price: $7500 Addr: West County: Description: Kennedy Hts Unrec Sub Lot 4 Desc As Follows: Comm At Sw Crn Of N 1/2 Of Sw 1/4 Of Sw 1/4 Of Sec 30-20-18 Thn N AIg W Ln Seller: 0 Hare Thomas Dennis Buyer: Padgett Harry Wm lii Price: $70000 Addr: West County: 08420 N Troccoli Ter Description: De Rosa Inc Pb 5 Pg 17 Lot 25 Seller: Padgett Harry Wm lii Buyer: Pelletti Marilyn Brooks Trust Price: $150000 Addr: West County: 02788 N Comanche Pt Description: Montezuma Waters Mobile Home Ests Pb 9 Pg 1 1st Add Lot 65 Seller: Sauve April A & Buyer: Sauve April A I Price: $5000 Addr: West County: 07220 S Blackberry Pt , Description: Gulf Hwy Land Unit 7 Pb 4 Pg I 109 W 277.55 Ft Of S1/2 Of Lot 36 Seller: Fox J Peter 3rd & Julie E Buyer: Schaffel Martin Price: $10000 Addr: West County: 02940 W Plantation Pines Ct Description: Plantation Pines Village Pb 13 Pg 115 Lot 102 Seller: Arendt Rita J Buyer: Seamer Brenda L & Price: $25500 Addr: West County: 06751 W Van Buren j Dr Description: Villa Ter Unit 10 Of Homosassa Pb 1 Pg 51 Pcl B Unrec Of Lots 8, 9, 10 & 11 Blk336: Com At E Cor Of Lot 8 BIk 336 Car Seller: Floyd Francis Lavon Buyer: Shirley T Trustee Price: $14000 Addr: West County: 12328 N G W Carver i Rd Description: Town Of Dunnellon Pb A Pg 174alot 699 Seller: Lowrey James R & Jane S Buyer: Smith Kennedy Jr & Carrol A Price: $3400000 Addr: West County: Description: Woodward Park Pb 2 Pg 70 Lot 5 Blk A Less: Beg At Nw Car Of Lot 5,. Th E Al N Bdry Of Lot, 56 Ft To Pt, Th Sw'Ly p To Pt On Seller: Lowrey James R & Jane S Buyer: Smith Kennedy Jr & Corral A Price: $3400000 Addr: West County: 09775 W Wynn Ct Description: Beg At Pt N 0 Deg 34m E 367 Ft & W 153.5 Ft From Se Cor Of Swl/4 Of Swl/4, Th W 63.5 Ft,.Th N 11 Deg 17mW 146.4 Ft Mo L Seller: Lyell Ronald D Buyer: Stender Anthony Jr & Price: $69900 Addr: West County: 07311 W Pinebrook St Description: Crystal Paradise Ests Unit 3 Unrec Sub Lot 1 BIk S Desc As: Coam At The Ne Corner Of Lt 15 BIk M Pb 4 Pg 88 Th N Odeg 29m * Seller: Vanderberg Scott & Buyer: Tidey Donald Allen Price: $17000 Addr: West County: 08806 N Cacalia Dr l Description: Crystal Manor Unit 2.Pb 8 Pg , 112 Lt 1 Blk 70 Seller: Hille Cart P & Barbara A Buyer: Vogdes James M lii & Kristine Price: $120000 Addr: West County: 11592 W Kingfisher Ct,. Description: The Bay Villas Bldg 32, 33, 34,% 35 & 36 Condo Unit 186 Desc In Or Bk 669. Pg 818 CEAC 0. 164N edo cetBv., rsa ieF 4429 016 M in St nensF 4 5 Mon.- Fi. a~m 5~m.Als viw yor a onineat ww~cronclenlin~co Mo. -Fri.8:3a~m pS. -pm Thursday Saturday Issue 1pm Friday 6 Lines for 10 Days! 2 items totaling 1 -'150.........................$550 $151 -$400................$1050 '401 -- 800 ...............15 $801 -$1,500 ...........$ 2050. CA1NOTICES002-L065 EIWANTE 1 160 LANCIA1 9 SI CS216 ANIMAS 4HI' RENT0OR*SA I50 4 IEAESTATEI P ENT 75 0 AETAT SAE10 -R90TAN RIO The Citrus County Fair Association J 6*% proudly presents Antique Traotor Pull ASRUtVo Re Open 4 P.M. PUN S P.M. januap ) so a In uaonm pBO noon Food on grounds Advanced sale tickets available at fair office and all chamber offices. Ticket prices: 1 day $8, 2 days $16, 3 days $23. Children: I day $5, 2 days $7, 3 days $10 For more information call 726-2993 i;.,,il., 11 A NEW BEGINNING SWM honest & sincere looking for old fashion- ed girl under 45 on the thin side, easy going, animal person, who enjoys classic rock & watching the stars at night, Lets find eacIh other. Respond to Citrus County Chronicle Blind Box #770P 1624 N. MeadOwcrest Blvd. Crystal River, FL 34429 786-271-9037 LETS SMELL THE ROSES TOGETHER Seeking attractive Lady 40-55 who enjoys dining out & weekend trips out of town. Looking to share quality times together & wants the nicer things in life. Call 228-1579 WM, Biker, 51, looks early 40s, 6'1', 180 Ilbs, blonde hair, blue eyes, good person. Seeks attractive lady 30 to 45, 100 to 1251bs for possible LTR. 352-804-6223 GET RESULTS IN THE CHRONICLE Music Show with Buddy Max every Saturday at 2pm. Cowboy Junction Opry, Lecanto. Freell REE VEHICLE REMOVAL Cars/Trucks, Running or Not, No title OK Phone 352-476-4392 Andy KCCB deductible receipt on request CALICO CAT I yr. spayed & declawed. Lovable. Shots current (352) 746-1070 FIND EXACTLY WHAT YOU NEED IN THE SERVICE DIRECTORY Canvas Fire Hose, 11ff to 50 ft. section, can be used boat dock bumpers (352) 795-6693 CAT Large neutered male, 5 yrs. all shots. Adult home (352) 726-4939 COMMUNITY SERVICE The Path Shelter Is available for people who need to serve their community service. (352) 527-6500 or (352) 794-0001 Leave Message FOUND 2 black/brown puppies in Floral City, vicinity of Stage Coach Rd. (352) 302-5700 COCKER MIX 35 lb. male shots current, 18 months (352) 564-0541 FREE American Bull Dog, female, llmths, (352) 302-1590 FREE SATTE DISH You remove. (352) 563-5851 FREE 4 year old male neutered Beagle great gentle guy, Great with other dogs Call evenings (352) 465-3760 FREE 8 YR OLD BASSETT HOUND w/papers, neutered & all shots, housebroken. Good dog, Must find home due to illness. (352) 465-6560 -= FREE 75 1-1/2 LIUTRE - thick wall gloss bottles, suitable for wine ,' making (352) 637-3634,,, FREE ADULT CAT Indoor only, all neutered & spayed, , homes will be screened. (352) 726-5546 FREE GROUP COUNSELING Depression/ Anxiety (352) 637-3196 or 628-3831 .. FREE KITTENS To a good home. (352) 564-9200 - FREE Lab Mix, male, neutered. (352) 527-8672 FREE PUPPIES 6 male Lab/Shepherd, Mix. 9 weeks old. (352) 726-1133 ',h -Sl CITRUSS COUNTY (FL) CHRONICLE FrleeBB a HOSPITAL BED Electric for someone who actually needs It, (352) 795-5849 KITTENS 5 mo DMH gray. M. Gray & white DSH, F. Spayed/neutered. Shots current. Litter trained (352) 447-3916 PIT MIX 6 month Female (352) 628-2810 Puppies need a good home ...Mom and Dad on premises...both sm/med build...call 352-341-3145 TEMP HOME NEEDED for gentle 7 yr. Lab. House trained, crate trained. Joining military! WANTED, DEAD OR ALIVE Vehicle & scrap, Removal. No title okay. Lv msg, (352) 563-6626 WHITE LAB & BLK LAB Both. 1/ 2 Years old. Female. To good homes) only. (352) 726-1133 pet.com Pet Adoption Saturday, 1/8 9am-1pm Allstate Insurance 433 Croft Rd. Inverness Cats Manx M. kitten, white 746-6186 DSH F, 8mos, gray/white 746-6186 Med. Fur F, 10-1 limos white w/ green eyes 746-6186 Kittens 11 wks 1-F & 2 M. black w/ orange stripes & med. fur. 746-6186 DSH M, 2 mo, gray, paw deformed due to Injury paw mobile & playful 628-4200 Dogs Catahula M, med. size tri-color merle. Young adult. Family pet. 249-1029 All spayed/neutered. All shots current. Donations tax deductible YOUNG BLACK MALE DOG, very mild. Abandoned, needs a home, not 'destroyed. 795-3938 Quality Care Tree Service * Tree Removal * Bucket Truck Work * Trimming & Topping * Lot Clearing 352-637-0004 10% Off w/this Ad A-I TALIAFERRO TREES Citrus County's Leading Team Professionals #7830257748 (352) 476-5372 DAVID'S ECONOMY TREE SERVICE, Free est., Sr. disc. Ic. 99990000273 Insured 352-637-0681 DOUBLE J STUMP GRINDING Cell 302-8852 (352) 726-0830 D's Landscape & Expert Tree Svce Personalized design, Cleanups & Br3bcat work, Fill/rock & Sod: 352-563-0272. R WRIGHT TREE SERVICE, free removal, stump grind, trim, lns,& Lic #0256879352-341-6827 STUMP GRINDING Lic. & Ins. Free Est. Billy (BJ) McLaughlin 352-628-3736/212-6067 TREE SURGEON Lrc#000783-0257763 & lrp. Exp'd friendly serv. ;Lowest rates Free estimates,352-860-1452 CRYSTAL WIND Repair, upgrade, networking. On-site & pick-up services. (352) 746-9696 SPC's-N-PARTS Spring Cleaning $19,99. ;Interior Cleaning/ System Check 564-8803 vChris Satchell Painting & Wallcovering.All work 2 full coats.25 yrs. Exp. Exc. Ref. Lic#001721/ Ins. (352) 795-6533 AFFORDABLE PAINTING WALLPAPERING & FAUX Lic. 0214277 & Ins. (352) 697-1564 All Around the House Gen. Home repairs plus Lic2120-0863567. 27 yrs. Free est, 352-465-1189 BlaCK & wnire Jack Russell w/ red collar, vicinity of Poplar St. & N. Bay Ave. 10/11/04 Goes by Petey Reward Cell 422-3702 (352) 795-5349 Cat lost, heart broke, 4 yr. old spayed female, smoke gray, on Monopoly & Chance/ Citrus Hills (352) 726-0078 LOST LOWER UNIT for Mercury outboard, couple miles south of Fort Island Beach, REWARD Please call (352) 726-7705 LOST ORANGE CAT Male, Morris type. 2 yrs. old. Vicinity of Lecanto, N Commerce Ter & 44 Answers to "Baby Day" (352) 527-7921 MISSING SINCE 12/29 Gray tiger-striped cat w/white chest- off Briarpatch in Crystal Manor. Please call (352) 564-0719 or 302-6172 White Chihuahua Mix, Injured, owner heart- broken, old Homosassa area 1/1/05. Reward please call 352-628-3510. YORKIE CHIHUAHUA SMIX 4LBS. Blonde. Mis- sing since New Years eve. Vic. of Dunnellon Hills, Citrus Springs. REWARD 352-489-0137 or 465-9183 BLACK DOG Found Crystal River near Archaeological Site (352) 795-9705 Cat, Male, large, gray tigerstrip, long hair, vocal, well cared for, Pine Ridge Golf Course area 527-3785 Found injured, White and Orange Tabby male kitten near Orange Tree road in Crystal River. Please call '257-9456 to describe and claim. LAB In area of Laurel Ridge & Forrest Ridge Blvd. Owner call to identify (352) 476-3158 YORKIE Highland Area Call to identify (352) 860-1360 Young Male Dog Beverly Hills area, call to identify. (352) 746-5114 T & T SERVICES Painting, Int/ext. Lic/Ins 212-1551 Wall & Ceiling Repairs Drywall, Texturing, Painting.;Vinyl. Tile work. 30 yrs. exp. 344-1952 CBC058268 Affordable Boat Maint. & Repair, Mechanical, Electrical, Custom Rig. John (352) 746-4521 LEE'S MOWER REPAIR'S We buy used lawn equipt, running or not. 352-564-2089 BATHTUB REGLAZING Old tubs & ugly ceramic tile is restored to new cond. All colors avail. 697-TUBS (8827) Kerry's Kustoms Custom Interior Window Treatments & Accents 25 yrs of professionalism and craftsmanship Free Est. (352) 621-4QPS In Home Childcare for every age-numerous qualifications, skills, & ref. Tender Care your child deserves. Stacy @ 212-2260 MY HOME DAY CARE CPR & first aid certified From Infant to school age. Monday Friday (352) 628-6248 VChris Satchell Painting & Wallcovering.AII work 2 full coats.25 yrs. Exp. Exc. Ref. Lic#001721/ Ins. (352) 795-6533 AFFORDABLE PAINTING WALLPAPERING & FAUX Lic, 0214277 & Ins. (352)697-1564 CLEANING of homes & offices. Quality work, I bring my own supplies. Hourly rates. 795-9705, please leave message. CLEANING. Reliable, affordable, Weekly, bi-weekly, monthly Joy, 352-746-6768 EXP. HOUSE CLEANING Brazilian/Amer. Citizen 14vrs. exp. Ref. Inver- ness area. 344-0053 ivorces .... R ,,$99 IBckrtuptcycsqcn$1891 WE COME I TO YOU! lInverness 6................37.4022| *CHRONICLE. INV. OFFICE 106 W. MAIN ST. Courthouse Sq. next to Angelo's Pizzeria Mon-Fri 8:30a-Sp Closed for Lunch 2om-3pm VACCINATION CLINICS Saturday 10am-2pm #1 DAPPC-Rabies .......... ...........................$26.00" K-9 Vaccines-Rabies only ........................... $7.00"" #2 DAPPC-Rabies-Naramune ........................... 32.00" "Distemper; Adenovirus 1 &2 (Hepatitis); Parainfluenza; Parvo Virus; Corona Virus; Naramune (Kennel Cough) #1 FVRCPC-Rabies........ ........................$24.00*" Feline Vaccines-Rabies only...................... $7.00" #2 FVRCPC-Rabies- ., FELU.................$31.00" **Feline Viral Rhinotracheitis; Calici; Panleukopenia; Chlamydia Psittici; Feline Leukemia January 8 & January 22 Carlj. Mee, D.VM. LITTLE GENERAL MARKET & FEED 4611 W Cardinal St. Homosassa S628-1577 "MR CITRUS COUNTY" ALAN NUSSO BRqKER Associate Real Estate Sales Exit Reality Leaders (352) 422-6956 HOMES & WINDOWS Serving Citrus County over 15 years. Kathy 465-7334 or 341-1603 HOUSEKEEPING Home/Office, Lis./bonded (352) 422-5600 PENNY'S Home & Office Cleaning Service Ref. avail., Ins., Lic. & bonded (352) 726-6265 ACE CABINET INSTALLER Quality woodworkI Lic. CB-00-00757 (352)464-4100 Additions/ REMODELING New construction Bathrooms/Kitchens Lic. & Ins. CBC 058484 (352)344-1620 Budget-Wise? Remdiing &Addltions, CBC057662/Ins. 637-0208/422-7918 cell STEVEN ROGERS CONSTRUCTION All Phases, Lic. & Ins. RR 0066895 637-4373 TMark Construction Co. Additions, remodels & decks, Lic. CRC1327335 Citrus Co (352)302-3357 All Around the House Gen. Home repairs plus Lic2120-0863567. 27 yrs. Free est. 352-465-1189 AUGIE'S PRESSURE Cleaning Quality Work, Low Prices. FREE Estimates: 220-2913 PICARD'S PRESSURE CLEANING & PAINTING Roofs w/no pressure, houses,driveways. 25 yrs exp. Lic./ins. 422-1956 PRESSURE CLEANING BY FRED.Houses, decks, Lic. & Ins. #99990001327 Low prices 352-225-1161 ROLAND'S Pressure Cleaning Roofs, houses, driveways., mobiles 21 yrs exp. Lic. 726-3878 #1 IN HOME REPAIRS, paint, press.wash, clean roof&gutters, clean up, haul #0169757 344-4409 AAA HOME REPAIRS Maint & repair prob- lems Swimming Pool Rescreen99990000162 352-746-7395 All Around the House Gen. Home repairs plus Lic2120-0863567. 27 yrs, Free est. 352-465-1189 Andrew Joehl Handyman. General Maintenance/Repairs Pressure & cleaning. Lawns, gutters, No job too small Reliable. Ins 0256271 352-465-9201 1 CALL STANDS BETWEEN YOUR BUSINESS and millions of potential customers. Place your ad in the FL Classified Advertising Network. For $450 your ad will be placed In 150 papers, Check out our 2x2 and 2x4 display network tool Call Healher Mola, FL Stinlewlide Advertising Nolwaik Director at (866) '742 13/3 or email hilnoliruflpress.com tor roate Inifornatlon, (Out of Slate Placonemei Is also available,) Visit us on-line at- classifieds,com FCAN DIVORCE $175-$275 "Covers children, etc, Only one signature required 'Excludes govt. fees! Call (800) 462-2000 ext, 600 (8am-7pm) Divorce Tech. Established 1977 FCAN PIANO/FRENCH TEACHER needed, 1 time per week, East Side. 637-1173. Ready to Stop Compulsive Overeating? Welcome to Overeat- ers Anonymous 726-9112,341-0777 REAL ESTATE CLASSES Now Enrolling 2/15/05 Sales Lie. We Eliminate Mold & Odors. Non-chem. Safe, Guar. Check us out Medallioncentrol florida com ALL TYPES OF HOME IMPROVEMENTS & REPAIRS #0256687 352-422-2708 EXP'D HANDYMAN All phases of home repair.Exc.work. Honest reliable, Good prices. LIc/Ins. 352-860-0085 Get My Husband Out Of The House & Into Yours! Custom woodwork, furniture repairs & refinishing, home repairs, etc. Lic. 1078 (352) 527-6914 GOT STUFF? You Call We Haul CONSIDER IT DONEI Handyman Service Cleanouts & Repairs Lic. 99990000665 (352) 302-2902 RB HOME * IMPROVEMENTS Quality work low prices. All aspects of home Improve. Lic # 0257455 (352) 228-7823 Seasons Greetinas to HANDYMAN, from New England. Small or big jobs. very exp. Reason- able (352) 489-1495 HANDYMAN/AII Around Free est. Will Do Any- thing, Lic.#73490257751 352-299-4241/563-5746 Joe, "The Handyman" Home Maintenance & Repair. Power washing, Painting. Lawn Service & Hauling. Lic 0253851 (352) 563-2328 NATURE COAST HOME REPAIR & MAINT. INC. Offering a full range of servlces.Llc.0257615/Ins. (352) 628-4282 Wall & Ceiling Repairs Drywall. Texturing, Painting, Vinyl. Tile work. 30 yrs. exp. 344-1952 CBC058268 JT'S TELEPHONE SERVICE Jack & Wire installation & repair. Free estimates: CALL 527-1984 DUN-RITE ELECTRIC INC. Elec. Serv./Repairs. New const. Remodel Free est 726-2907 ER0015123 All of Citrus Hauling/ Moving items delivered, clean ups.Everything from A to Z 628-6790 GOT STUFF? You Call We Haul CONSIDER IT DONEI Handyman Service Cleanouts & Repairs Lic. 99990000665 (352) 302-2902 ON SITE CLEANUP Const., debris, M.H. demolition, & stump grinding (352) 634-0329 ATTRACTIVE SWF seeking male companion. Candi, 352-628-1036 PILATES In Inverness Lose the extra weight. Mornings & Afternoons 476-1052 or 726-6250 Hi, I'am Max 8 wk, old Lab, need ride to Columbia, Tenn. area, Will pay my own way, (352) 564-9200 2 Mature Care Givers. Certified & Bonded. (352) 726-6229 or (352) 860-0326 LICENSED CNA Looking to take care of elderly. 20 years exp. Honest & dependable 352-860-1426 Relocating to Inverness very soon. Seeking Security Position, Exp. w/G.S.A.contracts & supervision. Will supply resume. I have lived & worked in Fl.and most of my family live here also. Please call James at. 570-346-6928 EXPERIENCED PRESCHOOL TEACHER Infant/Toddler Class. (352) 795-6890 CARPET FACTORY Direct Restrecth Clean * Repair Vinyl Tile * Wood (352) 341-0909 (352) 637-2411 BEACH FENCE Free est., Lic. #0258336 (352) 628-1190 813-763-3856 Cell JAMES LYNCH FENCE All kinds of fences. Free estimates. (352) 527-3431 John Gordon Roofing Areas. Rates. Free est Praioudto Serve You. ccc 1325492. 628-3516/800-233-5358 JT NEELY ROOFING, INC. Lic. ccc055011 & Ins. Metal Roofing & MH roof- overs. All Work Guarl (352) 637-6616 Benny Dye's Concrete Concrete Work All types Lic. & Insured. RX1677. (352) 628-3337 BIANCHI CONCRETE Driveway-Patio- Walks. Concrete Specialists. Lic#2579 /Ins. 746-1004 DANIEL ENO CONCRETE & MASONRY All types, All Sizes. Lic #2506. Ins. Free Est. 352-212-3492 DEVAUGHN RIP RAP SEAWALLS & CONCRETE WORK Lic#2699 & Insured. (352)795-7085/302-0206 JACO MASONRY INC Blck Work CBC060529 352-746-5364268 CERAMIC TILE INSTALLER Bathroom remodeling. handicap bathrooms. Lic/Ins. #2441 795-5024 JOBS GALORE!!! EMPLOYMENT.NET LEGAL SECRETARY Full Time, experience with wills, trusts and probates. Beverly Hills location. Fax Resume to: (352) 726-3180 RECEPTIONIST wanted w/ Excel, & Word skills. Fast paced office. Multi-tasks & phones. Auto insurance a + (352) 795-5129 RECEPTIONIST NEEDED Part-Time; Tuesday, Wednesday and Thursday, 8:30a.m. to 5:00p.m. $6.00 per hour. Must have transportation for occasional errands. Send Resumes To: Post Office 895, Inverness, Florida 34451 COSMETOLOGIST 422-1058 or 794-4150 LOOKING TO START A NEW YEAR? Now hiring commission & retirement available. (352) 628-5599 PT HOUSEKEEPER Wanted Call (352) 465-4019 3-11 RN / LPN Avante at Inverness is currently accepting applications for nurses on the 3-11 shift. Avante offers top of the line wages and excellent benefits. Please apply in person at: 304 S. Citrus Ave., Inverness, FL Wall & Ceiling Repairs Drywall, Texturing, Painting, Vinyl. Tile work. 30 yrs. exp. 344-1952 CBC058268 BUSHHOGGING, Rock, dirt, trash, trees, lawn service, &driveways. Call (352) 628-4743. MVEROPERTIES Grading, Driveways, Lawns. free Est. Lic.# 256667(35:')400-0150 All Tractor Works, By the hour or day Clean ups, Tree Removal, Bush Hog Land Clearing. All Major Credit Cards. 302-6955 CORNERSTONE 40 yrs. exp. Hallng, tree removal, bobcat serv., Lic/Ins. 99990000255 1 (877) 398-6698 LAND & LOT CLEARING + Hauling. Free Est. Helen's Nursery (352) 563-2313 LAND CLEARING EXCAVATION Lic. # 0257173 &Inc. MLK Enterprises Call Al Free Est. 352-628-1942 or 352-346-4776 LAND CLEARING, front end loader by the hour. Filldirt, rock, hauling and demolition. 302-2928 Nathan Gilstrap's Tractor Work, Free est (352) 302-0028 Camp. Tractor & Dump Serv. Owner/Builders Land clearing/fill dirt, concrete driveways, sidewalks, house floors, block work Lic. #001629-156 563-1873 D's Landscape & Expert Tree Svce Personalized design. Cleanups & Bobcat work. Fill/rock & Sod: 352-563-0272 All Around the House Gen. Home repairs plus Lic2120-0863567. 27 yrs. Free est. 352-465-1189 Bill's Landscaping Lawn Cuts $10. & up Clean ups, odd jobs Free est. (352) 628-4258 BOBS PRO LAWN CARE Yard clean up. Shrubs Residential/Comm. Lic./Ins.(352)613-4250 ClerHTical/ of Citrus County Now taking applications for FULL-TIME COOK $9/hour Woodland Terrace 124 Norvell Bryant Hwy. Hernando CNAs & HHAs Exp'd, Caring & Dependable. $8.50 per to eligible applicants. CALL LOVING CARE M-F, 9:00 AM to 4:00PM (352) 860-0885 P/T X-RAY TECH Citrus County, General Orthopedics, Competitive salary. Send Resume to: Blind Box 774-M c/o Citrus County Chronicle 106W. Main St. Inverness, FL 34450 PHARMACY TECH/ CASHIER Fulltime, no holidays or nights. Inverness. Send brief list of experience. Pharmacy experience is preferred. Send to: Blind Box 668P, Chronicle, 106 W. Main St. Inverness, FL 34450 Bruce's Lawn Service & Odd Jobs. 20 yrs. Call: (352) 637-5331 Cell: (352) 476-5603 CLEAN UP Free est. John Hall Lawn Maint. Reliable, Lic. & Ins. (352) 344-2429 Holiday Special $20. for lawns any size under 1 Acre. Mow, trim & blow. (352) 527-1836 ONE FREE MONTH Quality Property Services. Lawn Care & Landscape. Free Est. (352) 621-4QPS REFINISH DECKS, lanals, sidewalks, driveways, cracks fixed, pressure wash screen, repaints. Lic #17210254444 & Ins. (352) 527-8444 SWIMMING POOL LEAK DETECTION Over 40 vrsexoerience 352-302-9963/ 245-3919 Seasoned Oak Fire Wood, Split, $60,4x8. (352) 344-2696' FIREWOOD Split, seasoned. CRYSTAL PUMP REPAIR (352) 563-1911 $200 Off Water Filters No Chemicals WATER PUMP SERVICE & Repairs on all makes & models. Lic. Anytime, 344-2556, Richard "MR CITRUS COUNTY" ALAN NUSSO BROKER Associate Real Estate Sales Exit Reality Leaders (352) 422-6956 RAINDANCER Seamless Gutters, Soffit Fascia, Siding, Free Est. Lic. & Ins, 352-860-0714 ifL -es CNA's Avante at Inverness, is currently accepting applications for 3-11 and 11-7 shift CNAs. Avante offers top of the line wage scale along with shift differential and weekend differential. Excellent benefits package for fulitime employees Please apply in person at: 304 S. Citrus Ave., Inverness F/T HOUSEKEEPER (352) 860-2525 Or Apply in Person Highland Terrace 700 Medical Court E. Inverness ffm RN-FT Case Manager Excellent Benefits & Pay. Home Health exp, preferred. rkeefer@atlantic.net A+ Healthcare HOME HEALTH (352) 564-2700 START A NEW CAREER FOR THE NEW YEARIl EARN AS YOU LEARN CNA Test Prep/CPR 352-341-1715; 422-0762; 422-3656 FOUNTAINS MEMORIAL PARK CEMETERY In Homosassa needs experienced Family Services Counselor to meet with at need families & assist with arrangements. Good benefits. Call Donna 10 am -2pm (352) 628-2555 EOE DFWP INSURANCE Personal lines Office Manager sought for small branch office of independent insurance agency. Florida Agent's License mandatory. Commercial lines exp. a plus. Send resume to: Advertiser, P.O. Box 3252, Homosassa Springs, FL 34447. Jones' Restaurant is now hiring: Exp. Kitchen Manager Apply in person 216 NE HWY 19 C.R. (352) 563-1611 REAL ESTATE CLASSES Now Enrolling 2/15/05 Sales Lic. Class $249. RON NEITZ-BS,MBA BROKER/INSTRUCTOR CITRUS REAL ESTATE SCHOOL, INC. (352)795-0060 Accepting applications for All Positions Apply in person Mon thru Fri between 2 & 4 Applebees Inverness and Crystal River NO PHONE CALLS PLEASE COOKS Transport & phone req. Apply 5 6 PM The Cove COOKS & SERVERS High volume environment. Exp. preferred. Positions available in Inverness & Dunnellon. Apply in person only. 9am-Noon or 2pm-5pm Mon-Fri COACH'S Pub & Eatery 114 W. Main St., Inverness EOE DELI CLERK Experience only! NEAT & CLEAN! Ferrara's Deli Beverly Hills: 746-3354 Call between 2-4 pm. EXP. SERVERS & BARTENDERS 10386 W. Halls River Rd. Seagrass Pub & Grill EXPERIENCED SERVER, Banquet exp. preferred Benefits available. Apply in person IGCC (352) 726-2583 FULL & PART TIME BARTENDER COCKTAIL/SERVER Call after 1pm Colonel Frogs Lounge 628-1076 NOW HIRING FOR THE RIVERSIDE CRAB HOUSE & YARDARM LOUNGE All positions available Apply in person 5297 S. Cherokee Way, Homosassa. Syndicated Content Available from Comiercial News roviders" U o Advertise Here for less than you think!!! Call Today! 563-5966 F -, S NOW HIRING Scampi's Restaurant Crystal River 352-302-4098, 634-4537 SERVERS Apply at Fisherman's Restaurant 12311 E Gulf to Lake Hwy. Inverness. (352) 637-5888 BLACK DIAMOND RANCH is accepting applications for the following part-time positions: 4 BUSSERS 4 EXPERIENCED FOOD-SERVERS 4 EXPERIENCED BARTENDERS Apply in person at Black Diamond Human Resources Office 275 S. Rock Crusher Rd. Crystal River, FL No phone calls please $ GREAT $ OPPORTUNITY Highly Motivated Well Spoken Phone Sales We Train 9-5, 5 days Training Salary Commissions Call Sylvia 560-0056 $$$ SELL AVON $$$ FREE gift. Earn up to 50% Your own hrs, be your own boss. Call Jackie I/S/R 1-866-405-AVON Start The Year With A New Career... Real Estate Classes! Starting Jan.10, 2005 Call 352-683-6901 Alliance School of Real Estate Cooke School of Real Estate Inverness Location Flexible Times Call ERA American Realty for info 726-5855 John or Sandra CARPET & TILE SALES Exp. Prof. needed for busy retail store. Apply Cash Carpet & Tile 776 N. Enterprise Pt Lecanto(352) 746-7830 FOUNTAINS MEMORIAL PARK CEMETERY in Homosassa needs Services Counselor to meet with at need families & assist with arrangements. Good benefits. Call Donna 10 am -2pm (352) 628-2555 EOE DFWPU MARKETERS Earn income being a Liberty Tax Service marketer. America's tax service needs your help. (352) 344-8042 NATURE COAST BROADCASTING Is looking for Fun energetic people for their Sales & Marketing Team. Experienced Only, Fax Resume to 352-564-8750 Is ooing for HT URSDAYJANUARY 6 2005 TO m ;L; CLASSIFIED REAL ESTATE CLASSES Now Enrolliing2/15/05 Sales Lic. Class $249. RON NEITZ-BS,MBA BROKER/INSTRUCTOR CITRUS REAL ESTATE SCHOOL, INC. (352)795-0060. AUTO TECHNICIAN With Alignment & AC knowledge. Apply in person at Phillips Tire, 1000 E Hwy 44, Crystal River. CONCRETE PUMPING Must have drivers lic., Exp. a plus not neces- sary. (352) 726-0503 Construction Superintendent For Custom Builder. Experience only Fax Resume to: 352-382-4660 ELECTRONIC TECHNICIAN Must have excellent communication skills and electrical repair experience. Circuit board and mechani- cal trouble shooting, Apply within. RAINBOW CRANE 1181 W. Gulf to Lake Hwy., Lecanto EXP AC INSTALLER & ELECTRICAL INSTALLER Paid by piece work. EXP REFRIG TECH & ELEC SERV TECH Action Electric & Air (352) 795-7405 EXPERIENCED PLUMBER'S HELPER Driver's license req'd. (352) 726-5385 FRAMERS Steady work, Top pay in Marion, Sumter and Lake Counties. Health Insurance package, 401K, paid holidays and vacation time. 3 years experience. Tools and transportation required. Call Scofftt for interview 352-266-6756 After 5pm 352-341-0907 FRAMERS & LABORERS NEEDED (352) 726-0527 HEAVY EQUIPMENT OPERATOR TRAINING & EMPLOYMENT t vt _e Dump Trucks Graders, Scrapers, Excavators Next Class Jan. 3rd. National Certification Fnandel Astance Job e pace- ment in Your Area 800-383-7364 Associated Training Services 5177 Homosassa Trail Lecanto, FL 34461 8C TIHUiA', TAAv ( 2005 FRAMERS Local-Steady 352-302-3362 HELP WANTED Experienced. Neat & Tidy Lawn Service (352) 344-5134 IMMEDIATE OPENING SERVICE ELECTRICIAN For qualified electri- cian. Min. 2 yrs. exp. residential & light Industrial, service/ trouble shooting Good driving record, paid Sick, Holiday and Vacation. Apply in person S&S ELECTRIC 2692 W. Dunnellon Rd. CR-(488) Dunnellon EOE/DFWP (352) 746-6825 INSTALLERS Carpet & Vinyl. Work year round. Must have 2 yrs exp. Call: 877-577-1277 press 5 LABORER NEEDED For pool construction company. No exp. necessary. Valid FL. Drivers. Lic. w/ clean record, apply 593 E. Gulf to Lake Hwy. Lecanto 527-7946 LCT WANTS YOUll $$$$$$$$$$$$$$$$$$ NEW HIRE BONUS $500.00 Immediate processing for OTR drivers, solos or teams, CDLA/Haz. required Great benefits 99-04 equipment Call Now 800-362-0159 24 hours MECHANIC Exp. heavy duty & diesel repair for arge truck service & parts center. Full benefits, pay based on exp. Apply In person Raney's Truck Center PLASTERERS AND LABORERS Needed 352-621-1283 302-0743 Plasterers, Apprentices & Tenders Steady work, call John 302-1240 PROFESSIONAL WRECKER OPERATORS 24hr Towing Company seeks Drivers. Hiah Volume. Lona Hours. Good Pay. Clean License & dependable apply, 352-795-1002 ROOF SHEETERS Needed in Dunnellon area. Please call: (352) 266-6940 ROOFERS Exp. Must have tools & clean DL. 352-754-8880 WANTED AUTOMOTIVE TECHNICIAN Experienced in the accurate diagnosis & repair of General Motors vehicles. Excellent pay, opportunities & benefits available for the individual who desires the challenge of repairing today's technologically advanced vehicles. ASE certifications required & continu- ing education furnish- ed In this ever chang- ing field. Valid FL Driv- er's License required as well as reliable transporta- tion & own tools. You may apply in person at: Scoggins Chevy, Olds, Buick, Inc. in Chiefland, FL., or call Vernon Luckey Service Manager (352) 493-4263, ext. 24. . You may also e-mail your resume to: vernonl@bellsouth. net WANTED SOLID SURFACE COUNTER TOP FABRICATORS 40+ hrs. 18 yrs or older. Able to handle heavy lifting. Must be reliable. SValid Drivers license preferable. Apply DCI Countertops 6843 N. Citrus Ave. (Rt. 495) Crystal River, FL. (Shamrock Industrial Park) WELDER/ FITrER For Machine Building position. Min. 5 years experience In steel fabricating. Apply 6260 S Tex Pt, Homos. (352) 621-1255. Xcingular Clngular Wireless Authorized Agent Cingular Wireless Authorized Agent Stores in Citrus County & Marion County looking to fill Full & Part Time positions. o Sales Associate O Shift Supervisor o Store Manager O IT Support Specialist 0 Purchasing Specialist O Inventory Specialist Positions require proficiency In Microsoft Office. Please Call Shirley (352)726-2209 Ext. 228 or send resume online to cwrs@spectrumglobal networks.com -. GeUeral Payless Furniture -I 4 4 -A cross fro m Tire K in d am Brays Pest Control IS NOW HIRING SALES PEOPLE NEEDED Must have sales exp. SERVICE TECHS Also needed. Will train Apply In person 3447 E. Gulf to Lake Hwy, Inverness dfwp DELI CLERK Experience only NEAT & CLEAN Ferrara's Dell Beverly Hills: 746-3354 Call between 2-4 pm. DRIVER CLASS A CDL Roof Truss plant, full time, local only. Apply: 2591W .Hwy. 488, Dunnellon 352-465-0968 MERCANTILE BANK Elevate your career Mercantile Bank has opportunities for exceptional sales and service oriented professionals In the following areas: Elite Travel Team Member Position #0608902 Part-time Teller Inverness Position #0651001ile.com EEO Employer M/F/V/D FIBERGLASS DUCT SHOP Prod. wrkrs. $7/hr. Apply 2541 W Dunnellon Rd FRONT DESK CLERK Apply at Homosassa Riverside Resort (352) 628-2474 HUNGRY HOWIE'S DRIVERS NEEDED IMMEDIATELY In Beverly Hills, Crystal River and Homosassa locations. Earn up to $12 per hr w/tips. FT/PTavallable. Must have valid driver's I License and verification of Insurance. Apply In person at either location. IN SEARCH OF NEWSPAPER CARRIERS INVERNESS CRYSTAL RIVER FLORAL CITY HERNANDO SR-204 Citrus County's fastest growing newspaper Is looking for you! Fill out a carrier information form at the Chronicle office In Crystal River or Inverness Or call 563-3282 JOBS GALOREIII EMPLOYMENT.NET JOE'S CARPETS OFFICE HELP, SALES INSTALLERS Both locations Apply In Crystal River LINE COOK Please Apply In person at: CRACKERS BAR & GRILL Trades cm /Skills DRIVING CAREER! Increase In pay pack- age. Contractors & Company needed. Flatbed, refrigerated, tanker. Over-the-road. Some regional. Com- mercial driver's license training. (800) 771-6318. FCAN ADVERTISING NOTICE: This newspaper does not knowlingly accept ads that are not bonafide employment offerings. Please use caution when responding to employment ads. Antique & Collectible Show Sat. Jan.29 9am-4pm Citrus Springs Community Center $50. Booth Space. Deadline for entry Monday Jan. 24th. Sponsored by The VWr, weekly Newspaper for the Central Ridge Region. For Information contact Babara Hartley at (352)746-4292 3603 N. Lecanto Hwy. Winn Dixie Beverly Hills. and collectibles Welcome. OBREROS DE ALMACEN Se necesita ayuda en almacen para desarmar y re-empacar components de computadoras, 352-746-4359 or dear mensage. Vicente P/T Church Custodian 8 hrs/wk Salary neg. Call (352)793-3221 POOL SERVICE TECHNICIAN Exp. requested but not necessary. Will train, senior citizens welcome. Apply In person. Mon-Fri 8am-3pm1233 E. Norvell Bryant Hwy. REAL ESTATE CLASSES Now Enrolling 2/15/05 Sales LIc. Class $249. RON NEITZ-BS,MBA BROKER/INSTRUCTOR CITRUS REAL ESTATE SCHOOL, INC. (352)795-0060. REAL ESTATE CLASSES Now Enrolling 2/15/05 Sales Uc. Class $249. RON NEITZ-BS,MBA BROKER/INSTRUCTOR CITRUS REAL ESTATE SCHOOL, INC. (352)795-0060. RENTAL PROP. ASST. PT possible FT, Exp. preferred. Fax Resume 352-795-6133 ROOF TRUSS PLANT Now hiring truss builders. Full time. Will train. Apply: 2591W .Hwy. 488, Dunnellon 352-465-0968 ROOFERS/ SHINGLERS Exp Only. Pald Vacations, Benefits. 352-347-8530 SEPTIC SERVICE LABORERS NEEDED Full Time position for Septic Installations. Class A CDL license helpful. Apply within Monday- Friday between the hours of 7:30 AM & 10:00AM Only I TAX PREPARER Learn to prepare taxes in free week long AM or PM classes starting Jan.3. Employment opportulties available. (352) 344-8042 TECHNICIAN WANTED Must be ASE Certified in Heavy Duty trucks and repairs. Working In a high quality shop. If interested apply in person within 75 Truck Service Ask for Jamle 352-748-7575 Wildwood TOWER HAND Bldg Communication Towers. Travel, Good Pay & Benefits. OT, DFWP. Valid Driver's License. Steady Work. Will Train 352-694-1416 Mon-Frl WE BUY HOUSES Ca$h........Fast I 352-637-2973 P/T PROGRAM ASSISTANTS Needed for After School Programs In Homosassa. From 2:00PM 7:00PM Monday Thru Friday, Applicants Should Apply in Person by Appointment. Call Homosassa 795-8624, between 11am 7pm ADVANCE YOUR CASH LOANS UP TO $1,000. No credit check Cash In your checking account within 24 hrs. Employment req. Go to today.com or call (866) 756-0600 Unes (866) 6285 FCAN FREE 4-ROOM DIRECT SYSTEM Includes standard Installatino 2 months free HBO & Cinemaxi Access to over 225 channels LUmited time offer. S&H Restrictions Apply. (866) 500-4056 FCAN HEAVY EQUIPMENT OPERATOR CERTIFIED Training at Central Florida Community College Campus. Job Placement Assistance, (866) 933-1575. Associated training services, 5177 Homosassa Trail, Lecanto, FL 34461. FCAN INDIANA COMPANY HAS NEW CONTRACTS in Georgia & Florida & is seeking drivers.to deliver motor homes, busses & trucks. You will be most successful If you possess a CDL B & have a small tow vehl- cle. Backhauls avall- able. Check us out at qualltydriveaway.com or contact recruiting at (800) 695-9743 FCAN REAL ESTATE CLASSES Now Enrolling 2/15/05 Sales Lic. Class $249. RON NEITZ BROKER/INSTRUCTOR CITRUS REAL ESTATE SCHOOL, INC. (352)795-0060. CONCESSION STAND mobile, self contained, stove, refrigerator, $2,000. 302-2445 #1 CASH COW 90 vending machine Hd. You approve locations, $9,995 (800) 836-3464 #802428 FCAN ALL CASH CANDY ROUTE Do you earn $800 a day? 30 machines, free candy, All for $9,995. (800) 814-6323. B02000033 CALL US: We will not be undersold FCAN PAD PRINTER FOR SALE Print promotional prod- ucts. Great side bus. or add-on. New- $6495 asking $3495. (352) 746-9890 COFFEE & ICE CREAM SHOP 22,900. Crystal River (352) 795-0149 DJ KARAOKE BUS. All equip, CD's, trailer, over $17,000 Invested. $7500/obo. 352-746-3228 $$$ GET CASH NOW We buy structured settlements and Insurance annuities. Call Structured Asset Funding NOWII (877) 966-8669 $$$ FCAN AS SEEN ON TV $ All your cash now $ ProgramFL Company offers best cash now options. Have money due from settlements, annuities, or lotteries? Call (800) 774-3113 FCAN "LIVE AUCTIONS" For Upcoming Auctions 1-800-542-3877 ANTIQUES FOR SALE Beautiful, well pre- served furniture, Large English dining table w/6 chairs, $800. Very special buffet, $900. Grandfather clock, $800. European desk, $950. Special one of a kind Austrian 5-pc bedroom set, must see. More. Please- serious buyers only. (352) 382-0278 WANTED ANTIQUE & COLLECTIBLE DEALERS ANTIQUES WANTED Glassware, quilts, most anything old, Furn. We Also liquidate Estates. Ask for Janet or Paula 352-344-8731/860-0888 BARBER CHAIR $50 (352) 257-4401 Lots Antiques & Collectibles Large stamp collection. Very old pens & lead pencils collection. Many old books. Many more Items. For appointment (352) 746-6849 WILL PAY CASH FOR antiques, pottery, old furniture, estates, (352) 465-1544, Joe SPA, 5 PERSON, Never used. Waranty. Retd $4300. Sacrifice $1550. (352) 372-5287 SPA, HOTTUB, 5-PERSON 24 Jets, redwood cabinet. Warranty, must move, $1495. 352-286-9662 SPA/HOT TUB Brand Newl 7ft. therapy spa, 20 lets 5 HP. paid 2 Room Heating and Cooling Window Units 12,000 BTU's, good cond, $400. for both (352) 795-2317 21 CU.FT. UPRIGHT FRIGIDAIRE high efficiency freezer, exc. cond, 29x32x70, $200 UTILITY TRAILER, $350 (352) 637-3634 A/C & HEAT PUMP SYSTEMS. New in box 5 & 10 year Factory Warranties at Wholesale Prices -* 2 Ton $787.00 -3 Ton $887.00 4 Ton $994.00 Install kits available or professional Installation also avail. Free Delivery -ALSO POOL HEAT PUMPS AVAILABLE Uc.#CAC 057914 Call 302-4395 APPLIANCE CENTER Used Refrigerators, Stoves, Washers, Dryers. NEW AND USED PARTS Visa, M/C., A/E. Checks 6546 Hwy.44W, Crystal River. 352-795-8882 CERAMIC TOP RANGE $250. 20 CU.FT. FROST FREE FREEZER $250 (352) 249-3259 CLOTHES DRYER $60 (352) 628-4321 DRYER, KENMORE large capacity, white with stainless steel drum, 3 yrs old. Exc. cond. $175 (352) 465-2459 ELEC. STOVE 4 burner, white, good cond., $70 or best offer (352) 726-3856 Electric Range, Hot Point, good Cond. $100 - TV 27", Sony, $75. (352) 637-0721 FREEZER UPRIGHT 21 Cu. Ft. Frigidaire. Power freezer, defrost, temp, alarm. Exc. cond. 32"Wx28/2"Dx70"H. $300 (352) 382-1735 FRIGIDAIRE, 17 cu.ft. Refrigerator, runs good $50. Like new Whirlpool range, still In box, $250 (352) 637-6841 KENMORE REFRIGERATOR WHIRLPOOL RANGE Good condition, $150 each. (352) 527-4595 Kitchen Aid Mixer, w/ stand, splash cover, dough mixer& beaters, brand new cond. $75. Bread machine, toast master $25. 352 382-4324, 352-697-3354 MAGIC CHEF Self cleaning electric range w/delayed baking timer & clock. Exc. cond. $175. (352) 344-4183 WASHING MACHINE $50 GE DISHWASHER $75 Both in exc. cond. (352) 465-7929 WHIRLPOOL side by side refrigerator, $150 STAINLESS STEEL MICROWAVE & toaster oven, $40 (352) 341-3941 Whirlpool Stove 4 burners & oven (avocado green) Good cond. $50/obo (352) 746-0815 eF----1 S2 DAY AUCTION ANTIQUE STORE LIQUIDATION I FRI. JAN. 7 Preview: 4PM Auction: 5PM SAT. JAN. S Preview: 10AM Auction: 1PM 4000 S. Fla. Ave. Hwy. 41-S, Inverness Retirement Liquidation after 23 yrs. Olan & Mary Hall, 1000's of pcs. SAntique French clocks, vintage oill & elec. lighting. Sterling, pottery, glassware, turn., etc. Web: www. dudleysauction.com DUDLEY'S AUCTION S (352) 637-9588 AB1667 AU2246 12% Buyers Premium 2% disc. cash/check 2 SEALED BID ACREAGE AUCTIONS- Bids due: Jan. 10, 2 pm, Abbeville, AL 10% B.P. (800) 942-6475 Tranzon Hagen AL Lic #1194 FCAN NEED ASSISTANCE? Antiques, furniture, complete households We are CERTIFIED ESTATE SPECIALIST Call Dudleys Auction (352) 637-9588 www. dudleysauction.com AB 1667 AU2246 JFIEDS HONDA EB 3000 GENERATOR, never used, ($1,400 new) asking $1,000 (352) 212-0848 SOLO 643 CHAIN SAW, $100. CRAFTSMAN Chalnsaw, with case, $60 Both very clean, hardly used, (352) 628-7688 Blonde Entertainment Ctr. Holds 36" TV, 32" TV w/PP, CD Player. $500. 25" Console TV $50. (352) 795-7731 ENTERTAINMENT CENTER Lt. Oak w/ lighted bridge & glass doors. 36" Toshiba PIP TV, AIWA DVD Player, Pioneer Dolby 5.1 Digital Receiver, Powered Subwoofer & all speakers, Kenwood Tape Deck $750 takes all (352) 382-4324 Hitachi 53" Ultrascan HD Television, 3yrs old. Excellent condition. $700 firm 352-465-6899 OAK ENTERTAINMENT UNIT, 45"Hx52"W, $50. & ZENITH 27" TV, $50. (352) 637-1567 TV 25" GE Console, cable ready, beautiful wood cabinet, $75. After 5pm & weekends (352) 382-0557 TV, RCA, 65" HDTV, $1,500. (352) 795-2825 FIBERGLASS SHOWER 34'/2Wx34/V2Dx75H Fixture opening on left, $75. Multiple electrical supplies- breakers, receptacles, etc. $100 for all will sell separately (352) 697-2782 METAL ROOFING SAVE $$$ Buy Direct from manufacturer. 20 colors In stock with all accessories. Quick turn around Delivery available. Toll free - (888) 393-0335 FCAN DIESTLER COMPUTERS Internet service, New & Used systems, parts & upgrades. Visa/ MCard 637-5469 LEXMARK X73 All In One printer, USB cord, new cartridges, 2 yrs. old, $25. (352) 564-9665 6-PC. PVC PATIO SET .2 tables, one with glass top, 4 chairs with new cushions, $150 or best offer. (352) 465-2188 RECLINER.CHAIR $25 RCA TV 21" Color Console $75 (352) 637-5103 2 MATCHING CHAIRS, La-Z-Boy recliner & upholstered swivel chair, blue print fabric, $150 (352) 794-0414 2 TWIN BEDS, w/mattress, springs, frames, headboards, $45 ea. 2 wicker bar- stools, $25 ea. (352) 637-1916 4 PC. QUEEN BDRM SET, Ivory color w/darker tops & accents, mat- tress set only 3 yrs. old, $375. (352) 341-4520 6 Pc. Queen Size Master Bedroom set. $600 17" TV w/DVD Combo like new, $100. (352) 634-1869 3-PC. LIVING ROOM SET, like new, $550. 'RATTAN 6-PC. KITCHEN SET, w/3 Rattan bar stools, $350. (352) 344-3548 Twin Size Sets............$128 Full Size Sets..............$178 I Queen Size Sets........$2281 SKing Size Sets............$298' New In Factory Cartons I Free Delivery 1PAYLESS FURNITURE i Hwy, 44-Crystal River I SAcross from Tire Kingdom 795-9855 Zl L - - ALUMINUM FOLDING TABLE 3'X6' $25 obo CARD TABLE w/ 4 chairs $25 obo (352) 795-0049 BED queen size $85 22 Assorted BARBIE DOLLS $10 for all. (352) 637-5103 Bed Room Set, king sz. Thomasville, solid oak $1000. (352)341-0488 Bedroom Set, Whicker, w/ complete twin beds, dresser, mirror & night stand. $350. (352) 527-1933 $ GREAT DEALS $ Pillow Too Orthoaedic Firm. 5 vr warranty Full Size $105. Queen $145. 5-PC. LIGHT COLORED bedroom set, twin size, $150 (352) 560-0338 COMPUTER DESK & CHAIR $150 OAK DINETTE SET w/ 6 CHAIRS $400 All Llike Newl 352-257-4401 Couch & Love Seat, Floral pattern, green & pink, $200. (352) 341-3812 COUCH, LOVESEAT, CHAIR with matching tables, $350, QUEEN BRM SET, triple dresser, chest of drawers, $250. (352) 341-1734 Dark Blue 5 pc. Sectional, exc. cond. $400; Girl's Bed w/bullt In drawers & dresser, very gd. cond. $300 (352) 634-1869 DINING ROOM SET dark wood table w/ 5 chairs & hutch $200 (352) 344-1740 DINING ROOM SET Pine. Hutch, 6'8" high x 5' wide, 48" round table, 2" thick solid pine. Extends to 6' oval. 6 captains chairs. Asking $600. Excellent condition. 352-212-1002 Dinning Set, solid oak, 43 round, 68 oval, pedestal table 6 chairs $350 (352) 489-4405 DRESSER & MIRROR beautiful, large $200 2 pc. CHINA CABINET Large $200 (352) 726-2371 ENTERTAINMENT CENTER $35. KITCHEN TABLE, 2 chairs, $35 (352) 726-6061 Full Size Sofa Bedc Cream/Pastel Stripe, exc. cond. $250 (352) 382-2396 KITCHEN TABLE, glass top, 4 chairs, $50 cash, KITCHEN TABLE with glass top, $50 cash (352) 344-2752 LA-Z-BOY CHAIR w/ottoman. LIKE NEWI $300 (352) 746-6998 La-Z-Boy Sleeper $350. La-Z-Boy. recliner $250. Oak Kitchen table/4chalrs $200. Cof- fee table/2 end tables $-100; 6 pc. Lt. Pine bed- room set $400. Sm. desk 435; Cabinet Singer sewing machine $50. 746-6877 LIVING ROOM SET Sofa, loveseat, & chair. Cream & grey striped. Exc. cond. $550 After 6 pm call (352) 746-9212 LOVESEAT RECLINER Blue velour, clean, good condition, $200 or best offer. (352) 795-3587 between 9am & 7pm. Matching Living Room Chairs, custom from Southern Traditions. $1 50/both/obo (352) 382-1842 Mattress/Box Spring, Full size, $65. Plate Glass wall mirror, sz. 38"Hx47"W. $35. (352) 795-5410 MOVED DOESN'T FIT Chaise Lounge light yellow 2 vrs. old $300 (352) 628-4911 Iv. msg. PECAN WOOD ROCKER good condition, $25. (352) 621-0802 Preowned Mattress Sets from Twin $30; Full $40 Qn $50; Kg $75.JNew waterbed$299628-0808 QUEEN SIZE MATTRESS & boxspring, 2 pillows, sheets, & comforter, $150 cash (352) 344-2752 Queen Size Sofa Sleeper, plaid, Great condition. $200/obo (352) 563-2713 QUEENSIZE BED with headboard, bed pad, sheets, comforter, bedspread & matching curtains, $300 (352) 860-0124 ROUND COCKTAIL TABLE pedestal, oak wood, "marble top, excellent condition, $65. 352-628-2119 SOFA, cream color w/plant design, makes Into queen bed, $100; 5 PC. Round wrought Iron table & chairs, $50. (352) 341-4520 SOFA, LOVESEAT & SWIVEL ROCKER $400 OR BEST OFFER (352) 527-0397 SOFABED Queen brown faux Suede. Like newl Bought $800 Sell $400 (352) 746-1677 SOLD THE BUSINESSIIII Everything must go. Jan. 3, thru. 10, 2005 2423 Rockcrusher Rd. 621-5550 Solid Oak Fumrniture 2 upholstered love seats, and matching swivel rocker, good cond. $550. (352) 382-7139 TAILOR MADE valances, mauve & light teal green, must see Paid $800. 5 for $75. (352) 637-5352 FREE, I will hall away RIDING Lawn Mower & Tractors. 352-726-7362 PUSH MOWERS, full serviced & ready to mow. $35-$85. Buy/sell/ trade. (352) 726-5076 RIDER MOWERS I in/ill hrsn i\ them rr niii Leatner JacKer sz. small, $50. Fur Coat, sz. small, $65. Both In new condition. (352) 795-5410 DREAM MAKER SPAS Starting at $1,195. WEST WOOD POOL TABLES Complete Set $1,695. Set up & Delivery Available. 352-597-3112 15 Pc. Barb Arms for chain link fence. 15" long for 1 5/8 pipe $15. (352) 344-4984" TABLE SAW, Craftsman w/stand, $85. Golf clubs, bag, cart, new, Knight VIrage, oversized $100. (352) 382-0100 Antique Triple Mirror Vanity, late 1800's, needs refurbishing, $175.Sliding Glass Door, 6 ft, white, w/ grades In- side double pain glass, $195.(352) 795-1520 BEDROOM SET lighted bedwall unit w/ chest, & Iyr. old queen pillowtop mattress Like newi $700 (352) 344-1887 Bike rack for car trunk for 2 bikes $8. 344-4984 Blackshear's White Aluminum Sliding Window R.O. 35 3/8" x 52 1/8" w/ screen, new In box. $75. Call (352) 795-0646 FOUND Black & white male dog on Tram Rd., Hernando (352) 697-1692 or 563-5137 HERNANDO Contents of house,1991 Dodge Dynasty, boat, trailer & stainless steel tower, plumbing, tools & misc. items. Jan. 7 & 8 N. Harding Terrace Golden Village HOMOSASSA Fri & Sat 9am-4pm Liauldatina After 24 yrs. Collectibles, Antiques, Crafts & Tools, Dining Room Hutch & More. Some Junk. Off Hwy 19 to Chassahowitzka, right on Riviera, right on Debra Lane. HOMOSASSA Moving. Thurs, Fri, Sat. 1852 Carriage Terr. HOMOSASSA STOREWIDE SALE Through January 29th, 15%, 20% and 25% off. Paul's Furniture 628-2306 INGLIS Yard & porch sale. Jan. 6th, 7th & 8th, 10-4. Lots & lots of 25-cent Items. Look for signs Inglewood Estates. INVERNESS 3 Family Sale Sat. 8am-1lpm 5 N. Braemar Dr. Gospel Island Area PINE RIDGE Frl. Sat. Jan. 7&8 10a-3p 4583 N Allamandra Dr. SUGARMILL WOODS Estate Sale Fri. Sat. 9-3 Household items, crafts, linens, DR set, Flex-steel 3pc. LR sofa, Riding Mower, too much to list. 32 Mayflower Ct. S (Off Corkwood) The ads running in Garage / Yard Sale I | category are sorted by City or Town to assist the reader in I your quest for the Perfect Sale _ BUBBLE WRAP Perfect for moving & shipping. 16ft pcs., $1 a roll (352) 726-0072 BURN BARRELS $8 Each 860-2545 CAMERA SPEED GRAPHIC 21/ X 31/4 miniature w/ adapter . for 120 roll film & carry case. $400 (352) 637-1567 CARPET FACTORYDirect Restrecth Clean * Repair Vinyl Tile * Wood (352) 341-0909 (352) 637-2411 CARPET REMNANTS New, high quality 1 at $45- 1 at $100 (352) 795-5410 Chrome Bakers Rack good cond. $35. 7 52" White Shades, w/drapes & hardware, exc. cond. $50. (352) 746-5514 DIGITAL AUDIO CD RECORDER. Convert LP to CD. By TDK, Brand new $250, will sell for $150. (352) 637-1895 Digital Video/Still Camera, JVC, GR-DVL815U many accessories Included, like new $325 obo, Low Impact Treadmill, Precor M9.17. full digital display, excel, cond. $650. obo (352) 422-4092 ELECTRIC FIREPLACE w/ heater. Free stand- ing wood trim & glass doors. Looks like real flames. Use any room. New $1,700 Sell $1000 (352)465-2459 Entertainment Center $50. Corner Computer Desk $50. New condition (352) 637-1894 Entertainment Center, 6' x 5' x 2' will accept 32" tel, pickled oak finish $350. like new Miami Sun 3 Wheel Bike like new, suncoast bikes, red, $250. (352) 344-8869 EXPERIMENTAL AIR- CRAFT PARTS, tall feath- ers, struts, hardware, mags, Instruments and more. (352) 344-2438 FENCE, CHICKEN WIRE, 2" netting, 4'x150', new, $30. MICROWAVE CART $10 (352)341-1296 GE SELF CLEANING STOVE, electric, great condition, $60. CD PLAYER, Denon, great cond., household, $30 (352) 726-6075 HOGS, Corn fed from wild stock, all sizes, great fro BBQ's, $15-$40. (352) 726-7871 KENMORE WASHER, like new, bikes, Power Wheels, TV, microwave, lots of flea market items, all for $100. (352) 637-9521 LIFTCHAIR -RECLINER, Sealy.blue fabric, mas- sage & heat. Good cond. $200 (352) 489-7475 LOVESEAT, $25 DRYER, $65 Roll-a-way bed, $15 (352) 344-2752 MATCHING SOFA & CHAIR, recllners, like new, $295, $250 or both for $500. MAYTAG RANGE, elec. $100 (352) 465-7774 NEED RELIEF? Would you like me to give you money for your equity and pay off your mortgage? Also buying mobiles, houses & land contracts. Call Fred Farnsworth (352) 726-9369. Some address & phone number last 31 years OUTSIDE STEPS, metal frames, 38"Hx34W $25. also 32"H, 28"W, $30. Steps w/platform, $35. (352) 697-2782 SERTA KINGSIZE MATTRESS & BOXSPRINGS used 6 months, $200 (352) 382-0032 SILK SCREENING SHIRTS Wholesale < 40%. 500 + positive screen shirts & caps. All colors, styles, & sizes. Owner retired. (352) 489-5210 SPAI Overstocked! New 7 person spa, loaded! Includes cover, delivery & warranty. $2,999. Was $5,999. (888) 397-3529 FCAN SWING SET, 2 seat, durable, with green canopy, still In box. $60 (352) 726-6885 CITRUS COUNTY (FL) CHRONICmL "Copyrighted Material cj'. Aille from Commercial News Providers Advertise Here for less than you think!!! Call Today! 563-5966 f~enra cS hnyuthi Gnerl! * King $195. Nagsa Vsco Foam MattressSets * Full $395. * Queen $650. * King $850. Delivery Available, (352) 398-7202 BEDS BEDS BEDS Beautiful fact closeouts, Nat. Advertised Brands 50% off Local Sale Prtces,Twin $78 Double $98-Queen $139 King $199. (352)795-6006 BROYHILL QUEEN SLEEPER, $100. NICE EASY CHAIR, $50 (352) 341-3941 Burgundy Leather Barcalounger Sofa w/ reclining seats and matching love seat. 2 yrs old. $1400 (352) 344-5771 CHINA BUFFET & HUTCH Maple finish, older style $300 OBO gatorsmk/ltemsforsale. html (352) 447-3762 Table Saw, Crafts,mam, $95, Dinette Set, Oak w/ 4 chairs, good cond, $195. (352) 795-1520 TV Sony 25", 13",VCR, Stereo, coffee tables + misc. $75 for all (352) 746-4488 Wanted Paddle Boat good condition (352) 344-2382 WE MOVE SHEDS 564-0000 White Wicker Swing,' $100. Weight Bench $50. (352) 795-2825 Heavy Duty Walkeri with wheels, seat, - hand brakes, never used. $150. (352) 628-7393 Power Chair w/ Joystick Control, rechargeable $1500/obo (352) 795-6586 CRATE 6 channel mixer w/500 watt speaker cabs w/stands, $600. Fender acoustic/elec guitar, blue gloss finish w/hard shell case, $350. All In new condition. 352-422-2187 GUITAR Taylor Big Baby 307GB . 1 yr. old. Inc. soft bag $425 (352) 382-1587 LESSONS: Piano, Guitar, etc. Crystal River Music, 2520 N. Turkey Oak Dr- (352) 563-2234 Martin Guitar D16RGT, $950. (352) 628-0504 S&R MUSIC Lessons, drums, guitar, keyboard.352-563-2110 SPINET PIANO with bench, $595. Tuning & moving Included (352) 563-1173 Dual Action Mag Bike,' $25. Power Rider $25. (352) 637-1895 PROFORM FOLDING TREADMILL in good cond. $225/OBO (352) 794-4131 TREADMILL good cond. First $100. takes. For Info. (352) 382-2848 VITAMASTER Slender Cycle, tension control, $25. (352) 564-9440 CALLAWAY BIG BERTHA IRONS, 3-PW, nice, $250 obo (352) 344-1456 CROSSMAN AIR RIFLE. model 397, 177 caliber, with Bushnell 4x scope, like new, $135. (352) 637-4606 GOLF CART 2001, EZGO Windshield, Golf club cover. Special $2,100. (352) 795-6364 KING COBRA DRIVER 2004 Model 440sz Regular Flex. 9 degree.' Right hand. Like NEWI! $165 (352) 746-5966 Set of Golf Clubs & Bag 4 woods. 8 irons w/ - covers & putter, $300. (352) 746-7868 2004 PACE CARGO TRAILER W/SWAYBAR - 7x14, brand new, only used twice. Paid $4200> asking $3700.- (352) 302-0953 4X8 PACE, new, enclosed. $1200 (352) 637-1916 2 CHILD CARRIERS $10 each. 1 child stroller, $10 (352) 637-1916 BASSINET, Noah's Ark Theme, rocks, $35. Also two Activity Centers, $20 ea. (352) 637-5352 peacn, pink a yellow one gal. pots, $10 (352) 637-2147 CRS. RVR/ HOMOSA The Path Shelter Store Open Tues. Sat. 9-5. Nottingham Sq 1239 S HWY. 19. 352-794-0001 CRYSTAL RIVER Fri. & Sot. Jan 7 & 8 Estate Sale. Furniture, A to Z. Corner of 6th Ave & 10th St. In big garage. FLORAL CITY 8415 S. Great Oaks Dr. Jan 7,8,9 8 AM 7 Over 30' new store shelving, lawn equip. Lots of mics. Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2010 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Last updated October 10, 2010 - - mvs | http://ufdc.ufl.edu/UF00028315/01848 | CC-MAIN-2018-51 | refinedweb | 53,559 | 79.56 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
Yet it seems to me that the situation right now is that LtU has readers with very different backgrounds, among them many readers who haven't studied PL formally. Others come from academia, and study PL theory for a living.
Since we have such a lively community it occured to me to start a thread for advice on where to begin aimed at those who haven't studied PL theory, yet want to follow the papers and books we discuss.
So the question, mostly directed at old timers, is to which resources would you send a friend asking for advice on learning about the theoretical study of programming languages?
P.S
The early LtU archives may be helpful, since I used LtU to organize and collect the papers I read when I began my studies in the field.
(Thanks to Matt Hellige for pointing me more than a year ago to that direction!)
After that, I got interested in basic category theory (mostly because of Frank) - see this or this.
In general, googling for "Wadler", "Danvy", or "Filinski" always provided me with interesting and valuable reading. (This is not to say there are no other great authors)
On a practical side, I would recommend to at least install and go through the tutorial with some ML, Scheme, Haskell, and Erlang. I was impressed how I was able to express in several lines of Jocaml code what takes many classes with intricate synchronization and type casting in Java. You never forget that feeling of power and simplicity, but on the other side you will be never happy with Java again :-(
I should probably be ashamed to admit that it was Paul Graham's promotion of Lisp as the mind-tool of the programming übermensch that made me want to give it a try. I settled on Scheme because I had GNU Guile already up and running on my Linux box at home, although I suppose Emacs Lisp would have done just as well.
I started out by reading through The Little Schemer and The Seasoned Schemer, and would recommend them to anyone at the beginner level who doesn't tire quickly of pizza. Meanwhile a CS-graduate colleague of mine was amusing himself by taking my snippets of Scheme code and rewriting them for me in Haskell. Later on he lent me his copy of Bird's Introduction to Functional Programming using Haskell, which helped move things along quite a lot. It is always useful to know people who know just a bit more than you.
Non-programming books that have helped me a great deal are Hodges's Logic and Helmös's Naive Set Theory. There may be better books on both topics, but those are the ones I read.
The venerable SICP is available online, of course, and it's still possible to hunt down the draft pdf of CTM (although I really would recommend buying it).
I found Hutton and Meijer's paper on Monadic Parser Combinators brought a lot of functional programming topics into perspective for me. Hutton's Tutorial on the universality and expressiveness of fold is also a gem. Proceed from there to Meijer, Fokkinger and Paterson's Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire.
I think I've got most of the basics of Scheme down, can any recommend a book that covers more than an overview of some of the more advanced topics like call-cc, macros, the Y combinator, etc.?
...perhaps with the guide of SICP. That will expose enough detail of the language model to make both call/cc and macros clear. As for the Y combinator, I don't have any recommendations offhand... probably time to start digging in the papers indexed on readscheme.org.
I just finished my first lisp interpreter (in perl). I found Paul Graham's Roots of Lisp to be a simple and straight forward guide. But will implementing call/cc and macros in an interpreter really give a person a sense of how to put them to good use in practice? (No doubt it'll flesh out how they really work).
As to Y: Take a look at this paper. The paper uses ML, if you want Scheme versions of the code, email me and I'll try to dig them out for you.
Although I don't fully understand the Y combinator yet, I found Richard Gabriel's short essay helpful.
I am in that boat of people new to LtU and without formal PL background =) Pointers much appreciated!
Pointers much appreciated, but let's keep it real, eh guys? :-)
What in God's good name does that mean?
For starters, no square roots of negative numbers:-)
Oh, and there I thought "keep it real" was an appeal for solid foundations and robust epistemology! ;)
For example, the OP might be interested in denotational semantics, because of the mapping it provides from programming languages to well-defined Math, right down to the appeal to geometric intuition regarding lattices. Assuming one is willing to acknowledge the reality of anything, how much more real than that does it get?
Speaking of which, I mentioned it the other day, but I liked Schmidt's Denotational Semantics: A Methodology for Language Development, and the first few chapters could be useful as a general intro to some formal PL topics.
Another resource I haven't seen mentioned is Frank Attanassow's Programming language theory texts online, a list of online books, lectures, tutorials etc. on programming language theory.
Frank Atanassow's PLT is no longer at that location (and his homepage listed in his LtU profile also went 404; I don't know if this is permanent or transient).
However, I did find a copy here which Frank posted on The Software Technologist wiki.
Some may question the inclusion of CTM, since it isn't a PL design text, but I think its coverage of the various concepts that one might wish to include in a new language, and its pedagogical mechanism of gradual concept inclusion in a virtual machine specification, are extraordinarily useful.
LiSP is a bit better if you are really interested in building Lisp/Scheme interpreters.
Notice that TAPL is the first theoy book mentioned: the others don't teach formal techiques.
Notice that TAPL is the first theory book mentioned: the others don't teach formal techniques.
Actually, this is not quite true. CTM gives a formal semantics for all the concepts it introduces in the main body of the book, both as an abstract machine and as a structural operational semantics. It also explains logical semantics and axiomatic semantics, and gives a nod to denotational semantics. From our experience in teaching the semantics to engineering students, we find that the level of semantics given in CTM is just about right for a practicing programmer.
I agree that EOPL is a bit weak on OOP and typing. Obviously, my feeling is that TAPL addresses those weaknesses, but it's definitely richer meat, if you will, than EOPL, while I feel EOPL will prepare the reader so that their entry into TAPL will be somewhat easier.
LiSP I appreciate mostly for its coverage of the issues in continuations and closures, but also in its treatment of issues in namespaces.
TAPL, then, seems to expand on all of these subjects, deepen them, and put them on a truly rigorous footing—but calling EOPL "informal" may be accurate in some, er, formal sense, but its treatment of algebraic methods and the CPS transformation seems quite formal to me, albeit presented informally.
So not only do I recommend the texts I mentioned, but apparently I also recommend them in the order that I mentioned them.
Lest it be misunderstood, let me clarify that I am a fan of EOPL2. I just meant that by itself it doesn't provide you with the formal notation you will find in many of the papers discussed on LtU.
I think I got "serious" about programming languages when SML kept nagging at me. At first I hated the language, but it got under my skin. Finally something clicked and I wanted to go a little deeper, so I picked up The Definition of Standard ML. The striking elegance of the design and the clarity, beauty and rigor of the formal treatment hit me really, really hard and I've never really looked back. Of course it took me quite awhile and a lot of work to develop the conceptual tools to really make sense of a lot of that book, but after years of dabbling in compilers and language design (I'm sure I thought the K&R C book was as rigorous as it got), the Definition opened new vistas.
I also really liked the presentation in Elements of Functional Programming by Chris Reade. It covers a lot of very diverse ground in a really enjoyable way, dabbling in theory, design, implementation and actual applications of FP.
Only later did I really come to appreciate Scheme, EOPL, etc...
I've always been interested in mathematics and have been interested in programming for about as long. So looking for the theory side of things seemed natural. However, since I was (and am) a self-taught programmer and had nothing to guide me; the mainstream dominated my view of programming. That would've been fine except there is a rather wide chasm between theory and practice for mainstream languages (C++ for me) and techniques (read OOP). While I certainly looked at non-mainstream languages (including Scheme), the language that prompted my programming theory renaissance was Haskell (admittedly Scheme was the closest language to Haskell that I knew at the time, but at the time, I was explicitly looking to learn pure FP). One of the most striking things about Haskell is how close theory and practice are. The main examples are: monads, folds and unfolds, and the Curry-Howard correspondence holding fairly strongly.
I do want to emphasize the Curry-Howard correspondence to those unfamiliar with it. Lectures on the Curry-Howard Isomorphism (pdf) is a large, comprehensive paper covering it. Google will turn up lighter articles, but some minimal familiarity with the ideas in programming language theory (or related fields) is probably required to know and appreciate what it is saying.
Haskell is also how I got interested in Category Theory, Barr and Well's lecture notes are still one of my favorite online resources. It doesn't require much of the reader, and does a reasonably good job of motivating you to find out about the things that it does assume you know.
Just a random request to finish the Moonbase tutorial.
General book: PLAI by Krishnamurthi
Embedding Interpreters by Benton -- gathers a number of threads (interpreters, monads, reflection) together into a neat bow.
Others to google: Friedman, Kiselyov, Wand, Felleisen, Hughes.
I'm not sure I know anyone who would ask me where to start in PL theory. I'd want to know what the basis for their interest was and if they had an idea of the discussions and papers that they would like to be able to follow. Probing a little deeper, I'd ask whether there was something they wanted to be equipped to do or participate in that brings up the interest in PL theory.
I'm not sure how I would answer this myself were I a newcomer. These days I would say I'm mostly interested in how a PL theory bridges from the world of mathematics, with its well-definedness presumption, to the world of computational behavior with operational state and interaction, preserving applicability of mathematics in so doing.
Here's another question for everyone: I've a decent grasp on PL theory (or so I think) but don't know much about the formal models of PL semantics. Now the situation has arisen where I need to know more. What is a good introduction to the various different models and what are some pointers to deeper material on each? Your suggestions are much appreciated!
Maybe you find this book usefull:
Syntax and Semantics of Programming Languages. It introduces denotational, algebric and axiomatic semantics.
Here's a nice intro to Polymorphic Type Inference, by Michael Schwartzbach. It's not quite as specific as it might sound — it defines a "tiny functional language" in order to illustrate type inference, and also covers the relationship between types and logic, including the Curry-Howard isomorphism.
I'm of the belief that all you need to know about functional programming (or programming in general) and programming languages can be learned from HTDP. Everything from the basics of functions, to the universiality of fold, to polytypic programming, is there, if you look for it.
I'm assuming you mean programming languages rather than programming. Otherwise it sounds analogous to "all you need to know about bridge-building can be learned from the first volume of the Feynman notes." I'm trying to think of how knowing about the universality of fold will help my students program their compilers...
Fold for implementing programming languages:
Folds for language design:
Two ideas that may make an interesting component or basis for a language are:
Dealing with Large Bananas and
Metamorphic Programming
I was really just making the following uninteresting observation: The OP's claim that "all you need to know about programming [which to him evidently means 'functional programming'] is folds" is absurd. Lambda is, and should remain, a forum primarily for PL theory, and PL theory is part of practical programming knowledge. However, there is much to practical programming beyond PL theory, and precise language cools flamefests like the one on OO, and avoids the appearance of arrogance and condescencion.
The OP's claim that "all you need to know about programming [which to him evidently means 'functional programming'] is folds" is absurd.
Actually, what the OP wrote was "all you need to know about functional programming (or programming in general) and programming languages can be learned from HTDP", which is rather more defensible, if one is talking about students. You were the one who raised the question of how folds apply to compilers, which was answered quite comprehensively.
But have you ever been a student at, or TAed at, an American state university?
HTDP is being used at high schools and universities, including state universities. Indications are that it gives students a better grounding for learning and understanding languages like Java and C++ than more traditional approaches.
Are there other things students might need to learn? Of course. But if you were putting together a list of core concepts they should understand well, the contents of HTDP would rank very high.
You were the one who raised the question of how folds apply to compilers, which was answered quite comprehensively.
In my opinion, the students' difficulties stem from varied and poor backgrounds acquired at a dozen universities and community colleges, and from a lack of basic engineering skills (abstraction, modeling, automation of mundane tasks, ordering of one's environment, etc.). You may reply that knowing some PLT will encourage these skills, and I would agree, but only in so far as any mathematical training teaches one to think abstractly.
if you were putting together a list of core concepts they should understand well, the contents of HTDP would rank very high.
But have you ever been a student at, or TAed at, an American state university? They are training a lot of potential programmers, and hylomorphisms (had to look that up) and folds are not even on the radar.
Well, I have in fact been a TA at an American state university. I even held the lofty position of full-time "instructor" there for a year.
I can report that catamorphisms (folds) and anamorphisms (unfolds) did cross students' radar, right in CS1.
Lest you think this is some sort of anomaly, I can also report that many schools teach catamorphisms and (list) anamorphisms by at least CS2, using terms like "visitor pattern" and "implement the Iterator interface".
I guess what you're claiming is that at most places, students are kept in the dark about the fact that visitors and iterators have any mathematical properties at all. This is probably true, but probably also suboptimal when training students who intend to engineer our software.
Well, I have in fact been a TA at an American state university. I even held the lofty position of full-time "instructor" there for a year.
Yet I notice you didn't stick around ;). Your guess about my claims is correct, but not complete. I also claim that a lack of coding skills, from varied and poor backgrounds, makes even upper-division courses more about how to interact with a programming environment than about how to reason abstractly about the structure of programs. There is a large body of "common sense" knowledge necessary to program effectively, normally learned implicitly in the course of some other task (learning about PLT, being a sysadmin, writing a numerical model). I'm claiming that at least at one place, this common sense is not being absorbed, and gets in the way of learning.
There's a classic thread that's relevant on folds, unfolds and regular programming.
In particular Neel Krishnaswami's post highlights the value of understanding these morphisms:
The reason that unfolds and folds are so convenient is precisely because they are special cases, with powerful invariants coming along for free. Better still, a fold and an unfold composed together can describe any primitive recursive function, and that's a huge class of computations, which describes almost all of the programs I've written.
It's a good exercise to transform operations in either folds or unfolds: it helps to understand better the problem being solved and the specific solutions.
Other people have said lots of worthwhile things in reponse, so I'll just mention a couple points.
1. I've TAed HTDP-based courses at Northeastern University, which is comparable to a middling flagship state university (I think, having not studied at any).
2. HTDP doesn't tell anyone about the universiality of fold. But it's all there, if you look for it.
3. Proving theorems about polytypic programming isn't going to help most programmers, regardless of their background. But the important insights are still comprehensible by anyone.
4. Finally, you should actually take a look at HTDP. It's nothing like Feynman. It's more like saying that a high school physics text can teach you all about string theory (which is ridiculous for physics).
Types and Programming Languages -- Pierce
This is an amazing book. You will never look at a programming languages the same way after reading this.
Defintion of Standard ML (revised) --Millner, et al
A slim but dense volume. The insights you will gain are not unique to ML, but it is best to have played around with ML first. I think that Elements of ML Programming (Ullman) is a good gentle introduction to ML.
Esentials of Programming languages -- Friedman
Not formal, but very useful. Quite helpful to refer to when the formal definition isn't sinking in right.
Compiling with Continuations -- Appel
Not the latest word on compilation, but still an excellent book to read if you are interested in computation over programs.
Category Theory for Computer Scientists -- Pierce
Good to have alongside Types and Programming Languages (with a good Set Theory book if you're weak there). Read the first two chapters before TAPL gets into subtyping.
Categories for Types -- Crole
A possible alternative or companion to Category Theory for Computer Scientists. I must confess that I only recently obtained this and just started to look through it. But I like how it is written and organized.
Structure and Interpretation of Computer Programs -- Abelson & Sussman
On Lisp -- Graham
Neither of these is very formal, so they don't really belong on this list. Nonetheless, they can be very useful for thinking differently about what a program is. Note that Paul Graham has strong opinions and may occasionally present them as revealed truths.
We had differing views about Hankin's LC book.
I'm reading it, and I must say it is complete, with just the right blance between theory, code samples and historical background. It covers many different PL themes and make (IMHO) good choices, like starting with a not so short LISP introduction.
I think it's a good book for students who wants a broad introduction to past and current programming languages concepts.
It has been written by John Mitchell, and is published by Cambridge University Press.
A popular science introduction by Wadler.
More here:
Morten Heine
B. Sørenson and Pawel
Urzyczyn. Lectures on the Curry-Howard Isomorphism. (gzipped
PS)
Jean-Yves Girard,
Paul Taylor and
Yves Lafont.
Proofs and Types.
(link)
Many of the discussions on LtU relate to functional programming languages in one way or the other, since this is a major area of research and since many new and important ideas come from functional languages.
If you are not familiar with functional programming, a nice introduction (covering things like why there is a ban on assignment in [pure] functional languages, referential transparency, lazy evaluation etc.) can be found in the paper Why Functional Programming Matters by John Hughes.
This is a truly great (and short) paper. It neatly bundles up a wide range of reasons why functional languages are interesting, and has prompted me to attack Haskell and SML more seriously on at least two occasions.
This is my request for a "getting started" link on the left sidebar that's always visible and points to this thread.
I think the link from the FAQ should be enough. But if others think we should put it on the sidebar, we can do that.
...for linking this from the sidebar. (I think some people would be more inclined to click on a link called "Getting Started" than an "FAQ", and there's a whole host of really valuable links here).
OK. I added the link to the sidebar.
One paper which I think belongs here is Definitional Interpreters. The CMU link on that page seems dead, though. There's a version of it here, and the "Revisited" summary is here.
We should keep a collection of links to the Why Are X interesting threads, for X in {type systems, continuations, monads...}
...but the five that meet the immediate criteria would be:
hello ,
i am not so familar with functional languages semantics
what does mean lazy evaluation ?
thanks
This is allegedly a very good summary to many LtU topics.
Which of the following is a better approach to implement generic algorithms ; overloading or templates? Justify with the help of examples.
LtU is not the place to cheat on homework assignments.
From the PLT Scheme mailing list:
The plan:
So to revisit this again, what do you need to learn of the lambda calculus relative to FP?
A working programmer should have seen:
syntax
reductions (eval is a function via Church Rosser and Curry-Feys Standard Reduction theorems).
So to revisit this again, what do you need to learn of the lambda calculus relative to FP?
A working programmer should have seen:
That's approx 10 weeks worth of course material. Or 2 weeks of self-
study with a one-hour lunch break.
The texts:
What would your reading list be for the self study, apart from Barendregt?
When I present this piece of the puzzle in PhD seminars, I use
original literature as much as possible:
Barendregt, The Lambda Calculus, North Holland
chapters 2 and 3
Plotkin, Call-by-name, call-by-value, and the lambda calculus
Theoretical Computer Science, 1974
Plotkin, PCF considered a programming language
Theoretical Computer Science, 1978
Optionally, if you wish to hook up pure LC with effects:
Felleisen and Friedman, Control operators, the SECD-machine, and
the lambda-calculus.
Formal Description of Programming Concepts III, North Holland, 1986
What would your reading list be for the self study, apart from Barendregt?
When I present this piece of the puzzle in PhD seminars, I use
original literature as much as possible:
Optionally, if you wish to hook up pure LC with effects:
See also the NU PLT pubs page.
Thanks to Grant Rettke and Chris Stephenson for asking the questions quoted above.
Is there is any way to obtain a good trace(i.e. if no error occur in the PROMELA model and model satisfies the specification)
At present SPIN only provides only the bad traces(i.e. execution trace if error occurs)
So I want to find a way through which I can get the good trace in SPIN model checker
This isn't the right forum for your question. There's lots of spin resources here. | http://lambda-the-ultimate.org/node/view/492 | crawl-001 | refinedweb | 4,159 | 59.94 |
Back
Is there any way in Salesforce to group apex classes under a package or namespace? Can we use managed package for internal organization purpose?
So, according to me, this is a big condition in the force.com stack that makes medium sized projects difficult, if not impractical. If you use managed packages in order to get a package prefix, it won't solve any problems, so it's not really worth the trouble.
Want to learn Salesforce from the scratch? Here's is the right video for you on Salesforce provided by Intellipaat:
I try to organize a project into one level of namespaces. Instead of actual namespaces, you could give each would-be-namespace a 3-5 character name, to be used as a prefix. Any class which belongs in the 'namespace' gets prefixed.
Functional advantage of this type of convention is that it helps prevent name classes and clashes which are grouped by their 'namespace' when viewed in a sorted list, such as in an IDE, or Setup > Develop > Apex Classes
Sadly, several basic OO principles are still fundamentally broken. Apparently, the most important one is that every class forms an implicit dependency on each and every other class it has visibilty to, which is actually all of. | https://intellipaat.com/community/4488/organizing-apex-classes-under-namespace | CC-MAIN-2021-43 | refinedweb | 211 | 61.16 |
Gulp for WordPress: Creating the Tasks
This is the second post in a two-part series about creating a Gulp workflow for WordPress theme development. Part one focused on the initial installation, setup, and organization of Gulp in a WordPress theme project. This post goes deep into the tasks Gulp will run by breaking down what each task does and how to tailor them to streamline theme development.
Now that we spent the first part of this series setting up a WordPress theme project with Gulp installed, it's time to dive into the tasks we want it to do for us as we develop the theme. We're going to get our hands extremely dirty in this post, get ready to write some code!
Article Series:
- Initial Setup
- Creating the Tasks (This Post)
Creating the style task
Let’s start by compiling
src/bundle.scss from Sass to CSS, then minifying the CSS output for production mode and putting the completed
bundle.css file into the
dist directory.
We’re going to use a couple of Gulp plugins to do the heavy lifting. We’ll use gulp-sass to compile things and gulp-clean-css to minify. Then, gulp-if will allow us to conditionally run functions which, In our case, will check if we are in production or development modes before those tasks run and then execute accordingly.
We can install all three plugins in one fell swoop:
npm install --save-dev gulp-sass gulp-clean-css gulp-if
Let’s make sure we have something in our
bundle.scss file so we can test the tasks:
$colour: #f03; body { background-color: $colour; }
Alright, back to the Gulpfile to import the plugins and define the task that runs them:
import { src, dest } from 'gulp'; import yargs from 'yargs'; import sass from 'gulp-sass'; import cleanCss from 'gulp-clean-css'; import gulpif from 'gulp-if'; const PRODUCTION = yargs.argv.prod; export const styles = () => { return src('src/scss/bundle.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulpif(PRODUCTION, cleanCss({compatibility:'ie8'}))) .pipe(dest('dist/css')); }
Let’s walk through this code to explain what’s happening.
- The src and dest functions are imported from Gulp.
srcwill read the file that you pass as an argument and return a node stream.
- We pull in
yargsto create our flag that separates tasks between the development and production modes.
- The three plugins are called into action.
- The
PRODUCTIONflag is defined and held in the
prodcommand.
- We define
stylesas the task name we will use to run these tasks in the command line.
- We tell the task what file we want processed (
bundle.scss) and where it lives (
src/scss/bundle.scss).
- We create "pipes" that serve as the plungs that run when the
stylescommand is executed. Those pipes run in the order they are written: convert Sass to CSS, minify the CSS (if we’re in production), and place the resulting CSS file into the
dist/cssdirectory.
Go ahead. Run
gulp styles in the command line and see that a new CSS file has been added to your CSS directory
dist/css.
Now do
gulp styles --prod. The same thing happens, but now that CSS file has been minified for production use.
Now, assuming you have a functioning WordPress theme with
header.php and
footer.php, the CSS file (as well as JavaScript files when we get to those tasks) can be safely enqueued, likely in your
functions.php file:
function _themename_assets() { wp_enqueue_style( '_themename-stylesheet', get_template_directory_uri() . '/dist/css/bundle.css', array(), '1.0.0', 'all' ); } add_action('wp_enqueue_scripts', '_themename_assets');
That’s all good, but we can make our style command even better.
For example, try inspecting the body on the homepage with the WordPress theme active. The styles that we added should be there:
As you can see, it says that our style is coming from
bundle.css, which is true. However, it would be much better if the name of the original SCSS file is displayed here instead for our development purposes — it makes it so much easier to locate code, particularly when we’re working with a ton of partials. This is where source maps come into play. That will detail the location of our styles in DevTools. To further illustrate this issue, let's also add some SCSS inside
src/scss/components/slider.scss and then import this file in
bundle.scss.
//src/scss/components/slider.scss body { background-color: aqua; }
//src/scss/bundle.scss @import './components/slider.scss'; $colour: #f03; body { background-color: $colour; }
Run
gulp styles again to recompile your files. Your inspector should then look like this:
The DevTools inspector will show that both styles are coming from
bundle.css. But we would like it to show the original file instead (i.e
bundle.scss and
slider.scss). So let’s add that to our wish list of improvements before we get to the code.
The other thing we’ll want is vendor prefixing to be handled for us. There’s nothing worse than having to write and manage all of those on our own, and Autoprefixer is the tool that can do it for us.
And, in order for Autoprefixer to work its magic, we’ll need the PostCSS plugin.
OK, that adds up to three more plugins and tasks we need to run. Let’s install all three:
npm install --save-dev gulp-sourcemaps gulp-postcss autoprefixer
So gulp-sourcemaps will obviously be used for sourcemaps. gulp-postcss and autoprefixer will be used to add autoprefixing to our CSS. postcss is a famous plugin for transforming CSS files and autoprefixer is just a plugin for postcss. You can read more about the other things that you can do with postcss here.
Now at the very top let’s import our plugins into the Gulpfile:
import postcss from 'gulp-postcss'; import sourcemaps from 'gulp-sourcemaps'; import autoprefixer from 'autoprefixer';
And then let’s update the task to use these plugins:
export const styles = () => { return src('src/scss/bundle')); }
To use the the sourcemaps plugin we have to follow some steps:
- First, we initialize the plugin using
sourcemaps.init().
- Next, pipe all the plugins that you would like to map.
- Finally, Create the source map file by calling
sourcemaps.write()just before writing the bundle to the destination.
Note that all the plugins piped between
sourcemaps.init() and
sourcemaps.write() should be compatible with gulp-sourcemaps. In our case, we are using
sass(),
postcss() and
cleanCss() and all of them are compatible with sourcemaps.
Notice that we only run the Autoprefixer begind the production flag since there’s really no need for all those vendor prefixes during development.
Let’s run
gulp styles now, without the production flag. Here’s the output in
bundle.css:
body { background-color: aqua; } body { background-color: #f03; } /*#sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVuZGxlLmNzcyIsInNvdXJjZXMiOlsiYnVuZGxlLnNjc3MiLCJjb21wb25lbnRzL3NsaWRlci5zY3NzIl0sInNvdXJjZXNDb250ZW50IjpbIkBpbXBvcnQgJy4vY29tcG9uZW50cy9zbGlkZXIuc2Nzcyc7XG5cbiRjb2xvdXI6ICNmMDM7XG5ib2R5IHtcbiAgICBiYWNrZ3JvdW5kLWNvbG9yOiAkY29sb3VyO1xufVxuOjpwbGFjZWhvbGRlciB7XG4gICAgY29sb3I6IGdyYXk7XG59IiwiYm9keSB7XG4gICAgYmFja2dyb3VuZC1jb2xvcjogYXF1YTtcbn0iXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFDQUEsQUFBQSxJQUFJLENBQUM7RUFDRCxnQkFBZ0IsRUFBRSxJQUFJLEdBQ3pCOztBRENELEFBQUEsSUFBSSxDQUFDO0VBQ0QsZ0JBQWdCLEVBRlgsSUFBSSxHQUdaOztBQUNELEFBQUEsYUFBYSxDQUFDO0VBQ1YsS0FBSyxFQUFFLElBQUksR0FDZCJ9 */#
The extra text below is source maps. Now, when we inspect the site in DevTools, we see:
Nice! Now onto production mode:
gulp styles --prod
Check DevTools against style rules that require prefixing (e.g.
display: grid;) and confirm those are all there. And make sure that your file is minified as well.
One final notice for this task. Let’s assume we want multiple CSS bundles: one for front-end styles and one for WordPress admin styles. We can create add a new
admin.scss file in the
src/scss directory and pass an array of paths in the Gulpfile:')); }
Now we have
bundle.css and
admin.css in the
dist/css directory. Just make sure to properly enqueue any new bundles that are separated out like this.
Creating the watch task
Alright, next up is the watch task, which makes our life so much easier by looking for files with saved changes, then executing tasks on our behalf without have to call them ourselves in the command line. How great is that?
Like we did for the styles task:
import { src, dest, watch } from 'gulp';
We’ll call the new task
watchForChanges:
export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); }
Note that
watch is unavailable as a name since we already have a variable using it.
Now let’s run
gulp watchForChanges the command line will be on a constant, ongoing watch for changes in any
.scss files inside the
src/scss directory. And, when those changes happen, the styles task will run right away with no further action on our part.
Note that
src/scss/**/*.scss is a glob pattern. That basically means that this string will match any
.scss file inside the
src/scss directory or any sub-folder in it. Right now, we are only watching for
.scss files and running the styles task. Later, we’ll expand its scope to watch for other files as well.
Creating the images task
As we covered earlier, the images task will compress images in
src/images and then move them to
dist/images. Let’s install a gulp plugin that will be responsible for compressing images:
npm install --save-dev gulp-imagemin
Now, import this plugin at the top of the Gulpfile:
import imagemin from 'gulp-imagemin';
And finally, let’s write our images task:
export const images = () => { return src('src/images/**/*.{jpg,jpeg,png,svg,gif}') .pipe(gulpif(PRODUCTION, imagemin())) .pipe(dest('dist/images')); }
We give the
src() function a glob that matches all
.jpg,
.jpeg,
.png,
.svg and
.gif images in the
src/images directory. Then, we run the imagemin plugin, but only for production. Compressing images can take some time and isn’t necessary during development, so we can leave it out of the development flow. Finally, we put the compressed versions of images in
dist/images.
Now any images that we drop into
src/images will be copied when we run
gulp images. However, running
gulp images --prod, will both compress and copy the image over.
Last thing we need to do is modify our
watchForChanges task to include images in its watch:
export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', images); }
Now, assuming the
watchForChanges task is running, the images task will be run automatically whenever we add an image to the
src/images folder. It does all the lifting for us!
Important: If the
watchForChanges task is running and when the Gulpfile is modified, it will need to be stopped and restarted in order for the changes to take effect.
Creating the copy task
You probably have been in situations where you’ve created files, processed them, then needed to manually grab the production files and put them where they need to be. Well, as we saw in the images task, we can use the copy feature to do this for us and help prevent moving wrong files.
export const copy = () => { return src(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*']) .pipe(dest('dist')); }
Try to read the array of paths supplied to
src() carefully. We are telling Gulp to match all files and folders inside
src (
src/**/*), except the images, js and scss folders (
!src/{images,js,scss}) and any of the files or sub-folders inside them (
!src/{images,js,scss}/**/*).
We want our watch task to look for these changes as well, so we’ll add it to the mix:
export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', images); watch(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*'], copy); }
Try adding any file or folder to the src directory and it should be copied over to the the
/dist directory. If, however, we were to add a file or folder inside of
/images,
/js or
/scss, it would be ignored since we already handle these folders in separate tasks.
We still have a problem here though. Try to delete the added file and it won’t happen. Our task only handles copying. This problem could also happen for our
/images,
/js and
/scss, folders. If we have old images or JavaScript and CSS bundles that were removed from the
src folder, then they won’t get removed from the
dist folder. Therefore, it’s a good idea to completely clean the
dist folder every time to start developing or building a theme. And that’s what we are going to do in the next task.
Composing tasks for developing and building
Let’s now install a package that will be responsible for deleting the
dist folder. This package is called del:
npm install --save-dev del
Import it at the top:
import del from 'del';
Create a task that will delete the
dist folder:
export const clean = () => { return del(['dist']); }
Notice that
del returns a promise. Thus, we don’t have to call the
cb() function. Using the new JavaScript features allows us to refactor this to:
export const clean = () => del(['dist']);
The folder should be deleted now when running
gulp clean. What we need to do next is delete the
dist folder, run the images, copy and styles tasks, and finally watch for changes every time we start developing. This can be done by running
gulp clean,
gulp images,
gulp styles,
gulp copy and then
gulp watch. But, of course, we will not do that manually. Gulp has a couple of functions that will help us compose tasks. So, let’s import these functions from Gulp:
import { src, dest, watch, series, parallel } from 'gulp';
series() will take some tasks as arguments and run them in series (one after another). And
parallel() will take tasks as arguments and run them all at once. Let’s create two new tasks by composing the tasks that we already created:
export const dev = series(clean, parallel(styles, images, copy), watchForChanges) export const build = series(clean, parallel(styles, images, copy)) export default dev;
Both tasks will do the exact same thing: clean the
dist folder, then styles, images and copy will run in parallel one the cleaning is complete. We will start watching for changes as well for the dev (short for develop) task, after these parallel tasks. Additionally, we are also exporting dev as the default task.
Notice that when we run the build task, we want our files to be minified, images to be compressed, and so on. So, when we run this command, we will have to add the
--prod flag. Since this can easily be forgotten when running the build task, we can use npm scripts to create aliases for the dev and build commands. Let’s go to
package.json, and in the scripts field, we will probably find something like this:
"scripts": { "test": "echo "Error: no test specified" && exit 1" }
Let’s change it to this:
"scripts": { "start": "gulp", "build": "gulp build --prod" },
This will allow us to run
npm run start in the command line, which will go to the scripts field and find what command corresponds to start. In our case, start will run gulp and gulp will run the default gulp task, which is dev. Similarly,
npm run build will run
gulp build --prod. This way, we can completely forget about the
--prod flag and also forget about running the Gulp tasks using the
gulp command. Of course, our dev and build commands will do more than that later on, but for now, we have the foundation that we will work with throughout the rest of the tasks.
Creating the scripts task
As mentioned, in order to bundle our JavaScript files, we are going to need a module bundler. webpack is the most famous option out there, however it is not a Gulp plugin. Rather, it’s a plugin on its own that has a completely separate setup and configuration file. Luckily, there is a package called webpack-stream that helps us use webpack within a Gulp task. So, let’s install this package:
npm install --save-dev webpack-stream
webpack works with something called loaders. Loaders are responsible for transforming files in webpack. And to transform new Javascript versions into ES5, we will need a loader called babel-loader. We will also need @babel/preset-env but we already installed this earlier:
npm install --save-dev babel-loader
Let’s import webpack-stream at the top of the Gulpfile:
import webpack from 'webpack-stream';
Also, to test our task, lets add these lines in
src/js/bundle.js and
src/js/components/slider.js:
// bundle.js import './components/slider'; console.log('bundle'); // slider.js console.log('slider')
Our scripts task will finally look like so:
export const scripts = () => { return src('src/js/bundle.js') .pipe(webpack({ module: { rules: [ { test: /\.js$/, use: { loader: 'babel-loader', options: { presets: [] } } } ] }, mode: PRODUCTION ? 'production' : 'development', devtool: !PRODUCTION ? 'inline-source-map' : false, output: { filename: 'bundle.js' }, })) .pipe(dest('dist/js')); }
Let’s break this down a bit:
- First, we specify bundle.js as our entry point in the
src()function.
- Then, we pipe the webpack plugin and specify some options for it.
- The rules field in the module option lets webpack know what loaders to use in order to transform our files. In our case we need to transform JavaScript files using the babel-loader.
- The mode option is either production or development. For development, webpack will not minify the output JavaScript bundle, but it will for production. Therefore, we don’t need a separate Gulp plugin to minify JavaScript because webpack can do that depending on our
PRODUCTIONconstant.
- The devtool option will add source maps, but not in production. In development, however, we will use
inline-source-maps. This kind of source maps is the most accurate though it can be a bit slow to create. If you find it too slow, check the other options here. They won’t be as accurate as
inline-source-mapsbut they can be pretty fast.
- Finally, the output option can specify some information about the output file. In our case, we only need to change the filename. If we don’t specify the filename, webpack will generate a bundle with a hash as the filename. Read more about these options here.
Now we should be able to run
gulp scripts and
gulp scripts --prod and see a bundle.js file created in
dist/js. Make sure that minification and source maps are working properly. Let’s now enqueue our JavaScript file in WordPress, which can be in the theme’s functions.php file, or wherever you write your functions.
<?php function _themename_assets() { wp_enqueue_style( '_themename-stylesheet', get_template_directory_uri() . '/dist/css/bundle.css', array(), '1.0.0', 'all' ); wp_enqueue_script( '_themename-scripts', get_template_directory_uri() . '/dist/js/bundle.js', array(), '1.0.0', true ); } add_action('wp_enqueue_scripts', '_themename_assets');
Now, looking at the console, let’s confirm that source maps are working correctly by checking the file that the console logs come from:
Without the source maps, both logs will appear coming from
bundle.js.
What if we would like to create multiple JavaScript bundles the same way we do for the styles? Let’s create a file called admin.js in
src/js. You might think that we can simply change the entry point in the
src() to an array like so:
export const scripts = () => { return src(['src/js/bundle.js','src/js/admin.js']) . . }
However, this will not work. webpack works a bit differently that normal Gulp plugins. What we did above will still create one file called bundle.js in the
dist folder. webpack-stream provides a couple of solutions for creating multiple entry points. I chose to use the second solution since it will allow us to create multiple bundles by passing an array to the
src() the same way we did for the styles. This will require us to install vinyl-named:
npm install --save-dev vinyl-named
Import it:
import named from 'vinyl-named';
...and then update the scripts task:
export const scripts = () => { return src(['src/js/bundle.js','src/js/admin.js']) .pipe(named()) .pipe(webpack({ module: { rules: [ { test: /\.js$/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] }, mode: PRODUCTION ? 'production' : 'development', devtool: !PRODUCTION ? 'inline-source-map' : false, output: { filename: '[name].js' }, })) .pipe(dest('dist/js')); }
The only difference is that we now have an array in the
src(). We then pipe the named plugin before webpack, which allows us to use a
[name] placeholder in the output field’s filename instead of hardcoding the file name directly. After running the task, we get two bundles in
dist/js.
Another feature that webpack provides is using libraries from external sources rather than bundling them into the final bundle. For example, let’s say your bundle needs to use jQuery. You can run
npm install jquery --save and then import it to your bundle
import $ from 'jquery'. However, this will increase the bundle size and, in some cases, you may already have jQuery loaded via a CDN or — in case of WordPress — it can exist as a dependency like so:
wp_enqueue_script( '_themename-scripts', get_template_directory_uri() . '/dist/js/bundle.js', array('jquery'), '1.0.0', true );
So, now WordPress will enqueue jQuery using a normal script tag. How can we then use it inside our bundle using
import $ from
'jquery'? The answer is by using webpack’s externals option. Let’s modify our scripts task to add it in:')); }
In the externals option,
jquery is the key that identifies the name of the library we want to import. In our case, it will be
import $ from
'jquery'. And the value
jQuery is the name of a global variable where that the library lives. Now try to
import $ from ‘jquery’ in the bundle and use jQuery using the
$ — it should work perfectly.
Let’s watch for changes for JavaScript files as well:
export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', images); watch(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*'], copy); watch('src/js/**/*.js', scripts); }
And, finally, add our scripts task in the dev and build tasks:
export const dev = series(clean, parallel(styles, images, copy, scripts), watchForChanges); export const build = series(clean, parallel(styles, images, copy, scripts));
Refreshing the browser with Browsersync
Let’s now improve our watch task by installing Browsersync, a plugin that refreshes the browser each time tasks finish running.
npm install browser-sync gulp --save-dev
As usual, let’s import it:
import browserSync from "browser-sync";
Next, we will initialize a Browsersync server and write two new tasks:
const server = browserSync.create(); export const serve = done => { server.init({ proxy: "" // put your local website link here }); done(); }; export const reload = done => { server.reload(); done(); };
In order to control the browser using Browsersync, we have to initialize a Browsersync server. This is different from a local server where WordPresss would typically live. the first task is
serve, which starts the Browsersync server, and is pointed to our local WordPress server using the
proxy option. The second task will simply reload the browser.
Now we need to run this server when we are developing our theme. We can add the serve task to the dev series tasks:
export const dev = series(clean, parallel(styles, images, copy, scripts), serve, watchForChanges);
Now run
npm start and the browser should open up a new URL that’s different than the original one. This URL is the one that Browsersync will refresh. Now let’s use the reload task to reload the browser once tasks are done:
export const watchForChanges = () => { watch('src/scss/**/*.scss', series(styles, reload)); watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', series(images, reload)); watch(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*'], series(copy, reload)); watch('src/js/**/*.js', series(scripts, reload)); watch("**/*.php", reload); }
As you can see, we added a new line to run the reload task every time a PHP file changes. We are also using
series() to wait for our styles, images, scripts and copy tasks to finish before reloading the browser. Now, run
npm start and change something in a Sass file. The browser should reload automatically and changes should be reflected after refresh once the tasks have finished running.
Don’t see CSS or JavaScript changes after refresh? Make sure caching is disabled in your browser’s inspector.
We can make even one more improvement to the styles tasks. Browsersync allows us to inject CSS directly to the page without even having to reload the browser. And this can be done by adding
server.stream() at the very end of the styles task:()); }
Now, in the
watchForChanges task, we won’t have to reload for the styles task any more, so let’s remove the reload task from it:
export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); . . }
Make sure to stop
watchForChanges if it’s already running and then run it again. Try to modify any file in the
scss folder and the changes should appear immediately in the browser without even reloading.
Packaging the theme in a ZIP file
WordPress themes are generally packaged up as a ZIP file that can be installed directly in the WordPress admin. We can create a task that will take the required theme files and ZIP them up for us. To do that we need to install another Gulp plugin: gulp-zip.
npm install --save-dev gulp-zip
And, as always, import it at the top:
import zip from "gulp-zip";
Let’s also import the JSON object in the package.json file. We need that in order to grab the name of the package which is also the name of our theme:
import info from "./package.json";
Now, let’s write our task:
export const compress = () => { return src([ "**/*", "!node_modules{,/**}", "!bundled{,/**}", "!src{,/**}", "!.babelrc", "!.gitignore", "!gulpfile.babel.js", "!package.json", "!package-lock.json", ]) .pipe(zip(`${info.name}.zip`)) .pipe(dest('bundled')); };
We are passing the
src() the files and folders that we need to compress, which is basically all files and folders (
**/), except a few specific types of files, which are preceded by
!. Next, we are piping the gulp-zip plugin and calling the file the name of the theme from the package.json file (info.name). The result is a fresh ZIP file an a new folder called
bundled.
Try running
gulp compress and make sure it all works. Open up the generated ZIP file and make sure that it only contains the files and folders needed to run the theme.
Normally, though, we only need to ZIP things up *after* the theme files have been built. So let’s add the compress task to the build task so it only runs when we need it:
export const build = series(clean, parallel(styles, images, copy, scripts), compress);
Running
npm run build should now run all of our tasks in production mode.
Replacing the placeholder prefix in the ZIP file
One step we need to do before zipping our files is to scan them and replace the
themename placeholder with the theme name we plan to use. As you may have guessed, there is indeed a Gulp plugin that does that for us, called gulp-replace.
npm install --save-dev gulp-replace
Then import it:
import replace from "gulp-replace";
We want this task to run immediately before our files are zipped, so let’s modify the compress task by slotting it in the right place:
export const compress = () => { return src([ "**/*", "!node_modules{,/**}", "!bundled{,/**}", "!src{,/**}", "!.babelrc", "!.gitignore", "!gulpfile.babel.js", "!package.json", "!package-lock.json", ]) .pipe(replace("_themename", info.name)) .pipe(zip(`${info.name}.zip`)) .pipe(dest('bundled')); };
Try to building the theme now with
npm run build and then unzip the file inside the bundled folder. Open any PHP file where the
_themename placeholder may have been used and make sure it’s replaced with the actual theme name.
There is a gotcha to watch for that I noticed in the replace plugin as I was working with it. If there are ZIP files inside the theme (e.g. you are bundling WordPress plugins inside your theme), then they will get corrupted when they pass through the replace plugin. That can be resolved by ignoring ZIP files using a
gulp-if statement:
.pipe( gulpif( file => file.relative.split(".").pop() !== "zip", replace("_themename", info.name) ) )
Generating a POT file
Translation is a big thing in the WordPress community, so for our final task, we let’s scan through all of our PHP files and generate a POT file that gets used for translation. Luckily, we also have a gulp plugin for that:
npm install --save-dev gulp-wp-pot
And, of course, import it:
import wpPot from "gulp-wp-pot";
Here’s our final task:
export const pot = () => { return src("**/*.php") .pipe( wpPot({ domain: "_themename", package: info.name }) ) .pipe(dest(`languages/${info.name}.pot`)); };
We want the POT file to generate every time we build the theme:
export const build = series(clean, parallel(styles, images, copy, scripts), pot, compress);
Summing up
Here’s the complete Gulpfile, including all of the tasks we covered in this post:
import { src, dest, watch, series, parallel } from 'gulp'; import yargs from 'yargs'; import sass from 'gulp-sass'; import cleanCss from 'gulp-clean-css'; import gulpif from 'gulp-if'; import postcss from 'gulp-postcss'; import sourcemaps from 'gulp-sourcemaps'; import autoprefixer from 'autoprefixer'; import imagemin from 'gulp-imagemin'; import del from 'del'; import webpack from 'webpack-stream'; import named from 'vinyl-named'; import browserSync from "browser-sync"; import zip from "gulp-zip"; import info from "./package.json"; import replace from "gulp-replace"; import wpPot from "gulp-wp-pot"; const PRODUCTION = yargs.argv.prod; const server = browserSync.create(); export const serve = done => { server.init({ proxy: "" }); done(); }; export const reload = done => { server.reload(); done(); }; export const clean = () => del(['dist']);()); } export const images = () => { return src('src/images/**/*.{jpg,jpeg,png,svg,gif}') .pipe(gulpif(PRODUCTION, imagemin())) .pipe(dest('dist/images')); } export const copy = () => { return src(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*']) .pipe(dest('dist')); }')); } export const compress = () => { return src([ "**/*", "!node_modules{,/**}", "!bundled{,/**}", "!src{,/**}", "!.babelrc", "!.gitignore", "!gulpfile.babel.js", "!package.json", "!package-lock.json", ]) .pipe( gulpif( file => file.relative.split(".").pop() !== "zip", replace("_themename", info.name) ) ) .pipe(zip(`${info.name}.zip`)) .pipe(dest('bundled')); }; export const pot = () => { return src("**/*.php") .pipe( wpPot({ domain: "_themename", package: info.name }) ) .pipe(dest(`languages/${info.name}.pot`)); }; export const watchForChanges = () => { watch('src/scss/**/*.scss', styles); watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', series(images, reload)); watch(['src/**/*','!src/{images,js,scss}','!src/{images,js,scss}/**/*'], series(copy, reload)); watch('src/js/**/*.js', series(scripts, reload)); watch("**/*.php", reload); } export const dev = series(clean, parallel(styles, images, copy, scripts), serve, watchForChanges); export const build = series(clean, parallel(styles, images, copy, scripts), pot, compress); export default dev;
Phew, that’s everything! I hope you learned something from this series and that it helps streamline your WordPress development flow. Let me know if you have any questions in the comments. If you are interested in a complete WordPress theme development course, make sure to check out my course on Udemy with a special discount for you. 😀
Hi, this is very useful, do you have the files on github anywhere?
Hello, you can find most of it in this branch from my course’s repository here:
However I really recommend that you follow the article and type yourself. Good luck :)
There are some bugs with the
functions.phpfile. Plus without a proper
index.phpor
styles.cssfile demonstrating this does not work. First issue was with the source having
assetsin it should be
'/dist/js/bundle.js' also missing a closing?>`.
Yes I mentioned in the first article that I assume that you already have a WordPress theme with the necessary files (index.php, styles.css). And thanks for spotting the bug, I removed the ‘/assets’ but the closing tag is not necessary in this case.
After working through a bit more I think after you start talking about splitting JavaScript into pieces you walk through falls apart because you introduce an
admin.jsfile that does not exist. instead of the
admin.jsfile you should change it so that
slider.jsand
bundle.jsare not combined. Also if there are multiple JavaScript files will
functions.phpneed to be changed? To included the separate JavaScript files?
The idea of the admin.js is if you need to create another js bundle other than bundle.js, so in this case we will have 2 js bundles and thus you will have to modify functions.php to enqueue the second file. In this case enqueue admin.js just for the wp-admin panel.
Very nice and in-depth article.
One thing I’d change personally is that I would keep the root folder of the theme in a subfolder of the repo separating the theme and npm package root. The main (although not the only) reason for it is the performance of docker based environments on Mac OS and Windows, which really, really, REALLY don’t like mounting stuff like node modules as a volume. Such amount of files slows down read operation for such volume, even with :cached mode.
I am not sure if you completed the article but actually at the end we create a ZIP file for the theme with only the necessary files and folders; ignoring all the files & folders only used in development like the node_modules and so on. I am not sure but I think that will solve your problem.
Loving this in-depth tutorial thanks Ali! I made sure to copy the autoprefixer pipe in exactly, but the autoprefixing isn’t working for me. Everything else is so far (I’ve just finished adding the Watch Task. Any idea why the autoprefixer might not be working? I tried adding a display:grid; style rule as well as a transition style rule, but when I look in DevTools no -moz or -webkit etc. shows up.
Hi Zach, you can actually send me your theme folder if you don’t mind and I can take a look. My email is [email protected] :)
Hi !
Same problem here ;) I tried to add brackets after autoprefixer : .pipe(gulpif(PRODUCTION, postcss([ autoprefixer() ]))) because I’ve seen it in the post-css documentation, but it doesn’t work neither…
Do you remember what was the problem with Zack Miller ?
By the way, I learned a lot about Gulp thanks to this article, thank you very very much !
Hello Nicolas, you probably need to tell autoprefixer that you want to support old browsers. try this
.pipe(gulpif(PRODUCTION, postcss([ autoprefixer({ grid: true, browsers: [‘last 2 versions’, ‘ie 6-8’, ‘Firefox > 20’] }) ])))
Thanks a lot Ali, it works !
I even tried to get further by telling Autoprefixer to support old browsers in my package.json file, and it worked too…
Thanks again for your answer and help, and thanks for this article too ;)
Thanks Ali! I sent you an email with my theme folder.
What a perfectly timed article!!
While there are several excellent options, created by inspiring people, that we can simply download and activate, in my experience, unless you completely understand how these are put together you can become frustrated when something doesn’t work how you expect. I think you have to ( with research ) create your own process to truly understand this.
I was hoping to use a combination of Gulp and Webpack. A lot of documentation for Gulp is v3, and working with Webpack alone has its drawbacks when developing for WordPress. Your article is exactly what I was looking for.
I purchased your course on Udemy :-)
One addition I will make to this process is SVG sprites.
One question: Do we typically ignore the standard WordPress style.css file? In other words, just use it for the required header, but not enqueue it?
Hello Damian, Sorry for the late reply. For some reason I got the comment email in the spam. Anyways thanks a lot for your message :) I will try to look into the SVG thing when I have time. For your question, I personally keep the style.css just for the theme info and use my own CSS/SASS folder organization but of course the style.css can still be used it’s just my preference :)
Hi, this is awesome, but i have one confusion in prefix change Capital word. please explain it.
Hello Mominul, Which capital word do you mean? can you please clarify?
Hello, thanks for an incredible tutorial! I frankly didn’t really follow the tutorial, I just yarn installed the dependencies, copied over the gulp config and it works straight out of box for what I need – scss, es6 loader, minify, compress, build a zip file with the plugin.
I’ve been looking for this for a long time, thanks for this!
You are awesome!
Hi! If any of you have problems with this
npm install --save-dev gulp-sourcemaps gulp-postcss autoprefixertry installing
gulp-postcssat last
Thanks for the great article. Everything works great except for one thing. When I try to echo out that get_template_directory_uri() browsersync removes the http: from the returned url. So I get //localhost:3000/my/theme/directories instead of the expected Any ideas on how to fix this?
I doubt this is caused by browsersync. Does it work if you use the normal port?
Great article, I’ve learned a ton of things. Since I make mostly plugins I’m adapting it to fit my specific needs. There is just one thing that I’d like to do and it’s missing here. I want my final CSS file to have the extension .min.css. However, the file has always .css extension and I don’t find how pipe the output to change the file name like I do for the JS file. Can you please explain how to do that?
Hello, you can try piping gulp rename before dest:
Thank you very much! :)
Hello!
I tried your sample code with jQuery, doesn’t work.
I think, when you adding jquery into php functions, you have to write something like this:
wp_enqueue_script( ‘jquery’, ‘’, array(‘jquery’), ‘1.0.0’, true);
instead of:
wp_enqueue_script( ‘_themename-scripts’, get_template_directory_uri() . ‘/dist/js/bundle.js’, array(‘jquery’), ‘1.0.0’, true );
Maybe I don’t understand something?)
what exactly is not working? are there any specific errors?
Thank you for this tutorial, it has been extremely helpful in helping me understanding gulp 4 setup.
One question: How to you stop/pause the process when I need to work with git commits? For example I hit CTRL + C (Git Bash) to stop to merge git branch, this ends up running the watchforchanges and creates a new bundle.css file
I don’t understand, can you please clarify? you stop the process to merge a branch then you start the process again? what’s wrong with that exactly?
I’ve created a 1:1 installation using this code but for some reason, the watcher isn’t responding when I save my bundle.scss file. Do I need to amend a global Node or NPM config to get it to “listen”? I know that I have to add additional polling for Webpack, but can’t see any reference to this requirement here… Thanks for a great tutorial though!
Hello, it should work if you followed the tutorial. You must have some typo or something. If you can’t figure it out you can send me your folder and I can take a look.
After working through the code and ensuring that everything was up-to-date, I found out that the code worked fine on OSX but not on a Vagrant machine running Linux. () The solution was to change
to
Amazing. Starting my first WP theme and was looking to set up my env using Gulp. This was exactly what I was looking for. Thanks! | https://css-tricks.com/gulp-for-wordpress-creating-the-tasks/ | CC-MAIN-2020-10 | refinedweb | 6,616 | 65.01 |
Learning Resources for Software Engineering Students »
Authors: Vivek Lakshmanan
Concurrency is the ability to run several programs or several parts of a program out-of-order, in an interleaved fashion. Simply put, if a program is running concurrently, the processor will execute one part of the program, pause it, execute another part and repeat.
As such, Java Concurrency enables you to perform tasks using multi-threading in your code and therefore:
Do note that Concurrency often gets confused with Parallelism which is a different property altogether. Parallelism is where parts of the program are executed at the same time, for example, on a multi-core processor. This StackOverflow post explains this in much greater detail.
There are many tutorials that cover Java Concurrency in-depth, such as the Java tutorial by Oracle. Instead, this chapter will provide an overview and things to take note of.
First off, a process is simply a program in execution. It contains at least one thread and has it's own memory space.
A thread:
There are two ways to create a thread in Java:
Threadclass
Runnableinterface
After which, override the
run() method which contains the code that will be executed when the thread starts.
Depending on how you created the
Thread you can either create the class that extends the
Thread class or pass the class that implements the
Runnable interface into the
Thread constructor and then start it.
When deciding which method to use to create a
Thread, it is always advisable to implement the
Runnable interface as this results in composition which will allow your code to be more loosely coupled as compared to inheritance. Furthermore, you can extend another class if need be. Shown below are the two ways to create a
Thread.
Extending the
Thread class:
public class AnotherThread extends Thread { public void run() { System.out.println("This class extends the Thread class"); } }
Implemeting the
Runnable interface:
public class MyRunnable implements Runnable { public void run() { System.out.println("This class implements the Runnable interface"); } }
Do note that this is only for illustration and can be simplified using lambdas.
After creating and starting threads, you can carry out operations on them. There are several such operations you can use to manipulate threads:
try { Thread.sleep(1000); } catch (InterruptedException e){ // handle interruption }
try { thread2.join(); } catch (InterruptedException e) { // handle interruption }
Since threads share the resources of the process they exist in, there will inevitably be conflicts when using shared resources due to the unpredictable nature of threads. When threads try to write to the same resource, thread interference occurs. To illustrate this problem, here's a sequence of execution for two threads, A and B, that increment and decrement a counter variable respectively:
Without thread interference, the expected value of the counter variable would be 0, since one thread increments it while the other decrements it. But with thread interference, the value of counter is simply the value written by the last thread. This is due to the unpredictable nature of threads as there is no way to know when the operating system switches between the two threads.
To solve this issue of interference, the keyword
synchronized is used to ensure that method or block of code can only be accessed by one thread at a time. This is done through the use of the intrinsic lock system, a mechanism put in place by Java to control access to a shared resource. Simply put, each object has it's own intrinsic lock which:
This can be illustrated by the following image where once Thread 2 (T2) acquires the lock for the synchronized block of code, the other two threads (T1 and T3) must wait for the synchronized block of code to release it's lock once T2 to complete its execution:
For a deeper look, see the Java Synchronisation section.
While it is easy to create one or two threads and run them, it becomes a problem when your application requires creating 20 or 30 threads for running tasks concurrently. This is where the
Executors class comes in. It helps you with:
Thread Creation
It provides various methods for creating threads, more specifically a pool of threads, to run tasks concurrently.
Thread Management
It manages the life cycle of the threads in the thread pool. You don’t need to worry about whether the threads in the thread pool are active, busy or dead before submitting a task for execution.
Task submission and execution
It provides methods for submitting tasks for execution in the thread pool, and also allows you to decide when the tasks will be executed. For example, a task can be submitted to be executed instantly, scheduled to be executed later or even executed periodically. Tasks are submitted to a thread pool via an internal queue called the
Blocking Queue. If there are more tasks than the number of active threads, they are queued until a thread becomes available. New tasks are rejected if the blocking queue is full.
The
Executors class provides convenient factory methods for creating the
ExecutorService class. This class manages the lifecycle of tasks in various ways by assigning a
ThreadPool to it. Different thread pools manage tasks in different ways along with their own advantages and disadvantages. Some of these include:
CachedThreadPool - Creates new threads as they are needed. This would prove useful for short-lived tasks but otherwise would be resource intensive as it would create too many threads.
FixedThreadPool - A thread pool with a fixed number of threads. If all threads are active when a new task is submitted, they will be queued until a thread becomes available. This can come in handy when you know exactly how many threads you need, though that may be tricky by itself.
ThreadPoolExecutor - This thread pool implementation adds the ability to configure parameters such as the maximum number of threads it can hold and how long to keep extra threads alive.
Shown below is an image to illustrate how
ExecutorService and
ThreadPools are connected (Do note that the
Executor is not in the image as it creates the
ExecutorService):
A simple example of using the
Executors class is shown below where after passing in the task to be executed, it is automatically managed by the
ExecutorService. For a more detailed look at the workflow of the
ExecutorService, see this in-depth tutorial.
ExecutorService executor = Executors.newFixedThreadPool(10); executor.execute(() -> { System.out.println("Hello from: " + Thread.currentThread().getName()); }); executor.shutdown(); // Remember to shutdown the thread.
And the corresponding output would be
Hello from: pool-1-thread-1.
As the saying goes, there is no free lunch. While concurrency provides great benefits as mentioned above, it does come with several issues such as:
Singletondesign pattern:
Concurrent implementation where you have to ensure that thread interference does not happen
public class Singleton{ private static Singleton singleton; // Create a lock so only one thread can access this object at a time. private static final Lock lock = new ReentrantLock(); private Singleton() { //... } public static Singleton getSingleton() { // This thread has acquired this object, so lock to ensure other threads don't interfere. lock.lock(); try { if (singleton == null) { singleton = new Singleton(); } } finally { // Release lock once you're done so others can access this object. lock.unlock(); } return singleton; } }
Vs the usual implementation
public class Singleton { private static Singleton singleton; private Singleton() { //... } public static Singleton getSingleton() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
Harder debugging and testing process
The unpredictable nature of threads result in errors that can be hard to detect, reproduce and fix as these errors don't crop up consistently like normal errors do.
Context switching overhead
When a CPU switches from executing one thread to executing another, the CPU needs to save the state of the current thread, and load the state of the next thread to execute, making this process of context switching very expensive.
The following resources are the many in-depth tutorials that will help you get a better grasp of concurrency in Java.
The following resources are interesting reads for a deeper understanding. | https://se-education.org/learningresources/contents/java/JavaConcurrency.html | CC-MAIN-2019-26 | refinedweb | 1,339 | 50.57 |
NAME
kthread_start, kthread_shutdown, kthread_add, kthread_exit, kthread_resume, kthread_suspend, kthread_suspend_check -- kernel threads
SYNOPSIS
#include <sys/kthread.h> void kthread_start(const void *udata); void kthread_shutdown(void *arg, int howto); void kthread_exit(void); int kthread_resume(struct thread *td); int kthread_suspend(struct thread *td, int timo); void kthread_suspend_check(struct thread *td); #include <sys/unistd.h> int kthread_add(void (*func)(void *), void *arg, struct proc *procp, struct thread **newtdpp, int flags, int pages, const char *fmt, ...); int kproc_kthread_add(void (*func)(void *), void *arg, struct proc **procptr, struct thread **tdptr, int flags, int pages, char * procname, const char *fmt, ...);
DESCRIPTION
In FreeBSD 8.0, the older family of kthread_*(9) functions was renamed to be the kproc_*(9) family of functions, as they were previously misnamed and actually produced kernel processes. This new family of kthread_*(9) functions was added to produce real kernel threads. See the kproc(9) man page for more information on the renamed calls. Also note that the kproc_kthread_add(9) function appears in both pages as its functionality is split. The function kthread_start() is used to start ``internal'' daemons such as bufdaemon, pagedaemon, vmdaemon, and the syncer and is intended to be called from SYSINIT(9). The udata argument is actually a pointer to a struct kthread_desc which describes the kernel thread that should be created: struct kthread_desc { char *arg0; void (*func)(void); struct thread **global_threadpp; }; The structure members are used by kthread_start() as follows: arg0 String to be used for the name of the thread. This string will be copied into the td_name member of the new threads' struct thread. func The main function for this kernel thread to run. global_threadpp A pointer to a struct thread pointer that should be updated to point to the newly created thread's thread structure. If this variable is NULL, then it is ignored. The thread will be a subthread of proc0 (PID 0). The kthread_add() function is used to create a kernel thread. The new thread runs in kernel mode only. It is added to the process specified by the procp argument, or if that is NULL, to proc0. The func argument specifies the function that the thread should execute. The arg argument is an arbitrary pointer that is passed in as the only argument to func when it is called by the new thread. The newtdpp pointer points to a struct thread pointer that is to be updated to point to the newly created thread. If this argument is NULL, then it is ignored. The flags argument may be set to RFSTOPPED to leave the thread in a stopped state. The caller must call sched_add() to start the thread. td_name member of the new thread's struct thread. The kproc_kthread_add() function is much like the kthread_add() function above except that if the kproc does not already exist, it is created. This function is better documented in the kproc(9) manual page. The kthread_exit() function is used to terminate kernel threads. It should be called by the main function of the kernel thread rather than letting the main function return to its caller. The kthread_resume(), kthread_suspend(), and kthread_suspend_check() functions are used to suspend and resume a kernel thread. During the main loop of its execution, a kernel thread that wishes to allow itself to be suspended should call kthread_suspend_check() passing in curthread td argument points to the struct thread of the kernel thread to suspend or resume. For kthread_suspend(), the timo argument specifies a timeout to wait for the kernel thread to acknowledge the suspend request and suspend itself. The kthread_add(), kthread_resume(), and kthread_suspend() functions return zero on success and non-zero on failure.
EXAMPLES
This example demonstrates the use of a struct kthread_desc and the functions kthread_start(), kthread_shutdown(), and kthread_suspend_check() to run the bufdaemon process. static struct thread *bufdaemonthread; static struct kthread_desc buf_kp = { "bufdaemon", buf_daemon, &bufdaemonthread }; SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST, kthread_start, &buf_kp) static void buf_daemon() { ... /* * This process needs to be suspended prior to shutdown sync. */ EVENTHANDLER_REGISTER(shutdown_pre_sync, kthread_shutdown, bufdaemonthread, SHUTDOWN_PRI_LAST); ... for (;;) { kthread_suspend_check(bufdaemonthread); ... } }
ERRORS
The kthread_resume() and kthread_suspend() functions will fail if: [EINVAL] The td argument does not reference a kernel thread. The kthread_add() function will fail if: [ENOMEM] Memory for a thread's stack could not be allocated.
SEE ALSO
kproc(9), SYSINIT(9), wakeup(9)
HISTORY
The kthread_start() function first appeared in FreeBSD 2.2 where it created a whole process. It was converted to create threads in FreeBSD 8.0. The kthread_shutdown(), kthread_exit(), kthread_resume(), kthread_suspend(), and kthread_suspend_check() functions were introduced in FreeBSD 4.0 and were converted to threads in FreeBSD 8.0. The kthread_create() call was renamed to kthread_add() in FreeBSD 8.0. The old functionality of creating a kernel process was renamed to kproc_create(9). Prior to FreeBSD 5.0, the kthread_shutdown(), kthread_resume(), kthread_suspend(), and kthread_suspend_check() functions were named shutdown_kproc(), resume_kproc(), shutdown_kproc(), and kproc_suspend_loop(), respectively. | http://manpages.ubuntu.com/manpages/oneiric/man9/kthread.9freebsd.html | CC-MAIN-2015-40 | refinedweb | 797 | 55.84 |
update-manager -c -d DOESN'T work for going to Gutsy
Bug Description
Binary package hint: update-manager
Can reproduce by installing Fresh Install of Feisty Server Edition, then installing xubuntu-desktop, then trying to upgrade to Gutsy using this command: sudo update-manager -c -d and it will fail with some kind of error which I have pasted below.
sudo update-manager -c -d
warning: could not initiate dbus
extracting '/tmp/tmp1Pv9L5
authenticate '/tmp/tmp1Pv9L
As the second error suggests, file "/usr/lib/
I added "import os" at the top of that file and the update started.
(I still got the dbus problem, so I also added "import dbus" at the same file. Now I don't get either error.)
I'm trying to do the update now and hoping this will work...
I have the same problem on a fresh feisty VirtualBox install. I'll start it later and post the output but it's the same as the one posted above.
Update: OK, I've run the update.
The good news: it worked (but see below). I'm happily running Gutsy right now.
The bad news: it didn't work flawlessly. During the update there were several error messages. I did run a (probably unnecessary, perhaps harmful, and certainly lengthy) "dpkg-reconfigure -a -u", and a dist-update, and I had to pick the new kernel manually on boot. (Got me a bit of a scare the first time; I didn't notice the old kernel was running, and it had no network drivers...)
The other good news: it will probably work better for others. My system is a bit special: I've updated continuously from Dapper through Gutsy, and I always mess with configs and things, so it's very likely my system was a bit hard to update.
Same issue, used Bogdan Butnaru's fix (adding import os to /usr/lib/
Upgrading as of now. Hopefully turns out nicely. My feisty was dist-upgraded from edgy on this box. I didn't tweak too much so I'm hoping for a smooth upgrade :)
Same here on a up-to-date feisty install upgraded from edgy. No tweaks made in any config file. Seems like someone forgot to import os module
May I please ask why not one person has responded to this which will have some impact regarding it's fix or similar??? Why is this still in unconfirmed when other users have posted that they have the same problem? How does this bug thing work as this is the first I posted to help out with the Gutsy testing. Can anyone from the "bug team" or a "developer" please comment on how this works and or why there hasn't been at least a comment stating that this is being reviewed?
Thank you.
After applying this patch (derived from a comment by Bogdan), it seems to work, and I successfully upgraded.
Unixnewbie, please be patient. The developers in charge have been subscribed to this bug automatically. And as you can see, this bug is being worked on by the community. https:/
I've gone ahead and confirmed this as there's both a patch and several reports of replicating this bug.
i can confirm the problem
here is the bash output:
sudo update-manager -cdp
warning: could not initiate dbus
extracting '/tmp/tmpexgDC-
authenticate '/tmp/tmpexgDC-
Same problem seen here too.
I nominated this for feisty, since fixing it for gutsy doesn't really help too much -- if feisty is broken then I can't upgrade to gutsy!
Same here, but I get an ERROR window with the following text:
Error during update:
A problem occured during the update. This is usually some sort of network problem, please check your network connection and retry.
Failed to fetch http://
Failed to fetch http://
Failed to fetch http://
When the update manager is finally closed, I have a terminal with the following:
user@laptop:~$ sudo update-manager -c -d
warning: could not initiate dbus
extracting '/tmp/tmpQzkF9j
authenticate '/tmp/tmpQzkF9j
could not send the dbus Inhibit signal: global name 'dbus' is not defined
** (gutsy:10002): WARNING **: return value of custom widget handler was not a GtkWidget
/tmp/tmpQzkF9j/
self.
user@laptop:~$
I still have a problem with the update-manager. I also had the problem
global name 'dbus' is not defined
Following the instructions given above I added
import os
import dbus
to /usr/lib/
Now I get the error message
# update-manager -d
extracting '/tmp/tmpv8iqg6
authenticate '/tmp/tmpv8iqg6
could not send the dbus Inhibit signal: org.freedesktop
regards
adding import dbus and import os worked great for me. I'm now upgrading to gutsy.
Very much the same case here. ie same issue with dbus and the os.
Adding import os to the /usr/lib/
Please consider getting fixed fully
What version of update-manager and update-manager-core where you using?
Please run:
$ dpkg -l update-manager update-manager-core
Hi:
I can't upgrade I get to the same point as the other ppl. here is the result.
$ dpkg -l update-manager update-manager-core
Desired=
| Status=
|/ Err?=(none)
||/ Name Version Description
+++-===
ii update-manager 0.59.24 GNOME application that manages apt updates
ii update-manager 0.59.24 manage release upgrades
I have added the import dbus and import os, but still no luck the window of the actual upgrade appears but it only goes to the 1st step, and then it closes.
Guys:
If you are getting an error like this:
Error during update:
A problem occured during the update. This is usually some sort of network problem, please check your network connection and retry.
Failed to fetch http://
Failed to fetch http://
Failed to fetch http://
It's probably due to a setting that automatix made.
To fix it:
Open a terminal window, and do:
gksudo gedit /etc/apt/
then find the line that starts with:
and comment it out by adding a "#".
Then run update manager again. It should now work.
Gary
Same here, with a "normal" Feisty (without xubuntu or kubuntu). | https://bugs.launchpad.net/ubuntu/+source/update-manager/+bug/118862 | CC-MAIN-2015-27 | refinedweb | 1,015 | 62.48 |
Posts Tagged ‘WebForms’
Web…
<!-- Old Sample... <mvc:MyControl--> <!--!
Source Code
WebFormAccess.zip (Solution Files)
Previous Posts On WebControls In MVC
Here are some earlier posts messing around with this same concept — Admittedly, these are geared to using WebControls and the entire WebForms model._1<<.
Using.
The!
Using WebControls In ASP.NET MVC Views – Part 1
Check out my newest blog post about using WebControls inside of MVC (source code included)🙂
I always thought it would be interesting to be able to use WebControls within an MVC application. I’m sure that there is a lot of people that have invested a lot of time in developing custom WebControls that would hate to see them be thrown out just to use the newest framework from Microsoft.
If you think about it, using WebControls inside of MVC doesn’t seem to be that impossible of a goal. All we need to do it post back the ViewState and we’re good to go, right?
Well, as it turns out, it’s a little harder than I thought it might be. Over the next few weeks I’ll be discussing what I’ve tried and where I get. I’m really not even sure if it will end up working out, but here goes anyways.
Disclaimer: This post is the first in a series of experiments to see if bringing WebControls inline with MVC is even possible — the code in these posts do not work and are only for getting ideas and promoting discussion — basically, this code is crap. 🙂
Rendering The Control
I blogged awhile back about using WebControls inside an MVC application, but it covered only controls that didn’t need to postback to the server. Not really that much help but interesting to say the least. The basic idea was to simply create an extension method that performed the DataBind and Render event on the control and then spit out the HTML output to the page.
Unfortunately, there is a lot more to a WebControl than just the rendered output. You’ve got the entire page lifecycle that isn’t being processed anymore, no page level forms with unique IDs, missing your ViewState, on and on… Not looking so great at the moment.
The Plan
Have you ever used the BuildManager class? Its probably not the most commonly used class in .NET, but it has some interesting potential for what we’re wanting to do.
Let’s say for a moment that in the render event of the page we create a second page to host our control, process the page life-cycle and then dump the rendered content back into our page. Granted that won’t work for all of our controls, it might give us a point to start from. By using the BuildManager class we can load an instance of our host page and then process the request all from a helper method in MVC.
The Setup
Let’s hack out a few bits of code to get started. First, lets make a page in our Views directory and make some changes to the code behind.
[ControlLoader.aspx.cs]
//snip... namespace MvcTest.Views { public partial class ControlLoader : System.Web.UI.Page { //event to catch the formatted string public event Action<XDocument> ProcessOutput; //override the render event to send the string for processing protected override void Render(HtmlTextWriter writer) { XDocument document = null; using (StringWriter output = new StringWriter()) { using (HtmlTextWriter html = new HtmlTextWriter(output)) { base.Render(html); document = XDocument.Parse(output.ToString()); } } this.ProcessOutput(document); } } }
[ControlLoader.aspx]
<%@ Page <body> <form id="pf" runat="server" /> </body> </html>
So basically, we’re creating a page class that is going to raise an event that contains the rendered code as a parsed XDocument. With our output we’re now able to insert the relevant code into our MVC page.
Now let’s look at the code for our helper method.
//snip... namespace MvcTest { public static class RenderControlHelper { //renders a control and then attempts to perform the page //lifecycle using it ((WARNING: Doesn't work -- just experiment code)) public static void RenderControl(this HtmlHelper helper, Control control) { //load our control loader page ControlLoader page = (ControlLoader)BuildManager.CreateInstanceFromVirtualPath( "~/Views/ControlLoader.aspx", typeof(ControlLoader) ); //add the control to the page page.Init += (sender, e) => { page.Form.Controls.Add(control); }; //add our event to process the string after the render page.ProcessOutput += (output) => { //output any header stuff (trying to think of a better way) foreach (XElement element in output.XPathSelectElement("html/head").Elements()) { HttpContext.Current.Response.Write(element.ToString()); } //output any form stuff foreach (XElement element in output.XPathSelectElement("html/body/form").Elements()) { HttpContext.Current.Response.Write(element.ToString()); } }; //setup a separate context (maybe) HttpContext context = new HttpContext( HttpContext.Current.Request, HttpContext.Current.Response ); //process this request separately ((IHttpHandler)page).ProcessRequest(context); } } }
Our helper method is clearly a little more complicated, but the basic idea is to load a instance of a second page, insert the control into the page, render it and then output our content inline. There is probably several mistakes in the code above that needs to be sorted out (for example, do I need to make a new HttpContext or just use the current one), but those can be worked on later. For now, this method does exactly what we’re wanting.
Let’s actually try this out with a simple TextBox.
[Index.aspx]
<%@ Page TextBox box; //use this code to prepare our control void Page_Load(object sender, EventArgs args) { box = new TextBox(); box.Load += (s, e) => { box. <form method="post" > <% this.Html.RenderControl(box); %> </form> </asp:Content>
Okay, looks good – We want to see if our events are registering like we hoped so we add a
Load event to add a value to the page. When we load the page we see the following…
Whoa! Am I seeing this correctly? Did it work? We look at the HTML that is generated and we see what we were hoping to see.
<!--snip--> <form method="post" > <title></title><div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/<div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKeid+0CQKiwImNC/5nNKY1w+4g2ZcTRkCNUf9YR9ax" /> </div> </form> <!--snip-->
It’s ugly, but it’s what we we’re wanting to see — we can always come back later and do some cleanup. So what happens when we hit enter and post it back?
Ouch…
Back To The Drawing Board
I messed around with that error for a couple hours but couldn’t find anything that would make it go away. I tried turning off the ViewState encryption, hardcoding the encryption the keys, etc — no fix. I’m certainly not ready to give up on this idea, but for now it looks like I have to admit defeat. 🙂
If I understand correctly you can run WebForms pages side by side with MVC pages, so I may be trying to solve a non-existent problem.
What do you think? Is this a waste of time? Does it solve anything? Is there an easier way? | https://somewebguy.wordpress.com/tag/webforms/ | CC-MAIN-2017-17 | refinedweb | 1,162 | 62.68 |
.
r or rb Open file for reading.
w or wb Truncate to zero length or create file for writing.
a or ab Append; open or create file for writing at end-of-file.
r+ or rb+ or r+b Open file for update (reading and writing).
w+ or wb+ or w+b Truncate to zero length or create file for update.
a+ or ab+ or a+b Append; open or create file for update, writing at end-of-file.
The characterbshall have no effect, but is allowed for ISO C stan- dard conformance. Opening a file with read mode (r as the first char- acter in the mode argument) shall fail if the file does not exist or cannot be read.
Opening a file with append mode (a as the first character in the mode argument) shall cause oper- ation encounters end-of-file.
When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of- file indicators for the stream shall be cleared.
If mode is w, wb, a, ab, w+, wb+, w+b, a+, ab+, or a+b, and the file did not previously exist, upon successful completion, the fopen() func- tion shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent direc- tory.
If mode is w, wb, w+, wb+, or w+b, and the file did previously exist, upon successful completion, fopen() shall mark for update the st_ctime and st_mtime fields of the file. The fopen() function shall allocate a file descriptor as open() does.
After a successful call to the fopen() function, the orientation of the stream shall be cleared, the encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an initial fopen().
EISDIR The named file is a directory and mode requires write access.
ELOOP A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE {OPEN_MAX} file descriptors are currently open in the calling file- name fopen() function may fail if:
EINVAL The value of the mode argument is not valid.
ELOOP More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument..
The following sections are informative.
EXAMPLES Opening a File The following example tries to open the file named file for reading. The fopen() function returns a file pointer that is used in subsequent fgets() and fclose() calls. If the program cannot open the file, it just ignores it.
#include <stdio.h> ... FILE *fp; ... void rgrep(const char *file) { ... if ((fp = fopen(file, "r")) == NULL) return; ... }
APPLICATION USAGE None.
RATIONALE None.
FUTURE DIRECTIONS None.
SEE ALSO fclose(), fdopen(), freopen(),OPEN(3P) | https://man.linuxtool.net/centos6/u1/man/3p_fopen.html | CC-MAIN-2021-39 | refinedweb | 458 | 72.46 |
How do I automate database backups?
I would like to set up an automated action to make a backup of the database every 30 minutes. I think that I must define an server action with python code. I need help with python code. thank you in advance.
I would like to set up an automated action to make a backup of the database every 30 minutes. I think that I must define an server action with python code. I need help with python code. thank you in advance.
Alternatively, you can create a crontab to invoke a python script which does backup. refere following script
import os import time import subprocess dump_dir = '/home/openerp/db_backup' db_username = 'openerp' #db_password = '' db_names = ['DB_NAME'] for db_name in db_names: try: file_path = '' dumper = " -U %s --password -Z 9 -f %s -F c %s " # os.putenv('PGPASSWORD', db_password) bkp_file = '%s_%s.sql' % (db_name, time.strftime('%Y%m%d_%H_%M_%S')) # glob_list = glob.glob(dump_dir + db_name + '*' + '.pgdump') file_path = os.path.join(dump_dir, bkp_file) command = 'pg_dump' + dumper % (db_username, file_path, db_name) subprocess.call(command, shell=True) subprocess.call('gzip ' + file_path, shell=True) except: print "Couldn't backup database" % (db_name)
Thanks Arif!
Yes it works for version 7.0.
Thank you. Francesco I did bash sript and I run with crontab. I still have a little detail to be adjusted. I would like the file generated by crontab has a dynamic name for example: "namedatabase-date-hour-minute-seconde.dump". Is it possible?
On LINUX :
sudo mv path_to_the_script /etc/cron.hourly/
sudo chmod +x name_of_the_script.py
The crontab execute your script.py file for example every 5min after these commands in shell:
crontab -e
/5 * * * * /etc/cron.hourly/script.py
Press button F2 and Enter
use someting like namedatabase-$(date %H-%M-%S).dump. Look at man date for more options
Hi.
I working around this problem, and I waste a couple of time to find the solution. I use this module with a small problem, but this is works as well, the issue what is coming from the server time zone. (UTC) So if you want to test it under 6.1 (may 7.0 same) please setting the next schedule time according UTC, and it will be works. This time issue, is true not just this module, all of that what is use Openerp server as cron controller. I do not have a karma to share a link. (module name is : "db_backup_ept - Database Auto-Backup & Backup Auto-Transfer to FTP server")
Other case the backup is a bit painful under Linux, with cron. The automation of backup you need to store the database data in .pgpass according by this: you can find a good scripts at here: blog.ufsoft.org/2011/07/03/postgres-cron-backupsI want to avoid to store the db pass in cron script, because this is security hole.
Otherwise you can find some solution about Pgagent also, but I can't try it, because I didn't have a time for the trials.
Finally please never forget to test the restore. (I have a lot of problem with restore, under 9.1 from zip, now I can restore from plain text by psql command).
How to restore: psql NEW_DB_NAME -f SQL_FILE_NAME
You can use the module written by Tiny: auto_backup, works great! "name" : "Database Auto-Backup", "version" : "1.0", "author" : "Tiny", "website" : " "category" : "Generic Modules", "description": """The generic Open ERP Database Auto-Backup system enables the user to make configurations for the automatic backup of the database. User simply requires to specify host & port under IP Configuration & database(on specified host running at specified port) and backup directory(in which all the backups of the specified database will be stored) under Database Configuration.
Automatic backup for all such configured databases under this can then be scheduled as follows:
1) Go to Administration / Configuration / Scheduler / Scheduled Actions 2) Schedule new action(create a new record) 3) Set 'Object' to 'db.backup' and 'Function' to 'schedule_backup' under page 'Technical Data' 4) Set other values as per your preference""",
I use this cron script:
#!/bin/bash DIR=/var/backups/odoo DB=database_name rm $DIR/$DB*.tar sudo -u openerp pg_dump --format t --file "$DIR/$DB $(date --rfc-3339 seconds).tar" $DB
Put it into
/etc/cron.daily/ and give it execution permissions.
If you want to have more than one version of the database, you may put you own logic in the line
rm $DIR/$DB*.tar.
Access to our eLearning platform and experience all Odoo Apps through learning videos, use cases and quizzes.Test it now
Do you mean the OpenERP database? | https://www.odoo.com/forum/help-1/question/how-do-i-automate-database-backups-8899 | CC-MAIN-2019-30 | refinedweb | 766 | 67.76 |
WeTransfer-iOS-CI
Containing shared CI logic to quickly set up your repository with:
- Tests running for each pull request
- Danger reports for each pull request
Why should I use it?
What's in it for me? Well, quite a lot! With low effort to add it to your project.
- Integrate SwiftLint to lint source code and tests
- Integrate Fastlane to run tests for PRs
- Integrate Danger to automatically improve PR reviews
- Easily add automated releases based on tag-triggers
Danger features
Following is a list of features which are posted in a comment on PRs based on the submitted files.
- Warn for big PRs, containing more than 500 lines of code
- Warn for missing PR description
- Warn for missing updated tests
- Show code coverage of PR related files
- Show any failed tests
- Show all
warningsand
errorsin the project
All this is written in Swift and fully tested 🚀
Custom linting
These warnings are posted inline inside the PR, helping you to solve them easily.
- Check for
final classusage
overridemethods without adding logic
- Suggest
weakover
unowned
- Suggest
// MARK:usage for large files
This is an example comment. Note that
WeTransferBot will be replaced by your own bot. More info can be found here: Getting started with Danger.
How to integrate?
1: Add submodule
Add this repository as a submodule with the correct path
Submodules/WeTransfer-iOS-CI:
[submodule "Submodules/WeTransfer-iOS-CI"] path = Submodules/WeTransfer-iOS-CI url =
2: Create a fastlane file
Create a fastlane file which executes testing with code coverage enabled. Import the Fastfile from this repo and trigger the
validate_changes lane.
import "./../Submodules/WeTransfer-iOS-CI/Fastlane/Fastfile" desc "Run the tests and prepare for Danger" lane :test do |options| test_project( project_path: "YOUR_PROJECT_PATH/", project_name: "YOUR_PROJECT_NAME", scheme: "YOUR_PROJECT_SCHEME") end
3: Integrate SwiftLint in your project
Add a run script and use the common used SwiftLint script:
./Submodules/WeTransfer-iOS-CI/SwiftLint/swiftlint.sh
4: Make use of the shared Bitrise.yml workflows
The shared Bitrise.yml files make it really easy to integrate CI into open-source projects. It's been optimized using this blog post for caching and triggers like:
- Manage gems & brews
- Cache pulling
- Run fastlane for testing
- Run Danger from this repo
- Cache pushing
How to use this in your Bitrise configuration?
For Danger, you need to set the
DANGER_GITHUB_API_TOKEN in your Bitrise secrets.
Make sure your Bitrise.yml looks like this:
trigger_map: - pull_request_source_branch: "*" workflow: wetransfer_pr_testing workflows: wetransfer_pr_testing: steps: - activate-ssh-key: run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}' - git-clone: {} - script: title: Continue from WeTransfer-iOS-CI repo inputs: - content: |- #!/bin/bash set -ex bitrise run --config ./Bitrise/testing_bitrise.yml "${BITRISE_TRIGGERED_WORKFLOW_ID}"
Note: Don't change
wetransfer_pr_testing as this needs to match the Bitrise.yml file workflow.
5: Add automated releases based on tags
By making use of the Bitrise tag triggered builds we can automate the releases of open-source projects. The automation currently performs the following steps:
- Automatically fetch the changelog using the ChangelogProducer
- Create a GitHub release containing the changelog
- Update and push the podspec
- Update the
Changelog.mdwith the new changes
- Create a release branch and open a PR for those changes
How to use this in your Bitrise configuration?
As open-source projects are making use of HTTPS by default we need to force Bitrise to use SSH instead. Therefore, we need to add the SSH key manually to the secret environment variables with the key
SSH_RSA_PRIVATE_KEY. You can can read more about this here: How can I generate an SSH key pair?.
We also need to create a environment secret for CocoaPods trunk pushes with the key
COCOAPODS_TRUNK_TOKEN. How to do that is explained here: Automated CocoaPod releases with CI.
After all, you're secrets should look as follows:
After that, we need to add a new trigger for tags:
trigger_map: - pull_request_source_branch: "*" workflow: wetransfer_pr_testing - tag: "*" workflow: wetransfer_tag_releasing
And we need to add the new workflow:
wetransfer_tag_releasing: steps: - activate-ssh-key: run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}' - script: title: Force SSH inputs: - content: |- #!/usr/bin/env bash # As we work with submodules, make sure we use SSH for this config so we can push our PR later on. # See for more info: git config --global url."git@github.com:".insteadOf "" - git-clone: {} - script: title: Continue from WeTransfer-iOS-CI repo inputs: - content: |- #!/bin/bash set -ex bitrise run --config ./Submodules/WeTransfer-iOS-CI/Bitrise/tag_releasing_bitrise.yml "${BITRISE_TRIGGERED_WORKFLOW_ID}"
After that, you can simply create a new tag and the whole release process will be triggered! 🚀
License
WeTransfer-iOS-CI is available under the MIT license. See the LICENSE file for more info. | https://swiftpack.co/package/WeTransfer/WeTransfer-iOS-CI | CC-MAIN-2021-04 | refinedweb | 756 | 53.51 |
Basics of GPAW calculations¶
Atomization energy revisited¶
The below script calculates the total energies of H2O, H and O.
from __future__ import print_function from ase.build import molecule from gpaw import GPAW a = 8.0 h = 0.2 energies = {} resultfile = open('results-%.2f.txt' % h, 'w') for name in ['H2O', 'H', 'O']: system = molecule(name) system.set_cell((a, a, a)) system.center() calc = GPAW(h=h, txt='gpaw-%s-%.2f.txt' % (name, h)) if name == 'H' or name == 'O': calc.set(hund=True) system.set_calculator(calc) energy = system.get_potential_energy() energies[name] = energy print(name, energy, file=resultfile) e_atomization = energies['H2O'] - 2 * energies['H'] - energies['O'] print(e_atomization, file=resultfile)
Read the script and try to understand what it does. A few notes:
-
In most languages it is common to declare loops with integer counters. In Python, a
forloop always loops over elements of an iterable (in this case a list of the strings
H2O,
Hand
O). You can loop over integers, if desired, using
for x in range(17):.
-
The code in loops, if-statements and other code blocks is indented. The loop or if-statement stops when the lines are no longer indented. Thus, indentation determines control flow.
-
In this case we conveniently load the geometry from the G2 database of small molecules, using the
molecule()function from ASE.
-
By setting the
txtparameter, we specify a file where GPAW will save the calculation log.
-
The expression
'results-%.2f.txt' % hinserts the value of
hin place of the substitution code
%.2f(floating point number with 2 decimals). Thus the result file name evaluates to
results-0.20.txt. Similarly,
'gpaw-%s-%.2f.txt' % (name, h)evaluates to
gpaw-H2O-0.20.txtin the first loop iteration (
%sis a substitution code for a string).
-
The call to
openopens a file. The parameter
'w'signifies that the file is opened in write mode (deleting any previous file with that name!). The calculated energies are written to this file using a print statement. We could have chosen to just print the parameter as in the last exercise, but file handling will come in handy below.
Run the script. You can monitor the progress by opening one of the
log files (e.g.
gpaw.H2O.txt). The command
tail -f
filename can be used to view the output in real-time. The calculated
atomization energy can be found in the
results-0.20.txt file.
Parallelization¶
To speed things up, let us run the script using some more CPUs. The
actual GPAW calculation is coded to make proper use of these extra
CPUs, while the rest of the script (everything except
calc.get_potential_energy()) is actually going to be run
independently by each CPU. This matters little except when writing to
files. Each CPU will attempt to write to the same file, probably at
the same time, producing garbled data. We must therefore make sure
that only one process writes. ASE provides the handy
paropen() function for just that:
from ase.parallel import paropen ... resultfile = paropen('results-%.2f.txt' % h, 'w')
Apply the above modifications to the script and run it in parallel e.g. on four CPUs:
$ mpirun -np 4 gpaw-python script.py
Verify by checking the log file that GPAW is actually using multiple CPUs. The log file should reveal that the H2O calculation uses domain-decomposed with four domains, while the two atomic calculations should parallelize over the two spins and two domains.
Convergence checks¶
It is essential that the calculations use a sufficiently fine grid spacing, and that the cell is sufficiently large not to affect the result. For this reason, convergence with respect to these parameters should generally be checked. For now we shall only bother to check the grid spacings.
Modify the above script to include a loop over different grid spacings. For technical reasons, GPAW will always use a number of grid points divisible by four along each direction. Use a loop structure like:
for symbol in [...]: ... for ngridpoints in [24, 28, ...]: h = a / ngridpoints calc.set(h=h) energy = system.get_potential_energy() ...
The
set method can be used to change the parameters of a
calculator without creating a new one. Make sure that the numbers of
grid points are chosen to cover \(0.15<h<0.25\). While performing
this convergence check, the other parameters do not need to be
converged - you can reduce the cell size to e.g.
a = 6.0 to
improve performance. You may wish to run the calculation in parallel.
-
How do the total energies converge with respect to grid spacing?
-
How does the atomization energy converge?
Total energies (maybe surprisingly) do not drop as the grid is refined. This would be the case in plane-wave methods, where increase of the planewave cutoff strictly increases the quality of the basis. Grid-based methods rely on finite-difference stencils, where the gradient in one point is calculated from the surrounding points. This makes the grid strictly inequivalent to a basis, and thus not (necessarily) variational.
LCAO calculations¶
GPAW supports an alternative calculation mode, LCAO mode, which uses linear combinations of pre-calculated atomic orbitals to represent the wavefunctions. LCAO calculations are much faster for most systems, but also less precise.
Performing an LCAO calculation requires setting the
mode and
normally a
basis:
calc = GPAW(..., mode='lcao', basis='dzp', ...)
Here
dzp (“double-zeta polarized”) means two basis functions per
valence state plus a polarization function - a function corresponding
to the lowest unoccupied angular-momentum state on the atom. This
will use the standard basis sets distributed with GPAW. You can pick
out a smaller basis set using the special syntax
basis='sz(dzp)'.
This will pick out only one function per valence state
(“single-zeta”), making the calculation even faster but less precise.
Calculate the atomization energy of H2O using different basis sets. Instead of looping over grid spacing, use a loop over basis keywords:
for basis in ['sz(dzp)', 'szp(dzp)', 'dzp']: ... calc = GPAW(mode='lcao', basis=basis, ...)
Compare the calculated energies to those calculated in grid mode. Do the energies deviate a lot? What about the atomization energy? Is the energy variational with respect to the quality of the basis?
LCAO calculations do not in fact produce very precise binding energies (although these can be improved considerably by manually generating optimized basis functions) - however the method is well suited to calculate geometries, and for applications that require a small basis set, such as electron transport calculations.
Plane-wave calculations¶
For systems with small unit-cells, it can be much faster to expand the wave-functions in plane-waves. Try running a calculation for a water molecule with a plane-wave cutoff of 350 eV using this:
from gpaw import GPAW, PW calc = GPAW(mode=PW(350), ...)
Try to look at the text output and see if you can find the number of plane-waves used. | https://wiki.fysik.dtu.dk/gpaw/exercises/water/water.html | CC-MAIN-2020-05 | refinedweb | 1,144 | 58.69 |
Using data in a table in another org-file
Posted December 22, 2013 at 01:42 PM | categories: org-mode | tags:
Updated January 16, 2014 at 07:30 AM
I have found using tables in an org-file as data sources to code blocks very convenient for documenting work. A typical work flow might go like this:
- Use a code block to generate some data in an org-table.
- Use another code block to analyze the data.
For example, here is a code block that prints data in a table 1:
import numpy as np print '#+tblname: cos-data' print '| x | cos(x)|' print '|-' for x in np.linspace(0, 2*np.pi, 10): print '|{0}|{1}|'.format(x, np.cos(x))
Now, we use that table in a code block to plot the data. We do this by using some header arguments to the code block:
#+BEGIN_SRC python :var data=cos-data
Then we can use the
data variable inside the code block like this:
import numpy as np import matplotlib.pyplot as plt data = np.array(data) # data is a list coming in x = data[:, 0] y = data[:, 1] plt.plot(x, y) plt.xlabel('x') plt.ylabel('cos(x)') plt.savefig('images/cos-plot.png')
That is pretty awesome, but what if we have data in a table from another org-file? It turns out we can use it too. I have data for the sin(x) stored in a table called
sin-data in sin.org , which I now want to use. We can access that table like this in a header arg:
#+BEGIN_SRC python :var data=sin.org:sin-data
And now use the data variable just like before!
import numpy as np import matplotlib.pyplot as plt data = np.array(data) # data is a list coming in x = data[:, 0] y = data[:, 1] plt.plot(x, y) plt.xlabel('x') plt.ylabel('sin(x)') plt.savefig('images/sin-plot.png')
This is a powerful capability, as it allows you to pull data from other files into your current analysis. For example, the supporting information files from some of our recent publications have org-files embedded in them with data stored in org-tables. You could use that data in your own analysis without having to type it in yourself. The only thing you need to do is make sure each table in a document is uniquely named.
Special thanks to Eric Schulte for pointing out the syntax for using external tables!
Copyright (C) 2014 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.5c | https://kitchingroup.cheme.cmu.edu/blog/2013/12/22/Using-data-in-a-table-in-another-org-file/ | CC-MAIN-2021-31 | refinedweb | 436 | 66.33 |
Hi Oleg,Thanks for your comments, I'm still not convinced, however.On 6/26/07, Oleg Nesterov <oleg@tv-sign.ru> wrote:> On 06/26, Satyam Sharma wrote:> >> > Yes, why not embed a send_sig(SIGKILL) just before the wake_up_process()> > in kthread_stop() itself?>> Personally, I don't think we should do this.>> kthread_stop() doesn't always mean "kill this thread asap". Suppose that> CPU_DOWN does kthread_stop(workqueue->thread) but doesn't flush the queue> before that (we did so before 2.6.22 and perhaps we will do again). Now> work_struct->func() doing tcp_recvmsg() or wait_event_interruptible() fails,> but this is probably not that we want.[ Well, first of all, anybody who sends a possibly-blocking-foreverfunction like tcp_recvmsg() to a *workqueue* needs to get his headchecked. ]Anyway, I think _all_ usages of kthread_stop() in the kernel *do* wantthe thread to stop *right then*. After all, kthread_stop() doesn't evenreturn (gets blocked on wait_for_completion()) till it knows the targetkthread *has* exited completely.And if a workqueue is blocked on tcp_recvmsg() or skb_recv_datagram()or some such, I don't see how that flush_workqueue (if that is what youmeant) would succeed anyway (unless you do send the signal too),and we'll actually end up having a nice little situation on our hands ifwe make the mistake of calling flush_workqueue on such a wq.Note that the exact scenario you're talking about wouldn't mean thekthread getting killed before it's supposed to be stopped anyway.force_sig is not a synchronous wakeup, and also note that tcp_recvmsg()or skb_recv_datagram() etc will exit (and are supposed to exit) cleanly onseeing a signal.> > So could we have signals in _addition_ to kthread_stop_info and change> > kthread_should_stop() to check for both:> >> > kthread_stop_info.k == current && signal_pending(current)>> No, this can't work in general. Some kthreads do flush_signals/dequeue_signal,> so TIF_SIGPENDING can be lost anyway.Yup, I had thought of precisely this issue yesterday as well. The mental noteI made to myself was that the force_sig(SIGKILL) and wake_up_process() inkthread_stop() must be atomic so that the following race is not possible:Say:#1 -> thread that invokes kthread_stop()#2 -> kthread to be stopped, (may be) currently in wait_event_interruptible(), such that there is a bigger loop over the wait_event_interruptible() itself, which puts task back to sleep if this was a spurious wake up (if _not_ due to a signal).Thread #1 Thread #2========= ========= skb_recv_datagram() -> wait_for_packet() <sleeping>...force_sig(SIGKILL)<scheduled out> <wakes up, sees the pending signal, breaks out of wait_for_packet() and skb_recv_datagram() back out to our kthread code itself, but there we see that kthread_should_stop() is NOT yet true, we also see this spurious signal, flush it, and call skb_recv_datagram() all over again> ... skb_recv_datagram() -> wait_for_packet() <sleeping><scheduled in>kthread_stop() -> wake_up_process() <this time we don't even break out of the skb_recv_datagram() either, as no signals are pending any more>i.e. thread #2 still does not exit cleanly. The root of the problem is thatfunctions such as skb_recv_datagram() -> wait_for_packet() handle spuriouswakeups *internally* by themselves, so our kthread does not get a chance tocheck for kthread_should_stop().Of course, above race is true only for kthreads that do flush signals onseeing spurious ones periodically. If it did not, then skb_recv_datagram()called second time above would again have broken out because ofsignal_pending() and we wouldn't have gone back to sleep. But we have tobe on safer side and avoid races *irrespective* of what the kthread mightor might not do, so let's _not_ depend on _assumed kthread behaviour_.I suspect the above race be avoided by making force_sig() andwake_up_process() atomic in kthread_stop() itself, please correct meif I'm horribly wrong.> I personally think Jeff's idea to use force_sig() is right. kthread_create()> doesn't use CLONE_SIGHAND, so it is safe to change ->sighand->actionp[].>> (offtopic)>> cifs_mount:>> send_sig(SIGKILL,srvTcp->tsk,1);> tsk = srvTcp->tsk;> if(tsk)> kthread_stop(tsk);>> This "if(tsk)" looks wrong to me.I think it's bogus myself. [ Added linux-cifs-client@lists.samba.org to Cc: ]> Can srvTcp->tsk be NULL? If yes, send_sig()> is not safe. Can srvTcp->tsk become NULL after send_sig() ? If yes, this> check is racy, and kthread_stop() is not safe.That's again something the atomicity I proposed above could avoid?Please comment.Satyam-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 | https://lkml.org/lkml/2007/6/26/356 | CC-MAIN-2017-22 | refinedweb | 730 | 63.19 |
Raspberry tutorial series you will be able to do high profile projects by yourself. Check these for Getting Started with Raspberry Pi and Raspberry Pi Configuration.
We have discussed LED Blinky, Button Interfacing and PWM generation in previous tutorials. In this tutorial we will Control the Speed of a DC motor using Raspberry Pi and PWM technique. PWM (Pulse Width Modulation) is a method used for getting variable voltage out of constant power source. We have discussed about PWM in the previous tutorial.
There are 40 GPIO output pins in Raspberry Pi 2. But out of 40, only 26 GPIO pins (GPIO2 to GPIO27) can be programmed. Some of these pins perform some special functions. With special GPIO put aside, we have 17 GPIO remaining. To know more about GPIO pins, go through: LED Blinking with Raspberry Pi
Each of these 17 GPIO pin can deliver a maximum of 15mA. And the sum of currents from all GPIO Pins cannot exceed 50mA. So we can draw a maximum of 3mA in average from each of these GPIO pins. So one should not tamper with these things unless you know what you are doing.
There are +5V (Pin 2 & 4) and +3.3V (Pin 1 & 17) power output pins on the board for connecting other modules and sensors. This power rail is connected in parallel to processor power. So drawing High current from this power rail affects the Processor. There is a fuse on the PI board which will trip once you apply high load. You can draw 100mA safely from the +3.3V rail. We are talking about this here because; we are connecting the DC motor to +3.3V. With the power limit in mind, we can only connect low power motor here, if you want to drive high power motor, consider powering it from a separate power source. (3)
- Small DC Motor
- Buttons (2)
- 2N2222 Transistor
- 1N4007 Diode
- Capacitor- 1000uF
- Bread Board
Circuit Explanation:
As said earlier, we cannot draw more than 15mA from any GPIO pins and DC motor draws more than 15mA, so the PWM generated by Raspberry Pi cannot be fed to the DC motor directly. So if we connect the motor directly to PI for speed control, the board might get damaged permanently.
So we are going to use an NPN transistor (2N2222) as a switching device. This transistor here drives the high power DC motor by taking PWM signal from PI. Here one should pay attention that wrongly connecting the transistor might load the board heavily.
The motor is an induction and so while switching the motor, we experience inductive spiking. This spiking will heat up the transistor heavily, so we will be using Diode (1N4007) to provide protection to transistor against Inductive Spiking.
In order to reduce the voltage fluctuations, we will be connecting a 1000uF capacitor across the power supply as shown in the Circuit Diagram.
Working 35’ on the board is ‘GPIO19’. So we tell here either we are going to represent the pin here by ‘35’ or ‘19’.
IO.setmode (IO.BCM)
We are setting GPIO19 (or PIN35) as output pin. We will get PWM output from this pin.
IO.setup(19,IO.IN)
After setting the pin as output we need to setup the pin as PWM output pin,
p = IO.PWM(output channel , frequency of PWM signal)
The above command is for setting up the channel and also for setting up the frequency of the PWM signal. ‘p’ here is a variable it can be anything. We are using GPIO19 as the PWM output channel. ‘frequency of PWM signal’ has been chosen 100, as we don’t want to see LED blinking.
Below command is used to start PWM signal generation, ‘DUTYCYCLE’ is for setting the Turn On ratio, 0 means LED will be ON for 0% of time, 30 means LED will be ON for 30% of the time and 100 means completely ON.
p.start(DUTYCYCLE)
In case the Condition in the braces is true, the statements inside the loop will be executed once. So if the GPIO pin 26 goes low, then the statements inside the IF loop will be executed once. If the GPIO pin 26 does not goes low, then the statements inside the IF loop will not be executed.
if(IO.input(26) == False):
While 1: is used for infinity loop. With this command the statements inside this loop will be executed continuously.
We have all the commands needed to achieve the speed control with this.
After writing the program and executing it, all there is left is operating the control. We have two buttons connected to PI; one for incrementing the Duty Cycle of PWM signal and other for decrementing the Duty Cycle of PWM signal. By pressing one button the, speed of DC motor increases and by pressing the other button, the speed of DC motor decreases. With this we have achieved the DC Motor Speed Control by Raspberry Pi.
Also check:
import RPi.GPIO as IO # calling header file which helps us use GPIO’s of PI
import time # calling time to provide delays in program
IO.setwarnings(False) #do not show any warnings
x=0 #integer for storing the duty cycle value
IO.setmode (IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN35 as‘GPIO19’)
IO.setup(13,IO.OUT) # initialize GPIO13 as an output.
IO.setup(19,IO.IN) # initialize GPIO19 as an input.
IO.setup(26,IO.IN) # initialize GPIO26 as an input.
p = IO.PWM(13,100) #GPIO13 as PWM output, with 100Hz frequency
p.start(0) #generate PWM signal with 0% duty cycle
while 1: #execute loop forever
p.ChangeDutyCycle(x) #change duty cycle for changing the brightness of LED.
if(IO.input(26) == False): #if button1 is pressed
if(x<50):
x=x+1 #increment x by one if x<50
time.sleep(0.2) #sleep for 200ms
if(IO.input(19) == False): #if button2 is pressed
if(x>0):
x=x-1 #decrement x by one if x>0
time.sleep(0.2) #sleep for 200ms
Mar 18, 2017
Hi, can someone help me? I'm having trouble loading the code in the part of the while
Oct 28, 2017
hi sir..,
when am compiling the code i face many errrors in it
Oct 31, 2017
when am compiling the code i face many errrors in it
Dec 16, 2017
Hello, I have tested the circuit with two motors and a water pump, but the pump and motors will not run. I have changed the pin from BOARD 35 to BOARD 32 because of my current limitations. Is there a reason I might be doing this incorrectly?
Dec 19, 2017
What motor are you using? As you said current limitation should be the problem.. Try using a motor driver circuit
Sep 04, 2018
will this work on a raspberry pi 1 or 1 b+? if so what are the equivalent pins used in a 26 pin head?..thanks in advance.
Nov 15, 2019
Do I need the capacitor even if I change the stepper motor into a 5v fan?
Thanks | https://circuitdigest.com/microcontroller-projects/controlling-dc-motor-using-raspberry-pi | CC-MAIN-2020-50 | refinedweb | 1,192 | 73.17 |
As a developer, stack traces are one of the most common error types you’ll run into. Every developer makes mistakes, including you. When you make a mistake, your code will likely exit and print a weird-looking message called a stack trace.
But actually, a stack trace represents a path to a treasure, like a pirate map. It shows you the exact route your code traversed leading up to the point where your program printed an exception.
But, how do you read a stack trace? How does a stack trace help with troubleshooting your code? Let’s start with a comprehensive definition of a stack trace.
What Is a Stack Trace?
To put it simply, a stack trace represents a call stack at a certain point in time. To better understand what a call stack is, let’s dive a bit deeper into how programming languages work.
A stack is actually a data type that contains a collection of elements. The collection works as a last-in, first-out (LIFO) collection. Each element in this collection represents a function call in your code that contains logic.
Whenever a certain function call throws an error, you’ll have a collection of function calls that lead up to the call that caused the particular problem. This is due to the LIFO behavior of the collection that keeps track of underlying, previous function calls.
This also implies that a stack trace is printed top-down. The stack trace first prints the function call that caused the error and then prints the previous underlying calls that led up to the faulty call. Therefore, reading the first line of the stack trace shows you the exact function call that threw an error.
Now that you have a deeper understanding of how a stack trace works, let’s learn to read one.
How to Read a Stack Trace
Stack traces are constructed in a very similar way in most languages: they follow the LIFO stack approach. Let’s take a look at the Java stack trace below.
Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
The first line tells us the exact error that caused the program to print a stack trace. We see a NullPointerException, which is a common mistake for Java programmers. From the Java documentation, we note that a NullPointerException is thrown when an application attempts to use “null” in a case where an object is required.
Now we know the exact error that caused the program to exit. Next, let’s read the previous call stack. You see three lines that start with the word “at”. All three of those lines are part of the call stack.
The first line represents the function call where the error occurred. As we can see, the getTitle function of the Book class is the last executed call. Furthermore, the error occurred at line 16 in the Book class file.
The other calls represent previous calls that lead up to the getTitle function call. In other words, the code produced the following execution path:
- Start in main() function.
- Call getBookTitles() function in Author class at line 25.
- Call getTitle() function in Book class at line 16.
In some cases, you’ll experience chained exceptions in your stack trace. As you could have guessed, the stack trace shows you multiple exceptions that have occurred. Each individual exception is marked by the words “Caused by”.
The lowest “Caused by” statement is often the root cause, so that’s where you should look at first to understand the problem. Here’s an example stack trace that includes several “Caused by” clauses. As you can see, the root issue in this example is the database call
dbCall.
Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14) Caused by: com.example.ServiceException: Service level error at com.example.myproject.Service.serviceMethod(Service.java:15) ... 1 more Caused by: com.example.DatabaseException: Database level error at com.example.Database.dbCall(Database.java:39) at com.example.myproject.Service.serviceMethod(Service.java:13) ... 2 more
Hopefully, this information gives you a better understanding of how to approach a call stack. So, what’s a stack trace used for?
How to Use a Stack Trace
A stack trace is a valuable piece of information that can be used for debugging purposes. Whenever you encounter an error in your application, you want to be able to quickly debug the problem. Initially, developers should look in the application logs for the stack trace, because often, the stack trace tells you the exact line or function call that caused a problem.
It’s a very valuable piece of information for quickly resolving bugs because it points to the exact location where things went wrong.
In addition to telling you the exact line or function that caused a problem, a stack trace also tracks important metrics that monitor the health of your application. For example, if the average number of stack traces found in your logs increases, you know a bug has likely occurred. Furthermore, a low level of stack trace exceptions indicates that your application is in good health.
In short, stack traces and the type of errors they log can reveal various metrics related to your application as explained in the example.
Common Problems With Stack Traces and Third-Party Packages
Often, your projects will use many third-party code packages or libraries. This is a common approach for languages such as PHP or JavaScript. There is a rich ecosystem of packages maintained by the Open Source community.
In some cases, an error occurs when you send incorrect input to one of the third-party libraries you use. As you might expect, your program will print a stack trace of the function calls leading up to the problem.
However, now that you’re dealing with a third-party library, you’ll have to read many function calls before you recognize one associated with your code. In some cases, like when too many function calls happen within a third-party package, you may not even see any references to your code.
You can still try to debug your code by looking at where a particular package was used. However, if you use this particular package frequently throughout your code, debugging your application won’t be easy.
But there’s a solution to the third-party stack problem. Let’s check it out!
Solving the Third-Party Stack Trace Problem
Luckily, you can solve third-party stack trace problems by catching exceptions. A call to a third-party library may cause an exception, which will cause your program to print a stack trace containing function calls coming from within the third-party library. However, you can catch the exception in your code with the use of a try-catch statement, which is native to many programming languages such as Java or Node.js.
If you use a try-catch statement, the stack trace will start from the point where you included the try-catch logic. This presents you with a more actionable and readable stack trace that doesn’t traverse into third-party library’s function calls. It’s an effective and simple solution to make your stack traces easy to understand.
On top of that, when your program throws a Throwable instance, you can call the
getStackTrace() function on the instance to access the stack trace. You can then decide to print the stack trace to your terminal so you can collect the information for log analysis. Here’s a small example where we throw an exception and manually print the stack trace.
import java.io.*; class Sum { // Main Method public static void main(String[] args) throws Exception { try { // add positive numbers addPositiveNumbers(5, -5); } catch (Throwable e) { StackTraceElement[] stktrace = e.getStackTrace(); // print element of stktrace for (int i = 0; i < stktrace.length; i++) { System.out.println("Index " + i + " of stack trace contains = " + stktrace[i].toString()); } } } // method which adds two positive number public static void addPositiveNumbers(int a, int b) throws Exception { if (a < 0 || b < 0) { throw new Exception("Numbers are not Positive"); } else { System.out.println(a + b); } } }
The printed output will look like this.
Index 0 of stack trace contains = Sum.addPositiveNumbers(File.java:26) Index 1 of stack trace contains = Sum.main(File.java:6)
Next, let’s learn how log management and stack traces work together.
Log Management and Stack Traces
You might wonder what log management and stack traces have to do with each other, and actually, they’re very compatible.
It’s best practice for your DevOps team to implement a logging solution. Without an active logging solution, it’s much harder to read and search for stack traces. A logging solution provides you with an easy-to-use interface and better filtering capabilities.
A log management solution helps aggregate logs, index them, and make them searchable, all from a single interface. You can run advanced queries to find specific logs or stack trace information. This approach is much faster than using the CTRL+F key combination to look through your logs.
Conclusion
To summarize, we focused on the need for a logging solution to access stack traces and any other relevant information your application outputs. A stack trace is one of the most valuable pieces of information to help developers identify problems quickly.
Furthermore, a stack trace shows an exact execution path, providing context to developers trying to solve bugs. The first line in the call stack represents the last executed function call, so remember to always read a stack trace top-down. That first function call is responsible for throwing an exception.
Want to decrease your bug resolution time? Check out Scalyr’s log management solution. If you want to learn more about log formatting and best practices for logging, check out this log formatting article. | https://www.sentinelone.com/blog/stack-trace-what-is-it-and-how-does-it-help-you-debug/ | CC-MAIN-2022-21 | refinedweb | 1,690 | 65.52 |
: }
10: else
11: {
12: DoSomethingElse();
13: }
14: }
15: }
Look at lines 5 and 7, specifically. In this code, I’ve got a call being made to a dependency to check whether or not the dependency can handle whatever it is I want to send to it. If the dependency can handle it, I call another method on the same object, passing in the same parameter and expecting to be given a result of the processing.
This code bothers me, honestly, but I find myself constantly writing it. It appears to me, to be a violation of both the Tell, Don’t Ask and Don’t Repeat Yourself (DRY) principles. I don’t like how the class questions the dependency and then has it do something based on the response. This seems like a violation of Tell, Don’t Ask and is clearly falling back to simple procedural programming techniques. Then, having the same “anotherThing” variable passed into another method on the same dependency object seems like its violating DRY. Why should I have to pass the same thing to the same object twice?
Another example of this type of code can be found in my SOLID Principles presentation and sample code. In the Open Closed Principle, I create the following code:
1: public string GetMessageBody(string fileContents)
2: {
3: string messageBody = string.Empty;
4: foreach(IFileFormatReader formatReader in _formatReaders)
5: {
6: if (formatReader.CanHandle(fileContents))
7: {
8: messageBody = formatReader.GetMessageBody(fileContents);
9: }
10: }
11: return messageBody;
12: }
You can clearly see the same pattern with the CanHandle method on like 6 and the GetMessageBody method on line 8. For the same reasons, this code bothers me. It always has, but I’ve never done anything to correct it.
Is This A Violation Of Tell, Don’t Ask And/Or DRY?
Ultimately, that’s what I’m asking… are these code samples violating those principles? … and Why or Why Not? I would love to hear your opinion in the comments here or as your own blog post.
One Possible Solution
Assuming that this is a violation of those principles (and I’m all ears, listening for reasons why it is or is not), I have one solution that I’ve used a number of times for a similar scenario. Rather than having a method to check if the dependency can handle the data sent to it, just have one method that either processes the data or doesn’t, but tells you whether or not it did through the returned object.
1: public class Response<T>
2: {
3: public bool RequestWasHandled { get; private set; }
4: public T Data {get; private set;}
5: public Response(bool requestWasHandled, T data)
6: {
7: RequestWasHandled = requestWasHandled;
8: Data = data;
9: }
10: }
11:
12: public class TellDontAskCorrection
13: {
14: public void DoGoodThings()
15: {
16: var response = something.GetThatFromIt(anotherThing);
17: if (response.RequestWasHandled)
18: DoSomethingWithTheResponse(response.Data);
19: else
20: DoSomethingElse();
21: }
22: }
This works. I’ve used it a number of times in a number of different scenarios and it has helped clean up some ugly code in some places. There is still an if-then statement in the DoGoodThings method but that may not be avoidable and may not be an issue since the method calls in the two if-then parts are very different. I don’t think this is the solution to the problems, though. It’s only one possible solution that works in a few specific contexts.
Looking For Other Solutions
What are some of the patterns, practices and modeling techniques that you are using to prevent Tell, Don’t Ask and DRY violations? Not just for the scenario that I’ve shown here, but for any given scenario where you find yourself wanting to introduce procedural logic that should be encapsulated into the object being called. I would love to see examples of the code you are dealing with and the solutions to that scenario. Please share – here in the comments (please use Pastie or Github Gist or something else that formats the code nicely if you have more than a couple lines of code, though) or in your own blog, etc.
Get The Best JavaScript Secrets!
Get the trade secrets of JavaScript pros, and the insider info you need to advance your career!
Post Footer automatically generated by Add Post Footer Plugin for wordpress. | http://lostechies.com/derickbailey/2010/05/27/violations-of-the-tell-don-t-ask-and-don-t-repeat-yourself-principles/ | CC-MAIN-2014-15 | refinedweb | 724 | 61.06 |
i need to now how i can put the output from this code
for( int j = 0 ; j < start.length; j +=2 ) {
System.out.print( start[i] + " ");
into a new for loop.
Type: Posts; User: robingeldolf
i need to now how i can put the output from this code
for( int j = 0 ; j < start.length; j +=2 ) {
System.out.print( start[i] + " ");
into a new for loop.
i don't know how to remove something from an array, that the problem. And don't really see another approach
hi everyone, i have to make a java program that generates "lucky numbers" with arrays
The finishing result should be this
1 2 3 4 5 6 7 8 9 10 original
1 3 5 7 9 remove every second number...
the data in the string is used to create an amount of simulations. If the string is 100 the simulation has to run 100 times. But i want to make sure the users gives a number that is between 0 and...
ok i did what you said,but i still won't work.
I have to use the variables over 2 methods. So if i initialize them in the methods separately it doesn't work. Because it resets in each method. If i...
But i don't know what to do if i converted the string
Don't they have to be the same name, i'm adding them in 1 method,and printing them out in another method. I'm searching for a way to initialize them to zero every time they ask for a new simulation.
int i = Integer.parseInt(s);??
if i do that the input doesn't reset to zero if i want to run another simulation.If i run 5 simulations i will have 5 balls in the bottom,if i run a second simulation of 5 it wil add this to the...
i'm using the int type, i have to make sure any enter the users gives, not between 1 or 1000 gives the question again.
Is it a better way to use a string?And how do you compare al the numbers...
isn't there a way to repeat the loop so it keeps asking the amount of simulations that is required,the same way i did with the do while.
while ( aantalSimulaties <= 0 || 1000 <= aantalSimulaties...
do {
System.out.println("Hoeveel simulaties wil je uitvoeren?(minimaal 0,maximaal 1000)");
aantalSimulaties = Input.readInt();
}
while ( aantalSimulaties <= 0 || 1000 <= aantalSimulaties...
One more problem now, the loop has to repeat if the number isn't between 0 and 1000, but if the use enters a letter is has to loop aswell. How to do this without including the intire alphabet to the...
I have a project for java,i have to simulate the board of galton(Galton Board -- from Wolfram MathWorld).
My simulation code is ready but i'm having some final problems. I have to reset a value to...
if they press -1 or -12 is has to loop and if they press 1010 or 1020 it has the loop ,but you can only give one number at a time.
So better use the OR? Thanks for the help,my problem is solved....
I've changed it to tis but it still won't work.
public void keuzes2() {
do {
System.out.println("how many simulations do you ant to do(maximaal 1000)");
amountofsim = Input.readInt();...
else if(keuze.equals("2")) {
keuzes2();
AantalSim();
keuzes2a();
}
public void keuzes 2() {
do {
System.out.println("Hoeveel simulaties wil je uitvoeren?(maximaal...
do you mean like this
do {
System.out.println("Hoeveel simulaties wil je uitvoeren?(maximaal 1000)");
aantalSimulaties = Input.readInt();
for ( y = 0 ; y < aantalSimulaties ; y ++) {...
y <= number
thank you very much
if the input is 100, the loop has to be done 100 times but i don't think for is the right way.
i have to run SimulationThatHasToBeDoneXNumberOfTimes(); an amount of times==>that amount is chosen by...
i fixed it, thanks. used do while .
public class Bladsteenschaar6 {
final int blad = 0;
final int steen = 1;
final int schaar = 2;
int computer;
int keuzeSpeler;
...
public class Bladsteenschaar5 {
public void speel() {
final int BLAD = 0;
final int STEEN = 1;
final int SCHAAR = 2;
int keuzeSpeler = 0;
//...
hi, got a problem with my code i'm getting the following error
Bladsteenschaar5.java:39: illegal start of expression
public void speelde(){
^
Bladsteenschaar5.java:39: illegal start of... | http://www.javaprogrammingforums.com/search.php?s=a70e9dc748fcd285cf0312b4e3e1ea57&searchid=1813822 | CC-MAIN-2015-40 | refinedweb | 736 | 75.81 |
Parse JSP using BeautifulSoup
July 18, 2013 Leave a comment
I had to parse a tangle of JSP’s to identify how many HTML controls were calling JavaScript
functions that make AJAX calls back to the application.
So if a ‘key press’ event is fired when a user ‘tabs out’ or presses ‘Enter’ on a
textbox then I wanted the scan to find that.
<html:text</html:text>
My python skills are rudimentary but this code is able to scan and show a list of ‘html:text’ Struts tags. PyDev eclipse plugin comes in handy for python development.
The code can be further enhanced for more complex scans which I plan to do.
from bs4 import BeautifulSoup import fnmatch import sys import re import os import glob class Parse: def __init__(self): print 'parsing' self.parse() #self.folderwalk() def parse(self): try: path = "D:\\path" for infile in glob.glob(os.path.join(path, "*.jsp")): markup = (infile) print markup soup = BeautifulSoup(open(markup, "r").read()) data=soup.findAll(re.compile('^html:text'),attrs={'onkeypress':re.compile('^keyPressEvents')}) for i in data: print i except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] print "Unexpected error:", markup # Not used at this time def folderwalk(self): rootdir = "D:\\path" folderlist =0, [] #Pattern to be matched includes = ['*.jsp'] try: for root, subFolders, files in os.walk(rootdir): for extensions in includes: for filename in fnmatch.filter(files, extensions): print filename #folderlist.append() except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error:", sys.exc_info()[0] if __name__ == '__main__': instance = Parse() | https://branetheory.org/2013/07/18/parse-jsp-using-beautifulsoup/ | CC-MAIN-2019-04 | refinedweb | 279 | 57.87 |
?
A couple of months ago the Programming Praxis website put up a challenge to find a sum inside an array of integers (the direct wording of the challenge can be found here) and since I’ve come up with my own solution, this little challenge has provided me with a lot of feedback.
Just to get some of the geeky stuff out of the way, here is the code I wrote for the problem:
import Data.Listimport Data.Maybe sumCheck :: Int -> [Int] -> [Int] -> Maybe (Int, Int)sumCheck _ [] _ = NothingsumCheck total (x:xs) ys = if total' == Nothing then sumCheck total xs ys else return (x, (ys !! ( fromJust total'))) where total' = (total - x) `elemIndex` ys
After I wrote it, I submitted my code to the Haskell-beginners email list asking for critiques and possible enhancements. Arlen Cuss contributed a slight improvement of my code:
sumCheck total (x:xs) ys =let diff = total - x in if diff `elem` ys then Just (x, diff) else sumCheck total xs ys
sums i as bs = [(x,y) | x <- as, y <- bs, x + y == i]
print $ sumCheck 5000 [1..10000] [1..10000]
sumCheck1: 238,668
sumCheck2: 238,504
sumCheck3: 358,016
(unit: byte)
Out of the three code snippets, my function was in the middle, speed-wise. But I think that it’s also really nice to see how much better it is than the regular addition method. It’s also nice to see how the little change made to my code can improve the overall speed of the function.
At the end of the day I take a little bit of pride in myself for coming up with an improved algorithm for this task on my own. I know that on a hardware level, subtraction takes more time than addition. But I get the improvements I get because I reduce the number of additions and comparisons I have to make in order for the function to be complete. I also estimate the worst case speed for my algorithm to be O(n), which isn’t too shabby.
When I started learning Haskell, one of the things I read on the internet was how the people who programmed it were helpful to one another. I was skeptical when I first read that, but I have to say that all of my doubt has been removed. And it is interactions like this that make me glad to participate in a community as helpful as this one.
Sorry I haven't written in a while. Been rather busy with life recently. I'm still planning on continuing my Tweet Dump series, and I will post that up soon. One of the reasons for the delay is because I'm learning the Colemak keyboard layout has slowed down my typing quite a lot this week.
Anyway, yesterday's Programming Praxis question goes,
For today’s exercise we return to the world of recreational mathematics with two exercises due to the Indian mathematician Dattaraya Ramchandra Kaprekar. First we compute Kaprekar chains:.
So here is the code I wrote and submitted to the comments section. I will happily admit (like I did in my comment) that my isKaprekar function is a modified version of one I saw in the comments here as it was cleaner than my first version and I wanted to try out the "int(s[:-sz] or 0)" expression)
#!/usr/bin/python3 import itertools def isKaprekar(number): square = str(number ** 2) numlen = len(str(number)) return number == int(square[:-numlen] or 0) + int(square[-numlen:]) def keprekar_chain(number): retlist = [number] if len(set(str(number))) > 2: while retlist[-1] != 6174: pers = [int(''.join(x)) for x in itertools.permutations(str(retlist[-1]))] retlist.append(max(pers) - min(pers)) return retlist else: return [] if __name__ == "__main__": print('Keprekar numbers from 1 to 1000:') print(*[x for x in range(1,1001) if isKaprekar(x)]) print('Longest chain between 1000 and 9999') kep_list = [] for x in range(1000,10000): tlist = keprekar_chain(x) kep_list.append((len(tlist), tlist)) print(sorted(kep_list, key= lambda x: x[0], reverse=True)[0])
That's all for now; more to show up once I can type at normal speeds again.
If you made it this far down into the article, hopefully you liked it enough to share it with your friends. Thanks if you do, I appreciate it. | http://scrollingtext.org/category/catagories/programming-praxis | CC-MAIN-2015-11 | refinedweb | 723 | 66.27 |
Here is a simple CUDA program in its entirety (saved in a file called bug1.cuda) (NUMTHREADS and NUMBLOCKS must both be even. They can be set using the -D option to nvcc):
#ifndef NUMTHREADS #define NUMTHREADS 32 #endif #ifndef NUMBLOCKS #define NUMBLOCKS 14 #endif #include <iostream> #include <cassert> #include <cstdlib> using namespace std; __global__ void leibniz(long int n, double *result){ int tid = threadIdx.x+blockIdx.x*blockDim.x; double ans=0; int step = blockDim.x*gridDim.x; for(long int i=tid; i < n; i+=step) ans += 4.0/(2.0*i+1.0); if(tid%2==1) ans = -ans; result[tid] = 1.0*ans; } int main(){ long int n = 1000*1000*1000; double *dresult, *result; cudaMalloc((void **)&dresult, NUMTHREADS*NUMBLOCKS*sizeof(double)); result = new double[NUMTHREADS*NUMBLOCKS]; leibniz<<<NUMBLOCKS, NUMTHREADS>>>(n, dresult); cudaMemcpy(result, dresult, NUMTHREADS*NUMBLOCKS*sizeof(double),cudaMemcpyDeviceToHost); double ans=0; for(int i=0; i < NUMBLOCKS*NUMTHREADS; i++) ans += result[i]; cout<<"leibniz partial sum = "<<ans<<endl; cout<<"result[0] = "<<result[0]<<endl; delete[] result; cudaFree(dresult); }
It is supposed to compute the n-th partial sum of the series 4 - 4/3 + 4/5 - … which is equal to pi. However when I run the program I get the following output.
OUTPUT 1:
[root@ip-10-17-160-40 bq-gpu]# a.out
leibniz partial sum = -2.08849e+148
result[0] = -1.45682e+144
This output is dead wrong. However, if I modify the program by replacing ans += 4.0/(2.0i+1.0) by ans += 1.0/(2.0i+1.0) and then result[tid] = 1.0tid by result[tid] = 4.0tid, I get the following output.
[root@ip-10-17-160-40 bq-gpu]# a.out
leibniz partial sum = 3.14159
result[0] = 4.00164
This output is correct.
What is going on? Here are some items that may help.
- The source file is compiled using the following command:
[root@ip-10-17-160-40 bq-gpu]# nvcc -arch=compute_20 -DNUMTHREADS=1024 bug1.cu
The machine is Tesla M2050 (verified using cudaGetDeviceProperties).
The operating system is:
[root@ip-10-17-160-40 bq-gpu]# cat /etc/issue
CentOS release 5.5 (Final)
Kernel \r on an \m
- I have included a part of the ptx for the buggy version (the one with 4.0/(2.0*i+1.0)):
$Lt_0_2562: //<loop> Loop body line 16, nesting depth: 1, estimated iterations: unknown .loc 27 17 0 cvt.rn.f64.s64 %fd2, %rd2; mov.f64 %fd3, 0d4010000000000000; // 4 add.f64 %fd4, %fd2, %fd2; mov.f64 %fd5, 0d3ff0000000000000; // 1 add.f64 %fd6, %fd4, %fd5; div.rn.f64 %fd7, %fd3, %fd6; add.f64 %fd1, %fd1, %fd7; cvt.s64.s32 %rd4, %r7; add.s64 %rd2, %rd4, %rd2; setp.lt.s64 %p2, %rd2, %rd3; @%p2 bra $Lt_0_2562;
It looks fine.
- If you have an M2050 machine, I would like to know if you can reproduce this behavior. If not, for $5 you can reproduce it using a GPU cluster on Amazon EC2. I have attached a zip folder that has the source, the ptx for the two cases, as well as the compilation command.
On EC2, there are two ways you can reproduce this behavior. First you can put nvcc on your path, set LD_LIBRARY_PATH appropriately, “yum install gcc-c++” to get c++ and then use the compilation commands.
Second, you can follow the instructions in README that ask you to update the kernel and install the device driver. The device driver installation gives an error about something glx missing, but goes through to completion. Then if you like you can run the CUDA toolkit installer (version 3.1).
It makes no difference which way you do it. The strange behavior will occur.
I would greatly appreciate help in resolving this issue. | https://forums.developer.nvidia.com/t/bug-in-basic-arithmetic-on-m2050/20002 | CC-MAIN-2020-40 | refinedweb | 624 | 69.99 |
I can’t cover all platforms so I will only focus on Android. It’s pretty much the same stuff for other platforms. The name of the game will be : “Adam Must Live” (yes, it’s an in progress game ;))
Unity CLI
So, you have a game that you want to build for the Android platform. Great! What’s next ? Command line arguments.
The first thing to do is to create a script that can be used to build the game without any user interaction and the Unity CLI is the perfect target for doing that. Create a folder named Editor in your Assets folder and add a new script named MyEditorScript.cs :
using System.IO; using System.Linq; using UnityEditor; public class MyEditorScript { public static void PerformBuild() { // Get all actives scenes var scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray(); var outputFile = "./Builds/Android/AdamMustLive.apk"; if (File.Exists(outputFile)) { File.Delete(outputFile); } var buildPlayerOptions = new BuildPlayerOptions { scenes = scenes, locationPathName = outputFile, target = BuildTarget.Android, options = BuildOptions.None }; BuildPipeline.BuildPlayer(buildPlayerOptions); } }
This static method can now be called be the CLI to build the game and generate the .apk file. We just need to run the command :
C:\Program Files\Unity\Hub\Editor\2018.1.1f1\Editor\Unity.exe -quit -batchmode -projectPath UNITY_PROJECT_PATH -executeMethod MyEditorScript.PerformBuild
We use the -batchmode to run Unity editor in a non-interactive mode (no user interaction will be required). The -quit option forces Unity to close himself when the task ends.
If you planned to install Unity on a machine hat don’t have a graphic card, you may need to add the parameter -nographics but some restrictions will be applied.
In the next post, we will see how to create a build definition with Visual Studio Online. | http://blog.lordinaire.fr/2018/06/build-and-deploy-your-unity-game-with-visual-studio-online-and-app-center-part-1/?shared=email&msg=fail | CC-MAIN-2018-34 | refinedweb | 300 | 59.4 |
This action might not be possible to undo. Are you sure you want to continue?
08/30/2011
text
original
i n J a v a
Programming in Java
P r o g r a m m i n g
C o n c u r r e n t
Doug Lea State University of New York at Oswego
dl@cs.oswego.edu
1
Topics
Concurrency
J a v a
Models, design forces, Java Designing objects for concurrency Immutability, locking, state dependence, containment, splitting Introducing concurrency into applications Autonomous loops, oneway messages, interactive messages, cancellation Concurrent application architectures Flow, parallelism, layering Libraries Using, building, and documenting reusable concurrent classes
2
C o n c u r r e n t
P r o g r a m m i n g
i n
About These Slides ...
J a v a
Some slides are based on joint presentations with David Holmes, Macquarie University, Sydney Australia. More extensive coverage of most topics can be found in the book
i n
P r o g r a m m i n g
Concurrent Programming in Java, Addison-Wesley
and the online supplement The printed slides contain much more material than can be covered in a tutorial. They include extra backgound, examples, and extensions. They are not always in presentation order. Java code examples often omit qualifiers, imports, etc for space reasons. Full versions of most examples are available from the CPJ online supplement. None of this material should be construed as official Sun information. Java is a trademark of Sun Microsystems, Inc.
3
C o n c u r r e n t
Concurrency
J a v a
Why? Availability Minimize response lag, maximize throughput Modelling Simulating autonomous objects, animation Parallelism Exploiting multiprocessors, overlapping I/O Protection Isolating activities in threads Why Not? Complexity Dealing with safety, liveness, composition Overhead Higher resource usage
4
C o n c u r r e n t
P r o g r a m m i n g
i n
database servers. programming development tools. JavaBeans. databases. GUIs • Concurrently handle events. decision support tools 5 C o n c u r r e n t P r o g r a m m i n g i n . . Server Daemons • Concurrently service multiple client requests Simulations • Concurrently simulate multiple real objects Common examples • Web browsers. web services.. screen updates Hosting foreign code • Concurrently run applets...Common Applications I/O-bound tasks J a v a • Concurrently access web pages. sockets ..
. . specialpurpose architectures. sockets. Parallel programming mainly deals with mapping software to multiple CPUs to improve performance.. memory. J a v a Concurrent programs might or might not: Operate across multiple CPUs symmetric multiprocessor (SMPs). displays.Concurrent Programming Concurrency is a conceptual property of software.. • Threads and related constructs run on any Java platform • This tutorial doesn’t dwell much on issues specific to parallelism and distribution. file descriptors.. . clusters. 6 . Distributed programming mainly deals with concurrent programs that do NOT share system resources. C o n c u r r e n t P r o g r a m m i n g i n Concurrent programming mainly deals with concepts and techniques that apply even if not parallel or distributed. Share access to resources objects.
.. modularity • But uses and extends efficient implementations 7 C o n c u r r e n t P r o g r a m m i n g i n . partly due to Java Concurrent OO programming differs from . Sequential OO programming • Adds focus on safety and liveness • But uses and extends common design patterns Single-threaded Event-based programming (as in GUIs) • Adds potential for multiple events occuring at same time • But uses and extends common messaging strategies Multithreaded systems programming • Adds encapsulation.Concurrent Object-Oriented Programming J a v a Concurrency has always been a part of OOP (since Simula67) • Not a factor in wide-scale embrace of OOP (late 1980s) • Recent re-emergence.
Object Models Models describe how to think about objects (formally or informally) J a v a Common features • Classes. Two main categories: • Active vs Passive • Concurrent models include features of both • Lead to uniquely concurrent OO design patterns 8 C o n c u r r e n t P r o g r a m m i n g i n . references. state. methods. identity. constraints • Encapsulation — Separation between the insides and outsides of objects Four basic computational operations • Accept a message • Update local state • Send a message • Create a new object Models differ in rules for these operations.
multicast channels.Active Object Models J a v a state. Other protocols can be layered on. Most actions are reactive responses to messages from objects • But actions may also be autonomous • But need not act on message immediately upon receiving it All messages are oneway. Many extensions and choices of detailed semantics • Asynchronous vs synchronous messaging. . queuing. preemption and internal concurrency.. acquaintances i n message trigger anAction { update state send a message make an object } P r o g r a m m i n g oneway Every object has a single thread of control (like a process) so can do only one thing at a time.. 9 C o n c u r r e n t .
only the single Program object is active J a v a • Passive objects serve as the program’s data State: program counter. Program is the JVM (interpretor) • Sequentially simulates the objects comprising the program • All internal communication based on procedure calls 10 . } a passive object State: instance vars Methods: byte codes other passive objects C o n c u r r e n t In single-threaded Java. object addresses i n P r o g r a m m i n g main trigger I/O Program interpret() { ..Passive Object Models In sequential programs..
Concurrent Object Models Mixtures of active and passive objects J a v a Normally many fewer threads than passive objects Dumber Active Objects • Can perform only one activity — in Java. ‘run()’ • Share most resources with other threads • Require scheduling in order to coexist Smarter Passive Objects • May simultaneously participate in multiple threads • Protect themselves from engaging in conflicting activities • Communicate with objects participating in other threads • Initiate and control new threads C o n c u r r e n t P r o g r a m m i n g i n 11 .
Hardware Mappings remote messages J a v a remote messages memory cells state of an object CPU Cache CPU Cache P r o g r a m m i n g i n state of an object Shared memory multiprocessing • All objects visible in same (virtual) machine • Can use procedural message passing • Usually many more threads than CPUs Remote message passing • Only access objects via Remote references or copying • Must marshal (serialize) messages Mixed models including database mediation (‘‘three tier’’) 12 C o n c u r r e n t .
But now applies to most applications Concurrency • Thread-objects interpret passive objects Networking and Distribution • Server-objects pass around resources Persistence and Databases • Database-objects manage states of ground objects Component Frameworks • Design tools build applications from JavaBeans. 13 C o n c u r r e n t P r o g r a m m i n g i n . Once considered an arcane systems design principle.Vertical Objects Most OO systems and applications operate at multiple levels J a v a Objects at each level manipulate. . manage. etc Layered Applications • Design patterns based on reflection. interpretation... and coordinate lower-level ground objects as resources.
neat tricks.Design Forces J a v a Three main aspects of concurrent OO design Policies & Protocol System-wide design rules Object structures Design patterns. workarounds P r o g r a m m i n g i n Four main kinds of forces that must be addressed at each level Safety Liveness — Integrity requirements — Progress requirements C o n c u r r e n t Efficiency — Performance requirements Reusability — Compositional requirements 14 . microarchitecture Coding techniques Idioms.
• Span multiple objects — focus on LIVENESS 15 C o n c u r r e n t .. scenarios. JavaBeans. aggregate components.. • May be grouped according to origin. . function. . transactions. threads. ... sessions. scripts.. ... monitors. remote RMI objects.Systems = Objects + Activities J a v a P r o g r a m m i n g i n Objects • ADTs. mobile computations. call chains. data flows. subsystems. workflows. business objects. role. use cases. • May be grouped according to structure. • Usable across multiple activities — focus on SAFETY Activities • Messages..
Safe Objects Perform method actions only when in consistent states J a v a method1 legal method2 method3 method4 Usually impossible to predict consequences of actions attempted when objects are in temporarily inconsistent states • Read/write and write/write conflicts • Invariant failures • Random-looking externally visible behavior Must balance with liveness goals • Clients want simultanous access to services 16 i n temp states transient ?? P r o g r a m m i n g legal temp C o n c u r r e n t .
a nonsense value 17 C o n c u r r e n t P r o g r a m m i n g i n . old Y-value • Draws at location that figure never was at Withdraw from bank account while it is the midst of a transfer • Could overdraw account • Could lose money A storage location is read in the midst of being written • Could result in reading some old bytes and some new bytes • Normally.State Inconsistency Examples J a v a A figure is drawn while it is in the midst of being moved • Could draw at new X-value.
but isn’t produced by another activity • Insufficient or unfairly scheduled resources • Failures and errors of various kinds 18 C o n c u r r e n t . message or condition that should be.Live Activities Every activity should progress toward completion J a v a • Every called method should eventually execute P r o g r a m m i n g i n Related to efficiency • Every called method should execute as soon as possible An activity might not complete if • An object does not accept a message • A method blocks waiting for an event.
Design Dualities
Two extreme approaches:
J a v a
Safety-first Ensure that each class is safe, then try to improve liveness as optimization measure. • Characteristic of topdown OO Design
Liveness-first Design live ground-level code, then try to layer on safety features such as locking and guarding. • Characteristic of multithreaded systems programming • Can result in buggy code full of races
C o n c u r r e n t
P r o g r a m m i n g
i n
• Can result in slow, deadlock-prone code
Effective, practical, middle-out approaches combine these. For example, iteratively improving initial designs to be safe and live across different contexts
19
Guaranteeing Safety
J a v a
“Nothing bad ever happens” Concurrent safety is an extended sense of type safety • Adds a temporal dimension • Not completely enforceable by compilers Low-level view • Bits are never misinterpreted • Protect against storage conflicts on memory cells — read/write and — write/write conflicts High-level view • Objects are accessible only when in consistent states • Objects must maintain state and representation invariants • Presents subclass obligations
20
C o n c u r r e n t
P r o g r a m m i n g
i n
Guaranteeing Liveness
“Something eventually happens”
J a v a
Availability • Avoiding unnecessary blocking Progress • Avoiding resource contention among activities • Avoiding deadlocks and lockouts • Avoiding unfair scheduling • Designing for fault tolerance, convergence, stability Citizenship • Minimizing computational demands of sets of activities Protection • Avoiding contention with other programs • Preventing denial of service attacks • Preventing stoppage by external agents
21
C o n c u r r e n t
P r o g r a m m i n g
i n
Concurrency and Efficiency
Concurrency can be expensive
J a v a
• Performance profiles may vary across platforms Resources • Threads, Locks, Monitors Computation • Construction, finalization overhead for resources • Synchronization, context switching, scheduling overhead Communication • Interaction overhead for threads mapped to different CPUs • Caching and locality effects Algorithmic efficiency • Cannot use some fast but unsafe sequential algorithms Paying for tunability and extensibility • Reduces opportunities to optimize for special cases
22
C o n c u r r e n t
P r o g r a m m i n g
i n
Concurrency and Reusability Added Complexity J a v a • More stringent correctness criteria than sequential code — Usually not automatically statically checkable • Nondeterminism impedes debuggability. understandability P r o g r a m m i n g i n Added Context Dependence (coupling) • Components only safe/live when used in intended contexts — Need for documentation • Can be difficult to extend via subclassing — “Inheritance anomalies” • Can be difficult to compose — Clashes among concurrency control techniques 23 C o n c u r r e n t .
J a v a Example design policy domains State-dependence What to do if a request logically cannot be performed Combat complexity • High-level design rules and architectural constraints avoid inconsistent case-by-case decisions • Policy choices are rarely ‘‘optimal’’.Reuse and Design Policies Think locally. Act globally. but often religiously believed in anyway. Maintain openness • Accommodate any component that obeys a given policy • Fail but don’t break if they do not obey policy 24 i n Service availability Constraints on concurrent access to methods Flow constraints Establishing message directionality and layering rules C o n c u r r e n t P r o g r a m m i n g .
refine them to essences • Analyze for safety. extensibility. efficiency.Three Approaches to Reusability Patterns J a v a Reusing design knowledge • Record best practices. etc • Provide recipes for construction Frameworks Reusing policies and protocols P r o g r a m m i n g i n • Create interfaces and classes that establish policy choices for a suite of applications • Provide utilities and support classes • Mainly use by creating application-dependent (sub)classes Libraries Reusing code C o n c u r r e n t • Create interfaces that apply in many contexts • Provide high-quality implementations • Allow others to create alternative implementations 25 . liveness.
etc) • C-based syntax Main differences from C++: • Run-time safety via Virtual Machine — No insecure low-level operations — Garbage collection • Entirely class-based: No globals • Relative simplicity: No multiple inheritance. Applets.Java Overview J a v a Core Java is a relatively small. etc • Object-based implementations of Array. boring object-oriented language Main differences from Smalltalk: • Static typing • Support for primitive data types (int. etc • Large predefined class library: AWT. float. etc 26 C o n c u r r e n t P r o g r a m m i n g i n . String. Class. net.
GC. verifiers java.. components... class loaders Safety: Libraries: Ubiquity: Virtual machine. .. transports P r o g r a m m i n g i n Extensibility: Subclassing. unicode. classes.Java Features Java solves some software development problems J a v a Packaging: Portability: Objects.. CORBA... . . 27 . packages Bytecodes. JDBC. interfaces. Domains. Serialization. .* packages Run almost anywhere C o n c u r r e n t But new challenges stem from new aspects of programming: Concurrency: Threads. locks. Security managers. Distribution: Persistence: Security: RMI..
protected. float.Basic Java Constructs Classes J a v a Descriptions of object features Instance variables Fields representing object state Methods Statics Constructors Interfaces Subclasses Inner classes Packages Visibility control Qualifiers Statements Exceptions Primitive types Encapsulated procedures Per-class variables and methods Operations performed upon object creation Sets of methods implemented by any class Single inheritance from class Object Classes within other classes and methods Namespaces for organizing sets of classes private. per-package Semantic control: final. etc Nearly the same as in C/C++ Throw/catch control upon failure byte. char. boolean 28 C o n c u r r e n t P r o g r a m m i n g i n . abstract. int. short. long. public.
} } public void paint(Graphics g) { for (int i = 0.awt. particles = new Particle[nparticles]. public class ParticleApplet extends Applet { public void init() { add(new ParticleCanvas(10)). } } class ParticleCanvas extends Canvas { Particle[] particles. for (int i = 0.draw(g).*.length. ++i) particles[i]. i < particles.applet. ParticleCanvas(int nparticles) { setSize(new Dimension(100. new Thread(particles[i]).length. } } // (needs lots of embellishing to look nice) 29 J a v a C o n c u r r e n t P r o g r a m m i n g i n .Particle Applet import java.*. ++i) { particles[i] = new Particle(this). import java.start(). 100)). i < particles.
random()*10).0. private Canvas canvas.0. ly. } public void run() { for(. y += (int) (((Math.sleep((int)(Math. canvas.Particle Class public class Particle implements Runnable { private int x = 0.random() .repaint(). } g.. } public void draw(Graphics g) { int lx. ly = y. public Particle(Canvas host) { canvas = host. synchronized (this) { lx = x.5) * 5). } } } } 30 J a v a C o n c u r r e n t P r o g r a m m i n g i n . 10. } synchronized void moveRandomly() { x += (int) (((Math.5) * 5).} catch (InterruptedException e) { return.) { moveRandomly(). try { Thread.random() . ly.drawRect(lx. y = 0. 10).
but not double and long • synchronized statement also ensures cache flush/reload • volatile keyword controls per-variable flush/reload C o n c u r r e n t P r o g r a m m i n g i n Monitor methods in class Object control suspension and resumption: • wait(). sleep. and Object references. wait(ms). notify(). short. } synchronized methods and blocks control atomicity via locks • Java automates local read/write atomicity of storage and access of values of type byte. etc • Very weak guarantees about control and scheduling • Each Thread is a member of a ThreadGroup that is used for access control and bookkeeping • Code executed in threads defined in classes implementing: interface Runnable { public void run().Java Concurrency Support Thread class represents state of an independent activity J a v a • Methods to start. char. int. float. notifyAll() 31 .
Class Thread Constructors J a v a Thread(Runnable r) constructs so run() calls r. or join P r o g r a m m i n g i n C o n c u r r e n t isInterrupted() returns interruption state getPriority() returns current scheduling priority setPriority(int priorityFromONEtoTEN) sets it Static methods that can only be applied to current thread currentThread() reveals current thread sleep(ms) interrupted() suspends for (at least) ms milliseconds returns and clears interruption status 32 . ThreadGroup placement Principal methods start() isAlive() join() interrupt() activates run() then returns to caller returns true if started but not stopped waits for termination (optional timeout) breaks out of wait. sleep.run() — Other versions allow names.
Designing Objects for Concurrency J a v a Patterns for safely representing and managing state Immutability • Avoiding interference by avoiding change Locking • Guaranteeing exclusive access State dependence • What to do when you can’t do anything Containment • Hiding internal objects Splitting • Separating independent aspects of objects and locks 33 C o n c u r r e n t P r o g r a m m i n g i n .
Immutability J a v a Synopsis • Avoid interference by avoiding change • Immutable objects never change state • Actions on immutable objects are always safe and live Applications • Objects representing values — Closed Abstract Data Types — Objects maintaining state representations for others — Whenever object identity does not matter • Objects providing stateless services • Pure functional programming style 34 C o n c u r r e n t P r o g r a m m i n g i n .
No liveness problems • The methods do not interact with any other objects. No concurrent protocol design 35 J a v a C o n c u r r e n t P r o g r a m m i n g i n . } } There are no special concurrency concerns: • There is no per-instance state No storage conflicts • No representational invariants No invariant failures • Any number of instances of addOne and/or addTwo can safely execute at the same time. There is no need to preclude this. } int addTwo(int i) { return i + 2.Stateless Service Objects class StatelessAdder { int addOne(int i) { return i + 1.
Point or other AWT graphical representation classes (A design error?) 36 C o n c u r r e n t P r o g r a m m i n g i n .awt.Freezing State upon Construction J a v a class ImmutableAdder { private final int offset_.awt.String • java.lang. } int add(int i) { return i + offset_. } } Still no safety or liveness concerns Java (blank) finals enforce most senses of immutablity • Don’t cover cases where objects eventually latch into values that they never change from Immutability is often used for closed Abstract Data Types in Java • java.Color • But not java.Integer • java. // blank final ImmutableAdder(int x) { offset_ = x.lang.
Relay(Server s) { delegate = s.serve(). } } i n Partial immutability element next element next element next Methods dealing with immutable aspects of state do not require locking class FixedList { // cells with fixed successors private final FixedList next.Applications of Immutability Immutable references to mutable objects J a v a delegate relay server P r o g r a m m i n g class Relay { private final Server delegate. // immutable FixedList(FixedList nxt) { next = nxt. } } 37 C o n c u r r e n t . } private Object elem = null. } synchronized void set(Object x) { elem = x. } FixedList successor() { return next. // mutable synchronized Object get() { return elem. } void serve() { delegate.
} P r o g r a m m i n g i n Locking is a simple message accept mechanism • Acquire object lock on entry to method.Locking J a v a client lock client host internal state action { . release on return Precludes storage conflicts and invariant failures • Can be used to guarantee atomicity of methods Introduces potential liveness failures • Deadlock. lockouts Applications • Fully synchronized (atomic) objects • Most other reusable objects with mutable state 38 C o n c u r r e n t ...
Synchronized Method Example J a v a class Location { private double x_. } } 39 C o n c u r r e n t P r o g r a m m i n g i n . } } synchronized void moveBy(double dx. } synchronized double x() { return x_. } double y() { synchronized (this) { return y_. double y) { x_ = x. y_ = y. y_ += dy. Location(double x. y_. double dy) { x_ += dx.
} } Java locks are reentrant • A thread hitting synchronized passes if the lock is free or it already possesses the lock.Java Locks Every Java Object possesses one lock J a v a • Manipulated only via synchronized keyword • Class objects contain a lock used to protect statics • Scalars like int are not Objects so can only be locked via their enclosing objects Synchronized can be either method or block qualifier synchronized void f() { body. else waits • Released after passing as many }’s as {’s for the lock — cannot forget to release lock Synchronized also has the side-effect of clearing locally cached values and forcing reloads from main storage 40 C o n c u r r e n t P r o g r a m m i n g i n . } is equivalent to: void f() { synchronized(this) { body.
++n. return n. public int next(){ // POST?: next is always even ++n.Storage Conflicts class Even { int n = 0. as long as all other methods accessing n are also synchronized 41 J a v a C o n c u r r e n t P r o g r a m m i n g i n . For example. } } Postcondition may fail due to storage conflicts. one possible execution trace when n starts off at 0 is: Thread 1 Thread 2 read 0 write 1 read 1 write 2 read 2 read 2 write 3 return 3 write 3 return 3 Declaring next method as synchronized precludes conflicting traces.
Locks and Caching Locking generates messages between threads and memory J a v a Lock acquisition forces reads from memory to thread cache Lock release forces writes of cached updates to memory memory cells CPU Cache unlock lock CPU Cache P r o g r a m m i n g i n C o n c u r r e n t state of object Without locking. there are NO promises about if and when caches will be flushed or reloaded Can lead to unsafe execution Can lead to nonsensical execution 42 .
should use synchronization-based constructions 43 C o n c u r r e n t P r o g r a m m i n g i n . just the reference itself. and release after update If not. — Instead.Memory Anomalies J a v a Should acquire lock before use of any field of any object. • volatile never usefully applies to reference variables — The referenced object is not necessarily loaded/ flushed. • Has very limited utility. the following are possible: • Seeing stale values that do not reflect recent updates • Seeing inconsistent states due to out-of-order writes during flushes from thread caches • Seeing incompletely initialized new objects Can declare volatile fields to force per-variable load/flush.
but not always live or efficient Only process one request at a time • All methods are locally sequential Accept new messages only when ready No other thread holds lock Not engaged in another activity return client host Ready P r o g r a m m i n g i n aMessage . • No public variables or other encapsulation violations • Methods must not suspend or infinitely loop • Re-establish consistent state after exceptions 44 ..Fully Synchronized Objects Objects of classes in which all methods are synchronized J a v a • Always safe... C o n c u r r e n t • But methods may make self-calls to other methods during same activity without blocking (due to reentrancy) Constraints • All methods must be synchronized: Java unsynchronized methods execute even when lock held. actions..
getValue() v = other.} synchronized void swapValue(Cell other) { long t = getValue(). other.Deadlock J a v a class Cell { private long value_. synchronized long getValue() { return value_.getValue().getValue() 45 C o n c u r r e n t P r o g r a m m i n g i n . Can deadlock in trace: thread1 thread2 enter cell1.swapValue t = getValue() v = other.} synchronized void setValue(long v) {value_ = v. long v = other.swapValue t = getValue() enter cell2. setValue(v).setValue(t). } } SwapValue is a transactional method.
hashCode()) { fst = other. if (fst.hashCode() > snd.value. void swapValue(Cell other) { if (other == this) return. snd = this.value = snd.value. fst.value = t. // order via hash codes Cell snd = other.Lock Precedence J a v a Can prevent deadlock in transactional methods via resourceordering based on Java hash codes (among other solutions) class Cell { long value. } } } } 46 C o n c u r r e n t P r o g r a m m i n g i n . snd. // alias check Cell fst = this. } synchronized(fst) { synchronized (snd) { long t = fst.
operation(). Helper helper.Holding Locks class Server { double state. public synchronized void svc() { state = illegalValue. } } Potential problems with holding locks during downstream calls Safety: Liveness: What if helper.operation causes deadlock? J a v a C o n c u r r e n t P r o g r a m m i n g i n Availability: Cannot accept new svc requests during helper op Rule of Thumb (with many variants and exceptions): Always lock when updating state Never lock when sending message Redesign methods to avoid holding locks during downstream calls.operation throws exceptions? What if helper. state = legalValue. helper. while still preserving safety and consistency 47 .
increment sz_ ....Synchronization of Accessor Methods J a v a class Queue { private int sz_ = 0. } // synch? } Should size() method be synchronized? Pro: • Prevents clients from obtaining stale cached values • Ensures that transient values are never returned — For example. // number of elements public synchronized void put(Object x) { // .. } public int size() { return sz_... } public synchronized Object take() { // ... if put temporarily set sz_ = -1 as flag Con: • What could a client ever do with this value anyway? Sync always needed for accessors of mutable reference variables 48 C o n c u r r e n t P r o g r a m m i n g i n . decrement sz_ .
private static Singleton ref = null. public static Singleton instance(){ synchronized(lock) { if (ref == null) ref = new Singleton(). public class Singleton { // lazy initialization private int a. } } } 49 C o n c u r r e n t P r o g r a m m i n g i n . Both static and instance methods of Singleton classes should use it.Locking and Singletons J a v a Every Java Class object has a lock. private Singleton(){ a = 1. return ref. } } public int getA() { synchronized(lock) { return a.} private static Class lock = Singleton. } } public void setA(int v){ synchronized(lock) { a = v.class.
. So must implement policies in action methods themselves. C o n c u r r e n t P r o g r a m m i n g i n state.State Dependence J a v a Two aspects of action control: • A message from a client • The internal state of the host Design Steps: • Choose policies for dealing with actions that can succeed only if object is in particular logical state • Design interfaces and protocols to reflect policy • Ensure objects able to assess state to implement policy There is not a separate accept mechanism in Java.. } policy control 50 . acquaintances message accept anAction { .
streams.Examples of State-Dependent Actions J a v a Operations on collections. databases • Remove an element from an empty queue Operations on objects maintaining constrained values • Withdraw money from an empty bank account Operations requiring resources • Print a file Operations requiring particular message orderings • Read an unopened file Operations on external controllers • Shift to reverse gear in a moving car 51 C o n c u r r e n t P r o g r a m m i n g i n .
check if succeeded.and post. then fail First initiate activity that will achieve right state C o n c u r r e n t P r o g r a m m i n g i n 52 . if not. roll back Keep trying until success Wait or retry for a while.Policies for State Dependent Actions Some policy choices for dealing with pre.conditions J a v a Blind action Inaction Balking Guarding Trying Retrying Timing out Planning Proceed anyway. no guarantee of outcome Ignore request if not in right state Fail (throw exception) if not in right state Suspend until in right state Proceed.
void dec(). // INV: MIN <= value() <= MAX // INIT: value() == MIN void inc().Interfaces and Policies Boring running example J a v a P r o g r a m m i n g i n interface BoundedCounter { static final long MIN = 0. } Interfaces alone cannot convey policy • But can suggest policy — For example. long value(). static final long MAX = 10. should inc throw exception? What kind? — Different methods can support different policies • But can use manual annotations — Declarative constraints form basis for implementation 53 // PRE: // PRE: value() < MAX value() > MIN C o n c u r r e n t .
.... so can be checked upon entry Exit immediately if not in right state • Throw exception or return special error value • Client is responsible for handling failure The simplest policy for fully synchronized objects P r o g r a m m i n g i n inRightState . actions. etc) • In concurrent contexts. return C o n c u r r e n t • Usable in both sequential and concurrent contexts — Often used in Collection classes (Vector.Balking Check state upon method entry J a v a client aMessage host !inRightState throw • Must not change state in course of checking it • Relevant state must be explicitly represented. so host must control 54 . the host must always take responsibility for entire check-act/check-fail sequence — Clients cannot preclude state changes between check and act.
dec(). ++count_.} synchronized void inc() throws Failure { if (count_ >= MAX) throw new Failure(). } } // .} } 55 C o n c u r r e n t P r o g r a m m i n g . } catch (Failure ignore) {} } void betterUsage(BalkingCounter c) { try { c. } catch (Failure ex) {cope().. --count_. void suspiciousUsage(BalkingCounter c) { if (c. } synchronized void dec() throws Failure { if (count_ <= MIN) throw new Failure().dec(). synchronized long value() { return count_.Balking Counter Example class Failure extends Exception { } J a v a i n class BalkingCounter { protected long count_ = MIN.MIN) try { c.value() > BalkingCounter..
public Vec(int cap) { data_=new Object[cap]. data_[size_++] = x.Collection Class Example J a v a class Vec { // scaled down version of Vector protected Object[] data_.length) resize(). protected int size_=0. } public synchronized Object at(int i) throws NoSuchElementException { if (i < 0 || i >= size_ ) throw new NoSuchElementException(). data_[--size_] = null. } public synchronized void append(Object x) { if (size_ >= data_. } public synchronized void removeLast() throws NoSuchElementException { if (size_ == 0) throw new NoSuchElementException(). return data_[i]. } public int size() { return size_. } } 56 C o n c u r r e n t P r o g r a m m i n g i n .
Implement via version numbers updated on each change — Used in JDK1. Or conversely. • But can be expensive Indexed traversal • Clients externally synchronize when necessary • But coupled to particular locking policies Synchronized aggregate methods • Support apply-to-all methods in collection class • But deadlock-prone 57 C o n c u r r e n t P r o g r a m m i n g i n .2 collections • But can be hard to recover from exceptions Snapshot iterators • Make immutable copy of base collection elements. copy-on-write during each update.Policies for Collection Traversal How to apply operation to collection elements without interference J a v a Balking iterators • Throw exception on access if collection was changed.
} void printAllV2(XVec v) { // client-side synch synchronized (v) { for (int i = 0. ++i) System.Synchronized Traversal Examples J a v a interface Procedure { void apply(Object obj).println(x). } class XVec extends Vec { synchronized void applyToAll(Procedure p) { for (int i=0.++i) p. i < v.apply(data_[i]).out. } } } 58 C o n c u r r e n t P r o g r a m m i n g i n .out.applyToAll(new Procedure() { public void apply(Object x) { System.size(). } } class App { void printAllV1(XVec v) { // aggregate synch v.at(i)). }}).i<size_.println(v.
.. 59 .. actions. wait • Some other action in some other thread may eventually cause a state change that enables resumption Introduces liveness concerns • Relies on actions of other threads to make progress • Useless in sequential programs return client aMessage host inRightState C o n c u r r e n t ..Guarding Generalization of locking for state-dependent actions J a v a • Locked: • Guarded: Wait until ready (not engaged in other methods) Wait until an arbitrary state predicate holds i n P r o g r a m m i n g Check state upon entry • If not in right state.
long value() { return count_. } void dec() { while (count_ <= MIN). they never become false • You are sure that threads are running on multiple CPUs — Java doesn’t provide a way to determine or control this 60 . // spin ++count_. } void inc() { while (count_ >= MAX). // spin --count_.Guarding via Busy Waits J a v a class UnsafeSpinningBoundedCounter { // don’t use protected volatile long count_ = MIN. } } Unsafe — no protection from read/write conflicts C o n c u r r e n t P r o g r a m m i n g i n Wasteful — consumes CPU time But busy waiting can sometimes be useful. generally when • The conditions latch — once set true.
--count_. } synchronized void inc() throws InterruptedException { while (count_ >= MAX) wait(). notifyAll().Guarding via Suspension J a v a class GuardedBoundedCounter { protected long count_ = MIN. synchronized long value() { return count_. } } Each wait relies on a balancing notification • Generates programmer obligations Must recheck condition upon resumption 61 C o n c u r r e n t P r o g r a m m i n g i n . notifyAll(). ++count_. } synchronized void dec() throws InterruptedException { while (count_ <= MIN) wait().
join) to abort. that can only be invoked under synchronization of target wait() • Suspends thread • Thread is placed in wait set for target object • Synch lock for target is released notify() • If one exists.interrupt causes a wait (also sleep. Same as notify except thread resumed at the associated catch 62 C o n c u r r e n t P r o g r a m m i n g i n . any thread T is chosen from target’s wait set • T must re-acquire synch lock for target • T resumes at wait point notifyAll() is same as notify() except all threads chosen wait(ms)is same as wait() except thread is automatically notified after ms milliseconds if not already notified Thread.Java Monitor Methods Every Java Object has a wait set J a v a • Accessed only via monitor methods.
} } One possible trace for three threads accessing instance x: T1 T2 T3 enter x. after(). after(). enter x.Monitors and Wait Sets class X { synchronized void w() { before().n() notifyAll().w() before(). release lock wait().w() wait(). } synchronized void n() { notifyAll(). release lock after(). enter x. wait(). acquire lock acquire lock J a v a C o n c u r r e n t P r o g r a m m i n g i n x T1 T2 waitset 63 . before().
wait exitAcquire Acquiring Lock + Interrupted interrupt enterAcquire Running + interrupted interrupt 64 . force to exit wait and throw InterruptedException upon resumption notify.Interactions with Interruption J a v a Effect of Thread. timeout.interrupt(): • If thread not waiting. set the isInterrupted() bit • If thread is waiting. interrupt P r o g r a m m i n g i n Acquiring Lock exitAcquire Running wait Waiting enterAcquire C o n c u r r e n t Interrupt Interrupt Thread.interrupted. notifyAll.
(Many variants of definition) Threads waiting for lock eventually enter when lock free Guarded wait loops eventually unblock when condition true Usually implemented via First-in-First-Out scheduling policies • FIFO lock and wait queues • Sometimes.Fairness in Java Fairness is a system-wide progress property: J a v a Each blocked activity will eventually continue when its enabling condition holds. along with preemptive time-slicing Java does not guarantee fairness • Potential starvation — A thread never gets a chance to continue because other threads are continually placed before it in queue • FIFO usually not strictly implementable on SMPs • But JVM implementations usually approximate fairness • Manual techniques available to improve fairness properties 65 C o n c u r r e n t P r o g r a m m i n g i n .
network disconnects But cannot be used for high-precision timing or deadlines • Time can elapse between wait and thread resumption Java implementation constraints • wait(ms)does not automatically tell you if it returns because of notification vs timeout • Must check for both.Timeouts Intermediate points between balking and guarding J a v a • Can vary timeout parameter from zero to infinity Useful for heuristic detection of failures • Deadlocks. crashes. I/O problems. Order and style of checking can matter. depending on — If always OK to proceed when condition holds — If timeouts signify errors 66 C o n c u r r e n t P r o g r a m m i n g i n .
currentTimeMillis(). // .) { if (waitTime <= 0) throw new Failure(). } catch (InterruptedException e) { throw new Failure(). for (..currentTimeMillis(). synchronized void inc() throws Failure { if (count_ >= MAX) { long start = System. long waitTime = TIMEOUT. try { wait(waitTime). long now = System. } synchronized void dec() throws Failure. } } ++count_. notifyAll().start)..(now . } if (count_ < MAX) break.//similar } 67 J a v a C o n c u r r e n t P r o g r a m m i n g i n ..Timeout Example class TimeOutBoundedCounter { protected long TIMEOUT = 5000. waitTime = TIMEOUT .
} protected void doPut(Object x){ // mechanics data_[putPtr_] = x. } 68 J a v a C o n c u r r e n t P r o g r a m m i n g i n . data_[takePtr_] = null. notifyAll(). ++size_. return x.} boolean isEmpty(){ return size_ == 0. } protected Object doTake() { // mechanics Object x = data_[takePtr_]. BoundedBuffer(int capacity) { data_ = new Object[capacity].Buffer Supporting Multiple Policies class BoundedBuffer { Object[] data_.length.length. takePtr_ = (takePtr_ + 1) % data_. } boolean isFull(){ return size_ == data_. size_ = 0. putPtr_ = (putPtr_ + 1) % data_. int putPtr_ = 0.length. takePtr_ = 0. --size_. notifyAll().
doPut(x). return true. } synchronized Object take() { throws InterruptedException { while (isEmpty()) wait(). } 69 C o n c u r r e n t i n . doPut(x).Buffer (continued) J a v a P r o g r a m m i n g synchronized void put(Object x) throws InterruptedException { while (isFull()) wait(). } synchronized Object poll() { if (isEmpty()) return null. return doTake(). } synchronized boolean offer(Object x) { if (isFull()) return false. return doTake().
) { try { wait(waitTime). long ms) { if (isFull()) { if (ms <= 0) return false. } } return doTake(). waitTime = ms . } catch (InterruptedException e) { return false. long start = System. } if (!isFull()) break.start)..currentTimeMillis(). } synchronized Object poll(long ms).Buffer (continued) J a v a synchronized boolean offer(Object x. long waitTime = ms.(now . if (waitTime <= 0) return false. for (. long now = System. // similar } 70 C o n c u r r e n t P r o g r a m m i n g i n .currentTimeMillis().
Containment J a v a client lock client outer part1 subpart1 part2 P r o g r a m m i n g i n Structurally guarantee exclusive access to internal objects • Control their visibility • Provide concurrency control for their methods Applications • Wrapping unsafe sequential code • Eliminating need for locking ground objects and variables • Applying special synchronization policies • Applying different policies to the same mechanisms 71 C o n c u r r e n t .
Pixel(int x. } synchronized void moveBy(int dx. y).y). int y) { pt_ = new Point(x. pt_.x.awt.Rectangle.awt. java.Point pt_.x += dx. but its fields are in turn mutable (and public!) so is unsafe without protection Must make copies of inner objects when revealing state • This is the most common way to use java. } } Pixel provides synchronized access to Point methods • The reference to Point object is immutable.awt. pt_. } synchronized Point location() { return new Point(pt_.Point.Containment Example J a v a class Pixel { private final java. etc 72 C o n c u r r e n t P r o g r a m m i n g i n .y += dy. int dy){ pt_.
Implementing Containment Strict containment creates islands of isolated objects J a v a • Applies recursively • Allows inner code to run faster Inner code must be communication-closed • No unprotected calls in to or out from island Outer objects must never leak identities of inner objects • Can be difficult to enforce and check Outermost objects must synchronize access • Otherwise. possible thread-caching problems Seen in concurrent versions of many delegation-based patterns • Adapters. decorators. proxies 73 C o n c u r r e n t P r o g r a m m i n g i n .
Extreme case: one Giant Lock for entire subsystem Can use either internal or external conventions 74 .Hierarchical Locking Applies when logically contained parts are not hidden from clients J a v a client owner client part1 subpart1 part2 P r o g r a m m i n g i n Avoids deadlocks that could occur if parts fully synchronized m() part1 m() part2 part1 holds self lock needs part2 lock C o n c u r r e n t part1 part2 part2 holds self lock needs part1 lock Can eliminate this potential deadlock if all locking in all methods in all Parts relies on the common owner’s lock.
} } } Or implement using inner classes — Owner is outer class: class Container { class Part { public void m() { synchronized(Container. } void bareAction() { /* .Internal Hierarchical Locking Visible components protect themselves using their owners’ locks: J a v a class Part { protected Container owner_. */ } public void m() { synchronized(owner()) { bareAction().this){ bareAction()... unsafe . etc rather than synchronized blocks 75 C o n c u r r e n t P r o g r a m m i n g i n . transaction locks. // never null public Container owner() { return owner_..} } } } Can extend to frameworks based on shared Lock objects..
getTreeLock() Can sometimes avoid more locking overhead.bareAction().awt.Component. } } } Used in AWT • java.owner()) { p. at price of fragility • Can manually minimize use of synchronized • Requires that all callers obey conventions • Effectiveness is context dependent — Breaks encapsulation — Doesn’t work with fancier schemes that do not directly rely on synchronized blocks or methods for locking 76 C o n c u r r e n t P r o g r a m m i n g i n .External Hierarchical Locking Rely on callers to provide the locking J a v a class Client { void f(Part p) { synchronized (p.
} } What happens when Whole. } } class Whole { final Part part_ = new Part().signal(c).Containment and Monitor Methods J a v a class Part { protected boolean cond_ = false. synchronized void await() { while (!cond_) try { wait().await(). notifyAll(). } synchronized void set(boolean c){ part_. synchronized void rely() { part_.rely() called? 77 C o n c u r r e n t P r o g r a m m i n g i n . } catch(InterruptedException ex) {} } synchronized void signal(boolean c) { cond_ = c.
Nested Monitors J a v a whole part wait set: T i n .rely • It waits within part • The lock to whole is retained while T is suspended • No other thread will ever unblock it via whole.set Nested Monitor Lockout Policy clash between guarding by Part and containment by Whole Never wait on a hidden contained object in Java while holding lock 78 C o n c u r r e n t . P r o g r a m m i n g holds lock to If thread T calls whole...
...) Whole..... public void await() { synchronized (Whole.wait() // ..this) { while (.Avoiding Nested Monitors Adapt internal hierarchical locking pattern J a v a Can use inner classes.this. class Part { // . } } } Create special Condition objects • Condition methods are never invoked while holding locks • Some concurrent languages build in special support for Condition objects — But generally only deal with one-level nesting • Can build Condition class library in Java 79 C o n c u r r e n t P r o g r a m m i n g i n . where Part waits in Whole’s monitor class Whole { // .
etc • Improving concurrency — Reducing lock contention for host object • Reducing granularity — Enabling fine-grained concurrency control 80 C o n c u r r e n t P r o g r a m m i n g i n .Splitting Objects and Locks J a v a Synopsis • Isolate independent aspects of state and/or behavior of a host object into helper objects • The host object delegates to helpers • The host may change which helpers it uses dynamically Applications • Atomic state updates — Conservative and optimistic techniques • Avoiding deadlocks — Offloading locks used for status indicators.
... synchronized double x() { return x_... double dy) { x_ += dx.x().... } synchronized double y() { return y_..... } } No protection from interleaving problems such as: Thread 1: x=loc.y().6).... loc... y_ += dy........moveBy(1...Isolating Dependent Representations Does Location provide strong enough semantic guarantees? J a v a P r o g r a m m i n g class Location { // repeated private double x_..... Thread 1 can have incorrect view (old x. y_. } synchronized void moveBy(double dx. dy) 81 C o n c u r r e n t i n x() y() .... . y=loc. new y) Avoid by splitting out dependent representations in separate class xy XY Location XY xy() moveBy(dx. Thread 2: ..
y).y() + dy). } double x() { return x_. y_ = y. } } Locking moveBy() ensures that the two accesses of xy_ do not get different points Locking xy() avoids thread-cache problems by clients 82 J a v a C o n c u r r e n t P r o g r a m m i n g i n .x() + dx. double y) { x_ = x. XY(double x. LocationV2(double x.Conservative Representation Updates class XY { // immutable private final double x_. double y) { xy_ = new XY(x.double dy) { xy_ = new XY(xy_. } synchronized void moveBy(double dx. } } class LocationV2 { private XY xy_. } synchronized XY xy() { return xy_. xy_. y_. } double y() { return y_.
Thread.} synchronized XY xy() { return xy_. oldp. } LocationV3(double x.interrupted()){ XY oldp = xy().yield(). } void moveBy(double dx. XY newp = new XY(oldp. return success. } } } 83 C o n c u r r e n t P r o g r a m m i n g i n . if (success) xy_ = newp. private synchronized boolean commit(XY oldp.y). newp)) break.double y){xy_=new XY(x. if (commit(oldp.x()+dx.double dy) { while (!Thread.Optimistic Representation Updates J a v a class LocationV3 { private XY xy_.y()+dy). XY newp){ boolean success = (xy_ == oldp).
transaction IDs.Optimistic Update Techniques Every public state update method has four parts: J a v a Record current version Easiest to use reference to immutable representation — Or can assign version numbers. without any irreversible side effects All actions before commit must be reversable — Ensures that failures are clean (no side effects) — No I/O or thread construction unless safely cancellable — All internally called methods must also be reversable Commit to new version if no other thread changed version Isolation of state updates to single atomic commit method can avoid potential deadlocks Otherwise fail or retry Retries can livelock unless proven wait-free in given context 84 C o n c u r r e n t P r o g r a m m i n g i n . or time stamps to mutable representations Build new version.
Can be more efficient than guarded waits if • Conflicts are rare • Guard conditions usually hold • Running on multiple CPUs 85 .. actions. isolate state into versions. return inRightState !inRightState . undo. throw C o n c u r r e n t Retry policy is a tamed busy wait...... and isolate state changes to commit method In each method: • Record current version • Build new version • Commit to version if success and no one changed version • Otherwise fail or retry client aMessage host P r o g r a m m i n g i n .Optimistic State-Dependent Policies J a v a As with optimistic updates...
interrupted()) throw new InterruptedException().yield(). return success.Optimistic Counter class OptimisticBoundedCounter { private Long count_ = new Long(MIN).} private synchronized boolean commit(Long oldc. Long newc){ boolean success = (count_ == oldc).longValue(). } public void inc() throws InterruptedException{ for (. Thread. new Long(v+1))) break.) { // retry-based if (Thread.. long value() { return count(). } } public void dec() // symmetrical } 86 J a v a C o n c u r r e n t P r o g r a m m i n g i n . if (success) count_ = newc. if (v < MAX && commit(c. long v = c. Long c = count(). } synchronized Long count() { return count_.longValue().
} Location l = new Location(0. Delegate actions to helper via pass-through method class Shape { // Assumes size & dimension are independent int height_ = 0. synchronized void grow() { ++height_.moveBy(1. // fully synched C o n c u r r e n t P r o g r a m m i n g i n void shift() { l. ++width_. and protect associated methods using synchronized block on that lock — Useful for concurrent data structures 87 . 1). } // Use l’s synch } grow and shift can execute simultaneously When there is no existing object to delegate independent actions: • Use an arbitrary Object as a lock. int width_ = 0.0).Splitting Locks and Behavior J a v a Associate a helper object with an independent subset of state and functionality.
} } private Node head_ = new Node(null). } } 88 J a v a C o n c u r r e n t P r o g r a m m i n g i n . // only contention pt if (first != null) { x = first. private Object lastLock_ = new Object(). // old first becomes header } return x. Node first = head_.next. first.value. } } synchronized Object poll() { // null if empty Object x = null. Node(Object x) { value = x. // dummy hdr private Node last_ = head_. void put(Object x) { synchronized (lastLock_) { last_ = last_.Concurrent Queue class TwoLockQueue { final static class Node { Object value. Node next = null.value = null. head_ = first.next = new Node(x).
Concurrent Queue (continued) J a v a queue head hdr next first . (null) last P r o g r a m m i n g i n value (null) puts and polls can run concurrently • The data structure is crafted to avoid contending access — Rely on Java atomicity guarantees at only potential contention point • But multiple puts and multiple polls disallowed Weakens semantics • poll may return null if another thread is in midst of put • Balking policy for poll is nearly forced here — But can layer on blocking version 89 C o n c u r r e n t ...
90 C o n c u r r e n t P r o g r a m m i n g i n .Introducing Concurrency into Applications J a v a Three sets of patterns Each associated with a reason to introduce concurrency Autonomous Loops Establishing independent cyclic behavior Oneway messages Sending messages without waiting for reply or termination • Improves availability of sender object Interactive messages Requests that later result in reply or callback messages • Allows client to proceed concurrently for a while Most design ideas and semantics stem from active object models.
interrupted()) doSomething().Autonomous Loops J a v a Simple non-reactive active objects contain a run loop of form: public void run() { while (!Thread.start(). } Normally established with a constructor containing: new Thread(this). Perhaps also setting priority and daemon status Normally also support other methods called from other threads Requires standard safety measures Common Applications • Animations • Simulations • Message buffer Consumers • Polling daemons that periodically sense state of world 91 C o n c u r r e n t P r o g r a m m i n g i n .
0. private Canvas canvas. public Particle(Canvas host) { canvas = host.sleep((int)(Math. } g.Autonomous Particle Class public class Particle implements Runnable { private int x = 0.5) * 5)..} catch (InterruptedException e) { return.random() . } synchronized void moveRandomly() { x += (int) (((Math. 10. ly.) { moveRandomly().drawRect(lx. ly = y. ly.random()*10).0. } public void run() { for(. y = 0. y += (int) (((Math.repaint(). synchronized (this) { lx = x. 10). } public void draw(Graphics g) { int lx. try { Thread.random() . } } } } 92 J a v a C o n c u r r e n t P r o g r a m m i n g i n .5) * 5). canvas.
++i) particles[i].awt. } } public void paint(Graphics g) { for (int i = 0. ParticleCanvas(int nparticles) { setSize(new Dimension(100. public class ParticleApplet extends Applet { public void init() { add(new ParticleCanvas(10)).*.start().length. i < particles. } } // (needs lots of embellishing to look nice) 93 J a v a C o n c u r r e n t P r o g r a m m i n g i n . particles = new Particle[nparticles]. import java.*. ++i) { particles[i] = new Particle(this). i < particles. } } class ParticleCanvas extends Canvas { Particle[] particles.applet. 100)). new Thread(particles[i]).draw(g).Particle Applet import java. for (int i = 0.length.
Oneway Messages J a v a state. acquaintances Client accept react { update state send message } i n oneway Handler P r o g r a m m i n g Host Conceptually oneway messages are sent with • No need for replies • No concern about failure (exceptions) • No dependence on termination of called method • No dependence on order that messages are received But may sometimes want to cancel messages or resulting activities 94 C o n c u r r e n t .
etc Status change alerts.Oneway Message Styles J a v a Events Notifications Postings Activations Commands Relays Mouse clicks. etc P r o g r a m m i n g i n Some semantics choices Asynchronous: Entire message send is independent — By far. etc Print requests. repaint requests. etc Applet creation. most common style in reactive applications Synchronous: Caller must wait until message is accepted — Basis for rendezvous protocols Multicast: Message is sent to group of recipients — The group might not even have any members 95 C o n c u r r e n t . etc Chain of responsibility designs. etc Mail messages. stock quotes.
including AWT Request objects. mobile code systems 96 C o n c u r r e n t P r o g r a m m i n g i n . asking to perform encoded operation • Used in distributed object systems — RMI and CORBA Class objects (normally via .class files) • Recipient creates instance of class • Used in Java Applet framework Runnable commands • Basis for thread instantiation.Messages in Java Direct method invocations J a v a • Rely on standard call/return mechanics Command strings • Recipient parses then dispatches to underlying method • Widely used in client/server systems including HTTP EventObjects and service codes • Recipient dispatches • Widely used in GUIs.
Design Goals for Oneway Messages Object-based forces J a v a Safety • Local state changes should be atomic (normally. when applicable Availability • Minimize delay until host can accept another message Activity-based forces Flow • The activity should progress with minimal contention Performance • Minimize overhead and resource usage 97 C o n c u r r e n t P r o g r a m m i n g i n . locked) — Typical need for locking leads to main differences vs single-threaded Event systems • Safe guarding and failure policies.
Design Patterns for Oneway Messages J a v a Thread-per-Message client host start handler i n P r o g r a m m i n g new thread Thread-per-Activity via Pass-throughs client host handler same thread Thread-per-Object via Worker Threads (variants: Pools. Listeners) client put C o n c u r r e n t host take handler channel worker thread 98 .
...) { // Issue handler..) } } react() may be called directly from client.. event. sendMessage(... private long localState_.)... or indirectly after decoding command..Reactive Methods Code scaffolding for illustrating patterns: J a v a P r o g r a m m i n g class Host { // .. public void react(.) { // Assign to localState_.. } i n // Or any state vars // Message target C o n c u r r e n t private synchronized void updateState(.) { updateState(. private Handler handler_. } private void sendMessage(. etc 99 ..).process(..
public void react(.) { Runnable command = new Runnable() { // wrap final Handler dest = handler_.Thread-per-Message class Host { //.. // run } } Runnable is the standard Java interface describing argumentless..start().. } }..)...process(.... thunks) Synchronization of sendMessage desirable if handler_ or process() arguments not fixed/final Variants: Thread-per-connection (sockets) 100 J a v a C o n c u r r e n t P r o g r a m m i n g i n . public void run() { dest.... new Thread(command). sendMessage(.).) { updateState(.). } synchronized void sendMessage(. resultless command methods (aka closures.
.Thread-per-Message Protocol client J a v a react host handler command i n . updateState... start/run P r o g r a m m i n g process C o n c u r r e n t 101 ..
or • Use a single thread for all messages Depends on whether OK to wait each one out before sending next one 102 .Multicast TPM J a v a client react host handlers P r o g r a m m i n g i n return C o n c u r r e n t Multicasts can either • Generate one thread per message.
) { final Socket connection = socket. exit */ } } } class Handler { void process(Socket s) { InputStream i = s. // decode and service request. OutputStream o = s.close().. for (.accept().process(connection).getOutputStream().TPM Socket-based Server class Server implements Runnable { public void run() { try { ServerSocket socket = new ServerSocket(PORT). } } 103 J a v a C o n c u r r e n t P r o g r a m m i n g i n .getInputStream(). } } catch(Exception e) { /* cleanup. new Thread(new Runnable() { public void run() { new Handler(). handle errors s. }}).start().
MIN_PRIORITY to Thread.Thread Attributes and Scheduling Each Thread has an integer priority J a v a • From Thread.MAX_PRIORITY (currently 1 to 10) • Initial priority is same as that of the creating thread • Can be changed at any time via setPriority • ThreadGroup. implementation-dependent • No guarantees about fairness for equal-priority threads — Time-slicing is permitted but not required • No guarantees whether highest-priority or longest-waiting threads acquire locks or receive notifications before others Priorities can only be used heuristically • Build custom Queues to control order of sequential tasks • Build custom Conditions to control locking and notification 104 C o n c u r r e n t P r o g r a m m i n g i n .setMaxPriority establishes a ceiling for all threads in the group JVM schedulers give preference to threads with higher priority • But preference is left vague.
default parameters Useful as tool to eliminate need for locking • Used internally in JVMs to optimize memory allocation. current directories. transaction IDs. etc via per-thread caches 105 C o n c u r r e n t . not per-object • Timeout values. Principals. locks.Adding Thread Attributes J a v a Thread specific attributes P r o g r a m m i n g i n Thread specific attributes Thread objects can hold non-public Thread-Specific contextual attributes for all methods/objects running in that thread • Normally preferable to static variables Useful for variables that apply per-activity.
} static long getDelay() { return currentGameThread(). private long movementDelay_ = 3. } } class Ball { // ... static GameThread currentGameThread() { return (GameThread)(Thread.sleep(GameThread.getDelay())).movementDelay_ = t... } Define contextual attributes in special Thread subclasses • Can be accessed without locking if all accesses are always via Thread. } static long setDelay(long t) { currentGameThread().Implementing Thread-Specific Storage class GameThread extends Thread { // . } } class Main { .... void move() { // . Thread.movementDelay_.currentThread() • Enforce via static methods in Thread subclass 106 J a v a C o n c u r r e n t P r o g r a m m i n g i n . new GameThread(new Game()) ....currentThread()).
.longValue().lang.get()==null) delay.Using ThreadLocal java. Thread.ThreadLocal available in JDK1.. void move() { // .get())).sleep(d).set(new Long(3)). } } Can extend to implement inherited Thread contexts Where new threads by default use attributes of the parent thread that constructed them 107 C o n c u r r e n t P r o g r a m m i n g i n . long d = ((Long)(delay.2 J a v a • An alternative to defining special Thread subclasses Uses internal hash table to associate data with threads • Avoids need to make special Thread subclasses when adding per-thread data — Trade off flexibility vs strong typing and performance class Ball { static ThreadLocal delay = new ThreadLocal(). if (delay.
Other Scoping Options J a v a Choices for maintaining context information i n P r o g r a m m i n g per Application per Principal per Session per Thread per Method per Block per Class per Object per Role per Group per Site per Domain per Aggregate C o n c u r r e n t per System per Version 108 .
Choosing among Scoping Options Reusability heuristics J a v a • Responsibility-driven design • Factor commonalities. isolate variation • Simplify Programmability — Avoid long parameter lists — Avoid awkward programming constructions — Avoid opportunities for errors due to policy conflicts — Automate propagation of bindings Conflict analysis Example: Changing per-object bindings via tuning interfaces can lead to conflicts when objects support multiple roles • Settings made by one client impact others • Common error with Proxy objects • Replace with per-method. per-role. per-thread 109 C o n c u r r e n t P r o g r a m m i n g i n .
process to terminate.... or generate their own threads Host can respond to another react call from another thread immediately after updating state client react i n host handler C o n c u r r e n t ..Thread-per-Activity via Pass-Throughs class Host { //. } void sendMessage(. process 110 .) { // no synch updateState(). // isolate in synched method sendMessage(..) { // no synch handler_....... updateState.).. J a v a P r o g r a m m i n g void reactV1(..). // direct call } } A kind of forwarding — conceptually removing host from call chain Callers of react must wait for handler.process(..
Mediated • Register handlers in a common mediator structured as a pass-through. copy values to locals while under synchronization • Callers must be sure to create thread around call if they cannot afford to wait or would lock up Variants Bounded Thread-per-Message • Keep track of how many threads have been created. JavaBeans methods. But somewhat fragile: • There is no “opposite” to synchronized — Avoid self calls to react from synchronized methods • Need care in accessing representations at call-point — If handler_ variable or process arguments not fixed. fall back to pass-through. and other event-based components. 111 C o n c u r r e n t P r o g r a m m i n g i n .Using Pass-Throughs J a v a Common approach to writing AWT Event handlers. If too many.
so cannot be used in other contexts 112 C o n c u r r e n t P r o g r a m m i n g i n .process(..) { Iterator e = handlers_.iterator().Multicast Pass-Throughs J a v a class Host { //.hasNext()) ((Handler)(e.AWTEventMulticaster class • Employs variant of FixedList class design • But coupled to AWT Listener framework.. synchronized void addHandler(Handler h) { handlers_.next())). CopyOnWriteSet handlers_.). // copy } void sendMessage(..add(h). while (e. } } Normally use copy-on-write to implement target collections • Additions are much less common than traversals AWT uses java....awt.
etc Message might be a Runnable command. } Common variants Pools Use more than one worker thread Listeners Separate producer and consumer in different objects 113 C o n c u r r e n t P r o g r a m m i n g i n .Thread-Per-Object via Worker Threads Establish a producer-consumer chain J a v a Producer Reactive method just places message in a channel Channel might be a buffer.interrupted()) { m = channel.take(). event. queue. etc Consumer Host contains an autonomous loop thread of form: while (!Thread. stream. process(m).
) { channel_..put(new Runnable() { // enqueue public void run(){ handler_. Object take()..take())). etc void put(Object x). } class Host { //. Channel channel_ = . } } 114 J a v a C o n c u r r e n t P r o g r a m m i n g i n .interrupted()) ((Runnable)(channel_.. } Host() { // Set up worker thread in constructor // ..).process(.run()... }}).. stream. } }). new Thread(new Runnable() { public void run() { while (!Thread.... void sendMessage(.start(). queue..Worker Thread Example interface Channel { // buffer.
...Worker Thread Protocol client J a v a react host handler command channel i n .. updateState. put P r o g r a m m i n g take run !empty C o n c u r r e n t run process 115 .
remote execution Non-blocking channels • Must take evasive action if put or take fail or time out 116 C o n c u r r e n t P r o g r a m m i n g i n . drop oldest if full Priority queues • Run more important tasks first Streams or sockets • Enable persistence.Channel Options Unbounded queues J a v a • Can exhaust resources if clients faster than handlers Bounded buffers • Can cause clients to block when full Synchronous channels • Force client to wait for handler to complete previous task Leaky bounded buffers • For example.
• The request may beoptimized away if one already there • update/paint is called when request dequeued — Drawing is done by AWT thread..util.... dispatch .awt. not your threads 117 C o n c u r r e n t . } button click mouseEvent AWT Thread Events implement java.EventQueue J a v a • Single thread makes visual updates appear more coherent • Browsers may add per-Applet threads and queues AWT queue anEvent anEvent dequeue pass-through P r o g r a m m i n g i n applet actionPerformed(e) { .Example: The AWT Event Queue Thread AWT uses one thread and a single java.EventObject • Include both ‘‘Low-level’’ and ‘‘Semantic’’ events Event dequeuing performed by AWT thread repaint() places drawing request event in queue.
// attach add(button). boolean onOff = false.addActionListener(this). public void init() { button.AWT Example J a v a class MyApplet extends Applet implements ActionListener { Button button = new Button(“Push me”). } } 118 C o n c u r r e n t P r o g r a m m i n g i n .getSource() == button) // dispatch toggle(). // update state repaint(). // issue event(not necessary here) } synchronized void toggle() { onOff = !onOff. // add to layout } public void ActionPerformed(ActionEvent evt) { if (evt.
Using AWT in Concurrent Programs J a v a Most conservative policy is to perform all GUI-related state updates in event handling methods • Define and generate new EventObjects if necessary • Consider splitting GUI-related state into separate classes • Do not rely on thread-safety of GUI components Define drawing and event handling methods in reactive form • Do not hold locks when sending messages • Do not block or delay caller thread (the AWT thread) • Generate threads to arrange GUI-unrelated processing — Explicitly set their ThreadGroups • Generate events to arrange GUI-related asynch processing — Swing includes some utility classes to make this easier 119 C o n c u r r e n t P r o g r a m m i n g i n .
Thread Pools J a v a client put handler handler P r o g r a m m i n g i n channel take handler handler C o n c u r r e n t Use a collection of worker threads. not just one • Can limit maximum number and priorities of threads Often faster than thread-per-message • But slower than single thread working off a multislot buffer unless handler actions permit parallelism • Often works well for I/O-bound actions 120 .
.Listeners J a v a client host put take listener handler i n P r o g r a m m i n g channel House worker thread in a different object worker thread • Even in a different process. fault tolerance • Security. reliability. connected via socket But full support for remote listeners requires frameworks for • Naming remote acquaintances (via registries.. but wrap each message as queued command for later execution 121 C o n c u r r e n t . jndi etc) • Failure. . Can make more transparent via Proxies • Channels/Listeners that duplicate interface of Handler. protocol conformance.
writeObject(new SerializableRunnable() { public void run(){ new Handler().process(.readObject())). } } class Listener { // instantiate on remote machine ObjectInputStream c...) { c.Remote Worker Threads class Host { // . } } 122 J a v a C o n c u r r e n t P r o g r a m m i n g i n . me.start(). Thread me = new Thread(new Runnable() { public void run() { for (.... } }). // connected to a Socket void sendMessage(. ObjectOutputStream c.)..run().) { ((Runnable)(c.. // connected to a Socket Listener() { c = new ... }}}).
deterministic. except: J a v a • Caller must wait at least until message is accepted Simplest option is to use synchronized methods • Caller must wait out all downstream processing Increase concurrency via synchronous channel to worker thread • Every put must wait for take • Every take must wait for put Basis for synchronous message passing frameworks (CSP etc) • Enables more precise. so required more careful management of existing ones. analyzable. but expensive flow control measures. Variants • Barrier: Threads wait but do not exchange information • Rendezvous: Bidirectional message exchange at wait 123 C o n c u r r e n t P r o g r a m m i n g i n .Synchronous Channels Synchronous oneway messages same as asynchronous. • Relied on in part because CSP-inspired systems did not allow dynamic construction of new threads.
... return e. notifyAll()... item_ = e. notifyAll().Synchronous Channel Example class SynchronousChannel { Object item_ = null. notifyAll(). } catch . boolean putting_ = false. } } 124 J a v a C o n c u r r e n t P r o g r a m m i n g i n . Object e = item_.. while (putting_) try { wait(). } synchronized Object take() { while (item_ == null) try { wait(). item_ = null. } catch . putting_ = false. putting_ = true.//disable multiple puts synchronized void put(Object e) { if (e == null) return. while (item_ != null) try { wait(). } catch .
Can be hard to limit resource usage .No within-activity concurrency Worker Threads + Tunable semantics and structure + Can bound resource usage .Higher overhead .May block caller (if buffer full etc) C o n c u r r e n t P r o g r a m m i n g i n 125 .Thread start-up overhead Pass-Through + Low overhead .Some Pattern Trade-Offs J a v a Thread-perMessage + Simple semantics: When in doubt. make a new thread .Fragile .Can waste threads .
Interactive Messages J a v a Synopsis • Client activates Server with a oneway message oneway i n client server P r o g r a m m i n g • Server later invokes a callback method on client client callback server Callback can be either oneway or procedural Callback can instead be sent to a helper object of client Degenerate case: inform only of task completion Applications • Observer designs • Completion indications from file and network I/O • Threads performing computations that yield results 126 C o n c u r r e n t .
Observer Designs J a v a The oneway calls are change notifications The callbacks are state queries Examples • Screen updates • Constraint frameworks • Publish/subscribe • Hand-built variants of wait and notifyAll Notifications must use oneway design pattern Otherwise: changeNotification subject changeValue(v) observer i n changeNotification val==v P r o g r a m m i n g return currentValue C o n c u r r e n t return(val) display thread1 val==v cache == val can deadlock against: thread2 currentValue 127 .
} public void changeValue(double newstate) { setValue(newstate).start(). new Thread(new Runnable() { public void run() { o.} protected synchronized void setValue(double d){ val_ = d.iterator(). public void attach(Observer o) { obs_. } }). Iterator it = obs_.hasNext()){ final Observer o = (Observer)(it.Observer Example class Subject { protected double val_ = 0. while (it.changeNotification(this).} protected CopyOnWriteSet obs_ = new COWImpl(). } } } // More common to use pass-through calls instead of threads 128 J a v a C o n c u r r e n t P r o g r a m m i n g i n .next()). // modeled state public synchronized double getValue(){ return val_.0.add(o).
cachedState_ = subj_.Observer Example (Continued) J a v a i n class Observer { protected double cachedState_. // probe if (oldState != cachedState_) display(). } synchronized void changeNotification(Subject s){ if (s != subj_) return. // only one subject double oldState = cachedState_. cachedState_ = s.out. display(). } synchronized void display() { // default version System. } } 129 C o n c u r r e n t P r o g r a m m i n g . // only one here Observer(Subject s) { subj_ = s.//last known state protected Subject subj_.getValue().getValue().println(cachedState_).
.Completion Callbacks J a v a The asynch messages are service activations The callbacks are continuation calls that transmit results • May contain a message ID or completion token to tell client which task has completed Typically two kinds of callbacks Success – analog of return Failure – analog of throw Client readiness to accept callbacks may be statedependent • For example... success completed return P r o g r a m m i n g C o n c u r r e n t failure failed return 130 . try action.. if client can only process callbacks in a certain order app client start/run server i n return .
.IOException ex). readFailed(String fn. } Sample Client class FileReaderApp implements FileReaderClient { private byte[] data_. data_.this)). } } 131 ..start(). void readFailed(String filename. deal with failure . C o n c u r r e n t P r o g r a m m i n g i n void app() { new Thread(new FileReader(“file”..Completion Callback Example Callback interface J a v a interface FileReaderClient { void readCompleted(String filename)... void // } void // } readCompleted(String filenm) { ... IOException e){ .. use data .
readCompleted(nm_).. byte[] data.Completion Callbacks (continued) Sample Server J a v a class FileReader implements Runnable { final String nm_. } catch (IOException ex) { if (client_ != null) client_.readFailed(nm_.. } void run() { try { // . final byte[] d_. FileReaderClient c) { nm_ = name.. d_ = data. ex). client_ = c. // allow null public FileReader(String name. final FileReaderClient client_. } } } 132 C o n c u r r e n t P r o g r a m m i n g i n . read. if (client_ != null) client_..
• Read into a buffer serviced by a worker thread 133 C o n c u r r e n t P r o g r a m m i n g i n . run in same thread.Threads and I/O Java I/O calls generally block J a v a • Thread.setSoTimeOut • Can manually set up classes to arrange time-out interrupts for other kinds of I/O Common variants of I/O completion callbacks • Issue callback whenever there is enough data to process. rather than all at once • Send a Runnable completion action instead of callback • Use thread pools for either I/O or completion actions Alternatives • Place the I/O and the subsequent actions all in same method.interrupt causes them to unblock — (This is broken in many Java implementations) • Time-outs are available for some Socket operations — Socket.
not just those directly constructing threads Variants seen in Adaptors that call methods throwing exceptions that clients do not know how to handle: interface Server { void svc() throws SException.Rerouting Exceptions J a v a Callbacks can be used instead of exceptions in any asynchronous messaging context.svc(). void attachHandler(EHandler h) { handler = h. } } } Pluggable Handlers can do anything that a normal catch clause can • Including cancelling all remaining processing in any thread • But are less structured and sometimes more error-prone 134 C o n c u r r e n t P r o g r a m m i n g i n . EHandler handler. } catch (SException e) { if (handler != null) handler. } class SvcAdapter { Server server = new ServerImpl(). } interface EHandler { void handle(Exception e). } public void svc() { // no throw clause try { server.handle(e).
wait() — terminating threads call notifyAll() Can use to simulate futures and deferred calls found in other concurrent OO languages • But no syntactic support for futures 135 C o n c u r r e n t P r o g r a m m i n g i n .Joining Threads Thread.join() calls t.join() may be used instead of callbacks when J a v a • Server does not need to call back client with results • But client cannot continue until service completion Usually the easiest way to express termination dependence • No need to define callback interface or send client ref as argument • No need for server to explicitly notify or call client • Internally implemented in java by — t.
public void show(final byte[] rawPic) { class Waiter implements Runnable { Picture result = null. // . displayBorders()..start().result). } displayPicture(waiter. t.Join Example public class PictureDisplay { private final PictureRenderer myRenderer_. displayCaption(). } catch(InterruptedException e) { return.render(rawPic). } } 136 . // do other things // while rendering J a v a C o n c u r r e n t P r o g r a m m i n g i n try { t.join(). } }. Waiter waiter = new Waiter(). Thread t = new Thread(waiter).. public void run() { result = myRenderer_.
. 137 ... return(im) C o n c u r r e n t return !isAlive join !isAlive return displayPicture(result) .Join Protocol J a v a picturedisplay show start waiter thread renderer i n run P r o g r a m m i n g isAlive render ... other actions..
synchronized void setImage(byte[] img) { img_ = img. } class AsynchRenderer implements Renderer { static class FuturePic implements Pic { //inner byte[] img_ = null. } } // continued 138 C o n c u r r e n t P r o g r a m m i n g i n .Futures Encapsulate waits for results of operations performed in threads J a v a • Futures are ‘‘data’’ types that wait until results ready — Normally requires use of interfaces for types Clients wait only upon trying to use results interface Pic { byte[] getImage().. } public synchronized byte[] getImage() { while (img_ == null) try { wait(). notifyAll().. } return img_. } catch (InterruptedException e) { . } interface Renderer { Pic render(byte[] raw).
start(). // . } class App { // sample usage void app(byte[] r) { Pic p = new AsynchRenderer().Futures (continued) // class AsynchRender.setImage(doRender(raw)). // wait if not yet ready } } Could alternatively write join-based version. new Thread(new Runnable() { public void run() { p. continued J a v a P r o g r a m m i n g public Pic render(final byte[] raw) { final FuturePic p = new FuturePic(). return p. } }). display(p.. } private Pic doRender(byte[] r). 139 C o n c u r r e n t i n ..render(r). doSomethingElse().getImage()).
interrupt System.stop() called • User hits a CANCEL button • Threads performing computations that are not needed • I/O or network-driven activites that encounter failures Options Asynchronous cancellation: Polling and exceptions: Terminating program: Minimizing contention: Revoking permissions: Thread.Cancellation J a v a Threads normally terminate after completing their run methods May need to cancel asynchronous activities before completion • Applet.stop Thread.exit setPriority(MIN_PRIORITY) SecurityManager methods C o n c u r r e n t P r o g r a m m i n g i n Unlinking resources known to cause failure exceptions 140 .
} } } What happens if stop occurs during compute()? In principle. // invariant: v >= 0 synchronized void f() { v = -1.stop stops thread by throwing ThreadDeath exception J a v a Deprecated in JDK1. // temporarily set to illegal value compute(). • Most other thread systems (including POSIX) either do not support or severely restrict asynchronous cancellation 141 C o n c u r r e n t P r o g r a m m i n g i n . something().2 because it can corrupt object state: class C { private int v. Impractical.Asynchronous Cancellation Thread. could catch(ThreadDeath) • But this would only work well if done after just about every line of code in just about every Java class. // set to legal value } synchronized void g() { // depend on invariant while (v != 0) { --v. // call some other method v = 1.
returning previous status. (static) Thread. also clearing status • Blocking IO methods in the java. Thread.wait if blocked during interruption.io package respond to interrupt by throwing InterruptedIOException 142 C o n c u r r e n t P r o g r a m m i n g i n .isInterrupted • Returns current interruption status. Object.sleep.join.interrupted • Clears status for current thread. and also causes applicable methods to throw InterruptedException • Threads that are blocked waiting for synchronized method or block entry are NOT awakened by interrupt InterruptedException • Thrown by Thread. thread.interrupt • Sets interrupted status.Interruption J a v a Safety can be maintained by each object checking cancellation status only when in an appropriate state to do so. relying on: thread.
Implementing a Cancellation Policy Best-supported policy is: J a v a Thread. Options: Thread.currentThread().isInterrupted() means cancelled Any method sensing interruption should • Assume current task is cancelled.interrupt() throw new InterruptedException() Alternatives • Local recovery and continuation • Centralized error recovery objects • Always ignoring/resetting status 143 C o n c u r r e n t P r o g r a m m i n g i n . • Ensure that callers are aware of cancellation. • Exit as quickly and cleanly as possible.
and poll frequency require engineering tradeoffs • How important is it to stop now? • How hard is it to stop now? • Will another object detect and deal with at a better time? • Is it too late to stop an irreversable action? • Does it really matter if the thread is stopped? 144 C o n c u r r e n t P r o g r a m m i n g i n . } catch (InterruptedException ex) { cancellationCode(). or rethrown as an exception try { somethingThrowingInterruptedException(). etc Can be caught. style. as in InterruptedIOException Placement. } • Or as a subclass of a general failure exception. • Also in loop headers of looping methods.isInterrupted()) cancellationCode().Detecting Cancellation Cancellation can be checked as a precondition for any method J a v a if (Thread.currentThread(). thrown.
Responses to Cancellation Early return J a v a • Clean up and exit without producing or signalling errors — May require rollback or recovery • Callers can poll status if necessary to find out why action was not carried out. • Reset (if necessary) interruption status before return: Thread.interrupt() Continuation (ignoring cancellation status) • When it is too dangerous to stop • When partial actions cannot be backed out • When it doesn’t matter (but consider lowering priority) Throwing InterruptedException • When callers must be alerted on method return Throwing a general failure Exception • When interruption is one of many reasons method can fail 145 C o n c u r r e n t P r o g r a m m i n g i n .currentThread().
join(maxWaitToDie).interrupt().isAlive()) return true.isAlive()) return true. try { t. // phase 3 -. J a v a Dealing with this forms part of any security framework.denyAllChecksFor(t).isAlive()) return true.minimize damage t. // already dead // phase 1 -. } 146 C o n c u r r e n t P r o g r a m m i n g i n .MIN_PRIORITY). // success // phase 2 -. } catch(InterruptedException e){} // ignore if (!t. // or even unsafe last-resort t.stop() return false. } catch(InterruptedException ex) {} if (!t.Multiphase Cancellation Foreign code running in thread might not respond to cancellation.graceful cancellation t. // made-up try { t. Example: static boolean terminate(Thread t) { if (!t.setPriority(Thread.join(maxWaitToDie).trap all security checks theSecurityMgr.
stop) • Ensure that activities check cancellation often enough • Consider last-resort Thread. it is impossible to predict lifecycle • No guarantees about when browsers will destroy.stop in Applet.destroy 147 move off/on page P r o g r a m m i n g i n init invoke on load start main action stop revisit/reload after finalized leave page C o n c u r r e n t destroy finalization .Shutting Down Applets Applets can create threads J a v a instantiate — usually in Applet. or whether threads automatically killed when unloading Guidelines • Explicitly cancel threads (normally in Applet.start and terminate them — usually in Applet.stop These threads should be cancellable • Otherwise.
synchronization • Avoid inconsistent case-by-case decisions Samplings from three styles Flow systems Wiring together processing stages — Illustrated with Push Flow designs Parallel execution Partitioning independent tasks — Illustrated with Group-based designs Layered services Synchronization and control of ground objects — Illustrated with Before/After designs 148 C o n c u r r e n t P r o g r a m m i n g i n .Concurrent Application Architectures J a v a Establishing application.(or subsystem-) wide Policies • Communication directionality.
Push Flow Systems J a v a Systems in which (nearly) all activities are performed by objects issuing oneway messages along paths from sources to sinks • Each message transfers information and/or objects Examples Control systems Assembly systems Workflow systems Event processing Chain of command Pipeline algorithms Requires common directionality and locality constraints • Precludes many safety and liveness problems • Success relies on adherence to design rules — potentially formally checkable The simplest and sometimes best open systems protocol 149 contractor invoices supplier invoices approval payment returns tempSensor comparator heater C o n c u r r e n t P r o g r a m m i n g i n .
Stages in Flow Systems Every stage is a producer and/or consumer J a v a Stages implement common interface with method of form void put(Object item) May have multiple successors Outgoing elements may be — multicasted or — routed May have multiple predecessors Incoming elements may be — combined or — collected Normally require explicit linkages — only one stage per connection producer put consumer P r o g r a m m i n g i n splitter put C o n c u r r e n t put merger Each stage can define put using any appropriate oneway message implementation pattern — may differ across stages 150 .
then you can do something (with it) that you couldn’t do otherwise. then you no longer have it.Exclusive Ownership of Resources Elements in most flow systems act like physical resources in that J a v a • If you have one. • If you give it to someone else. • If you have one. then no one will ever have it. Examples • Invoices • Network packets • File and socket handles • Tokens • Mail messages • Money 151 C o n c u r r e n t P r o g r a m m i n g i n . • If you destroy it. then no one else has it.
*/ } } Both reference-passing ‘‘shared memory’’ and copy-based ‘‘message passing’’ policies can encounter problems: Shared memory stage1 access put(r) P r o g r a m m i n g i n C o n c u r r e n t Message passing stage1 access put(r) stage2 access stage2 access resource resource copy Synchronize access to resource Deal with identity differences 152 ...Accessing Resources J a v a How should stages manage resource objects? class Stage { Resource res. void put(Resource r) { /* .
Ownership Transfer Transfer policy J a v a At most one stage refers to any resource at any time Require each owner to forget about each resource after revealing it to any other owner as message argument or return value • Implement by nulling out instance variables refering to resources after hand-off — Or avoiding such variables • Resource Pools can be used to hold unused resources — Or just let them be garbage collected Before message stage1 access put(r) C o n c u r r e n t P r o g r a m m i n g i n After message stage1 put(r) stage2 stage2 access resource (null) (null) resource 153 .
combine into composite boxes A viewer applet serves as the sink See CPJ p233-248 for most code omitted here • Some code here differs in minor ways for sake of illustration 154 C o n c u r r e n t . transform.Assembly Line Example J a v a P r o g r a m m i n g i n Boxes are flow elements • Have adjustable dimension and color • Can clone and draw themselves Sources produce continuous stream of BasicBoxes Boxes are pushed through stages • Stages paint.
} putA PushStage interface PushStage { void putA(Box p). } C o n c u r r e n t putA DualInput PushStage putB interface DualInputPushStage extends PushStage { public void putB(Box p).Interfaces J a v a start PushSource P r o g r a m m i n g i n interface PushSource { void start(). } 155 .
} } Allows all other stages to issue putA • Use adapter when necessary to convert to putB • Simplifies composition Alternatively. could have used a single put(command) interface • Would require each stage to decode type/sense of command 156 C o n c u r r e n t P r o g r a m m i n g i n . DualInputAdapter(DualInputPushStage stage) { stage_ = stage. } void putA(Box p) { stage_.Adapters putA J a v a DualInput Adapter putB class DualInputAdapter implements PushStage { protected final DualInputPushStage stage_.putB(p).
void attach1(PushStage s) { next1_ = s.Connections J a v a SingleOutput PushStage next1 i n P r o g r a m m i n g class SingleOutputPushStage { protected PushStage next1_= null. could have used a collection (Vector etc) of nexts We assume/require all attaches to be performed before any puts 157 . } } next1 DualOutput PushStage next2 C o n c u r r e n t class DualOutputPushStage extends SingleOutputPushStage { protected PushStage next2_ = null. } } Alternatively. void attach2(PushStage s) { next2_ = s.
color(color_). } } C o n c u r r e n t Painter is immutable after initialization 158 . next1_. } public void putA(Box p) { p. public Painter(Color c) { super().Linear Stages J a v a putA Painter putA next1 P r o g r a m m i n g i n class Painter extends SingleOutputPushStage implements PushStage { protected final Color color_. color_ = c.putA(p).
Dual Input Stages
J a v a putA Collector putB P r o g r a m m i n g putA next1
i n
public class Collector extends SingleOutputPushStage implements DualInputPushStage { public synchronized void putA(Box p) { next1_.putA(p); } public synchronized void putB(Box p) { next1_.putA(p); } } Synchronization used here to illustrate flow control, not safety
159
C o n c u r r e n t
Joiners
class Joiner extends SingleOutputPushStage implements DualInputPushStage { protected Box a_ = null; // incoming from putA protected Box b_ = null; // incoming from putB protected abstract Box join(Box p, Box q); protected synchronized Box joinFromA(Box p) { while (a_ != null) // wait until last consumed try { wait(); } catch (InterruptedException e){return null;} a_ = p; return tryJoin(); } protected synchronized Box tryJoin() { if (a_ == null || b_ == null) return null; Box joined = join(a_, b_); // make combined box a_ = b_ = null; // forget old boxes notifyAll(); // allow new puts return joined; } void putA(Box p) { Box j = joinFromA(p); if (j != null) next1_.putA(j); } } // (mechanics for putB are symmetrical)
160 J a v a C o n c u r r e n t P r o g r a m m i n g i n
Dual Output Stages
putA J a v a putA Cloner putA next2 next1
i n
P r o g r a m m i n g
class Cloner extends DualOutputPushStage implements PushStage { protected synchronized Box dup(Box p) { return p.duplicate(); } public void putA(final Box p) { Box p2 = dup(p); // synched update (not nec.) Runnable r = new Runnable() { public void run() { next1_.putA(p); } }; new Thread(r).start(); // use new thread for A next2_.putA(p2); // current thread for B } } Using second thread for second output maintains liveness
161
C o n c u r r e n t
Configuration
J a v a
P r o g r a m m i n g
i n
BBSource
Painter
Alternator
DIAdaptor
HorizJoin
Collector
BBSource
Painter
DIAdaptor
C o n c u r r e n t
All setup code is of form Stage aStage = new Stage(); aStage.attach(anotherStage);
Would be nicer with a visual scripting tool
162
Overlapped I/O Key to speed-up is independence of tasks Minimize thread communication and synchronization Minimize sharing of resource objects Rely on groups of thread-based objects Worker thread designs Scatter/gather designs 163 C o n c u r r e n t P r o g r a m m i n g i n .Parallel Execution J a v a Classic parallel programming deals with Tightly coupled. fine-grained multiprocessors Large scientific and engineering problems Speed-ups from parallelism are possible in less exotic settings SMPs.
} } 164 .//via callback or join if (have enough results) // one. for each part p start up a thread to process p.Interacting with Groups Group Proxies encapsulate a group of workers and protocol J a v a client proxy serve members scatter P r o g r a m m i n g i n return gather C o n c u r r e n t class GroupProxy implements Service { public Result serve(Data data) { split the data into parts. for each thread t { collect results from t. or some return aggegrate result. all.
k < n. k < n. for (int k = 0. Thread threads[] = new Thread[n]. return results. results[i] = r.Group Service Example public class GroupPictureRenderer { J a v a public Picture[] render(final byte[][] data) throws InterruptedException { int n = data.start(). k++) { final int i = k. threads[i]. } }. } // block until all are finished for (int k = 0. // inner vars must be final threads[i] = new Thread(new Runnable() { public void run() { PictureRenderer r = new PictureRenderer().render(data[i]).join(). final Picture results[] = new Picture[n].length. k++) threads[k]. } } 165 C o n c u r r e n t P r o g r a m m i n g i n .
for (int ii = 0. } catch(InterruptedException e){return.data[(i+1)%NWORKERS]). ii < NWORKERS. public void processPicture(final byte[][] data){ final CyclicBarrier barrier = new CyclicBarrier(NWORKERS). try { barrier. Runnable worker = new Runnable() { public void run() { while (!done()) { transform(data[i]).Iteration using Cyclic Barriers CyclicBarrier is synchronization tool for iterative group algorithms J a v a • Initialize count with number of members • synch() waits for zero.} combine(data[i]. } } }...barrier(). then resets to initial count class PictureProcessor { // . new Thread(worker). ++ii) { final int i = ii. } } } 166 C o n c u r r e n t P r o g r a m m i n g i n .start().
} synchronized boolean barrier() throws Inte. // return true if caller tripped } } } C o n c u r r e n t 167 . private int resets_ = 0. ++resets_. CyclicBarrier(int c) { count_ = initial_ = c.{ if (--count_ > 0) { // not yet tripped int r = resets_.. } else { count_ = initial_.Implementing Cyclic Barriers class CyclicBarrier { J a v a P r o g r a m m i n g i n private int count_. } while (resets_ == r). return false. // wait until next reset do { wait(). notifyAll().. private int initial_. return true.
Layered Services J a v a client Control client part1 subpart1 part2 P r o g r a m m i n g i n Providing concurrency control for methods of internal objects • Applying special synchronization policies • Applying different policies to the same mechanisms Requires visibility control (containment) • Inner code must be communication-closed • No unprotected calls in to or out from island • Outer objects must never leak identities of inner objects • Can be difficult to enforce and check Usually based on before/after methods 168 C o n c u r r e n t .
waiting.Three-Layered Application Designs J a v a Interaction with external world generating threads P r o g r a m m i n g i n Concurrency Control locking. failing C o n c u r r e n t Basic mechanisms Common across many concurrent applications Generally easy to design and implement Maintain directionality of control and locking 169 .
action(). delegate. } } Used by built-in Java synchronized(obj) { action(). post()....Before/After Control Control access to contained object/action via a method of the form J a v a P r o g r a m m i n g void controlled() { pre(). Post: ‘}’ releases lock i n Control code must be separable from ground action code • Control code deals only with execution state • Ground code deals only with intrinsic state Basis for many delegation-based designs ControlledService service() { pre(). } Pre: ‘{‘ obtains lock . } finally { post().. } delegate C o n c u r r e n t GroundService action() { . try { action(). } 170 .
post(). C o n c u r r e n t 171 . protected action(). protected post(). action(). P r o g r a m m i n g i n Template methods • Isolate ground code and control code in overridable protected methods • Public methods call control and ground code in an established fashion • Can provide default versions in abstract classes • Can override the control code and/or the ground code in subclasses ConcreteService override pre() or action() or post(). } protected pre().Template Method Before/After Designs J a v a Subclassing is one way to implement before/after containment designs • Superclass instance variables and methods are “contained” in subclass instances AbstractService public service() { pre().
controlling access to data repository • Any number of reader threads can run simultanously. but writers require exclusive access Many policy variants possible • Mainly surrounding precedence of waiting threads — Readers first? Writers first? FIFO? 172 C o n c u r r e n t .Readers & Writers Policies J a v a threads read write data P r o g r a m m i n g i n Apply when • Methods of ground class can be separated into readers (accessors) vs writers (mutators) — For example.
waitingReaders_ = 0. } finally { afterWrite(). // exec state activeWriters_ = 0. } 173 . } protected boolean allowWriter() { return activeReaders_ == 0 && activeWriters_ == 0. } finally { afterRead(). try { doRead(). J a v a P r o g r a m m i n g i n C o n c u r r e n t public void read() { beforeRead(). } } protected boolean allowReader() { return waitingWriters_ == 0 && activeWriters_ == 0. } } public void write(){ beforeWrite(). waitingWriters_ = 0.Readers & Writers via Template Methods public abstract protected int protected int protected int protected int class RW { activeReaders_ = 0. try { doWrite().
while (!allowReader()) try { wait(). ++activeReaders_. notifyAll(). } catch (InterruptedException ex) { .Readers & Writers (continued) J a v a protected synchronized void beforeRead() { ++waitingReaders_. } { 174 . } --waitingReaders_.. protected synchronized void afterRead() --activeReaders_.. } C o n c u r r e n t P r o g r a m m i n g i n protected abstract void doRead().
while (!allowWriter()) try { wait(). } --waitingWriters_.Readers & Writers (continued) J a v a protected synchronized void beforeWrite() { ++waitingWriters_. protected synchronized void afterWrite() { --activeWriters_. } } 175 C o n c u r r e n t P r o g r a m m i n g i n . } catch (InterruptedException ex) { . notifyAll(). ++activeWriters_. } protected abstract void doWrite()...
Channels.Using Concurrency Libraries J a v a Library classes can help separate responsibilities for Choosing a policy. for example — Exclusive versus shared access — Waiting versus failing — Use of privileged resources Applying a policy in the course of a service or transaction — These decisions can occur many times within a method Standard libraries can encapsulate intricate synchronization code But can add programming obligations • Correctness relies on all objects obeying usage policy • Cannot automatically enforce Examples • Synchronization. Transactions 176 C o n c u r r e n t P r o g r a m m i n g i n .
. // return false if fail boolean attempt(long timeOut). try { action().) { cond.. } finally { cond.release().acquire().Interfaces Sync encompasses many concurrency control policies J a v a Sync void acquire() void release() boolean attempt(long timeOut) P r o g r a m m i n g i n Service service(. // Possibly allow other threads to pass the gate void release(). } } cond ConcreteSync implementations C o n c u r r e n t public interface Sync { // Serve as a gate. fail only if interrupted void acquire() throws InterruptedException. // Try to pass for at most timeout msecs. } 177 .
but that may be acquired and released as needed Mutexes • Non-reentrant locks Read/Write Locks • Pairs of conditions in which the readLock may be shared.Synchronization Libraries Semaphores J a v a • Maintain count of the number of threads allowed to pass Latches • Boolean conditions that are set once. but the writeLock is exclusive 178 C o n c u r r e n t P r o g r a m m i n g i n . ever Barriers • Counters that cause all threads to wait until all have finished Reentrant Locks • Java-style locks allowing multiple acquisition by same thread.
resource controllers • Designs that would otherwise encounter missed signals — Where one thread signals before the other has even started waiting — Semaphores ‘remember’ how many times they were signalled 179 C o n c u r r e n t P r o g r a m m i n g i n . • The semaphore just maintains the current count. no actual permits change hands. then takes one • release adds a permit But in normal implementations.Semaphores Conceptually serve as permit holders J a v a • Construct with an initial number of permits (usually 0) • require waits for a permit to be available. • Enables very efficient implementation Applications • Isolating wait sets in buffers.
release(). synchronized(this) { ++count_. synchronized(this) { --count_. } void inc() throws InterruptedException { incPermits_.acquire().release(). } decPermits_. This avoids nested monitor lockouts 180 C o n c u r r e n t P r o g r a m m i n g i n . } } This uses native synch for update protection. Sync decPermits_= new Semaphore(0). } void dec() throws InterruptedException { decPermits_. } incPermits_.Counter Using Semaphores class BoundedCounterUsingSemaphores { J a v a long count_ = MIN. synchronized long value() { return count_. Sync incPermits_= new Semaphore(MAX-MIN).acquire(). but only inside permit blocks.
acquire(). Semaphore putPermit = new Semaphore(1).acquire().release().Semaphore Synchronous Channel J a v a class SynchronousChannelVS { Object item = null. Object x = item. } } 181 C o n c u r r e n t P r o g r a m m i n g i n . } Object take() throws InterruptedException { takePermit. Semaphore takePermit = new Semaphore(0). item = x.release().release().acquire(). ack. putPermit. ack. takePermit. Semaphore ack = new Semaphore(0). return x. void put(Object x) throws InterruptedException { putPermit.
start(). Worker(Latch l) { go = l. for (int i = 0.acquire().Using Latches Conditions starting out false. } } class Driver { // . } public void run() { go. remain true forever J a v a • Initialization flags • End-of-stream conditions • Thread termination • Event occurrences class Worker implements Runnable { Latch go. doSomethingElse(). // don’t let run yet go. i < N. ++i) // make threads new Thread(new Worker(go)). doWork(). but once set true. // let all threads proceed } } 182 C o n c u r r e n t P r o g r a m m i n g i n .. void main() { Latch go = new Latch().release()..
done.release().acquire(). doSomethingElse(). } } class Driver { // . } public void run() { doWork(). for (int i = 0.. // wait for all to finish } } 183 C o n c u r r e n t P r o g r a m m i n g i n .Using Barrier Conditions Count-based latches J a v a • Initialize with a fixed count • Each release monotonically decrements count • All acquires pass when count reaches zero class Worker implements Runnable { Barrier done.start(). i < N. ++i) new Thread(new Worker(done)).. done. void main() { Barrier done = new Barrier(N). Worker(Barrier d) { done = d.
} } 184 C o n c u r r e n t P r o g r a m m i n g i n . try { d = state_. } finally { lock_.acquire(). } } catch(InterruptedException ex){} return d.acquire(). } void changeState(double d) { try { lock_. private Sync lock_. try { state_ = d. try { lock_.release().0.release(). } finally { lock_. HandSynched(Sync l) { lock_ = l. } } catch(InterruptedException ex) { } } double getState() { double d = 0.0.Using Lock Classes J a v a class HandSynched { private double state_ = 0.
Wrapper Classes Standardize common client usages of custom locks using wrappers J a v a P r o g r a m m i n g i n • Wrapper class supports perform method that takes care of all before/after control surrounding a Runnable command sent as a parameter • Can also standardize failure control by accepting Runnable action to be performed on acquire failure Alternative perform methods can accept blocks that return results and/or throw exceptions • But need to create new interface type for each kind of block Similar to macros in other languages • But implement more safely via inner classes — Wrappers are composable Adds noticeable overhead for simple usages • Most useful for controlling “heavy” actions 185 C o n c u r r e n t .
run(). } } public void perform(Runnable command. public WithLock(Sync c) { cond = c. } catch (InterruptedException ex) { if (onInterrupt != null) onInterrupt.Before/After Wrapper Example J a v a i n class WithLock { Sync cond.run(). else // default Thread.acquire(). } public void perform(Runnable command) throws InterruptedException { cond. try { command. } } } 186 C o n c u r r e n t P r o g r a m m i n g . Runnable onInterrupt) { try { perform(command).release(). } finally { cond.currentThread().interrupt().
HandSynchedV2(Sync l) { withlock_ = new WithLock(l)..0. // use default interrupt action } double getState() { // (need to define interface & perform version) try { return withLock_.perform( new Runnable() { public void run() { state_ = d. private WithLock withlock_.} } } 187 C o n c u r r e n t P r o g r a m m i n g i n . } }. } catch(InterruptedException ex){return 0.Using Wrappers J a v a class HandSynchedV2 { // .perform(new DoubleAction(){ public void run() { return state_. } }). } void changeState(double d) { withlock_..0. private double state_ = 0. null).
attempt can be used in conditional locking idioms Back-offs • Escape out if a lock not available • Can either retry or fail Reorderings • Retry lock sequence in different order if first attempt fails Heuristic deadlock detection • Back off on time-out Precise deadlock detection • Implement Sync via lock manager that can detect cycles 188 C o n c u r r e n t P r o g r a m m i n g i n .Using Conditional Locks J a v a Sync.
value.. Sync lock = new SyncImpl(). try { if (other.value = t. return. } } } finally { lock. } } catch (InterruptedException ex) { return. void swapValue(Cell other) { for (.acquire().lock. } finally { other.lock.release().) { try { lock.attempt(100)) { try { long t = value. } } } } 189 J a v a C o n c u r r e n t P r o g r a m m i n g i n .release(). other. value = other.Back-off Example class Cell { long value.
try { if (!b.value = b. Sync lock = new SyncImpl().attempt(0)) return false. private static boolean trySwap(Cell a.acquire(). a.value = t.lock. other) && !tryswap(other.lock.release(). this)) Thread. try { long t = a. return true. b.Lock Reordering Example class Cell { long value. } } finally { lock. } } 190 J a v a C o n c u r r e n t P r o g r a m m i n g i n . Cell b) { a. } finally { other.lock.value. } void swapValue(Cell other) { while (!trySwap(this. } return false.release().value.yield().
readLock().acquire().run(). Sync writeLock().. try { readCommand.readlock(). } public void performRead(Runnable readCommand) throws InterruptedException { rw..Using Read/Write Locks public interface ReadWriteLock { Sync readLock().) // similar } J a v a C o n c u r r e n t P r o g r a m m i n g i n 191 . } finally { rw. } } public void performWrite(. } Sample usage using wrapper class WithRWLock { ReadWriteLock rw.release(). public WithRWLock(ReadWriteLock l) { rw = l.
adding mechanisms and protocols so keys serve as capabilities Sample interface interface TransactionLock { void begin(Object key).Transaction Locks Associate keys with locks J a v a • Each key corresponds to a different transaction. — Thread. // get rid of key C o n c u r r e n t P r o g r a m m i n g i n void acquire(Object key) throws InterruptedException. void release(Object key). // bind key with lock void end(Object key). } 192 .currentThread() serves as key in reentrant Java synchronization locks • Supply keys as arguments to gating methods • Security frameworks can use similar interfaces.
// update state to reflect current transaction void commit(Object key) throws Failure. // return true if transaction can be committed boolean canCommit(Object key).Transactional Classes J a v a Implement a common transaction control interface. } Transactors must ensure that all objects they communicate with are also Transactors • Control arguments must be propagated to all participants 193 C o n c u r r e n t . // roll back state void abort(Object key). for example: interface Transactor { i n P r o g r a m m i n g // enter a new transaction void join(Object key) throws Failure.
void deposit(Object key. long amount) throws InsufficientFunds. long amount) throws InsufficientFunds. InterruptedException. • They are generally interoperable 194 C o n c u r r e n t P r o g r a m m i n g i n .Per-Method Transaction Control Add transaction control argument to each method. void withdraw(Object key. } The same interfaces can apply to optimistic transactions • Use interference detection rather than locking. J a v a For example: interface TransBankAccount extends Transactor { long balance(Object key) throws InterruptedException. InterruptedException.
. } class Account extends Transactor { private long balance_.currentThread().getThreadGroup())) .Per -ThreadGroup Transaction Control Assumes each transaction established in own ThreadGroup J a v a class Context { // . { tlock_. void deposit(long amount) throws .getContext(). Object get(Object name).. else .. // . private TransactionLock tlock_... Object val)... void bind(Object name.. } } } 195 C o n c u r r e n t P r o g r a m m i n g i n . Context getContext().get("TransactionID")). } class XTG extends ThreadGroup { // . synchronized (this) { if (amount >= 0) balance_ += amount...acquire(((XTG) (Thread.
. checkpointing.. timing. lock dependencies Introducing new policies in sub-actions • New threads. . transactions. . subtransactions • Avoiding policy conflicts: policy compatibility matrices. computational resources Dealing with multiple outcomes • Block. save state.. Encapsulating associated policy control information • For example access control lists.Integrating Control Policies Dealing with multiple contextual domains. keys. including J a v a • Security: Principal identities. groups. layered virtual machines 196 C o n c u r r e n t P r o g r a m m i n g i n . • Scheduling: Priorities. etc • Synchronization: Locks. commit state. Avoiding excessive programming obligations for developers Tool-based code generation.. rights-transfers.. conditions. notify. fail. etc • Environment: Location. . proceed. conditions..
db. balance += amount.Using Integrated Control J a v a Methods invoke helpers to make control decisions as needed class Account { // .. amount). acl). } } Not much fun to program. void deposit(long amount.acquire().release(). transID. db..checkpoint(this).. 197 C o n c u r r e n t P r o g r a m m i n g i n . UIObservers. accessController.) { authenticator.). .authenticate(clientID). logger. lock.shadowDeposit(.commit(balance.. replicate...checkAccess(clientID..logDeposit(clientID..notifyOfChange(this). . lock.).
but more complex and fragile code 198 C o n c u r r e n t P r o g r a m m i n g i n . locking.Implementing Library Classes J a v a Classes based on Java monitor methods can be slow • Involve context switch. and scheduling overhead • Relative performance varies across platforms Some performance enhancements State tracking • Only notify when state changes known to unblock waits Isolating wait sets • Only wake up threads waiting for a particular state change Single notifications • Only wake up a single thread rather than all waiting threads Avoiding locks • Don’t lock if can be sure won’t wait Can lead to significantly faster.
on exit from top or bottom — When count goes up from MIN or down from MAX • Still need notifyAll unless add instrumentation State tracking leads to faster but more fragile code • Usually many fewer notification calls • Harder to change guard conditions • Harder to add subclasses with different conditions 199 C o n c u r r e n t .Tracking State in Guarded Methods J a v a Partition action control state into categories with same enabling properties top P r o g r a m m i n g State Condition top value == MAX middle MIN < value < MAX bottom value == MIN inc no yes yes dec yes yes no i n dec from MAX inc to MAX middle dec to MIN inc from MIN bottom Only provide notifications when making a state transition that can ever unblock another thread • Here.
if (count_++ == MIN) notifyAll(). } synchronized void inc() throws InterruptedException { while (count_ == MAX) wait(). .== MAX) } } 200 C o n c u r r e n t P r o g r a m m i n g i n notifyAll(). synchronized long value() { return count_. if (count_-.Counter with State Tracking J a v a class FasterGuardedBoundedCounter { protected long count_ = MIN. } synchronized void dec() throws InterruptedException { while (count_ == MIN) wait().
Buffer with State Tracking
J a v a
class BoundedBufferVST { Object[] data_; int putPtr_ = 0, takePtr_ = 0, size_ = 0; protected void doPut(Object x){ data_[putPtr_] = x; putPtr_ = (putPtr_ + 1) % data_.length; if (size_++ == 0) notifyAll(); } protected Object doTake() { Object x = data_[takePtr_]; data_[takePtr_] = null; takePtr_ = (takePtr_ + 1) % data_.length; if (size_-- == data_.length) notifyAll(); return x; } synchronized void put(Object x) throws Inte... { while (isFull()) wait(); doPut(x); } // ... }
201
C o n c u r r e n t
P r o g r a m m i n g
i n
Inheritance Anomaly Example
class XBuffer extends BoundedBufferVST { synchronized void putPair(Object x, Object y) throws InterruptedException { put(x); put(y); } } PutPair does not guarantee that the pair is inserted contiguously To ensure contiguity, try adding guard: while (size_ > data_.length - 2) wait(); But doTake only performs notifyAll when the buffer transitions from full to not full • The wait may block indefinitely even when space available • So must rewrite doTake to change notification condition Would have been better to factor out the notification conditions in a separate overridable method • Most inheritance anomalies can be avoided by fine-grained (often tedious) factoring of methods and classes
202 J a v a C o n c u r r e n t P r o g r a m m i n g i n
Isolating Waits and Notifications
Mixed condition problems
J a v a
i n
• Threads that wait in different methods in the same object may be blocked for different reasons — for example, not Empty vs not Full for buffer • notifyAll wakes up all threads, even those waiting for conditions that could not possibly hold Can isolate waits and notifications for different conditions in different objects — an application of splitting Thundering herd problems • notifyAll may wake up many threads • Often, at most one of them will be able to continue Can solve by using notify instead of notifyAll only when All threads wait on same condition At most one thread could continue anyway • That is, when it doesn’t matter which one is woken, and it doesn’t matter that others aren’t woken
203
C o n c u r r e n t
P r o g r a m m i n g
Implementing Reentrant Locks
J a v a
final class ReentrantLock implements Sync { private Thread owner_ = null; private int holds_ = 0; synchronized void acquire() throws Interru... { Thread caller = Thread.currentThread(); if (caller == owner_) ++holds_; else { try { while (owner_ != null) wait(); } catch (InterruptedException e) { notify(); throw e; } owner_ = caller; holds_ = 1; } } synchronized void release() { Thread caller = Thread.currentThread(); if (caller != owner_ || holds_ <= 0) throw new Error("Illegal Lock usage"); if (--holds_ == 0) { owner_ = null; notify(); } }}
204
C o n c u r r e n t
P r o g r a m m i n g
i n
Implementing Semaphores
J a v a
final class Semaphore implements Sync { int permits_; int waits_ = 0; Semaphore(int p) { permits_ = p; } synchronized void acquire() throws Interrup.. { if (permits_ <= waits_) { ++waits_; try { do { wait(); } while (permits_ == 0); } catch(InterruptedException ex) { --waits_; notify(); throw ex; } --waits_; } --permits_; } synchronized void release() { ++permits_; notify(); } }
205
C o n c u r r e n t
P r o g r a m m i n g
i n
Implementing Latches
Exploit set-once property to avoid locking using double-check:
J a v a
Check status without even locking • If set, exit — no possibility of conflict or stale read • Otherwise, enter standard locked wait But can have surprising effects if callers expect locking for sake of memory consistency. final class Latch implements Sync { private boolean latched_ = false; void acquire() throws InterruptedException { if (!latched_) synchronized(this) { while (!latched_) wait(); } } synchronized void release() { latched_ = true; notifyAll(); } }
206
C o n c u r r e n t
P r o g r a m m i n g
i n
} void acquire() throws InterruptedException { if (count_ > 0) synchronized(this) { while (count_ > 0) wait(). } } 207 C o n c u r r e n t P r o g r a m m i n g i n . CountDown(int initialc) { count_ = initialc. } } synchronized void release() { if (--count_ == 0) notifyAll().Implementing Barrier Conditions J a v a Double-check can be used for any monotonic variable that is tested only for a threshold value CountDown Barriers monotonically decrement counts • Tests against zero cannot encounter conflict or staleness (This technique does not apply to Cyclic Barriers) class CountDown implements Sync { private int count_.
Implementing Read/Write Locks class SemReadWriteLock implements ReadWriteLock { J a v a // Provide fair access to active slot Sync active_ = new Semaphore(1). // Control slot sharing by readers class ReaderGate implements Sync { int readers_ = 0. } synchronized void release() { if (--readers_ == 0) active_. public Sync writeLock() { return active_. synchronized void acquire() throws InterruptedException { // readers pile up on lock until first passes if (readers_++ == 0) active_. } } 208 C o n c u r r e n t P r o g r a m m i n g i n .release().acquire(). } } Sync rGate_ = new ReaderGate(). } public Sync readLock() { return rGate_.
usage limitations. protocols. and interfaces • Standard design patterns. etc • Describe necessary data invariants etc Use checklists to ensure minimal sanity 209 C o n c u r r e n t P r o g r a m m i n g i n . and frameworks • Standard coding idioms and conventions Document decisions • Use javadoc to link to more detailed descriptions • Use naming and signature conventions as shorthand clues • Explain deviations from standards.Documenting Concurrency J a v a Make code understandable • To developers who use components • To developers who maintain and extend components • To developers who review and test components Avoid need for extensive documentation by adopting: • Standard policies. libraries.
.).. throws InterruptedException Intentional limitations. and how to work around them /** . methods that can block have signature . * so accessor method is unsynchronized **/ protected int bufferSize.. Certification /** Passed safety review checklist 11Nov97 **/ 210 C o n c u r r e n t P r o g r a m m i n g .html”>Thread-per-Message</a> **/ void handleRequest(...Sample Documentation Techniques Patlet references J a v a i n /** . Default naming and signature conventions Sample rule: Unless specified otherwise. **/ Decisions impacting potential subclassers /** .. Uses * <a href=”tpm.. Always maintains a legal value. NOT Threadsafe.... but can be used with * @see XAdapter to make lockable version.
OUT — Guaranteed message send (relays... C o n c u r r e n t P r o g r a m m i n g i n INIT — Object constraint that must hold upon construction /** INIT: bufferCapacity greater than zero. WHEN — Guard condition (always checked) /** WHEN not empty return oldest .signal().. RELY — Required property of other objects/methods /** RELY: Must be awakened by x.... INV — Object constraint true at start/end of every activity /** INV: x.. 211 ..y are valid screen coordinates. etc) /** OUT: c...process(buff) called after read...Semiformal Annotations PRE J a v a — Precondition (normally unchecked) /** PRE: Caller holds synch lock . callbacks... POST — Postcondition (normally unchecked) /** POST: Resource r is released.
race conditions Atomicity errors • Breaking locks in the midst of logically atomic operations Representation inconsistencies • Allowing dependent representations to vary independently Invariant failures • Failing to re-establish invariants within atomic methods for example failing to clean up after exceptions Semantic conflicts • Executing actions when they are logically prohibited Slipped Conditions • A condition stops holding in the midst of an action requiring it to hold Memory ordering and visibility • Using stale cached values 212 C o n c u r r e n t P r o g r a m m i n g i n .Safety Problem Checklist Storage conflicts J a v a • Failure to ensure exclusive access.
CPU limitations 213 C o n c u r r e n t P r o g r a m m i n g i n . bandwidth.Liveness Problems Lockout J a v a • A called method never becomes available Deadlock • Two or more activities endlessly wait for each other Livelock • A retried action never succeeds Missed signals • A thread starts waiting after it has already been signalled Starvation • A thread is continually crowded out from passing gate Failure • A thread that others are waiting for stops Resource exhaustion • Exceeding memory.
Efficiency Problems Too much locking J a v a • Cost of using synchronized • Cost of blocking waiting for locks • Cost of thread cache flushes and reloads Too many threads • Cost of starting up new threads • Cost of context switching and scheduling • Cost of inter-CPU communication. etc 214 C o n c u r r e n t P r o g r a m m i n g i n . messages. cache misses Too much coordination • Cost of guarded waits and notification messages • Cost of layered concurrency control Too many objects • Cost of using objects to represent state.
and/or error-prone programming obligations 215 C o n c u r r e n t P r o g r a m m i n g i n . premature optimization Policy clashes • Components with incompatible concurrency control strategies Inheritance anomalies • Classes that are difficult or impossible to subclass Programmer-hostile components Components imposing awkward. implicit .Reusability Problems Context dependence J a v a • Components that are not safe/live outside original context Policy breakdown • Components that vary from system-wide policies Inflexibility • Hardwiring control.
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/63448084/Concurrent-Prog | CC-MAIN-2016-07 | refinedweb | 21,260 | 53.71 |
Opened 5 years ago
Closed 5 years ago
Last modified 5 years ago
#19283 closed Bug (fixed)
Django CBV examples have broken import.
Description (last modified by )
In several places it is
from django import models.
It is supposed to be
from django.db import models.
Change History (8)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
comment:3 Changed 5 years ago by
For sure they're there
element:docs (master)$ ack -a 'from django import models' ./ref/class-based-views/generic-editing.txt 19: from django import models ./topics/class-based-views/generic-editing.txt 93: from django import models 163: from django import models element:docs (master)$
comment:4 follow-up: 5 Changed 5 years ago by
Oh ok, i was grepping for "djangoimport" actually. Can the description of the bug be updated ?
comment:5 Changed 5 years ago by
Replying to ssidorenko:
Oh ok, i was grepping for "djangoimport" actually. Can the description of the bug be updated ?
I lack the ability to edit the ticket now that it's been accepted. Perhaps a core developer has those rights?
I cannot find the problem you are describing, can you post a link or a path where it can be found ? | https://code.djangoproject.com/ticket/19283 | CC-MAIN-2018-09 | refinedweb | 210 | 56.86 |
Cross Language Integration
Note: This has been written as a notebook so you can download it to run it yourself using jupyter or nteract, view it on GitHub, or on nbviewer if you prefer the classical notebook rendering. It originally should have appeared on my blog.
I would be happy to know if you can get it to work on binder.
[UPDATE]
Thanks to Michael Pacer for copy-editting this. Also note that this notebook is basedaround multiple example that have been written by various people across many years.
An often requested feature for the Jupyter Notebook is the ability to have multiple kernels, often in many languages, for a single notebook.
While the request in spirit is a perfectly valid one, it is often a misunderstanding of what having a single kernel means. In particular having multiple language is often easier if you have a single process which handle the dispatching of various instructions to potentially multiple underlying languages. It is possible to do that in a Single Kernel which does orchestrate dispatching instruction and moving data around.
Whether the multiple languages that get orchestrated together are remote processes, or simply library calls or more complex mechanisms becomes an implementation detail.
Python is known to be a good "glue" language, and over the year the IPython kernel have seen a growing number of extensions showing that dynamic cross language integration can be seamless form the point of view of the user.
In the following we only scratch the surface of what is possible across a variety of languages. The approach shown here is one among many. The Calysto organisation for example has several projects taking different approaches on the problem.
In the following I will show a quick overview on how you can in single notebook interact with many languages, via subprocess call (Bash, Ruby), Common Foreign function interface (C, Rust, Fortran, ...), or even crazier approaches (Julia).
The rest of this is mostly a demo on how cross-language integration works in a Jupyter notebook by using the features of the Reference IPython Kernel implementation. These features are completely handled in the kernel so need to be reimplemented on a per-kernel basis. Though they also work on pure terminal IPython, nbconvert or any other programmatic use of IPython.
Most of what you will see here are just thin wrappers around already existing libraries. These libraries (and their respective authors) do all the heavy lifting. I just show how seamless a cross language environment can be from the user point of view. The installation of these library might not be easy either and getting all these language to play together can be complex task. It is though becoming easier and easier.
The term just does not imply that the wrappers are simple, or easy to write. It indicate that the wrappers are far from being complete. What is shown here is completely doable using standard Python syntax and bit of manual work. SO what you'll see here is mostly convenience.
Understanding the multiple languages themselves is not necessary; most of the code here should self explanatory and straightforward. We'll define many function that compute the nth
Fibonacci number more or less efficiently. We'll define them either using the classic recursive implementation, or sometime using an unrolled optimized version. As a reminder the Fibonacci sequence is defines a the following:
The fact that we calculate the Fibonacci sequence as little importance, except that the value of $F_n$ can grow really fast in $O(e^n)$ if I remember correctly. And the recursive implementation will have a hard time getting beyond (n=100) as the number of call will be greater than $O(e^n)$ as well. Be careful especially if you calculate $F_{F_n}$ or more composition. Remembering that n=5 is stable via $F$ might be useful.
Here are the first terms of the Fibonacci sequence:
- 1
- 1
- 1+1 = 2
- 2+1 = 3
- 3+2 = 5
- 5+3 = 8
- 8+5 = 13 ...
import sys sys.version_info
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
Python offer many facilities to call into other languages, whether we "shell-out" or use the C-API. The easiest for the end user is often to use
subprocess , with the recently added
run command. Though it might be annoying to define all foreign code in strings and calling the subprocess run function manually.
This is why in the following you will see 2 constructs:
optional_python_lhs = %language (language RHS expression)
As well as
%%language --cli like arguments A block: containing expressions and statement from another: language
IPython define these which are called Magics. A single percent :
%something for line magics, act only on the rest of the line, and cells magics (start with
%%)
One example of line magic is
%timeit, which runs the following statement multiple time to get statistics about runtime:
%timeit [x for x in range(1000)]
10000 loops, best of 3: 34.9 µs per loop
The IPython team special cased a couple of these for foreign languages, here ruby. We define the
fibonacci function, compute the 15th value, print it to standard out from Ruby, and capture the value variable in the python
fib15.
%%ruby --out fib15 def fibonacci( n ) return n if ( 0..1 ).include? n ( fibonacci( n - 1 ) + fibonacci( n - 2 ) ) end puts fibonacci( 15 )
fib15
'610\n'
Now from with Python we can do a crude parsing of the previous string output, and get the value of Fibonacci of 15.
int(fib15.strip())
610
Ok, that's somewhat useful, but not really that much. It's convenient for self contain code. You cannot pass variable in... or can't you ?
Calling subprocess can be quite cumbersome when working interactively, we saw above that
%% cells-magics can be of help, but you might want to shell out in the middle of a python function. Let's create a bunch of random file-names and fake some subprocess operations with it.
import random import string def rand_names(k=10,l=10): for i in range(k): yield '_' + ''.join(random.choice(string.ascii_letters) for i in range(l))+'.o'
The
!something expression is – for the purpose of these demo – equivalent to
%sh something $variable where
$variable is looked up in
locals() and replaced by it's
__repr__
for f in rand_names(): print('creating file',f) !touch $f
creating file _XiKZxtsLwX.o creating file _DKCjzvlTuF.o creating file _ShTGoJMxCp.o creating file _nbockcrTbT.o creating file _cZnVpuYsxJ.o creating file _UYxnHlwJwy.o creating file _fxoVMPQbJV.o creating file _wJJUbrPzpq.o creating file _ngMMBxaDkG.o creating file _uKbssAzHBP.o
ls -1 *.o
We can as well get values back using the
! syntax
files = !ls *.o files
['']
!rm -rf *.{o,c,so} Cargo.* src target
ls *.o
ls: *.o: No such file or directory
Ok, our directory is clean !
Ok, that was kind of cute, fire-up a subprocess, serialize, pipe data in as a string, pipe-data out as a string, kill subprocess... What about something less state-less, or more stateful?
Let's define the
fibonacci function in python:
def fib(n): """ A simple definition of fibonacci manually unrolled """ if n<2: return 1 x,y = 1,1 for i in range(n-2): x,y = y,x+y return y
[fib(i) for i in range(1,10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
Store the value from 1 to 30 in
Y, and graph it.
%matplotlib inline import numpy as np X = np.arange(1,30) Y = np.array([fib(x) for x in X]) import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.scatter(X, Y) ax.set_xlabel('n') ax.set_ylabel('fib(n)') ax.set_title('The Fibonacci sequence grows fast !')
<matplotlib.text.Text at 0x10caff470>
It may not surprise you, but this looks like an exponential, so if we were to look at $log(fib(n))$ × $n$ it would look approximately like a line. We can try to do a linear regression using this model. R is a language many people use to do statistics. So, let's use R.
(Side note, you might need to change the environment variable passed to your kernel for this to work. Here is what I had to do only once.)
#!a2km add-env 'python 3' DYLD_FALLBACK_LIBRARY_PATH=$HOME/anaconda/pkgs/icu-54.1-0/lib:/Users/bussonniermatthias/anaconda/pkgs/zlib-1.2.8-3/lib
import rpy2.rinterface %load_ext rpy2.ipython
The Following will "Send" the X and Y array to R.
%Rpush Y X
And now let's try to fit a linear model ($ln(Y) = A.X + B$) using R. I'm not a R user myself, so don't take this as idiomatic R.
%%R my_summary = summary(lm(log(Y)~X)) val <- my_summary$coefficients plot(X, log(Y)) abline(my_summary)
%%R my_summary
Call: lm(formula = log(Y) ~ X) Residuals: Min 1Q Median 3Q Max -0.183663 -0.013497 -0.004137 0.006046 0.296094 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -0.775851 0.026173 -29.64 <2e-16 *** X 0.479757 0.001524 314.84 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.06866 on 27 degrees of freedom Multiple R-squared: 0.9997, Adjusted R-squared: 0.9997 F-statistic: 9.912e+04 on 1 and 27 DF, p-value: < 2.2e-16
Good, we have now the some statistics on the fit, which also looks good. And we were able to not only send variable to R, but to plot directly from R !
We are happy as $F_n = \left[\frac{\phi^n}{\sqrt 5}\right]$, where
[] is closest integer and $\phi = \frac{1+\sqrt 5}{2}$
We can also look at the variables more carefully
%%R val
Estimate Std. Error t value Pr(>|t|) (Intercept) -0.7758510 0.026172673 -29.64355 3.910319e-22 X 0.4797571 0.001523832 314.83597 1.137181e-49
Or even the following that looks more like python
%R val
array([[ -7.75850975e-01, 2.61726725e-02, -2.96435519e+01, 3.91031947e-22], [ 4.79757090e-01, 1.52383191e-03, 3.14835966e+02, 1.13718145e-49]])
We can even get the variable back from R as Python objects:
coefs = %Rget val y0,k = coefs.T[0] y0,k
(-0.77585097534858738, 0.4797570904348315)
That's all from the R part. I hope this shows you some of the power of IPython, both in notebook and command line.
Great! We were able to send data back and forth! If does not works for all objects, but at least for the basic ones. It requires quite some work from the authors of the underlying library to allow you to do that. Though we are still limited to data. We can't (yet) send functions over which limits the utility.
One of the critical point of any code may at some point be performance. Python is known to not be the most performant language, though it is convenient and quick to write and has a large ecosystem. Most of the function you requires are probably available in a package, battle tested and optimized.
You might still need here and there the raw power of an ubiquitous language which is known for its speed when you know how to wield it well: C.
Though one of the disadvantage of C is the (relatively) slow iteration process due to the necessity of compilation/run part of the cycle. Let see if we can improve that by leveraging the excellent CFFI project, using my own small cffi_magic wrapper.
import cffi_magic
rm -rf *.o *.c *.so Cargo.* src target
ls *.c *.h *.o
ls: *.c: No such file or directory ls: *.h: No such file or directory ls: *.o: No such file or directory
Using the
%%cffi magic we can define in the middle of our python code some C function:
%%cffi int cfib(int); int cfib(int n) { int res=0; if (n <= 1){ res = 1; } else { res = cfib(n-1)+cfib(n-2); } return res; }
The first line take the "header" of the function we declare, and the rest of the cell takes the body of this function. The
cfib function will automatically be made available to you in the main python namespace.
cfib(5)
8
Oops there is a mistake as we should have
fib(5) == 5. Luckily we can redefine the function on the fly. I could edit the above cell, but here as this will be rendered statically for the sake of demo purpose, I'm going to make a second cell:
%%cffi int cfib(int); int cfib(int n) { int res=0; if (n <= 2){ /*mistake was here*/ res = 1; } else { res = cfib(n-1)+cfib(n-2); } return res; }
cfib(5)
5
Great ! Let's compare the timing.
%timeit cfib(10)
The slowest run took 73.42 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 379 ns per loop
%timeit fib(10)
The slowest run took 4.65 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 853 ns per loop
Not so bad considering the C implementation is recursive, and the Python version is manually hand-rolled.
So how do we do that magically under the hood? The knowledgeable reader is aware that CPython extensions cannot be reloaded. Though here we redefine the function... how come?
Using the user provided code we compile a shared object with a random name, import this as a module and alias using a user friendly name in the
__main__ namespace. If the user re-execute we just get a new name, and change the alias mapping.
If one wan to optimize you can use a hash of the codecell string to not recompile if the user hasn't changed the code.
ls *.o *.c
_cffi_cWtAstIlGT.c _cffi_cWtAstIlGT.o _cffi_yxGAKIqXRR.c _cffi_yxGAKIqXRR.o
With this in mind you can guess the same can be done for any language which can be compiled to a shared object, or a dynamically loadable library.
%%rust int rfib(int); #[no_mangle] pub extern fn rfib(n: i32) -> i32 { match n { 0 => 1, 1 => 1, 2 => 1, _ => rfib(n-1)+rfib(n-2) } }
injecting rfib in user ns
[rfib(x) for x in range(1,10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
I'm not a Rustacean, but the above seem pretty straightforward to me. Again this might not be idiomatic Rust but you should be able to decipher what's above. The same than for C applies.
Both the C and Rust example shown above use the
cffi_magic on which I spent roughly 4 hours total, so the functionalities can be really crude and the documentation minimal at best. Feel free to send PRs if you are interested.
The fortran magic does the same as above, but has been developed by mgaitan and is slightly older. Again no surprise except you are supposed to mark fortran variable that are used to return the values.
%load_ext fortranmagic
/Users/bussonniermatthias/anaconda/lib/python3.5/site-packages/fortranmagic.py:147: UserWarning: get_ipython_cache_dir has moved to the IPython.paths module since IPython 4.0. self._lib_dir = os.path.join(get_ipython_cache_dir(), 'fortran')
%%fortran RECURSIVE SUBROUTINE ffib(n, fibo) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER, INTENT(OUT) :: fibo INTEGER :: tmp IF (n <= 2) THEN fibo = 1 ELSE CALL ffib(n-1,fibo) CALL ffib(n-2,tmp) fibo = fibo + tmp END IF END SUBROUTINE ffib
[ffib(x) for x in range(1,10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
No surprise here, you are well aware of what we are doing.
import cython
%load_ext cython
%%cython def cyfib(int n): # note the `int` here """ A simple definition of fibonacci manually unrolled """ cdef int x,y # and the `cdef int x,y` here if n < 2: return 1 x,y = 1,1 for i in range(n-2): x,y = y,x+y return y
[cyfib(x) for x in range(1,10)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
%timeit -n100 -r3 fib(5)
100 loops, best of 3: 648 ns per loop
%timeit -n100 -r3 cfib(5)
The slowest run took 11.60 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 578 ns per loop
%timeit -n100 -r3 ffib(5)
100 loops, best of 3: 147 ns per loop
%timeit -n100 -r3 cyfib(5)
100 loops, best of 3: 45.6 ns per loop
The benchmark result can be astonishing, but keep in mind that the Python and Cython version use manually unrolled loop. Main point being that we reached our goal and used Fortran, Cython, C (and Rust) in the middle of our Python program.
[let's skip the Rust fib version, it tends to segfault, and it would be sad to segfault now :-) ]
# %timeit rfib(10)
So can we do a layer cake? Can we call rust from Python from Fortran from Cython? Or Cython from C from Fortran? Or Fortron from Cytran from Cust?
import itertools lookup = {'c':cfib, # 'rust': rfib, # as before Rust may segfault, but I dont' know why ... 'python': fib, 'fortran': ffib, 'cython': cyfib } print("Pray the demo-gods it wont segfault even without rust...")
Pray the demo-gods it wont segfault even without rust...
for function in lookup.values(): assert function(5) == 5, "Make sure all is correct or will use 100% CPU for a looong time."
for order in itertools.permutations(lookup): t = 5 for f in order: t = lookup[f](t) print(' -> '.join(order), ':', t)
fortran -> cython -> python -> c : 5 fortran -> cython -> c -> python : 5 fortran -> python -> cython -> c : 5 fortran -> python -> c -> cython : 5 fortran -> c -> cython -> python : 5 fortran -> c -> python -> cython : 5 cython -> fortran -> python -> c : 5 cython -> fortran -> c -> python : 5 cython -> python -> fortran -> c : 5 cython -> python -> c -> fortran : 5 cython -> c -> fortran -> python : 5 cython -> c -> python -> fortran : 5 python -> fortran -> cython -> c : 5 python -> fortran -> c -> cython : 5 python -> cython -> fortran -> c : 5 python -> cython -> c -> fortran : 5 python -> c -> fortran -> cython : 5 python -> c -> cython -> fortran : 5 c -> fortran -> cython -> python : 5 c -> fortran -> python -> cython : 5 c -> cython -> fortran -> python : 5 c -> cython -> python -> fortran : 5 c -> python -> fortran -> cython : 5 c -> python -> cython -> fortran : 5
print('It worked ! I can run all the permutations !')
It worked ! I can run all the permutations !
If you have a small idea about how the above layer-cake is working you'll understand that there is (still) a non-negligible overhead as between each language switch we need to go back to Python-land. And the scope in which we can access function is still quite limited. The following is some really Dark Magic concocted by Fernando Perez and Steven Johnson using the Julia programming language. I can't even pretend to understand how this possible, but it's really impressive to see.
Let's try to handwave what's happening. I would be happy to get corrections.
The crux is that the Python and Julia interpreters can be started in a way where they each have access to the other process memory. Thus the Julia and Python interpreter can share live objects. You then "just" need to teach the Julia language about the structure of Python objects and it can manipulate these as desired, either directly (if the memory layout allow it) or using proxy objects that "delegate" the functionality to the python process.
The result being that Julia can import and use Python modules (using the Julia
PyCall package), and Julia functions are available from within Python using the
pyjulia module.
Let's see how this look like.
%matplotlib inline
%load_ext julia.magic
Initializing Julia interpreter. This may take some time...
julia_version = %julia VERSION julia_version # you can see this is a wrapper
<PyCall.jlwrap 0.5.0>
He we tell the julia process to import the python matplotlib module, as well as numpy.
%julia @pyimport matplotlib.pyplot as plt
%julia @pyimport numpy as np
%%julia # Note how we mix numpy and julia: t = linspace(0, 2*pi,1000); # use the julia `linspace` and `pi` s = sin(3*t + 4*np.cos(2*t)); # use the numpy cosine and julia sine fig = plt.gcf() # **** WATCH THIS VARIABLE **** plt.plot(t, s, color="red", linewidth=2.0, linestyle="--", label="sin(3t+4.cos(2t))")
[<matplotlib.lines.Line2D at 0x327caeb70>]
All the above block of code is Julia, where,
linspace,
pi,
sin are builtins of Julia.
np.* and
plt.* are referencing Python function and methods.
We see that
t is a Julia "Array" (technically a
1000-element LinSpace{Float64}), which can get sent to
numpy.cos, multiply by a Julia int, (..etc) and end up being plotted via matplotlib (Python), and displayed inline.
Let's finish our graph in Python
import numpy as np fig = %julia fig fig.axes[0].plot(X[:6], np.log(Y[:6]), '--', label='fib') fig.axes[0].set_title('A weird Julia function and Fib') fig.axes[0].legend() fig
Above we get the reference to our previously defined figure (in Julia), plot the log of our
fib function.
The key value here is that we get the same object from within Python and Julia. But let's push even further.
Above we had explicit transition between the Julia code and the Python code. Can we be more sneaky?
One toy example is to define the Fibonacci function using the recursive form and explicitly pass the function with which we recurse.
We'll define such a function both on the Julia and Python side, ask the Julia function to recurse by calling the Python one, and the Python one to recurse using the Julia one.
Let's print
(P when we enter Python Kingdom,
(J when we enter Julia Realm, and close the parenthesis accordingly:
from __future__ import print_function # julia fib function jlfib = %julia _fib(n, pyfib) = n <= 2 ? 1 : pyfib(n-1, _fib) + pyfib(n-2, _fib) def pyfib(n, _fib): """ Python fib function """ print('(P', end='') if n <= 2: r = 1 else: print('(J', end='') # here we tell julia (_fib) to recurse using Python r = _fib(n-1, pyfib) + _fib(n-2, pyfib) print(')',end='') print(')',end='') return r
fibonacci = lambda x: pyfib(x, jlfib) fibonacci(10)
(P(J(P(J(P(J(P(J(P)(P)))(P(J))(P(J))(P)))(P(J(P(J))(P)(P)(P)))(P(J(P(J))(P)(P)(P)))(P(J(P)(P)))))(P(J(P(J(P(J))(P)(P)(P)))(P(J(P)(P)))(P(J(P)(P)))(P(J))))(P(J(P(J(P(J))(P)(P)(P)))(P(J(P)(P)))(P(J(P)(P)))(P(J))))(P(J(P(J(P)(P)))(P(J))(P(J))(P)))))
55
I hope you enjoyed that, I find it quite interesting and useful when you need to leverage the tools available across multiple domains. I'm sure there are plenty of other tools that allow this kind of things and a host of other languages that can interact with each other in this way.
From the top of my head I know of a few magics (SQL, Redis...) that provide such integration. Every language has its strong and weak points, and knowing what to use is often hard. I hope I convinced you that mixing languages is not such a daunting task.
The other case when this is useful is when you are learning a new language, you can leverage your current expertise temporarily and get something that work before learning the idiomatic way and available libraries.
Here is a Fibonacci cat to thank you from reading until the end, sorry, no banana for scale.
from IPython.display import Image print('Pfiew') Image('')
Pfiew | https://matthiasbussonnier.com/posts/23-Cross-Language-Integration.html | CC-MAIN-2019-09 | refinedweb | 3,985 | 72.56 |
Part 7. Capital Budgeting
- Philomena Booth
- 2 years ago
- Views:
Transcription
1 Part 7. Capital Budgeting What is Capital Budgeting? Nancy Garcia and Digital Solutions Digital Solutions, a software development house, is considering a number of new projects, including a joint venture with another company. Digital Solutions would provide the software expertise to do the development, while the other company, American Financial Consultants (AFC) would be responsible for the marketing. Nancy Garcia of Digital Solutions would be responsible for assessing the financial viability of the plan. Information about the costs and revenues of the project would come from the accounting, production and marketing groups of the two companies; however, Ms. Garcia would have to put the information together, and provide a preliminary analysis that she would present to the company s managers. Capital budgeting is the process of making a decision about the financial desirability of a project. The proposed software development project at Digital Solutions is an example of this kind of problem. We will see how Nancy Garcia approaches this problem as a way to learn the techniques of capital budgeting. The Big Picture Businesses are about increasing the wealth of their owners, which means that they should pursue all the profitable projects that they can. Capital budgeting is about deciding which projects are profitable and add to the value of the firm. Sometimes the firm has to choose between two or more projects and can only pick one. For example, you may have a choice between two air-conditioning systems with different installation costs and energy costs. Your decision to install one rules out the installation of the other. Both systems may be wealth improving but you can t accept both. You want to pick the one that increases wealth by the most. When you have mutually exclusive projects, such as in this situation, you take a ranking approach to decision making, by ranking projects in order from best to worst. Other times, there are independent projects, where the choice to do one project does not affect the returns of the other projects. For example, an airline may be considering proposals to expand into 10 different cities. It could choose to add routes to all cities, to some cities, or to none. This leads to the accept-reject approach to making decisions. You accept all proposals that increase owners wealth and reject those that don t. Of course, even if projects are not technically mutually exclusive, businesses can find themselves limited in the projects they can do by capital rationing. Capital rationing means that there are limits on the amount of funds a company can raise to finance capital expansion. Ideally, capital markets should provide funds for all wealth improving projects, however, in certain circumstances firms may be restricted in what they can do. For example, the airline may not be able to issue enough debt to buy new airplanes to service all ten new cities. Or it may be that a business is reluctant to issue new stock because of concerns of diluting ownership. When there is capital rationing, firms need to treat their new projects like mutually exclusive projects and use a 72
2 ranking approach. The airline should rank which cities provide the greatest potential for profits and expand into those cities first. Sometimes the number of projects that can be done may also be limited by other resources of the company such as managerial expertise or specialized machinery. In this case, you also need to rank projects according to desirability, while recognizing that this is probably a short-run constraint. Once some projects are done, the company can move on to other projects; and given time, it can also hire additional employees and equipment. Nancy Garcia s Plan of Action Nancy s instructions are, for the moment, to treat this proposal as an independent project, and so not worry about other projects the firm is considering. Given this, she now needs to develop a plan of how to proceed. She (and we) will approach the problem in five steps: 1. Determine the relevant cash flows including different possible outcomes. 2. Assess the rough financial viability of the most-likely outcome. 3. Use more sophisticated capital budgeting techniques to evaluate the project. 4. Provide quantitative measures of risks the project faces. 5 Determine how these risks affect the decision to do the project. The Time-Line of a Capital Project The first step in any capital budgeting decision is to list all the relevant cash flows. This is the hardest part of the process since it depends on having a detailed understanding of the business and requires the manager to forecast what will happen with the project in the future. It is also the most important part of the process, since if the cash flows are wrong, measures of the profitability of the project will be wrong too. Many capital projects have a similar structure: An initial investment by a firm, followed by a number of periods of regular cash inflow, followed by a terminal payment that ends the project. Our methods of evaluating projects don t depend on this structure, but it can be helpful to think of a project this way when determining cash flows in order to be sure that you don t forget any beginning or ending payments or costs. Nancy s project has this kind of structure. The plan is for Digital Solutions to use its own software engineers and some temporary contract workers to develop the software over the next two years. Over the subsequent four years, Digital Solutions and AFC will share the revenue from sales according to a preset formula. At the end of the four years, AFC will have the option of buying all rights to the software at a fixed price. The basic structure of the cash flows for Digital Solutions is as follows: Year 1: outflow: development costs Year 2: outflow: development costs Year 3: inflow: revenue from software sales Year 4: inflow: revenue from software sales Year 5: inflow: revenue from software sales Year 6: inflow: revenue from software sales + inflow: sale of future rights to ACF 73
3 Whenever you are measuring cash flows it is important to be thorough and list all the flows, both in and out, that are affected by the project. Since there are a number of common pitfalls to measuring cash flows, we will go through several rules that you should follow. Use Cash Flows Not Accounting Profits What matters to the company is the amount of cash coming in and going out. Accounting measures of profits will differ from cash flow calculations because of the inclusion and timing of non-cash expenses such as depreciation. A correct decision requires using the timing of the cash payments. Example: Depreciation is a non-cash expense that is deducted from revenue. If a company needs to buy machinery to do a project, the cash might be paid when the machinery is purchased, but the cost of the machinery is represented in the accounting statements by depreciation, which would be spread out over a number of years. Because the depreciation, but not the cash, is deferred to the future, the accounting statements will underestimate the cost of the machinery. Be Sure to Include Taxes The owners of the company only get the net cash generated from the project after the company pays taxes. A project should be evaluated on an after-tax basis. This provides an exception to our rule not to use accounting profits. Taxes are based on accounting profits, not directly on cash flows. Because of this, you may need to calculate both cash flows and accounting profits. The accounting profits are used to calculate the taxes associated with the project, which are then factored back into the cash flows. Example: When the company depreciates the machinery (in the previous example) it reduces the taxes the company has to pay, increasing the cash flow to the company. When calculating the cash flow it is important to calculate accounting earnings because this determines the taxes the company will pay. Only Include Incremental Cash Flows We are not interested in all the cash flows generated by the firm, but only the extra cash flows that this project creates. We are comparing the cash flows if we take the project and the cash flows if we don t do this project. The difference is the incremental cash flows of the project. The next few paragraphs give some examples of using the only incremental cash flow principal. Don t Include Sunk Costs Sunk costs are costs that have been already been paid and so can t be changed. If costs can t be changed then they shouldn t be included in the calculation this is just an application of our incremental cash flow rule. 74
4 Example: You have just been appointed CFO of a small movie studio specializing in low budget horror movies. The movie studio s latest project Bride of the Zombie has been halfway produced at a cost of $500,000. However, there are concerns that the horror movie craze is diminishing and revenues will be less than expected. It is projected that the film will earn $400,000 in its first year of release (next year) and $30,000 per year for the following 10 years from various revenue sources. It is estimated that it will cost an additional $500,000 to complete the movie. The president of the company argues that the movie will be a money loser and so should not be completed. He points out that the cost of the movie is $1,000,000, while total revenue adds up to $700,000 with a big chunk of that coming in the future. Is he right? The key fact is that the initial $500,000 spent on the movie is gone whether you finish the movie or not. You should only look at costs that affect your decision. You should compare the $500,000 it takes to complete the movie with the stream of revenue that you get by completing the movie. In the case of Digital Solutions, an example of this kind of cost would be if they had already spent a year developing this kind of software (assuming it still takes the two years we assumed). If so, the cost has already been paid, and whether they pursue the project or not, it will not affect that cost. If there were any previous development costs, they should be ignored. Include Opportunity Costs When you take some action, you often give up the opportunity to do something else. These costs should be included as part of the project. Example: An airline is considering expanding to a new city using planes it owns that aren t being used on any other route. While it might seem like there is no cost to using these planes, the company could conceivable sell them, or lease them out to another airline. By expanding they are giving up that opportunity. The (foregone) potential revenue from selling the planes needs to be added to the cost of the project. Include External Effects Sometimes the activity on one project will affect the cash flow of other projects. A common example of this is when sales of one project cannibalizes sales of another project. Example: General Groceries is planning on introducing a new cinnamon raisin bran breakfast cereal. Once established in the market place, it believes that it will generate revenues of $50 million per year. Does it need to look at any other costs besides the costs of developing and selling this cereal? An important thing to check is if General Groceries makes any other similar kinds of cereal, for example, a regular raisin bran. If it did, then it is likely that some of the sales of the cinnamon raisin bran would come at the cost of lower sales of the regular raisin brand. The reduction in profits of the regular raisin brand should be included as a cost of introducing the new cereal. 75
5 Be Careful When Allocating Overhead Costs Overhead costs are costs not related to any particular project, but pay for functions that support all the activities of the firm. This could include personnel involved in general management, finance and accounting, and human resources, the cost of buildings used by more than one division or project, or various activities such as advertising and promotion. Since these costs cannot be allocated to any specific project they are sometimes allocated mechanically, perhaps as a fraction of sales or costs. The problem with that approach is that it doesn t tell us the incremental cost. How much extra are we spending on overhead because of this project? If the answer is zero, then we should not be adding this to the cost of the project. The answer can get a little more complicated if we recognize that our project specifically might not require additional overhead, but if the company did enough new projects then sooner or later it would have to expand general management and incur additional overhead costs. If this is true, and the company expects to expand, our project should reflect part of those overhead cost. Include All Terminal and Replacement Costs This is just a reminder not to forget any costs and benefits that come at the end of a project Example: You are considering starting up a flower shop that you will run until you retire. As part of this venture you would buy a small retail space. While the costs of buying this space would be obvious to include, you don t want to forget the revenue you get from selling the shop when you retire. Example: You are a purchasing manager for a local city and are choosing between two street sweeping machines. The first machine is expected to last 10 years. The second machine is more expensive but is expected to last four years longer. Since you are going to have to buy replacement street sweepers when they wear out, how long they last will certainly affect their value. We will see how to handle this situation later on. Be Consistent in Adjusting for Inflation When calculating cash flows it is necessary to include the effect of inflation. One way to do this is to directly factor in inflation. For example, if we expect prices to increase by three percent per year, future revenues and costs that are not fixed should be increased by the same amount each year. An equivalent way to do the calculation is to measure all costs and benefits in real terms (that is, adjusted for inflation). Needless to say, it is important to be consistent, do one or the other. Also, when we get to the capital budgeting decision we will be using interest rates to discount future payments. We must be consistent here as well. If we are including inflation in our cash flows we should use nominal interest rates. If we are adjusting our cash flows for inflation, we should use real interest rates. Example: We are evaluating a project that earns income of $100,000 now, with a similar level of business continuing into the future. We expect inflation be 3% per year over the life of the project, which should increase the income we get in the future. The nominal interest rate used to evaluate this project is 7%. We have two ways to factor inflation into our evaluation of the project. The first way is to increase our estimates of 76
6 future income by the inflation rate, and then discount those payments using the 7% nominal interest rate. An alternate approach is to keep the payments at the (inflationadjusted) level of $100,000 and use a real interest rate to calculate the present value. Both approaches will give us the correct answer as long as we are consistent in our treatment of inflation across the payments and the interest rate. (A technical note: we will get the same answer as long as we calculate the real interest rate as 1+r = (1+i)/(1+ π e ). If we use the approximation r = i-π e, the numbers will be slightly off, but still close enough for most applications) Do Not Include the Cost of Financing We do not want to be including financing costs as part of our cash flows as the relevant financing costs will enter at the evaluation stage Example: We are buying a truck for $20,000 that will generate income from a hauling service. To buy the truck we will get a loan at 8% interest that will require payments over the next 3 years. For purposes of evaluating this venture, the interest payments are not included as a negative cash flow. Rather, the 8% interest rate will be factored in when we make our decision. We will discuss this in more detail in a moment. Back to Digital Solutions As part of the project evaluation, Nancy Garcia would sit down with each of the parties and go through their estimates of their costs. Some of our concerns will be important while others will not matter much. For this project, she decides that all costs will be adjusted for inflation. Opportunity costs show up in this project if it requires resources that might be used for other projects. For example, if using the software engineers meant that the company couldn t pursue other projects, then any profits the company missed out on should be included as a cost of this project. Similarly, if doing this project requires using office space owned by the company that could also be rented out, the lost rent should be included as part of the project On the other hand, what if the engineers would just be sitting idle if the company didn t pursue this project? In this case, the salaries of the engineers are a sunk cost (they will be paid in any case) and there is no opportunity cost to using the engineers in this project. Because it is a sunk cost, the salaries of the engineers would not be included. Since Digital Solutions is not selling any other software, this does not apply, although we can think of the opportunity cost of the software engineers as an example of an indirect cost. For this project, it looks like there will be little affect on overhead costs, except for human resources, since so much of the software engineering will be outsourced. Some extra cost associated with this will be added to the project. After making the appropriate investigations, Ms. Garcia comes up with estimates of the cash flows. Because these expenses are mostly in the future, they are uncertain and so she requested that the managers provide a most-likely estimate of what the costs and revenues would be, and some idea of the range of possible outcomes. We will think about how to evaluate risks of a project more thoroughly in the next section; at this point we are just collecting data. Whenever you are coming up with estimates of cash flows you want to provide a range of possible outcomes and some guide to how likely the different 77
7 outcomes are. Also, you would want to present specific alternate scenarios, such as what would happen to costs if it took longer than expected to design the software, or what revenue would be if the competition introduced a similar product and so your sales were lower than expected. Forecasts of this type can be quite complicated, but to keep things simple, we will report the basic information for the most-likely estimate and an optimistic and pessimistic estimate. Outflows are shown as negative numbers and inflows as positive numbers. Table 1. Estimates of Cash Flows for Proposed Project Year Activity Pessimistic Most likely Optimistic 1 Development -$350,000 -$300,000 -$250,000 2 Development -$600,000 -$400,000 -$200,000 3 Sales $0 $100,000 $150,000 4 Sales $50,000 $200,000 $400,000 5 Sales $50,000 $300,000 $500,000 6 Sales $50,000 $300,000 $500,000 7 Sell Software $600,000 $600,000 $600,000 There is a fair amount of uncertainty about the outcome of the project, particularly in the amount of sales in future years. Underlying these figures would be detailed calculations showing where the costs come from and the assumptions about price and units sold that determine sales revenue. This detailed information can be important as it allows us to ask hypothetical questions such as, what would happen to our costs if the labor market changes making temporary software engineers more expensive, or if we could only sell half as many units at our assumed price? For convenience, the revenue from selling the rights to the software in year 7 is treated as a certain amount, even though in our initial description of the contract this was given as an option. How to Evaluate Projects Once we have determined all the cash flows, the next step is to determine if the project should be done. This section introduces the three major ways of making the decision: Payback Period, Net Present Value, and Internal Rate of Return. We will start off by looking some simple examples of each approach, and then return to the Digital Solutions project at the end of the section. All of these approaches assess the profitability of the project, that is, does the revenue from the project exceed the costs? However, what makes capital budgeting a special task is that the payments are often made at different times and so we have to adjust for the time value of money. Payback Period Imagine that we have a project that costs $80,000 and returns $20,000 each year over the next 5 years. The sum of the returns ($100,000) exceeds the cost, so on its face the project is worth doing. However, we have ignored the fact that some of the returns to the project are being paid in the future. For example, consider a project that offered returns of $10,000 over the next 10 years. The total return is still $100,000, but we would probably think that this project is not as good as the first one The returns are coming farther in the future and we know money in future is worth less. Also, the farther into the future the payments are, the more time there is for things to 78
8 change, and perhaps make the returns to the project worse. To make a correct decision, we need to take into account when the payments are made. Payback period asks how long it takes for the accumulating returns to pay for the initial cost of the capital improvement. For example, if you install a new air conditioner that costs $1,600 and that saves you $200 in energy costs per year, then the payback period would be 8 years (after 8 years of saving $200 we have earned $1,600, to equal our initial cost). If this is less than the maximum acceptable payback period then we would decide to install the new air conditioner. The farther in the future the payments are, the longer the payback period, and so it is less likely that the project would be accepted. (What would the payback period be if we saved $100 per year?) Example: A project costs $1,500 and pays $1,000 over the next three years. What is the payback period? The payback period is 1.5 years assuming that the cash flow is evenly spread over the period. Often, because of the degree of uncertainty about cash flows, it is not necessary to be exact, and we can round off the payback period. For example, a payback period of 7.6 years, might be called 7-8 years, or rounded up to 8. Right off the bat you can see there are some problems with this method; we are adding up dollars across years and yet we know from our discussion on present value that payments in different years are not the same. We are also not taking into account the risk associated with the cash flows, or including any of the cash flows after the 8 years. And how do we know if 8 years is too long, anyway? Given all these problems, why would anyone ever look at the payback period? The answer is that it is quick and easy to calculate and it captures some of the intuition behind capital budgeting decisions. The longer the payback period, the worse the project probably is. If it takes more years for the cash flows to accumulate to cover the initial investment, it means that we have to wait longer for our money. Since we know that money in the future is worth less, this is not desirable. Also, the longer we have to wait to get the positive cash flows, the more time there is for something to change, and so the cash flows are less certain and therefore less desirable. The payback period provides a rough and ready way of evaluating a project. You can use it to get an initial idea of the project s worth, and sometimes that is enough. If the cash generated by the project does not cover the initial cost, there is no payback period, and so we should definitely not do the project. On the other hand, if the payback period is a year and a half, with further payments to come it would seem to be a very good project, since there would be little discounting and so the benefits would surely cover the costs. However, most capital budgeting decisions require a more careful treatment. We need to be explicit about our adjustments for risk and the time value of money. The next two techniques can do just that. Net Present Value A better method of evaluation (in fact, the best method) is called net present value (NPV). The NPV of a project is the just the present value of all the cash flows of the project, including the 79
9 initial investment. In fact, NPV is just another example of discounted cash flow analysis. Once we know a project s NPV, we can make a decision about whether we should do it. Rules for evaluating projects using NPV are: If the projects under evaluation are independent, then you should accept all projects with a positive NPV and reject those with a negative NPV. If the projects are mutually exclusive, choose the project with the highest NPV (as long as it is greater than 0) Example: An air conditioner costs $1,600 and saves $300 per year for the next 10 years. The discount rate used to value future cash payments is 10%. The present value of the cost savings is $1,843. We subtract away the cost to give an NPV of $243. Since the NPV of the project is positive, we should do this project. The discount rate plays an important part in NPV, but where does it come from? We will examine this more thoroughly in a later section, but the basic idea is that it is the cost to the company of obtaining the funds to do this project. For example, if we borrowed the $1,600 to buy the air conditioner, we can think of the discount rate as the interest rate we would pay on the loan. In order to generate the savings, we had to borrow money at 10% and so any future proceeds from the project should be discounted at 10%. Example: We have a project that costs $100,000 and pays $20,000 per year for the next 6 years. To fund this project we would need to get a bank loan at 8%. The present value of the payments to us is $92,458, which is less than $100,000, so the project has a negative NPV. Another way to evaluate the project would be to calculate 6 equal payments for a loan of $100,000 at 8%, which is what we would need to finance this project. The interest costs would be $21,632, which exceeds the cash payments, so this would be a bad project to do. This is the same answer we get from NPV since NPV incorporates the opportunity cost of funds in its discount rate. What if we already had the money and didn t need to get a loan? Is our cost of funding equal to 0? No, there is still an opportunity cost of using the funds in this project. If we didn t buy the air conditioner we could invest in another project or save the money, or return it to the owners of the company. In most large companies, the non-financial managers will be responsible for determining cash flows and understanding capital budgeting techniques, but the actual calculation of the cost of capital, for the company as a whole, will be done by the Finance Department. Internal Rate of Return A method very similar to NPV is the internal rate of return (IRR). However, instead of reporting the dollar amount of the project, it gives a rate of return. IRR is calculated as the discount rate that equates the present value of cash inflows with the initial investment associated with the project. Another way of saying this is that IRR is the discount rate that sets the NPV of the project equal to zero. 80
10 Example: A project costs $10,000 now and returns $12,000 in two years. The NPV of the project is given by 12,000/(1+k) 2 - $10,000 (the present value of the payments). If we set the present value equal to 0, we get the equation 12,000/(1+k) 2 - $10,000 = 0, and we can solve for k = 9.54% The rules for using IRR are: For independent projects, if the IRR is greater than the cost of capital, accept the project. If it is less than the cost of capital, reject the project. For mutually exclusive projects, choose the project with the highest IRR, assuming that it is also above the cost of capital. In the last example, the IRR of the project was 9.54%, so the project just breaks even, in terms of NPV, at 9.54%. If the actual cost of capital is 7% then we know that the NPV will be positive and so we should do the project. If instead, the cost of capital is 15% we would know that the NPV is negative, since the NPV is just equal to 0 at 9.54% Unlike NPV, when there are there are multiple and unequal payments the math can get complicated. Spreadsheets are the way to handle these problems. However, if there are regular payments, we can use our annuity math and a financial calculator to find the answer. Example. Return to the air conditioner problem. Solving this by hand would be tedious but a spreadsheet or a financial calculator can do the work for us. Using a financial calculator, we enter the following numbers (N = 10, PV = -1,600, PMT = 300, FV = 0, I=?) The IRR for this project is 13.43%, which is greater than the 10% cost of capital, and so we should do this project. Comparing NPV and IRR NPV and IRR are very closely related; however, there are a few differences. Some of the differences are technical (which we will not pursue here) while others are easier to see. Differing Assumptions about the Reinvestment Rate NPV assumes that money is reinvested at the cost of capital. Money earned early on in the project can be reinvested over the life of the project at that interest rate. IRR assumes that money is reinvested at the IRR rate, which for acceptable projects will be above the cost of capital. This may not be a reliable assumption. For example, if you come across a very special project that offers you a 50% IRR you may not be able to earn that return elsewhere when investing cash generated by that project. Differing Types of Numbers Reported NPV reports a dollar amount while IRR reports a percentage. For example, the return on a project might be given as $100,000 or 10%. People are often more comfortable looking at rates of return when making decisions, which leads to IRR s popularity as a decision rule. 81
11 Sometimes Reach Different Conclusions Generally, NPV and IRR will produce the same answers for accept-reject decisions, but they may rank mutually exclusive projects differently. If they give different answers, NPV provides the correct answer. The bottom line is that NPV is the better approach, but IRR is often easier to interpret, and since they both provide similar answers, IRR is often used in practice. Since both are straightforward to calculate, you should be sure to calculate the NPV, but also have the IRR on hand if someone wants to know it. Back to Digital Solutions Nancy finds out from the Finance Department at her company that she should discount future payments by 8% annually. She constructs a table that lists the (most likely) payment, and the value of the discount factor 1/(1+k) n for each year. She then calculates the present value of each of the payments. Year Payment Discount Present Value 1-300, , , , , , , , , , , , , ,094 NPV 348,996 Adding up the present values of each of the payments gives a NPV for the project of $348,996. Since this is greater than zero, the company should do this project. Of course, we are not certain about the value of payments in the future. The next section will discuss ways of coming to grips with this uncertainty. 82
CHAPTER 7: NPV AND CAPITAL BUDGETING
CHAPTER 7: NPV AND CAPITAL BUDGETING I. Introduction Assigned problems are 3, 7, 34, 36, and 41. Read Appendix A. The key to analyzing a new project is to think incrementally. We calculate the incremental Basic 1. To calculate the payback period, we need to find the time that the project has recovered its initial investment. After two years, the
Net Present Value and Capital Budgeting. What to Discount
Net Present Value and Capital Budgeting (Text reference: Chapter 7) Topics what to discount the CCA system total project cash flow vs. tax shield approach detailed CCA calculations and examples project
Course 3: Capital Budgeting Analysis
Excellence in Financial Management Course 3: Capital Budgeting Analysis Prepared by: Matt H. Evans, CPA, CMA, CFM This course provides a concise overview of capital budgeting analysis. This course is recommended
11.3 BREAK-EVEN ANALYSIS. Fixed and Variable Costs
385 356 PART FOUR Capital Budgeting a large number of NPV estimates that we summarize by calculating the average value and some measure of how spread out the different possibilities are. For example,
Chapter 09 - Using Discounted Cash-Flow Analysis to Make Investment Decisions
Solutions to Chapter 9 Using Discounted Cash-Flow Analysis to Make Investment Decisions 1. Net income = ($74 $42 $10) [0.35 ($74 $42 $10)] = $22 $7.7 = $14.3 million Revenues cash expenses taxes paid =
WHAT IS CAPITAL BUDGETING?
WHAT IS CAPITAL BUDGETING? Capital budgeting is a required managerial tool. One duty of a financial manager is to choose investments with satisfactory cash flows and rates of return. Therefore, a financial
Chapter 7: Net Present Value and Other Investment Criteria
FIN 301 Class Notes Chapter 7: Net Present Value and Other Investment Criteria Project evaluation involves: 1- Estimating the cash flows associated with the investment project (ch. 8) 2- Determining the Cash Flow and Capital Budgeting
Chapter 9 Cash Flow and Capital Budgeting MULTIPLE CHOICE 1. Gamma Electronics is considering the purchase of testing equipment that will cost $500,000. The equipment has a 5-year lifetime with no salvage
Investment Decision Analysis
Lecture: IV 1 Investment Decision Analysis The investment decision process: Generate cash flow forecasts for the projects, Determine the appropriate opportunity cost of capital, Use the cash flows and 02 How to Calculate Present Values
Chapter 02 How to Calculate Present Values Multiple Choice Questions 1. The present value of $100 expected in two years from today at a discount rate of 6% is: A. $116.64 B. $108.00 C. $100.00 D. $89.00
Issues in Capital Budgeting
Lecture: Week V 1 Issues in Capital Budgeting What is Capital Budgeting? The process of making and managing expenditures on long-lived assets. Allocating available capital amongst investment opportunities.
Which projects should the corporation undertake
Which projects should the corporation undertake Investment criteria 1. Investment into a new project generates a flow of cash and, therefore, a standard DPV rule should be the first choice under consideration.
Introduction to Discounted Cash Flow and Project Appraisal. Charles Ward
Introduction to Discounted Cash Flow and Project Appraisal Charles Ward Company investment decisions How firms makes investment decisions about real projects (not necessarily property) How to decide which
CHAPTER 4. The Time Value of Money. Chapter Synopsis
CHAPTER 4 The Time Value of Money Chapter Synopsis Many financial problems require the valuation of cash flows occurring at different times. However, money received in the future is worth less than money
CE Entrepreneurship. Investment decision making
CE Entrepreneurship Investment decision making Cash Flow For projects where there is a need to spend money to develop a product or establish a service which results in cash coming into the business in
CHAPTER 9 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA
CHAPTER 9 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA 1. To calculate the payback period, we need to find the time that the project has recovered its initial investment. After three years, the project
Answers to Warm-Up Exercises
Answers to Warm-Up Exercises E10-1. Answer: E10-2. Answer: Payback period The payback period for Project Hydrogen is 4.29 years. The payback period for Project Helium is 5.75 years. Both projects are acceptable
EXAM 2 OVERVIEW. Binay Adhikari
EXAM 2 OVERVIEW Binay Adhikari FEDERAL RESERVE & MARKET ACTIVITY (BS38) Definition 4.1 Discount Rate The discount rate is the periodic percentage return subtracted from the future cash flow for computing
Chapter 8. Using Discounted Cash Flow Analysis to Make Investment Decisions
Chapter 8 Using Discounted Cash Flow Analysis to Make Investment Decisions 8-2 Topics Covered Discounted Cash Flows (not Accounting Profits) Incremental Cash Flows Treatment of Inflation Separate Investment
Chapter 011 Project Analysis and Evaluation
Multiple Choice Questions 1. Forecasting risk is defined as the: a. possibility that some proposed projects will be rejected. b. process of estimating future cash flows relative to a project. C. possibility
Understanding Financial Management: A Practical Guide Guideline Answers to the Concept Check Questions
Understanding Financial Management: A Practical Guide Guideline Answers to the Concept Check Questions Chapter 8 Capital Budgeting Concept Check 8.1 1. What is the difference between independent and mutually 6 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA
CHAPTER 6 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA Answers to Concepts Review and Critical Thinking Questions 1. Assuming conventional cash flows, a payback period less than the project s life means
FINANCIAL INTRODUCTION
FINANCIAL INTRODUCTION In earlier sections you calculated your cost of goods sold, overhead expenses and capital cost in order to help you determine the sales price of your product. In your business plan,
Chapter 7: Net Present Value and Capital Budgeting
Chapter 7: Net Present Value and Capital Budgeting 7.1 a. Yes, the reduction in the sales of the company s other products, referred to as erosion, should be treated as an incremental cash flow. These lost
Oklahoma State University Spears School of Business. Capital Investments
Oklahoma State University Spears School of Business Capital Investments Slide 2 Incremental Cash Flows Cash flows matter not accounting earnings. Sunk costs do not matter. Incremental cash flows matter.
Capital Budgeting II. Professor: Burcu Esmer
Capital Budgeting II Professor: Burcu Esmer 1 Cash Flows Last chapter introduced valuation techniques based on discounted cash flows. This chapter develops criteria for properly identifying and calculating
Project Management Seminars. Financial Management of Projects
Project Management Seminars Financial Management of Projects.inproject managementandsystems engineering, is a deliverable-oriented decomposition of a project into smaller components. (source: Wikipedia)
Chapter 7. Net Present Value and Other Investment Criteria
Chapter 7 Net Present Value and Other Investment Criteria 7-2 Topics Covered Net Present Value Other Investment Criteria Mutually Exclusive Projects Capital Rationing 7-3 Net Present Value Net Present
Economic Feasibility Studies
Economic Feasibility Studies ١ Introduction Every long term decision the firm makes is a capital budgeting decision whenever it changes the company s cash flows. The difficulty with making these decisions
Cost Benefits analysis
Cost Benefits analysis One of the key items in any business case is an analysis of the costs of a project that includes some consideration of both the cost and the payback (be it in monetary or other terms).
1.040 Project Management
MIT OpenCourseWare 1.040 Project Management Spring 2009 For information about citing these materials or our Terms of Use, visit:. Project Financial Evaluation
CHAPTER 7. Fundamentals of Capital Budgeting. Chapter Synopsis
CHAPTER 7 Fundamentals of Capital Budgeting Chapter Synopsis 7.1 Forecasting Earnings A firm s capital budget lists all of the projects that a firm plans to undertake during the next period. The selection
Net Present Value and Other Investment Criteria
Net Present Value and Other Investment Criteria Topics Covered Net Present Value Other Investment Criteria Mutually Exclusive Projects Capital Rationing Net Present Value Net Present Value - Present value
CHAPTER 4 DISCOUNTED CASH FLOW VALUATION
CHAPTER 4 DISCOUNTED CASH FLOW VALUATION Solutions to Questions and Problems NOTE: All-end-of chapter problems were solved using a spreadsheet. Many problems require multiple steps. Due to space and readability
CHAPTER 4. FINANCIAL STATEMENTS
CHAPTER 4. FINANCIAL STATEMENTS Accounting standards require statements that show the financial position, earnings, cash flows, and investment (distribution) by (to) owners. These measurements are reported,
Module 10: Assessing the Business Case
Module 10: Assessing the Business Case Learning Objectives After completing this section, you will be able to: Do preliminary assessment of proposed energy management investments. The measures recommended
What is a business plan?
What is a business plan? A business plan is the presentation of an idea for a new business. When a person (or group) is planning to open a business, there is a great deal of research that must be done
Investment Decisions and Capital Budgeting
Investment Decisions and Capital Budgeting FINANCE 350 Global Financial Management Professor Alon Brav Fuqua School of Business Duke University 1 Issues in Capital Budgeting: Investment How should capital
Multiple Choice Questions (45%)
Multiple Choice Questions (45%) Choose the Correct Answer 1. The following information was taken from XYZ Company s accounting records for the year ended December 31, 2014: Increase in raw materials inventory
(Relevant to AAT Examination Paper 4 Business Economics and Financial Mathematics)
Capital Budgeting: Net Present Value vs Internal Rate of Return (Relevant to AAT Examination Paper 4 Business Economics and Financial Mathematics) Y O Lam Capital budgeting assists decision makers in a
CHAPTER 9 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA
CHAPTER 9 NET PRESENT VALUE AND OTHER INVESTMENT CRITERIA Answers to Concepts Review and Critical Thinking Questions 1. A payback period less than the project s life means that the NPV is positive
FIN 534 Quiz 8 (30 questions with answers) 99,99 % Scored
FIN 534 Quiz 8 (30 questions with answers) 99,99 % Scored Find needed answers here - FIN 534 Quiz 8 (30 questions with answers)
( ) ( )( ) ( ) 5 Capital Budgeting
Chapter 5 Capital Budgeting Road Map Part A Introduction to finance. Part B Valuation of assets, given discount rates. Fixed-Income securities. Common stocks. Real assets (capital budgeting). Part C Determination
Investment, Time, and Present Value
Investment, Time, and Present Value Contents: Introduction Future Value (FV) Present Value (PV) Net Present Value (NPV) Optional: The Capital Asset Pricing Model (CAPM) Introduction Decisions made by a
Leasing vs. Buying Farm Machinery
Leasing vs. Buying Farm Machinery Department of Agricultural Economics MF-2953 Machinery and equipment expense typically represents a major cost in agricultural production. Purchasing
On September 27, 2010, Southwest Airlines announced that it
Cash Flows and Capital Budgeting 11 Learning Objectives 1 Explain why incremental after-tax free cash flows are relevant in evaluating a project and calculate them for a project. 2 Discuss the five general
Understanding A Firm s Financial Statements
CHAPTER OUTLINE Spotlight: J&S Construction Company () 1 The Lemonade Kids Financial statement (accounting statements) reports of a firm s financial performance and resources,
Part 9. The Basics of Corporate Finance
Part 9. The Basics of Corporate Finance The essence of business is to raise money from investors to fund projects that will return more money to the investors. To do this, there are three financial questions)
PROJECT INTERACTIONS, SIDE COSTS AND SIDE BENEFITS
1 CHAPTER 6 PROJECT INTERACTIONS, SIDE COSTS AND SIDE BENEFITS In much of our discussion so far, we have assessed projects independently of other projects that the firm already has or might have in the
Chapter 11 Cash Flow Estimation and Risk Analysis ANSWERS TO SELECTED END-OF-CHAPTER QUESTIONS
Chapter 11 Cash Flow Estimation and Risk Analysis ANSWERS TO SELECTED END-OF-CHAPTER QUESTIONS 11-1 a. Cash flow, which is the relevant financial variable, represents the actual flow of cash. Accounting
Capital Budgeting Further Considerations
Capital Budgeting Further Considerations For 9.220, Term 1, 2002/03 02_Lecture10.ppt Lecture Outline Introduction The input for evaluating projects relevant cash flows Inflation: real vs. nominal analysis
Chapter 6 Making Capital Investment Decisions
University of Science and Technology Beijing Dongling School of Economics and management Chapter 6 Making Capital Investment Decisions Oct. 2012 Dr. Xiao Ming USTB 1 Key Concepts and Skills Understand
Numbers 101: Cost and Value Over Time
The Anderson School at UCLA POL 2000-09 Numbers 101: Cost and Value Over Time Copyright 2000 by Richard P. Rumelt. We use the tool called discounting to compare money amounts received or paid at different
Investment Appraisal
Investment Appraisal Article relevant to F1 Business Mathematics and Quantitative Methods Author: Pat McGillion, current Examiner. Questions 1 and 6 often relate to Investment Appraisal, which is underpinned
Measuring Investment Returns
Measuring Investment Returns Aswath Damodaran Stern School of Business Aswath Damodaran 156 First Principles Invest in projects that yield a return greater than the minimum acceptable hurdle rate. The
Understanding Financial Management: A Practical Guide Guideline Answers to the Concept Check Questions
Understanding Financial Management: A Practical Guide Guideline Answers to the Concept Check Questions Chapter 7 Capital Investments and Cash Flow Analysis Concept Check 7.1 1. What is capital budgeting?
MBA350 INTEGRATIVE CAPSTONE COURSE
MBA350 INTEGRATIVE CAPSTONE COURSE Individual Assignment Spring 2008 Raffaello Curtatone Team # 6 Index Introduction and general drivelines... 3 S&A Report... 4 Marketing Research... 4 Cost of Goods Sold...
Page 1 of 23 Module 5: Interest concepts of future and present value Overview In this module, you learn about the fundamental concepts of interest and present and future values, as well as ordinary annuities (
Preparing a Successful Financial Plan
Topic 9 Preparing a Successful Financial Plan LEARNING OUTCOMES By the end of this topic, you should be able to: 1. Describe the overview of accounting methods; 2. Prepare the three major financial statements
Vol. 2, Chapter 4 Capital Budgeting
Vol. 2, Chapter 4 Capital Budgeting Problem 1: Solution Answers found using Excel formulas: 1. Amount invested = $10,000 $21,589.25 Compounding period = annually Number of years = 10 Annual interest rate
AGENDA LEARNING OBJECTIVES ANALYZING PROJECT CASH FLOWS. Chapter 12. Learning Objectives Principles Used in This Chapter
Chapter 12 ANALYZING PROJECT CASH FLOWS AGENDA Learning Objectives Principles Used in This Chapter 1. Identifying Incremental Cash Flows 2. Forecasting Project Cash Flows 3. Inflation and Capital Budgeting +
Solutions to Problems: Chapter 5
Solutions to Problems: Chapter 5 P5-1. Using a time line LG 1; Basic a, b, and c d. Financial managers rely more on present value than future value because they typically make decisions before the start
Cash Flow Estimation. Topics to be covered
Cash Flow Estimation Topics to be covered Discount Cash Flow, Not Profit Discount Incremental Cash Flow - Include all direct effects. - Forget Sunk Costs - Include Opportunity Costs - Recognize the Investment
ADVANCED INVESTMENT APPRAISAL
RELEVANT TO ACCA QUALIFICATION PAPER F9 Studying Paper F9? Performance objectives 15 and 16 are relevant to this exam Investment appraisal is one of the eight core topics within Paper F9, Financial Management
Chapter 7 Fundamentals of Capital Budgeting
Chapter 7 Fundamentals of Capital Budgeting Copyright 2011 Pearson Prentice Hall. All rights reserved. Chapter Outline 7.1 Forecasting Earnings 7.2 Determining Free Cash Flow and NPV 7.3 Choosing Among
Capital Budgeting Decisions Tools
Management Accounting 217 Capital Budgeting Decisions Tools In many businesses, growth is a major factor to business success. Substantial growth in sales may eventually means a need to expand plant capacity.
Final Examination, BUS312, D1+ E1. SFU Student number:
Final Examination, BUS312, D1+ E1 NAME: SFU Student number: Instructions: For qualitative questions, point form is not an acceptable answer. For quantitative questions, an indication of how you arrived 6. Investment Decision Rules. Chapter Synopsis
CHAPTER 6 Investment Decision Rules Chapter Synopsis 6.1 and Stand-Alone Projects The net present value () of a project is the difference between the present value of its benefits and the present value | http://docplayer.net/4131387-Part-7-capital-budgeting.html | CC-MAIN-2018-34 | refinedweb | 8,261 | 59.53 |
One of the joys of working at the Echo Nest is the communal music playlist. Anyone can add, rearrange or delete music from the queue. Of course, if you need to bail out (like when that Cindi Lauper track is sending you over the edge) you can always put on your headphones and tune out the mix. The other day, George Harrison’s “Here Comes the Sun” started playing, but this was a new version – with a funky drum beat, that I had never heard before – perhaps this was a lost track from the Beatle’s Love? Nope, turns out it was just Ben, one of the Echo Nest developers, playing around with The Echo Nest Remix SDK.
The Echo Nest Remix SDK is an open source Python library that lets you manipulate music and video. It sits on top of the Echo Nest Analyze API, hides all of the messy details of sending audio back to the Echo Nest, and parsing the XML response, while still giving you access to the full power of the API.
remix – is one of The Echo Nest’s secret weapons – it gives you the ability to analyze and manipulate music – and not just audio manipulations such as filtering or equalizing, but the ability to remix based on the hierarchical structure of a song. remix sits on top of a very deep analysis of the music that teases out all sorts of information about a track. There’s high level information such as the key, tempo time signature, mode (major or minor) and overall loudness. There’s also information about the song structure. A song is broken down into sections (think verse, chorus, bridge, solo), bars, beats, tatums (the smallest perceptual metrical unit of the song) and segments (short, uniform sound entities). remix gives you access to all of this information.
I must admit that I’ve been a bit reluctant to use remix – mainly because after 9 years at Sun Microsystems I’m a hard core Java programmer (the main reason I went to Sun in the first place was because I liked Java so much). Every time I start to use Python I get frustrated because it takes me 10 times longer than it would in Java. I have to look everything up. How do I concatenate strings? How do I find the length of a list? How do I walk a directory tree? I can code so much faster in Java. But … if there was ever a reason for me to learn Python it is this remix SDK. It is just so much fun – and it lets you do some of the most incredible things. For example, if you want to add a cowbell to every beat in a song, you can use remix to get the list of all of the beats (and associated confidences) in a song, and simply overlap a cowbell strike at each of the time offsets.
So here’s my first bit of Python code using remix. I grabbed one of the code samples that’s included in the distribution, had the aforementioned Ben spend two minutes walking me through the subtleties of Audio Quantum and I was good to go. My first bit of code just takes a song and swaps beat two and beat three of all measures that have at least 3 beats.
def swap_beat_2_and_3(inputFile, outputFile): audiofile = audio.LocalAudioFile(inputFile) bars = audiofile.analysis.bars collect = audio.AudioQuantumList() for bar in bars: beats = bar.children() if (len(beats) >= 3): (beats[1], beats[2]) = (beats[2], beats[1]) for beat in beats: collect.append(beat); out = audio.getpieces(audiofile, collect) out.encode(outputFile)
The code analyzes the input, iterates through the bars and if a bar has more than three beats, swaps them. (I must admit, even as a hard core Java programmer, the ability to swap things with (a,b) = (b,a) is pretty awesome) and then encodes and writes out a new audiofile. The resulting audio is surprisingly musical. Here’s the result as applied to Maynard Ferguson’s “Birdland”:
This is just great programming fun. I think I’ll be spending my spare coding time learning more Python so I can explore all of the things one can do with remix.
#1 by tpetr on February 28, 2009 - 12:20 pm
That’s pretty awesome!
#2 by brian on February 28, 2009 - 1:37 pm
interested parties in NYC may like to know that i’m presenting the remix API at Dorkbot-NYC on wednesday (march 4). See you there if you can make it!!
#3 by Janani on May 26, 2010 - 12:37 am
Awesome!! | https://musicmachinery.com/2009/02/28/the-echo-nest-remix-sdk/ | CC-MAIN-2021-04 | refinedweb | 775 | 70.63 |
In the last two posts, I revealed that field-like events in C# 4 have a better synchronization story, and that we changed += and -= in a kind of subtle way to protect you, in many cases, from the semantic differences this introduces between C# 3 and C# 4.
Now I’m here to tell you about some more in-your-face breaks that are a lot less subtle, and related to the binding change for += and -=. My hope is that anyone who actually sees these breaks will find this post and learn how to fix them. Let’s go.
Break #1: warning CS0067: The event 'MyClass.MyEvent' is never used
So imagine you have the following C# 3 code. It compiles just fine. No warnings, no errors. (Forget the about the actual utility of this piece of code for a moment).
using System;
class MyClass
{
static void Main()
{
MyClass x = new MyClass();
x.MyEvent += () => Console.WriteLine("Yay!");
}
public event Action MyEvent;
}
You upgrage to C# 4 and now you get a warning!
test.cs(10,25): warning CS0067: The event 'MyClass.MyEvent' is never used
What happened? Well, remember the subtle change in the way we interpreted += from the last post? It affects line 8 above. In C# 3, since this code is inside the class that defines the event, the += was a compound operator. Therefore it was a direct operation on the delegate field that backs MyEvent. In C# 4, however, we’ve changed the interpretation so that the += on line 8 is now calling the add accessor instead.
So why the warning? Because the warning is trying to tell you something about the private backing field, not the event accessors! In C# 4, this class has a delegate field that no one ever uses for anything. No one invokes it, no one passes it to Delegate.Combine, no one does anything with it. Of course the event accessors use it, but compiler generated code doesn’t count for this warning (and it never has).
The first possible fix here is: make use of the event! Perhaps you meant to raise the event, but you never got around to adding the code, and now this warning is actually telling you about a bug. If you were to add an “OnMyEvent” method that invoked MyEvent with “MyEvent()”, then you’ve made use of the field, the warning goes away, and you’ve fixed a bug.
The second fix is to get rid of the event, or at least the backing field. In this case, you don’t actually want to raise the event, and you might as well delete the thing. So you can safely remove the event and all the references to it and all’s well. It didn’t do anything anyway.
Of course, you might want to delete the event but be unable to. This can be the case if some base class or interface that you implement requires you to define the event. In that case, you probably have code like this:
interface IHasSomeEvent
{
event Action SomeEvent;
}
class MyClass : IHasSomeEvent
{
// there is a backing delegate here that goes unused!
public event Action SomeEvent;
}
and my recommendation would be that you change your class to look like this:
class MyClass : IHasSomeEvent
{
// this takes no storage and does nothing!
event Action IHasSomeEvent.SomeEvent { add { } remove { } }
}
This last case, where you are obligated to implement some event that you don’t care about, is the context in which I’ve seen these warning 67’s pop up most frequently. Notice that the fix I recommend actually does nothing more than fulfill the obligation of implementing the interface, and it doesn’t pollute the public surface area of your class with the event name. If you wanted to be especially hard-nosed, you could throw a NotImplementedException from those accessors, but that seems like a bit much to me.
Break #2: error CS0029: Cannot implicitly convert type 'void' to 'System.Action'
This break can also show up as “CS1503: Argument n: cannot convert from 'void' to 'System.Action'” or any of a few different errors where a conversion is required but does not exist. And it comes from code like this:
class MyClass
{
event Action MyEvent;
public void DoSomething()
{
Action a = MyEvent += () => Console.WriteLine("Yay!");
a();
}
}
Here, what we’re doing is adding the little Console.WriteLine delegate to my event, and then call the result. This works in C# 3, again, because += binds directly to the event. Therefore, the result of the compound assignment is the new delegate that is now referenced by MyEvent. However, in C# 4, since += is a call to an event add accessor, and the result of an event accessor call is void, you cannot directly look at the result like this. Event accessors are designed this way so that code outside your class can’t break encapsulation and get their hands on your delegates.
This is really weird code. I have never actually seen it in the wild. If you have such code, why not just call the accessor and then call the event?
class MyClassOr, generally, call the accessor and then do whatever you were going to do with the result but with the event instead? The semantics are not 100% the same if you do this (for instance, someone on another thread could have modified the event in the meantime), but if you think that makes a difference to you, then you should re-examine your requirements and possibly implement the event accessors yourself because the original code was wrong (if you left out the lock(this)) or terribly unsafe (if you used lock(this)).
{
event Action MyEvent;
public void DoSomething()
{
MyEvent += () => Console.WriteLine("Yay!");
MyEvent();
}
}
Other meaningless behavioral differences
There are a few other things that are different now that your +=’s are all calls to an accessor. But none that you should spend any time whatsoever worrying about; I list them here only to be thorough.
For instance, there’s another method call here. That could consume extra stack space. If you had just achieved the limit on your stack before, this one extra method call could push you over the edge and give you a StackOverflowException.
Also, there is a theoretical resource starvation problem with the compare and swap lock-free code when two threads sort of “line up” perfectly forever. This will affect you with probability zero.
And you could do silly things, such as: put a SecurityCriticalAttribute on your field-like event accessors (use the “method:” attribute target specifier), purely for the purpose of creating a situation wherein you can run in partial trust and a += in the event-defining class used to work in C# 3 but now it does not. Just... don’t do this.
Next time I’ll conclude this short series by going over the standard event pattern in C# 4, with recommendations about exactly how you should implement and use field-like events, and when you should not.
Hi Chris,
What about the breaking changes that compiler won’t detect? I mean lets say someone relied on the implementation of accessors to lock on this?.
for example someone relied that in the code like this
lock(this)
{
delegateA();
delegateA(); // or actually any other delegateB()
}
Code could have relied on the fact that the delegate doesn’t change while under lock.
@Dmitry:
In the code you give, the value of delegate backing the event absolutely can change under lock. Consider:
class Foo {
public event Action E1;
public event Action E2;
public void Raise() {
lock (this) {
E1(); E2();
}
}
}
Foo foo = new Foo();
foo.E1 += () => foo.E2 += () => {};
So handler for E1 changes E2. The reason why this works is this aspect of Monitor.Enter (quoted from MSDN):
"It is legal for the same thread to invoke Enter more than once without it blocking"
Locks are to synchronize threads, not to prevent the same thread from accessing resource; so if the thread has already acquired a lock, it will succeed on any nested attempts to do the same.
So any such code is already broken, in a sense that it does not guarantee something that his author may think it does.
I was not saying that there is no way to change the underlying event.
I was arguing that there could be a case (another thread in my example) that modifies E1/E2 was not able to do it while thread 1 was holding the lock.
Chris, any idea if there will ever be support for weak delegates in the CLR?
At the moment there’s no easy way to implement an Observer pattern. People like IanG have tried to cobble something together and failed.
The only workarounds seem to require support from the observed object, and require a tremendous about of code. The WeakEvent pattern in WPF is worthless for any code not pumping a dispatch queue.
Where are weak delegates? For that matter, what has the CLR team been doing since 2.0 came out, five years ago?
There’s been an issue (ID 94154) on MS Connect about this since 2004, and still no word from Microsoft on when (if?) it’s going to be fixed. | https://blogs.msdn.microsoft.com/cburrows/2010/03/18/events-get-a-little-overhaul-in-c-4-part-iii-breaking-changes/ | CC-MAIN-2017-39 | refinedweb | 1,533 | 70.73 |
Hibernate code - Hibernate
Hibernate code firstExample code that you have given for hibernate... inserted in the database from this file.
Thanks
Hibernate Code - Hibernate
Hibernate Code
How to Invoke Stored Procedure in Hibernate????????
Plz provide details code
hibernate code problem - Hibernate
hibernate code problem suppose i want to fetch a row from the table... it
plz give the complete code Hi friend,
I am sending you a link . Please visit for more information. problem - Hibernate
hibernate code problem String SQL_QUERY =" from Insurance...: "
+ insurance. getInsuranceName());
}
in the above code,the hibernate... that is dynamically assigned like this
lngInsuranceId="'+name+'"
plz help me out
Plz Help Me
Plz Help Me Write a program for traffic light tool to manage time...?
Program must be written in Micro C.
Here is a code that displays...{
Color on;
int radius = 40;
int border = 10;
boolean change;
Signal
java - Hibernate
java HI guys can any one tell me,procedure for executing spring and hibernate in myeclipse ide,plz very urgent for me,thank's in advance. .../hibernate/runninge-xample.shtml
Thanks
plz send code for this
plz send code for this Program to calculate the sum of two big numbers (the numbers can contain more than 1000 digits). Don't use any library classes or methods (BigInteger etc
Hibernate - Hibernate
Hibernate What is a lazy loading in hibernate?i want one example of source code?plz reply
jsp code plz
jsp code plz write jsp code which takes student roll number as input and prints the student group,study center, and his grade card
Please visit the following links:
plz help
plz help what is the procedure and code to design an interactive GUI in java using swings
hibernate
hibernate how to impot mysql database client jar file into eclipse for hibernate configuration
Hi Friend,
Please visit the following link:
Thanks
To change font in java code
To change font in java code I am sending system generated mail through MIME message and Transport. Now i need to change the font.. Can you please help me as how to change the font of string body in java code
Plz give me code for this question
Plz give me code for this question Program to find depth of the file in a directory and list all files those are having more number of parent directories
Hibernate 1 - Hibernate
Hibernate 1 what is a fetchi loading in hibernate?i want source code?plz reply
Java - Hibernate
();
}
}
}
---------------------------
Simple problem in your code.
please change the setId...Java friends plz help me. when i run hybernate program i got, this type of output.
----------------------------
Inserting Record
Done
Hibernate
ans plz
class MyThread2 extends Thread Hi Friend,
Try the following code:
import java.io.*;
import java.util.*;
class MyThread1 extends Thread {
private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr
help again plz sorry - Java Beginners
help again plz sorry Thanks for giving me thread code
but i have a question
this code is comletelly right
and i want to make it runs much faster...,
Please change some code,
public void run(){
try{
Thread.sleep(10
Hibernate code
Hibernate code programm 4 hibernate Hi,
Read hibernate tutorial at
Thanks
please read at the the link
need the answer vry urgently..plz help me...[plzzzzzzzz
code...hpw to write in eclipse platform....plz plz mail me...to panda.pragnya7@gmail.com/panda_pragnya@yahoo.com...plz plz...help....me..it can change my lyfe...need the answer vry urgently..plz help me...[plzzzzzzzz the question
sir plz send the project on quiz system code
sir plz send the project on quiz system code sir plz send the client server based project in core java
database in my sql
Plz help me in writing the code - Java Beginners
Plz help me in writing the code Write a two user Chess Game. (users must be on different systems code - Hibernate
Hibernate code how to write hql query for retriveing data from multiple tables
password change
password change Hi ,
I am using jsf and trying to write a code to change the password of a user .
Ihave to retrine userid fromdata base how to do that using session
Help me quickly plz??
Help me quickly plz?? Can you help me to write code quickly this code is a java code take input as double and should use command line arguments and enhanced for statement then find the combine of the numbers plz help quickly
php brute force code.. hlp plz .....
php brute force code.. hlp plz ..... hello friends,
from somewhere i got a code that can generate all posible combination via recursive function...
//////////////////////////////////// Started PHP Code //////////////////////
set_time_limit(0
Plz send - Java Beginners
Plz send Hi,
please send whole code i understood ur sending... the code... without knowing ur table structure...from where should the search occur... be a troublesome...then again wat r ur needs....
so plz...provide a deatiled structure
Plz Provide correct program code for all questions.
Plz Provide correct program code for all questions.
Write a program to find the difference between sum of the squares and the square of the sums... the following code:
1)
import java.util.*;
class FindDifference
{
public static Code - Hibernate Interview Questions
Hibernate Code
Hi Friends,
In Hibernate, wat is Annotation. There is no need of hibernate configuration file in hibernate version 3 - right . but hbm is necessary for all versions
plz tell me
plz tell me how to get no. of times the 'button' is pressed
Here is a java swing code that counts the number of times the button clicked.
import javax.swing.*;
import java.awt.event.*;
public class
plz answer - Java Beginners
plz answer Write a Binary Search program that searches an array of ordered data. Compose an ordered array of 500 integers that contains..., 89, ... Hi Friend,
Try the following code:
import java.util.
Plz give java coding for this
Plz give java coding for this ****** *
* *
***********
* *
* ******
Hello Friend;
below is the code :
public class Pattern {
public static void main(String[] args) {
int
plz help me find a program
plz help me find a program plz help..i want a source code in jsp for order processing
Hibernate application - Hibernate
Hibernate application Hi,
Could you please tell me how to implement hibernate application in eclipse3.3.0
Thanks,
Kalaga. Hi Friend,
Please visit the following link:
Gui plz help
Gui plz help Create a Java application that would allow a person to practice math (either addition, subtraction, multiplication or division... handling code here:
try{
int num = Integer.parseInt(jLabel4.getText
plz help - Java Beginners
plz help i have to programs and it takes too long to run them so i.....
but i dont know how to aplly that on my 2 programs:
the first code: creating and inserting data in it and the second code reads the inserted data to do
plz help me - Java Beginners
plz help me Deepak I can write a sessioon code plz help me admin_home.jsp page is display but data is not disply plz help me what is wrong
JAVA - Hibernate
JAVA hello friends please answer me.
1. what is hibernate...?
2. why hibernate..?
3. Hibernate Vs JDBC...?
plz plz plz answer me, i have... of by the developer manually with lines of code.
Hibernate provides transparent persistence
Hibernate Code - Hibernate Interview Questions
Hibernate Code This is the question asked in CAPEGEMINI
Write a sample code how to persist inner class,interface,final class and how to invoke stored procedure in hibernate?
From Surjeet
plz - Java Interview Questions
; Hi Friend,
Try the following code:
import java.util.*;
class dieare Lazy - Hibernate
Hibernare Lazy What is a lazy loading in hibernate?i want one example of source code?plz reply
plz send immediately - Java Beginners
should be updated.
plz write a code and immediate response its very urgent plz...plz send immediately Hi Deepak,
How are you,
Deepak I face some problem in my project,plz help me
My Questin is user input
hibernate web project - Hibernate
links: web project hi friends,very good morning,how to develop
plz help me - Java Beginners
plz help me Thanks deepak continue response..i face some problem
i... is true...but i very confuse that how it is not displayed admin page plz any one... of mapping code.
ParamLoop
ParamLoopTag
Problem in running first hibernate program.... - Hibernate
/FirstExample
Exception in thread "main" " in running first hibernate program.... Hi...I am using... programs.It worked fine.To run a hibernate sample program,I followed the tutorial below
Change Password - JSP-Servlet
Change Password Hi all, Please kindly help me with jsp code and explanations to enable me write a change password program. This program will connect to mssql database 2000. Thanks tell me the code & execution process - Java Beginners
plz tell me the code & execution process Write a program to download a website from a given URL. It must download all the pages from that website... must be stored in a folder. Hi friend,
Code to help in solving
change player dress color
change player dress color Hai friends,
Can we change player dress color using J2ME. Please provide me an code for this.
I can able to attain three colors only. Send the code to mail id.
vijaikiranit@gmail.com
i need help plz .... Quickly
i need help plz .... Quickly how can i count how many numbers enterd by the user so the output would be like this
Total number of Scores = ....
this is my code :-
import java.util.Scanner;
public class SCORES
{
public
Change Password Code in JSP
Change Password Code in JSP
In this example we will see how to change password code in jsp. First of all we have
created a form where we have displayed...("");
ChangePasswordForm.jsp
<html>
<head>
<title>Change password in jsp<
Hibernate - Hibernate
a doubt in that area plz help me.That is
In Hibernate mapping file I used tag... plz help me. Hi friend,
Read for more information.
Thanks
plz help - Java Interview Questions
plz help 1)write a java program that prompts the user to input a decimal number and print the number rounded to the nearest integer?
2)write... don't use "for" Hi Friend,
Try the following code
1)
import
conert java code to jsp... plz imm i wan...
conert java code to jsp... plz imm i wan... how to convert this java code into jsp??
Java| Frameworks| Databases| Technology| Development| Build... to format currency according to the locale. In the code given below we
Dirty Checking In Hibernate Example
Dirty Checking In Hibernate Example What is the example of Dirty Checking in Hibernate? Give me some of the example code?
Thanks
... in its state.
If there is change in entity status only then the Hibernate
Hibernate delete a row error - Hibernate
the executeUpdate();
and change the jar file of hibernate...Hibernate delete a row error Hello,
I been try with the hibernate delete example (
Download.jsp Urgent plz - JSP-Servlet
for it..
In this code, as an output, I am getting the open/Save dialog as desired.. But when I... inserted after every upload very successfully..
I am sending the code for your kind...){
e.printStackTrace();
}
}
%>
Please modify the code as soon as possible and send
Dialect in Hibernate
in
Hibernate framework.
How to change the database in hibernate.cfg.xml...Dialect in Hibernate
In this article I will list down all the dialects available in Hibernate Core
framework for using the different databases
change password - JSP-Servlet
change password hi,
my problem is as follows:
i am creating...-varchar]
userPassword [data type-varchar]
now suppose user wants to change his....
thanks and regards
Nishi KIshore Hi Friend,
Try the following code Criteria Transformer Example code
Hibernate Criteria Transformer Example code Hello,
I am trying to find the example of Hibernate Criteria Transformer. Tell me the good tutorial of Hibernate Criteria Transformer with source code.
Thanks
Hi,
Check
Change Listener
Java: Change Listener
Introduction
Listeners and getting the slider value
Add a change listener to the slider so that it will
be called when the slider... button. See example below.
Change Listener
A change listener must have
JavaScript Change link
JavaScript Change link's text...;
In this section, you will learn how to change the link's text in
JavaScript.
The modification of HTML code is quite simple. Now to modify the link's text
Change Week Days Format
Change Week Days Format
This Example shows you how to change week days format. In the code given below we are change week days
format.
Methods used
hibernet code - Hibern SessionFactory Can anyone please give me an example of Hibernate SessionFactory? Hi friend,package roseindia;import... { } }}-------------------------- This is mapping code,<?xml version=" - Development process
Hibernate 3.0 core is 68,549 lines of Java code together with 27,948 lines of unit... is suit for.
what are the steps to develop hipernate
plz answer this Hi friend,
Hibernate 3.0, the latest Open Source persistence technology
hibernate - Hibernate
hibernate hi i am new to hibernate.
i wan to run a select query... hibernate for use
SessionFactory sessionFactory = new Configuration... is:
plz help me as i m unable to do
To change the color of text hyperlinks midway
To change the color of text hyperlinks midway Is there a way to change the color of text hyperlinks midway through a page? If so, what code do I use | http://roseindia.net/tutorialhelp/comment/90204 | CC-MAIN-2014-10 | refinedweb | 2,224 | 65.01 |
Hide Forgot
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.10) Gecko/20050909 Fedora/1.0.6-1.2.fc3 Firefox/1.0.6
Description of problem:
NO dependency conflicts showing. everything installed from apt rpm repos for fc3. running any python program causes crash with tracebacks like:
ImportError: /usr/lib/python2.3/site-packages/<some library.so>: undefined symbol: PyUnicodeUCS4_<something>
Looks like these add-on libraries are somehow incompatible with the python interpreter installed.
Dunno how this happened.
Note to developers: You have my full cooperation. If this is a packaging problem, please let me know what I can do to help fix it (hariseldon99@gmail.com). I really need python to be working.
Version-Release number of selected component (if applicable):
python-2.3.4-13.1
How reproducible:
Always
Steps to Reproduce:
1.Execute any python program (eg, Bram Cohen's bittorrent client)
2. It crashes with errors of the type mentioned above
3.
Actual Results: crash:
Traceback (most recent call last):
File "/usr/bin/bittorrent", line 32, in ?
import gtk
File "/usr/lib/python2.3/site-packages/PIL/__init__.py", line 33, in ?
ImportError: /usr/lib/python2.3/site-packages/gtk-2.0/gobject.so: undefined symbol: PyUnicodeUCS4_AsUnicode
Expected Results: application should have started
Additional info:
This is actually something that we've fixed in FC4
(In reply to comment #1)
> This is actually something that we've fixed in FC4
Erm, here's the wierd thing. There is a bug in fc4 installer that causes it to
crash whenever I try to install it. I tried the "garbage' fix in:
. It started the installer, but it crashed whenever I tried to upgrade.
Screenshots of tty's at the time of the crash are here:
Is there any possibility that this can be fixed in fc3?
Very unlikely for this to be backported to fc3, mostly because it requires
significant packaging changes. | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=168769 | CC-MAIN-2019-30 | refinedweb | 326 | 51.75 |
OTA LTE modem update
- DonovanBlackLab last edited by
Hi,
Is there a way to update my LTE modem's firmware over the air?
I'm guessing that I'd need an SD card to write to first (using CAT-M1), and then do the update from there? Ideally, I would like to do this safely without UART/SD.
I'd much appreciate some guidance on how I would approach this. Also is this something that's indeed necessary/ wise/ advisable?
Thank you in advance
@DonovanBlackLab The documentation is a bit vague. After a lot of trials, I was able to upgrade firmware from the module's flash over wifi (no UART, no SD). I copied one of the diff file into the /flash over ftp (I used FileZilla GUI Client). And in the micropython REPL execute following code:
import sqnsupgrade sqnsupgrade.run('/flash/diff_file')
You should copy the diff file based on your current modem firmware version which you can check with,
sqnsupgrade.info() | https://forum.pycom.io/topic/5077/ota-lte-modem-update | CC-MAIN-2022-33 | refinedweb | 164 | 72.97 |
wholesale chinese kitchen metal stainless steel oil soy sauce vinegar water tea pot
US $0.98-$4.50 / Piece
100 Pieces (Min. Order)
High Borosilicate Glass Oil Pot In The Kitchen Oil Pot With Handle Kitchen Cooking Oil Pot
US $4.80-$5.30 / Piece
500 Pieces (Min. Order)
brass Metal Planter (10", 8" or 6" & 5" Set) - Large Indoor Plant Pot For Indoor Plants and House Plants (Gold)
US $18.39 / Piece
1000 Pieces (Min. Order)
2020 new design antique metal flower zinc pot
US $1.00-$2.50 / Piece
1000 Pieces (Min. Order)
wholesale garden succulent mini terracotta flower planter brown cute animal ceramic clay pots for plants
US $0.66 / Pieces
500 Pieces (Min. Order)
factory cast iron wholesale urns, garden pot, antique cast iron flower pots
US $10.00-$300.00 / Set
10 Sets (Min. Order)
custom antique cast iron flower pots designs
US $1.00-$20.00 / Piece
10 Pieces (Min. Order)
Outdoor Wooden Garden Pot for Flower
US $180.00-$200.00 / Set
5 Sets (Min. Order)
Decorative antique outdoor cast iron flower pots wholesale
US $80.00-$400.00 / Piece
30 Pieces (Min. Order)
2015 new design oil painting oval flax handle pots for wholesale
US $12.00-$15.00 / Set
500 Sets (Min. Order)
Stainless Steel Kitchen Oil Jug,Oil Pot,Oil Can Or Kitchen Oil Bottle
US $1.99-$5.99 / Piece
500 Pieces (Min. Order)
supplier galvanized flower bucket planter bucket metal plant pot for garden
US $0.60-$2.60 / Piece
1000 Pieces (Min. Order)
Indoor Decorative Wrought Iron Metal Shelves Display Stands For Flower Pots
US $6.00-$30.00 / Piece
50 Pieces (Min. Order)
Cheap Wholesale Electroplate Oil Tall Outdoor Glazed Ceramic Planter
US $130.00-$190.00 / Piece
50 Pieces (Min. Order)
New metal transparent glass vase hanging flower stand
US $3.59-$7.98 / Piece
200 Pieces (Min. Order)
wooden plant pot,big large wpc wooden flower planter
US $80.00-$200.00 / Piece
10 Pieces (Min. Order)
metal plant pot stands designs
US $1.00-$100.00 / Piece
10 Pieces (Min. Order)
wholesale garden urn/flower pot/planter cast iron urns
US $10.00-$300.00 / Set
10 Sets (Min. Order)
kitchen Accessory SS 316 Mirror finished Oil Pot
US $1.99-$5.99 / Piece
500 Pieces (Min. Order)
2015 new design oil painting embossing flower pots for wholesale
US $16.00-$19.00 / Set
500 Sets (Min. Order)
Factory wrought iron flower pot stands Metal Plant Stands
US $6.00-$30.00 / Piece
50 Pieces (Min. Order)
Antique metal flower pot home decor
US $0.60-$2.60 / Piece
1000 Pieces (Min. Order)
European Style Small Oil Boat Shaped Vase
US $200.00-$240.00 / Piece
50 Pieces (Min. Order)
Factory wooden frame metal glass hanging flower stand decoration
US $2.69-$5.98 / Piece
200 Pieces (Min. Order)
planter,outdoor rectangular wood pot,decorative pots for garden decoration large vase wooden color flower pot
US $79.00-$299.00 / Piece
10 Pieces (Min. Order)
2015 new design oil painting embossing garden pots for wholesale
US $18.00-$21.00 / Set
500 Sets (Min. Order)
Cone shaped stainless steel 304 oil pot
US $1.99-$5.99 / Piece
500 Pieces (Min. Order)
garden decorative cast iron urn,metal planters,cast iron flower pot
US $50.00-$500.00 / Set
10 Sets (Min. Order)
Garden Black Flower Pot Wrought Iron Plant Stands
US $6.00-$30.00 / Piece
50 Pieces (Min. Order)
Decorative wrought iron flower pot stand metal flower stand for garden decorative flower stand shelf
US $1.00-$10.00 / Piece
20 Tons (Min. Order)
Rustic Farmhouse Bucket Cheap Colored galvanized metal milk jug For Halloween
US $0.60-$2.60 / Piece
1000 Pieces (Min. Order)
New Style Clear Glass Flower Vase Hydroponic Terrarium Container With Metal Holder
US $3.29 / Piece
2 Pieces (Min. Order)
Elegant Style Stainless Steel 500ml Olive Bottle Dispenser Metal Oil Pot
US $5.20-$7.90 / Piece
2000 Pieces (Min. Order)
import china goods spice tools leak proof metal oil pot for kitchen
US $2.80-$3.70 / Piece
300 Pieces (Min. Order)
Kitchenware 250ml/500ml/1000ml Set of stainless steel metal olive oil kettle/oil pot/oil bottle
US $18.00-$20.00 / Piece
1000 Pieces (Min. Order)
Seasoning Set With Metal Stand 4pcs Salt Pepper Shaker Oil Bottle Pot
US $5.00-$8.00 / Sets
2000 Sets (Min. Order)
Kitchenware Stainless Steel Metal Olive Oil Kettle/Oil Pot/Oil Bottle
US $1.20-$1.60 / Piece
800 Pieces (Min. Order)
High grade metal stainless steel Cooking oil pot
US $5.00-$15.00 / Piece
1000 Pieces (Min. Order)
3pcs cruet set salt pepper shakers oil sauce pepper pot
US $4.60-$7.00 / Set
300 Sets (Min. Order)
- About product and suppliers:
Alibaba.com offers 4,409 metal oil pot products. About 15% of these are soup & stock pots, 11% are cookware sets, and 8% are herb & spice tools. A wide variety of metal oil pot options are available to you, such as stainless steel, iron, and cast iron. You can also choose from eco-friendly, stocked. As well as from food, beverage, and home decoration. And whether metal oil pot is ce / eu, sgs, or fda. There are 4,409 metal oil pot suppliers, mainly located in Asia. The top supplying country or region is China, which supply 100% of metal oil pot respectively. Metal oil pot products are most popular in United States, United Kingdom, and Australia.
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show metal oil pot or other products of your own company? Display your Products FREE now!
Related Category
Product Features
Supplier Features
Supplier Types | https://www.alibaba.com/countrysearch/CN/metal-oil-pot.html | CC-MAIN-2019-51 | refinedweb | 962 | 79.36 |
hftp only supports remote hdfs servers
--------------------------------------
Key: HDFS-2336
URL:
Project: Hadoop HDFS
Issue Type: Bug
Affects Versions: 0.20.205.0, 0.23.0
Reporter: Daryn Sharp
Fix For: 0.23.0
The new token renewal implementation appears to introduce invalid assumptions regarding token
kinds.
Any token acquired over http is assumed to be hftp, so the kind is unconditionally changed
to hftp. This precludes the acquisition of any other token types over http. This new limitation
was added to a generic method in a public class. It should have been encapsulated in the
hftp class, not the generic http token fetching methods.
Furthermore, hftp will unconditionally change a hftp token's kind to hdfs. I believe this
assumption means that hftp is now broken if the remote cluster's default filesystem is not
hdfs.
--
This message is automatically generated by JIRA.
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/hadoop-hdfs-dev/201109.mbox/%3C2126720971.28182.1316032269038.JavaMail.tomcat@hel.zones.apache.org%3E | CC-MAIN-2014-49 | refinedweb | 149 | 58.69 |
Hello developers,
our patch extends the functionality of "Import into new database" and "Import into current database" in that way, that the user could now choose multiple files and although directories. All directories will be recursivly searched for files.
All files will be grouped by their import format corresponding to the import file filter. Currently their will be only one file format retrieved by the choosen file type, but our code is also usable with multiple file formats.
All groups of files will be imported together by the use of the existing method "automatedImport", which needs an Array of Strings representing the filenames. Before the patch, there was only one filename within the Array, but this was easy to change.
The user gets then the normal dialog with all BibTeX-entries found within the files, where he could also choose the "deselect all duplicates"-option. The results of all files of one group are summarized within one dialog.
We was inspired for this patch by the feature request 2163626 [0], but we have only extended the existing import possibilities, so that the user could do something like that by the use of this option.
One point, where we have different opinions is, if it is requested that also PDF-files without any meta data should also be imported (e.g. as entry of type "Other" with only the file link). We did not change the behavior of the handling of those files, but if it is requested, it could be easyly solved by an new import format for that type of files.
Best regards, pjhimself
[0]
Morten Omholt Alver
2008-12-02
Hi,
thank you for this patch! What do you mean by "all files will be grouped by their import format corresponding to the
import file filter"?
Hi mortenalver,
as we wrote this patch, we want to group the imported files by their import format, so that the user could get a summary for each import format. But after some test, I noticed that their would only be one import format in every case (depends on the file filter) and that the further differentiation would be performed by trial-and-error method at the importing itself. Therefore, this could currently only be a later possibility, if this behavior would be changed.
Because of that, I changed the patch a little bit, so that now all files (filenames) are only collected and then send to the automated import.
The used files depends on the file filter in every case.
You could delete the old patch whenever you want.
I hope, I could clear all of your open questions.
Best regards, pjhimself
File Added: jabref_patch_ImportFormats.diff | http://sourceforge.net/p/jabref/patches/105/ | CC-MAIN-2014-52 | refinedweb | 445 | 59.84 |
Continuing with my Getting Physical blog posts series (CanSec2016’s presentation), in this third episode I’m going to talk about how Windows Paging is related to the HAL's heap and how it can be abused by kernel exploits. This is probably the simplest way of abusing Windows paging structures, because deep knowledge about how Intel paging works is not necessary to implement the attack.
"Windows 10" Anniversary Update - notes
After installing and testing the "Windows 10" 64 bits Anniversary Update (version 1607) , I can confirm what Microsoft announced in its presentation "Windows 10 Mitigation Improvements" in BH-USA-2016 and that Windows has started to randomize Paging Tables. To confirm that, I wrote a "test.exe" program that contains a breakpoint in the "main" function. When this program is executed, a breakpoint is hit in the kernel debugger. Before, when the "!pte eip" command was executed in Windows 10 "version 1511" (TH2), the result was the following:
Now, in Windows 10 "version 1607", the result is different:
It's clear that something has changed and that the Windows kernel debugger is not able to read the PAGE TABLE memory address located at 0xFFFFF6BF'FBBA0088. It means that the paging tables that map the code pointed by the instruction pointer are not present; at least, not in the usual addresses. Now, and as we proposed in our presentation "Windows SMEP bypass: U=S" given in October 2015 at Ekoparty with @KiqueNissim
The only way to randomize paging tables that use the self-referential technique is by randomizing the PML4 self-ref entry position. In the case of Windows 64 bits versions, it's located in the position 0x1ED. If the PML4 self-ref entry is moved +/-1 position, the difference will be +/- 512GB (0x80'00000000) from the original paging table entry. Knowing that, I started to manually look for the PTE that maps RIP, and the result was this:
It means that, after rebooting the virtual machine, Windows has chosen the position 0x1ED minus 0xE6 (0x107) as self-ref entry. This behavior proves that Windows has stopped using the position 0x1ED in the PML4, and now, it changes after every reboot. To be clear, from NOW on it's no longer possible to use arbitrary writes, in a 100% reliable way, against the Windows 10 paging tables, because the probability of hitting the right one is near to 1/256 (256 kernel entries).
Windows HAL's Heap
When Windows is booting, one of the first modules to be loaded is HAL.DLL (Hardware Abstraction Layer). This module, that runs in kernel mode, is used to abstract the Windows kernel from basic hardware like APIC, I/O PORTS, etc. In this way, the Windows kernel is able to interact with different architectures by calling to the same HAL.DLL exported functions. To run, HAL.DLL needs stack and heap, like the 99.99% of the modules written for Windows. The most interesting thing can be seen in the HEAP side, because it's created by HAL.DLL during the booting process. What is really interesting here is that, this HEAP is ALWAYS mapped at the same virtual address, at least since Windows 2000. This attack vector was mentioned some time ago in a very interesting presentation called "Bypassing kernel ASLR - Target: Windows 10 (remote bypass)". The virtual address used for the HAL's heap initial address is: - Windows 32 bits - 0xffd00000 - Windows 64 bits - 0xffffffff’ffd00000 Here, we can see a table with the latest 64-bit Windows versions:
If we look at the right column ("Physical Address"), we can see that the physical address used by the HAL's heap is FIXED, and this one changes depending on the Windows version. Both for Windows 8.1 and Windows 10 (including "Anniversary Update"), the PHYSICAL address used by the virtual address 0xFFFFFFFF’FFD00000 is 0x1000 (PFN 0x1). This means that, both PHYSICAL and VIRTUAL addresses are NOT randomized ! Now, the HAL's heap became really interesting since Windows 8, when it started to contain a function pointer list called "HalpInterruptController". This list is exported by HAL.DLL and can be found by using the next command:
dq poi(hal!HalpInterruptController)
Let's see an example:
One of the most interesting pointers, at least in the 64 bits versions, is “hal!HalpApicRequestInterrupt”, located in the position 15 (offset 0x78) of this table:
This function pointer is used all the time by the Windows kernel, which means that if we overwrite it, we will get controlled execution quickly. It's important to say that, depending on the Windows version and the target configuration (number of CPUs), this function pointer list tends to be kept in the same virtual address, and that it can be overwritten by a simple arbitrary write, because it's mapped as writable. So, if it's kept in a fixed virtual address, it means that it can be abused by LOCAL and REMOTE exploits.
Testing Windows Paging
Before we start listing the most useful arbitrary write cases against Windows paging structures, let's do a little demo. I created a program called "test2.exe" with the following code:
#include <windows.h> #include <stdio.h> main () { void *p = 0x1000000; // Allocating memory p = VirtualAlloc ( p, 0x1000, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE ); printf ( "p = %llx\n", p ); // Setting memory memset ( p, 0x41, 0x1000 ); // Hitting breakpoint __debugbreak (); }
When this program is executed, we hit a breakpoint in the Windows kernel debugger. Knowing that this program allocates memory at 0x1000000 (RAX value), let's see its content:
Now, if we execute the command "!pte rax" to obtain the PAGE TABLE entry used to map this address:
In the screenshot above, we can see that the PTE used to map the virtual address 0x1000000 is at the PHYSICAL address 0x23FD2000 (lowest 12 bits are ignored). Here comes the interesting part. To simulate an arbitrary write, let's use the same kernel debugger to overwrite the physical address used by this PTE with the physical address of the HAL's heap (0x1000 address)
Now, we trace one instruction to refresh the TLBs and then, we dump the content of 0x1000000 ("rax" register). We can see that the HAL's heap has been mapped in this address, which means that, now we can read/write/execute this memory area from USER SPACE :-)
To confirm that we are really seeing the HAL's heap, let's check if we are able to read the "hal!HalpInterruptController" function pointer table.
Effectively, when the offset 0x4a0 is added to the memory page mapped at 0x1000000, we can see this table. Let's do the last test, let's overwrite the address 0x1000000+0x518 (“hal!HalpApicRequestInterrupt” pointer offset) with the value 0x41414141'41414141:
and let's continue with the normal execution ...
ops! ... this function pointer has been used by the Windows kernel almost instantly :-)
Shooting all valid ways of kernel arbitrary writes
Depending on the kind of arbitrary write that we have, either fully controllable or not, and what it allows us to do like writing one byte, one word, one dword or one qword, we will see that it's possible to find a way to map the heap created by HAL.DLL in USER SPACE ! Let's start by understanding that, when we call VirtualAlloc to allocate memory, the Windows kernel usually creates PAGE TABLE entries, and depending on the virtual address allocated by this function, it could be necessary to create more entries in higher paging levels like PML4 or PDPT. For example, if we want to allocate 4KB at 0x1000000, we would do something like that:
VirtualAlloc ( 0x1000000, 0x1000, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
After allocation, if we execute the command "!pte 0x1000000" in KD, we can see the PTE created by the kernel:
Now, if we look at the consecutive PTEs, we can see that all of them are empty:
It makes sense, because only 4KB have been mapped at virtual address 0x1000000, the rest are unused. Now, what would happen if we use an arbitrary write to create our own entries ? - Using arbitrary writes to create new paging entries The trick here is to make sure that the PAGE TABLE where we want to point our arb.write is present. The best way to do that is by allocating 4KB in an unused 2MB memory range. This is to make sure that a new PAGE TABLE with only a single used entry will be created. The most interesting thing here is that, as the Windows kernel doesn't use the empty entries nor checks them, they are ignored. So, it's possible to create spurious entries during Windows kernel exploitation (or post exploitation) without the knowledge of the MMU, and when the exploitation process finishes, no BSoD will appear ... ;-) - Using 2-byte/4-byte/8-byte arbitrary writes Let's start with the simplest case, where we have a kernel bug that allows us to write a word, dword or qword where we want. In the following examples, all our arbitrary writes will be used to map the HAL's HEAP in user space by creating a new paging entry. To create a PTE that allows us to do this it's necessary to have an arb.write like this:
- "67 10" 00 00 00 00 NN NN
The value 0x67 means DIRTY + ACCESSED + USER + WRITABLE + PRESENT. It's not really necessary to set the DIRTY and ACCESSED flags, because they are set by the CPU in runtime, so we could use the value 0x07 instead of the 0x67. The XX 1X 00 00 value represents the PFN number 1, which is equal to the physical address 0x1000. Now, let's simulate a 2-byte arbitrary write by using the kernel debugger:
We can see that before overwriting the PTE that maps the virtual address 0x1001000, it wasn't possible to read the constant from this address. After overwriting this empty entry, we got access from USER SPACE to the HAL's heap. Now, if we only control the highest part of our arbitrary write, we could overwrite two consecutive empty-entries like this:
PREVIOUS PTE | NEXT PTE NN NN NN NN NN NN | "67 10"
In this way we get the same result that above. - Using 1-byte/2-byte/4-byte/8-byte arbitrary writes In this case, we are going to analyze the most interesting paging tables arbitrary write where, instead of creating a PAGE TABLE entry, we are going to create a PAGE DIRECTORY entry. For this one, we will use our arb.write to create a LARGE PAGE, and we will use 0x00 (NULL address) as the physical address. To create a LARGE PAGE, we need to turn on the PS bit (Page Size):
If this physical address points to the NULL address, it means that this PDE is mapping the 0~2MB memory range, which includes the HAL's heap. This is really cool because we are able to do that by using a single 1-byte arbitrary write :-D The arbitrary write that we need to use should be like that:
- "e7" 00 00 00 00 00 NN NN
Or, if we only control the highest part, we should overwrite 2 consecutive empty-entries like that:
PREVIOUS PDE | NEXT PDE NN NN NN NN NN NN NN | e7
In the same way as PTEs, it's necessary to make sure that the PAGE DIRECTORY that we are going to overwrite is present. Knowing that a PAGE DIRECTORY TABLE can address up to 2MB * 512 entries (1GB), it's advisable that our memory allocation creates a PAGE DIRECTORY away from memory areas previously allocated. To do this, the best option is to allocate in the first 4KB of memory addresses that are multiples of one gigabyte, like 1GB, 2GB, nGB. In this example, I'm going to use the virtual address 1 GB.
VirtualAlloc ( 1024*1024*1024*1, 0x1000, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
After allocation, we can see that when we read the PAGE DIRECTORY table, we see the entry created by Windows:
At the same time, we can see that the following entries are empty, so it means that there is no virtual memory mapped in 1GB+2MB, 1GB+4MB, etc. So, it's easy to deduce that we are going to use our arb.write against one of them. For our example, I'm going to use the first empty PDE, which maps the range 1GB+2MB~1GB+4MB.
In the above screenshot, we can see that there is not memory mapped at 1GB+2MB (0x4020000), and that its PDE is obviously empty. Now, let's simulate a 1-byte arbitrary write, an then let's read the content of the address 1GB+2MB (0x4020000):
Once the arb.write was used to create a LARGE PAGE, we can see that when we read at 0x4020000, we are seeing the very old and famous IVT (Interrupt Vector Table) located at the physical address 0x00 (PFN 0) :-D If we move at offset 0x14A0, we can see the "hal!HalpInterruptController" table:
It's important to say that we could allocate in any virtual address, and then we could find an empty PDE to do exactly the same. I used an empty PAGE DIRECTORY TABLE to simplify the explanation. - Decrementing a memory address in one unit This is one of my favorites arb.writes, because the ability of the exploit writer can be seen in all different forms. In general, we find these kind of scenarios when we have an UAF (Use After Free), usually in win32k.sys. The instruction that allows to do that is almost always:
- dec [reg+0xNN]
Some time ago, one of the simplest ways to abuse this kind of arbitrary writes was by using Cesar Cerrudo's "Second trick", where the SEP_TOKEN_PRIVILEGES field of the PROCESS TOKEN structure was decremented by 1. With this trick, it was possible to enable some special bits which allows us to get some privileges like injecting code in system processes like "lsass.exe". Since Windows 8.1, all processes running in Low Integrity Level are no longer able to get TOKEN PROCESS addresses by calling NtQuerySystemInformation with the "SystemInformationClass" parameter equal to "SystemHandleInformation". As a replacement of this technique, we can use our arbitrary decrement to create a LARGE PAGE :-) Reviewing the last technique explained above, to create a PAGE DIRECTORY entry that works as LARGE PAGE it's necessary to use the value 0xE7:
0xE7 = PAGE SIZE (4KB) + DIRTY + ACCESSED + USER + WRITABLE + PRESENT
Now, if we use the "dec" instruction to decrement, in a shifted way, two consecutive PAGE DIRECTORY empty entries like this:
PREVIOUS PDE | NEXT PDE FF FF FF FF FF FF FF | FF 00 00 00 00 00 00 00
we will turn on all the PDE bits resulting in the next one:
0xFF = PAGE SIZE (4KB) + DIRTY + ACCESSED + PCD (PAGE-LEVEL CACHE DISABLED) + PWT (PAGE-LEVEL WRITE THROUGH) + USER + WRITABLE + PRESENT
Fortunately, this bits combination works, allowing us to create a LARGE PAGE that uses the physical address 0x00 (NULL address ) ! Simulating a shifted decrementation in the PDEs that map the virtual address range 1GB+4MB ~ 1GB+6MB, we would see something like that:
After decrementation, the last 0xFF value maps a LARGE PAGE that starts at 0x00 physical address and finishes at 2MB physical address, where the whole HAL's heap is contained :-D
Although I have only mentioned the most common arb.write cases, it's important to point out that we could use other variants of them, because it's only necessary to turn on some specific bits to create valid entries.
Special comments
- SMEP bypass After using an arb.write, we will have access to the HAL's heap from user space with read/write privileges. Now, when the “hal!HalpApicRequestInterrupt” function pointer is modified, we are able to jump wherever we want. There is a problem here, because at the same time that the HAL.DLL function pointer list was introduced by Windows 8, Windows started to support SMEP (Supervisor Mode Execution Prevention), which forces us to bypass it when this is supported by the target. The best way to do that is by ROPing to HAL.DLL, because its base address can be calculated by reading the function pointers contained by this table. Some of the ways to do that were explained in this presentation.
- Process context after overwriting HAL's HEAP function pointers It's VERY IMPORTANT to say that, when this function pointer is overwritten, the control of RIP won't be taken necessarily by our process context, because this is used all the time by the Windows kernel, independently of the current process. It complicates much more the exploitation when a ROP-Chain is used, because the addresses of the ROP gadgets have to be contained by stack created by the exploit itself. As a simple solution for this problem, after overwriting the “hal!HalpApicRequestInterrupt” function pointer, we could consume the 100% of the CPU by using a simple "while(1)", and then just wait for the Windows kernel invocation. To be continued … For more information on our Core Labs team and what they are working on, visit our Services Page and see how our services can work for your organization. | https://www.coresecurity.com/article/getting-physical-extreme-abuse-of-intel-based-paging-systems | CC-MAIN-2019-26 | refinedweb | 2,882 | 55.58 |
Gradle Plugin Conventions: Groovy Magic Explained
Join the DZone community and get the full member experience.Join For Free
Hackergarten last Friday was a big success. About 10 of us (not all Canooies!) stayed up late and created an Announce plugin for Gradle. In the 0.9 release you will be able to announce build events to Twitter, Snarl, and the Ubuntu notification service (sorry, no Growl yet, it is coming). It was fun, educational, and energizing, and you should sign up for the Google Group and come to the next event.
While writing the plugin, we were briefly delayed by a technical detail. The user guide explains how to pass simple parameters to a plugin, but does not explain how to nest parameters within a closure. For instance, in the announce plugin you specify the Twitter username and password within an announce block:
announce {It turns out to be easy (just not documented, but we will fix that soon). Here is the full gradle build that shows you how to do it, with a detailed explanation of how it works below. As an example, we'll extend the Gradle documentation greeter custom plugin. This whole thing is runnable from the command line with "gradle hello":
username 'your-username'
password 'your-password'
}
apply plugin: GreetingPluginStarting at the top... there is a property declaration called "message" within a "greet" block. This is a much nicer configuration option than just using build-global variables, and your plugin should do something like this. It is important to understand what this block actually is and how it works. In Groovy, parentheses on method calls are optional and curly braces declare a closure. So this greet block is really an invocation of a method with type "Object greet(Closure)". To read and capture this message variable, you must somewhere declare and wire in this "Object greet(Closure)" method within your plugin.
greet {
message = 'Hi from Gradle'
}
class GreetingPlugin implements Plugin<Project> {
def void apply(Project project) {
project.convention.plugins.greeting = new GreetingPluginConvention()
project.task('hello') << {
println project.convention.plugins.greeting.message
}
}
}
class GreetingPluginConvention {
String message
def greet(Closure closure) {
closure.delegate = this
closure()
}
}
Moving on to the Plugin declaration. Plugin configuration is captured in something Gradle calls a "Convention" object. It is just a plain old Groovy object, and there is no Gradle magic... all the magic happending is standard Groovy. Let's examine the apply() method closely:
def void apply(Project project) {During the configuration phase (before any targets are run) you will be given a Project object, and that Project object has a Convention object that holds onto a Map of all the project conventions. Three pieces of Groovy magic: Getters can be accessed with property notation, Map entries can be accessed with dot notation, and Map.put can be called with the = sign. So this line:
project.convention.plugins.greeting = new GreetingPluginConvention()
project.task('hello') << {
println project.convention.plugins.greeting.message
}
}
project.convention.plugins.greeting = new GreetingPluginConvention()Is the same as the Java equivalent:
project.getConvention().getPlugins().put("greeting", new GreetingPluginConvention());During the build, Gradle is going to execute the build script. Any time an unknown property is assigned or an undeclared method is invoked, Gradle will look at this plugins Map and use the respondTo method to check if any of the Plugin conventions accepts that variable. If it does, then your convention object gets invoked and that variable is set. Gradle takes care of translating an unknown method call of "Object greet(Closure)" into a call to your convention object. All that you need to do is make sure the greet(Closure) method is defined properly:
class GreetingPluginConvention {
String message
def greet(Closure closure) {
closure.delegate = this
closure()
}
}
Now
it is up to you to dispatch the parameters declared within the closure
into fields on your convention object. If you just try to execute the
closure then you will receive a nice PropertyMissingException because
the "message" field is not declared anywhere. You get around this by
defining a "message" field on your object and then setting "this" to
the closure's delegate. Groovy method dispatch is flexible (complex?).
Closures have a delegate object that will act as a sort of "this"
reference when the closure executes. So the message field was out of
scope when the closure was created, but adding a delegate makes the
message field from the convention object in scope. When the closure
assigns message a value, it will be the message on your Convention
object. Check out my old blog post Fun with Closures for a more in depth explanation.
Now your convention object has the message String, hooray! You can do something interesting with it, like printing it out to the console:
println project.convention.plugins.greeting.message
Or maybe you had something more interesting in mind for your cool plugin. Let us hope.
By the way, you can just as easily declare a settings variable. This is an equivilent implementation of apply:
def settings = new GreetingPluginConvention()
project.convention.plugins.greeting = settings
project.task('hello') << {
println settings.message
}
And now there is just one last piece of Groovy magic left unexplained:
apply plugin: GreetingPlugin
This too is plain old Groovy. Method parenthesis are optional. Method parameters can be passed in as name value pairs. And Class literals can be referenced without the .class extension. The apply plugin statement is really just a plain old method call in disguise, and it is an invocation of apply(Map). The apply statement can be written in Java as:
Map map = new HashMap();
map.put("plugin", GreetingPlugin.class);
apply(map);
Groovy magic is good. Thanks for taking some time to understand it. Hopefully this example makes it to the Gradle user guide in the next few days.
From
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/gradle-plugin-conventions | CC-MAIN-2021-10 | refinedweb | 967 | 57.37 |
io
java io
java io by using java coding how to invoke a particular directory
Working With File,Java Input,Java Input Output,Java Inputstream,Java io
Tutorial,Java io package,Java io example
File(path)
Create File object for default
directory...;Create File object for directory
path given as string.
File(dir, fname)
Create File object for
directory.
Thus
Java IO Path
Java IO Path
In this section we will discuss about the Java IO Path.
Storage of a file or folder(Directory/Subdirectory) in a Hard Drive or other
media.... These sub folders can contains a file or sub folders and so on. For
example
Java Create Directory
The following example will show how to Create Directory in Java. Though... is already created" will be displayed.
Example of Java Create Directory... of the program.
For this we cerate a file object in File class which will create a new
java IO programing
java IO programing how Java source file is used as input the program will echo lines
Java Create Directory - Java Tutorial
Java Create Directory - Java Tutorial
...;java CreateDirectory
Directory: test created
Directories...;. the mkdir( ) method is
used to create a single directory while the mkdirs( ) method
java-io - Java Beginners
java-io Hi Deepak;
down core java io using class in myn...://
Thanks
Java IO OutputStreamWriter
");
bw.newLine();
bw.write("Java IO OutputStreamWriter Example...Java IO OutputStreamWriter
In this section we will learn about the Java...");
osw = new OutputStreamWriter(os);
osw.write("Java IO
IO File - Java Beginners
IO File Write a java program which will read an input file & will produce an output file which will extract errors & warnings.
It shall exclude the standard errors & warnings. The standard errors & warnings you can find out
Java Create Directory - Java Tutorial
Java Create Directory - Java Tutorial
... how to
create directory using java program. This program also explains... directory in Java?"
Here is the code for creating directory and all non
IO concept
IO concept Write a java program that moves the contents of the one file to another and deletes the old file.
Hi Friend,
Try...!");
}
}
For more information, visit the following link:
Java Move File
Thanks
Copy Directory or File in Java
Copy Directory in Java
... the features of the copying the directory and it's contents. This
example shows.... otherwise read the source directory name and
create the OutputStream instance
Java IO FilterWriter
Java IO FilterWriter
In this example we will discuss about the FilterWriter...();
bw.write("Java IO FilterWriter Example");
System.out.println("Data is written... an example is being given which demonstrates about how to use Java
FilterWriter
Java IO CharArrayWriter
Java IO CharArrayWriter
In this tutorial we will learn about the CharArrayWriter in Java.
java.io.CharArrayWriter extends the java.io.Writer.... constructor is used to create a new CharArrayWriter.
Syntax : public CharArrayWriter)? "
Java Directory - Directory and File Listing Example in Java
Java Directory - Directory and File Listing Example in Java...;
This example illustrates how to list files and
folders present in the specified directory. This topic is related to the
I/O
(input/output Telephone directory management system
Java Telephone directory management system
Here we are going to create a java application for Telephone directory system. For this, we have accepted ID, name...:
import java.io.*;
import java.util.*;
class Directory implements FileInputStream
Java FileInputStream
In this section we will discuss about the Java IO... of bytes.
Syntax : public long skip(long n) throws IOException
Example :
In this example I have created a class named ReadFileInputStream.java
Java IO SequenceInputStream Example
Java IO SequenceInputStream Example
In this tutorial we will learn about...; started form the offset 'off'.
Example :
An example... or concatenate the contents of two files. In this
example I have created two text
Getting the Current Working Directory in Java
C:\nisha>javac GetCurrentDir.java
C:\nisha>java GetCurrentDir
Current Working Directory : C:\nisha
C:\nisha>
Download this example
Open Source Directory
Open Source Directory
Open Source Java Directory
The Open Source Java... - to many different
platforms.
Open Source Java Directory
The Open Source Java Directory is maintained by Steve Mallett, creator
Rename the File or Directory in Java
Rename the File or Directory in Java
... is the video tutorial of: "How to Rename the File or Directory in Java?"... that how a file or directory is renamed. This program illustrates you
the procedure
Find Current Temp Directory
directory is C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
Download this
example...;
In this
example we are find the current Temp directory.
We are using getProperty(String
key) method to find
Java IO OutputStream
Java IO OutputStream
In this section we will read about the OutputStream class...)
throws IOException
Example :
An example... to the specified file. In this example I have tried to read the
stream of one file
Java file get parent directory
Java file get parent directory
In this section, you will learn how to get the parent directory of the file.
Description of code:
The package java.io.... and directories. You can see in the given example we
have created a File object
Find User Home Directory
;
In this
example we are find user home directory.
We... information.
The method used into this example... for passing Key
values.
In this example we are passing "user.home
Java delete non empty directory
Java delete non empty directory
This section demonstrates you how to delete a non empty directory.
It is easy to delete a directory if it is empty by simply... that are available in the directory.
You can see in the given example, we have created
The JDK Directory Structure
Directory structure of JDK
Welcome to Java tutorial series. In this lesson, you will learn about the
directory structure of Java Development Kit, JDK. Since...\jre
It is the root directory of the Java Runtime Environment. It is used
Create Directory in PHP
Create Directory in PHP Hi,
I want to create a small php program like how to create directory in PHP. I need the help of PHP programmer, who could... here with suggest the best examples and syntax related how to create directory
Create File in Java
of how to create a file in java:
package FileHandling;
import java.io.File...File is nothing but a simple storage of data in Java language. We call one... or directory and also use the pathname. File is collection of stored
Create File in Java
Create a File
... in string, rows, columns and lines etc.
In this section, we will see
how to create a file. This example takes the file name and text data for storing BufferedReader
Java IO BufferedReader
In this section we will discuss about the BufferedReader class in Java.
BufferedReader class in java.io package is used for read... for example
FileReader, InputStreamReader etc.
Constructor of BufferedReader
ls: cannot access >: No such file or directory
java.io.BufferedReader;
import java.io.InputStreamReader;
public class Example.../f.txt from terminal in linux its creating f.txt.But cant run from java program ls: cannot access >: No such file or directory error is displayed .No f.txt
How to create charts in Java?
How to create charts in Java? Is there any example of creating charts and graphs in Java?
thanks
Hi,
check the tutorial: Chart & Graphs Tutorials in Java
Thanks
Java I/O - Java Beginners
:// run...Creating Directory Java I/O Hi, I wanted to know how to create a directory in Java I/O? Hi, Creating directory with the help of Java
Spring IO Platform 1.0.0 Released
Spring IO Platform 1.0.0 Released - Check the new features of this release
The Spring IO is platform for developing and building the modern day
applications.... The Spring IO is 100% open source system and it is modular.
The latest version
create
create how to create an excel file using java SDK Directory Structure
Java SDK Directory Structure
... of command provided by Java compiler.
Demo directory - This directory consists... to combine C code into a Java
program.
Jre directory - When you run
Determining if a File or Directory exist
Determining if a File or Directory Exist
... to determine whether a file or directory exists or not.
If it exists it ... or directory denoted by this pathname
exists or not.
Here is the video tutorial
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/56231 | CC-MAIN-2015-40 | refinedweb | 1,398 | 50.23 |
Algorithm::SkipList - Perl implementation of skip lists
The following non-standard modules are used:
enum
my $list = new Algorithm::SkipList(); $list->insert( 'key1', 'value' ); $list->insert( 'key2', 'another value' ); $value = $list->find('key2'); $list->delete('key1');
This is an implementation of skip lists in Perl.
Skip lists are similar to linked lists, except that they have random links at various levels that allow searches to skip over sections of the list, like so:
4 +---------------------------> +----------------------> + | | | 3 +------------> +------------> +-------> +-------> +--> + | | | | | | 2 +-------> +--> +-------> +--> +--> +--> +-------> +--> + | | | | | | | | | 1 +--> +--> +--> +--> +--> +--> +--> +--> +--> +--> +--> + A B C D E F G H I J NIL
A search would start at the top level: if the link to the right exceeds the target key, then it descends a level.
Skip lists generally perform as well as balanced trees for searching but do not have the overhead with respect to inserting new items. See the included file
Benchmark.txt for a comparison of performance with other Perl modules.
For more information on skip lists, see the "SEE ALSO" section below.
Only alphanumeric keys are supported "out of the box". To use numeric or other types of keys, see "Customizing the Node Class" below.
A detailed description of the methods used is below.
$list = new Algorithm::SkipList();
Creates a new skip list.
If you need to use a different node class for using customized comparison routines, you will need to specify a different class:
$list = new Algorithm::SkipList( node_class => 'MyNodeClass' );
See the "Customizing the Node Class" section below.
Specialized internal parameters may be configured:
$list = new Algorithm::SkipList( max_level => 32 );
Defines a different maximum list level.
The initial list (see the "list" method) will be a random number of levels, and will increase over time if inserted nodes have higher levels, up until "max_level" levels. See "max_level" for more information on this parameter.
You can also control the probability used to determine level sizes for each node by setting the P and k values:
$list = new Algorithm::SkipList( p => 0.25, k => 1 );
See P for more information on this parameter.
You can enable duplicate keys by using the following:
$list = new Algorithm::SkipList( duplicates => 1 );
This is an experimental feature. See the "KNOWN ISSUES" section below.
$list->insert( $key, $value );
Inserts a new node into the list.
You may also use a search finger with insert, provided that the finger is for a key that occurs earlier in the list:
$list->insert( $key, $value, $finger );
Using fingers for inserts is not recommended since there is a risk of producing corrupted lists.
if ($list->exists( $key )) { ... }
Returns true if there exists a node associated with the key, false otherwise.
This may also be used with search fingers:
if ($list->exists( $key, $finger )) { ... }
$value = $list->find_with_finger( $key );
Searches for the node associated with the key, and returns the value. If the key cannot be found, returns
undef.
Search fingers may also be used:
$value = $list->find_with_finger( $key, $finger );
To obtain the search finger for a key, call "find_with_finger" in a list context:
($value, $finger) = $list->find_with_finger( $key );
$value = $list->find( $key ); $value = $list->find( $key, $finger );
Searches for the node associated with the key, and returns the value. If the key cannot be found, returns
undef.
This method is slightly faster than "find_with_finger" since it does not return a search finger when called in list context.
If you are searching for duplicate keys, you must use "find_with_finger" or "find_duplicates".
@values = $list->find_duplicates( $key ); @values = $list->find_duplicates( $key, $finger );
Returns an array of values from the list.
This is an autoloading method.
Search is an alias to "find".
$key = $list->first_key;
Returns the first key in the list.
If called in a list context, will return a search finger:
($key, $finger) = $list->first_key;
A call to "first_key" implicitly calls "reset".
$key = $list->next_key( $last_key );
Returns the key following the previous key. List nodes are always maintained in sorted order.
Search fingers may also be used to improve performance:
$key = $list->next_key( $last_key, $finger );
If called in a list context, will return a search finger:
($key, $finger) = $list->next_key( $last_key, $finger );
If no arguments are called,
$key = $list->next_key;
then the value of "last_key" is assumed:
$key = $list->next_key( $list->last_key );
Note: calls to "delete" will "reset" the last key.
($key, $value) = $list->next( $last_key, $finger );
Returns the next key-value pair.
$last_key and
$finger are optional.
This is an autoloading method.
$key = $list->last_key; ($key, $finger, $value) = $list->last_key;
Returns the last key or the last key and finger returned by a call to "first_key", "next_key", "index_by_key", "key_by_index" or "value_by_index". This is not the greatest key.
Deletions and inserts may invalidate the "last_key" value. (Deletions will actually "reset" the value.)
Values for "last_key" can also be set by including parameters, however this feature is meant for internal use only:
$list->last_key( $node );
Note that this is a change form versions prior to 0.71.
$list->reset;
Resets the "last_key" to
undef.
$index = $list->index_by_key( $key );
Returns the 0-based index of the key (as if the list were an array). This is not an efficient method of access.
This is an autoloading method.
$key = $list->key_by_index( $index );
Returns the key associated with an index (as if the list were an array). Negative indices return the key from the end. This is not an efficient method of access.
This is an autoloading method.
$value = $list->value_by_index( $index );
Returns the value associated with an index (as if the list were an array). Negative indices return the value from the end. This is not an efficient method of access.
This is an autoloading method.
$value = $list->delete( $key );
Deletes the node associated with the key, and returns the value. If the key cannot be found, returns
undef.
Search fingers may also be used:
$value = $list->delete( $key, $finger );
Calling "delete" in a list context will not return a search finger.
$list->clear;
Erases existing nodes and resets the list.
$size = $list->size;
Returns the number of nodes in the list.
$list2 = $list1->copy;
Makes a copy of a list. The "p", "max_level" and node class are copied, although the exact structure of node levels is not copied.
$list2 = $list1->copy( $key_from, $finger, $key_to );
Copy the list between
$key_from and
$key_to (inclusive). If
$finger is defined, it will be used as a search finger to find
$key_from. If
$key_to is not specified, then it will be assumed to be the end of the list.
If
$key_from does not exist,
undef will be returned.
This is an autoloading method.
$list1->merge( $list2 );
Merges two lists. If both lists share the same key, then the valie from
$list1 will be used.
Both lists should have the same node class.
This is an autoloading method.
$list1->append( $list2 );
Appends (concatenates)
$list2 after
$list1. The last key of
$list1 must be less than the first key of
$list2.
Both lists should have the same node class.
This method affects both lists. The "header" of the last node of
$list1 points to the first node of
$list2, so changes to one list may affect the other list.
If you do not want this entanglement, use the "merge" or "copy" methods instead:
$list1->merge( $list2 );
or
$list1->append( $list2->copy );
This is an autoloading method.
$list2 = $list1->truncate( $key );
Truncates
$list1 and returns
$list2 starting at
$key. Returns
undef is the key does not exist.
It is asusmed that the key is not the first key in
$list1.
This is an autoloading method.
($key, $value) = $list->least;
Returns the least key and value in the list, or
undef if the list is empty.
This is an autoloading method.
($key, $value) = $list->greatest;
Returns the greatest key and value in the list, or
undef if the list is empty.
This is an autoloading method.
@keys = $list->keys;
Returns a list of keys (in sorted order).
@keys = $list->keys( $low, $high);
Returns a list of keys between
$low and
$high, inclusive. (This is only available in versions 1.02 and later.)
This is an autoloading method.
@values = $list->values;
Returns a list of values (corresponding to the keys returned by the "keys" method).
This is an autoloading method.
Internal methods are documented below. These are intended for developer use only. These may change in future versions.
($node, $finger, $cmp) = $list->_search_with_finger( $key );
Searches for the node with a key. If the key is found, that node is returned along with a "header". If the key is not found, the previous node from where the node would be if it existed is returned.
Note that the value of
$cmp
$cmp = $node->key_cmp( $key )
is returned because it is already determined by "_search".
Search fingers may also be specified:
($node, $finger, $cmp) = $list->_search_with_finger( $key, $finger );
Note that the "header" is actually a search finger.
($node, $finger, $cmp) = $list->_search( $key, [$finger] );
Same as "_search_with_finger", only that a search finger is not returned. (Actually, an initial "dummy" finger is returned.)
This is useful for searches where a finger is not needed. The speed of searching is improved.
$k = $list->k;
Returns the k value.
$list->k( $k );
Sets the k value.
Higher values will on the average have less pointers per node, but take longer for searches. See the section on the P value.
$plevel = $list->p;
Returns the P value.
$list->p( $plevel );
Changes the value of P. Lower values will on the average have less pointers per node, but will take longer for searches.
The probability that a particular node will have a forward pointer at level i is: p**(i+k-1).
For more information, consult the references below in the "SEE ALSO" section.
$max = $list->max_level;
Returns the maximum level that "_new_node_level" can generate.
eval { $list->max_level( $level ); };
Changes the maximum level. If level is less than "MIN_LEVEL", or greater than "MAX_LEVEL" or the current list "level", this will fail (hence the need for setting it in an
eval block).
The value defaults to "MAX_LEVEL", which is 32. There is usually no need to change this value, since the maximum level that a new node will have will not be greater than it actually needs, up until 2^32 nodes. (The current version of this module is not designed to handle lists larger than 2^32 nodes.)
Decreasing the maximum level to less than is needed will likely degrade performance.
$level = $list->_new_node_level;
This is an internal function for generating a random level for new nodes.
Levels are determined by the P value. The probability that a node will have 1 level is P; the probability that a node will have 2 levels is P^2; the probability that a node will have 3 levels is P^3, et cetera.
The value will never be greater than "max_level".
Note: in earlier versions it was called
_random_level.
$node = $list->list;
Returns the initial node in the list, which is a
Algorithm::SkipList::Node (See below.)
The key and value for this node are undefined.
$node = $list->_first_node;
Returns the first node with a key (the second node) in a list. This is used by the "first_key", "least", "append" and "merge" methods.
$node = $list->_greatest_node;
Returns the last node in the list. This is used by the "append" and "greatest" methods.
$node_class_name = $list->_node_class;
Returns the name of the node class used. By default this is the
Algorithm::SkipList::Node, which is discussed below.
$list->_build_distribution;
Rebuilds the probability distribution array
{P_LEVELS} upon calls to "_set_p" and "_set_k".
These methods are used during initialization of the object.
$list->_debug;
Used for debugging skip lists by developer. The output of this function is subject to change.
Methods for the Algorithm::SkipList::Node object are documented in that module. They are for internal use by the main
Algorithm::SkipList module.
Hashes can be tied to
Algorithm::SkipList objects:
tie %hash, 'Algorithm::SkipList'; $hash{'foo'} = 'bar'; $list = tied %hash; print $list->find('foo'); # returns bar
See the perltie manpage for more information.
The default node may not handle specialized data types. To define your own custom class, you need to derive a child class from
Algorithm::SkipList::Node.
Below is an example of a node which redefines the default type to use numeric instead of string comparisons:
package NumericNode; our @ISA = qw( Algorithm::SkipList::Node ); sub key_cmp { my $self = shift; my $left = $self->key; # node key my $right = shift; # value to compare the node key with unless ($self->validate_key($right)) { die "Invalid key: \'$right\'"; } return ($left <=> $right); } sub validate_key { my $self = shift; my $key = shift; return ($key =~ s/\-?\d+(\.\d+)?$/); # test if key is numeric }
To use this, we say simply
$number_list = new Algorithm::SkipList( node_class => 'NumericNode' );
This skip list should work normally, except that the keys must be numbers.
For another example of customized nodes, see Tie::RangeHash version 1.00_b1 or later.
A side effect of the search function is that it returns a finger to where the key is or should be in the list.
We can use this finger for future searches if the key that we are searching for occurs after the key that produced the finger. For example,
($value, $finger) = $list->find('Turing');
If we are searching for a key that occurs after 'Turing' in the above example, then we can use this finger:
$value = $list->find('VonNeuman', $finger);
If we use this finger to search for a key that occurs before 'Turing' however, it may fail:
$value = $list->find('Goedel', $finger); # this may not work
Therefore, use search fingers with caution.
Search fingers are specific to particular instances of a skip list. The following should not work:
($value1, $finger) = $list1->find('bar'); $value2 = $list2->find('foo', $finger);
One useful feature of fingers is with enumerating all keys using the "first_key" and "next_key" methods:
($key, $finger) = $list->first_key; while (defined $key) { ... ($key, $finger) = $list->next_key($key, $finger); }
See also the "keys" method for generating a list of keys.
This module intentionally has a subset of the interface in the Tree::Base and other tree-type data structure modules, since skip lists can be used in place of trees.
Because pointers only point forward, there is no
prev method to point to the previous key.
Some of these methods (least, greatest) are autoloading because they are not commonly used.
One thing that differentiates this module from other modules is the flexibility in defining a custom node class.
See the included Benchmark.txt file for performance comparisons.
If you are upgrading a prior version of List::SkipList, then you may want to uninstall the module before installing Algorithm::SkipList, so as to remove unused autoloading files.
Certain methods such as "find" and "delete" will return the the value associated with a key, or
undef if the key does not exist. However, if the value is
undef, then these functions will appear to claim that the key cannot be found.
In such circumstances, use the "exists" method to test for the existence of a key.
Duplicate keys are an experimental feature in this module, since most methods have been designed for unique keys only.
Access to duplicate keys is akin to a stack. When a duplicate key is added, it is always inserted before matching keys. In searches, to find duplicate keys one must use "find_with_finger" or the "find_duplicates" method.
The "copy" method will reverse the order of duplicates.
The behavior of the "merge" and "append" methods is not defined for duplicates.
Skip lists are non-deterministic. Because of this, bugs in programs that use this module may be subtle and difficult to reproduce without many repeated attempts. This is especially true if there are bugs in a custom node.
Additional issues may be listed on the CPAN Request Tracker at or.
Robert Rothenberg <rrwo at cpan.org>
Carl Shapiro <cshapiro at panix.com> for introduction to skip lists.
Feedback is always welcome. Please use the CPAN Request Tracker at to submit bug reports.
Copyright (c) 2003-2005 Robert Rothenberg. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See the article by William Pugh, "A Skip List Cookbook" (1989), or similar ones by the author at which discuss skip lists.
Another article worth reading is by Bruce Schneier, "Skip Lists: They're easy to implement and they work", Doctor Dobbs Journal, January 1994.
Tie::Hash::Sorted maintains a hash where keys are sorted. In many cases this is faster, uses less memory (because of the way Perl5 manages memory), and may be more appropriate for some uses.
If you need a keyed list that preserves the order of insertion rather than sorting keys, see List::Indexed or Tie::IxHash. | http://search.cpan.org/~rrwo/Algorithm-SkipList/lib/Algorithm/SkipList.pm | CC-MAIN-2017-43 | refinedweb | 2,760 | 65.73 |
30 December 2010 16:35 [Source: ICIS news]
LONDON (ICIS)--Crude oil gained about 50 cents/bbl on Thursday, recouping some of the earlier losses when this week’s ?xml:namespace>
February NYMEX light sweet crude futures rose from a low of $89.96/bbl before the figures were published to around $90.45/bbl, a loss of $0.67 from Wednesday’s close.
However, it then lost a little ground and at 16:10 GMT, February NYMEX crude was trading around $90.10/bbl, down $1.02/bbl from Wednesday’s close of $91.12/bbl.
On ICE Futures, February Brent also gained ground, rising from around $93.25/bbl before the figures were published to around $93.65/bbl. At 16:10 GMT, February Brent was trading around $93.30/bbl, down $0.84/bbl from Wednesday’s close of $94.14/bbl.
Analysts’ predictions for this week’s US Stock figures were that they would show draws on crude stocks of about 2.6m bbl and on distillate of around 600,000 bbl, but a build on gasoline of around 1.4m bbl.
Earlier, the weekly Natural Gas stock figures from the EIA showed a draw of 136 billon cubic feet (BCF), smaller than the forecast draw of 147 BCF.
The American Petroleum Institute (API) figures were published late on Wednesday.
( | http://www.icis.com/Articles/2010/12/30/9422581/crude-makes-brief-recovery-on-us-stock-figures.html | CC-MAIN-2015-06 | refinedweb | 224 | 77.13 |
Started playing with nxml-mode, which makes editing XML much nicer in emacs (psgml-1.3 does an okay job, but the indenter and tag closer sometimes get confused by empty elements). There is a nice article about nxml-mode on xmlhack which gives an introduction to the mode.
The first thing that struck me about nxml in comparison to psgml was the lack of syntax highlighting. It turned out that the reason for this was that colours were only specified for the light background case, and I was using a dark background. After setting the colours appropriately (customise faces matching the regexp ^nxml-), I could see that the highlighting was a lot better than what psgml did.
One of the big differences between nxml and psgml is that it uses RELAX-NG schemas rather than DTDs. It comes with schemas for most of the common formats I want to edit (xhtml, docbook, etc), but I also wanted to edit documents in a few custom formats (the module description files I use for jhbuild being a big one).
Writing RELAX-NG schemas in the compact syntax is very easy to do (the tutorial helps a lot). I especially like the interleave feature, since it makes certain constraints much easier to express (in a lot of cases, your code doesn’t care what order the child elements occur in, as long as particular ones appear). While it is possible to express the same constraint without the interleave operator, you end up with a combinatorial explosion (I guess that’s why XML Schema people don’t like RELAX-NG people making use of it). For example, A & B & C would need to be expressed as:
(A, B, C) | (A, C, B) | (B, A, C) | (B, C, A) | (C, A, B) | (C, B, A)
(for n interleaved items, you’d end up with n! groups in the resulting pattern).
After writing a schema, it was a simple matter of dropping a schemas.xml file in the same directory as my XML documents to associate the schema with the documents. This is required because RELAX-NG doesn’t specify a way to associate a schema with a document, so nxml has its own method. Matching rules can be based on file extensions, document element names, XML namespaces or public IDs, but I used the document element name for simplicity. You can specify other locations for schema locator rules, but putting it in the same directory is the easiest with multiple developers.
Once that is done, you get background revalidation of the document, and highlighting of invalid portions of the document (something that psgml doesn’t seem to be able to do). It also says whether the document is valid or not in the modeline, which is helpful when editing documents.
Now all we need is for libxml2 to be able to parse RELAX-NG compact syntax schemas … | http://blogs.gnome.org/jamesh/2004/05/04/nxml-mode/ | crawl-001 | refinedweb | 483 | 65.86 |
.
Working with Modules
In the previous part, media files were imported into the project.
As a project gets more complex, it is highly recommended to place classes within their own files to better help with organization and code maintenance. These can then be imported into the “index.js” file as well.
For each of the classes in previous example, they could be broken up into their own files.
ShoppingList.js
import React from 'react'; import Item from './Item.js'; class ShoppingList extends React.Component { createItem(x) { return ( <Item number={x} /> ) } render() { return ( <ul> {this.createItem(1)} {this.createItem(2)} {this.createItem(3)} </ul> ); } } export default ShoppingList;
Item.js
import React from 'react'; import checkmark from './images/checkmark.png' class Item extends React.Component { render() { return ( <li><img src={checkmark} />I am number {this.props.number}</li> ); } } export default Item;
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import ShoppingList from './ShoppingList.js' ReactDOM.render( <ShoppingList />, document.getElementById('root') );
Notice how ShoppingList now import Item, which now imports the checkmark image. All that “index.js” imports is ShoppingList, which now handles its own importing of the files it uses.
Such a modular approach helps to break up the code into the same components as the interface itself. Now, code can be updated or changed without needing to update all the classes.
Importing and Export Defaulting
Any use of the import expression understands only what is exported from another file. Depending on what is exported (or not), an import expression can pass variables, functions, or objects directly into their code or change their name.
When exporting multiple variables, functions, or objects, an import expression can choose to use all of them or a subset. However, the use of the combination export default constraints this.
In the above examples, the code uses export default and the name of its class to quick convey that the default export is the class itself. Nothing else is exported.
In the “index.js”, then, its import expressions can take in the object as they are, passing them from their files into the one importing them.
From Images to Emoji
The image of the checkmark is useful, but some emoji would be better. Not only would they scale with the device on which they are shown, but they would also match the font sizes of the text around them.
To safely include emoji in React, symbols needs to be enclosed in an element.
<span role="img" aria-✅</span>
Along with the role attribute and an aria-label to help screen readers and other assistive technologies, a checkmark can be included.
For right now, it can be enough that the HTML around the emoji is saved as a const and then imported as part of Item. (In order to use JSX, React must be within the scope of the file. In other words, to use JSX, React has to be imported.)
Checkmark.js
import React from 'react'; const Checkmark = <span role="img" aria-✅</span>; export default Checkmark;
Item.js
import React from 'react'; import Checkmark from './Checkmark.js' class Item extends React.Component { render() { return ( <li>{Checkmark}I am number {this.props.number}</li> ); } } export default Item; | https://videlais.com/2019/05/26/using-react-part-2-working-with-modules/ | CC-MAIN-2020-45 | refinedweb | 534 | 59.3 |
February 13, 2008
Overview
There's plenty of sites that keep track of the most popular of something on a daily basis, such as delicious, digg, reddit, flickr, etc. They keep track of the days most popular items, where popularity is recorded implicitly, recording a link in delicious, or explicitly, voting up and down on reddit. One of the interesting aspects of these sites is "decay", the drifting down in the rankings of older items so newer items can rise to the top. Overheard is an example application for Google App Engine that demonstrates both voting and decay, using amusing quotes as the subject. It also demonstrates optimizations such as using memcache and the AJAX Libraries API. Obviously not a world rocking application, but the principles outlined can be applied to many different kinds of applications.
Our basic model will be to have Quotes, which contain a string for the quotation, and Votes, which contain the user name and vote for a particular user.
Here are the models for the program:
Models
class Quote(db.Model): """Storage for a single quote and its metadata Properties quote: The quote as a string uri: An optional URI that is the source of the quotation rank: A calculated ranking based on the number of votes and when the quote was added. created: When the quote was created, recorded in the number of days since the beginning of our local epoch. creation_order: Totally unique index on all quotes in order of their creation. creator: The user that added this quote. """ quote = db.StringProperty(required=True, multiline=True) uri = db.StringProperty() rank = db.StringProperty() created = db.IntegerProperty(default=0) creation_order = db.StringProperty(default=" ") votesum = db.IntegerProperty(default=0) creator = db.UserProperty() class Vote(db.Model): """Storage for a single vote by a single user on a single quote. Index key_name: The email address of the user that voted. parent: The quote this is a vote for. Properties vote: The value of 1 for like, -1 for dislike. """ vote = db.IntegerProperty(default=0) class Voter(db.Model): """Storage for metadata about each user Properties count: An integer that gets incremented with users addition of a quote. Used to build a unique index for quote creation. hasVoted: Has this user ever voted on a quote. hasAddedQuote: Has this user ever added a quote. """ count = db.IntegerProperty(default=0) hasVoted = db.BooleanProperty(default=False) hasAddedQuote = db.BooleanProperty(default=False)
Votes
One of the most common optimizations done in App Engine to create a
performant application is to precompute values at write time as opposed to
read time. We will do that in this case and will calculate the vote total and
rank for a Quote each time a vote is cast. That slows down writes just a
little, but vastly speeds up reading, and makes our searches possible. That
is, if we want to present a page with the Quotes ordered by their ranking, we
need a
rank property that is up to date to sort on. If we want to keep the
vote count consistent we are going to have to add in a vote and modify the
sum of votes for that quote in the same transaction. For that to work both
the quote and the vote need to be in the same entity group, and we accomplish
that by making each vote a child of its associated quote. There's more
details in the documentation on entity
groups and transactions.
With each vote a child of its associated quote we can put voting into a
transaction where the
Quote.votesum and
Quote.rank
are updated at the same time that the users vote is recorded.
models.set_vote()
def set_vote(quote_id, user, newvote): """ Record 'user' casting a 'vote' for a quote with an id of 'quote_id'. The 'newvote' is usually an integer in [-1, 0, 1]. """ if user is None: return email = user.email() def txn(): quote = Quote.get_by_id(quote_id) vote = Vote.get_by_key_name(key_names = user.email(), parent = quote) if vote is None: vote = Vote(key_name = user.email(), parent = quote) if vote.vote == newvote: return quote.votesum = quote.votesum - vote.vote + newvote vote.vote = newvote # See the docstring of main.py for an explanation of # the following formula. quote.rank = "%020d|%s" % ( long(quote.created * DAY_SCALE + quote.votesum), quote.creation_order ) db.put([vote, quote]) memcache.set("vote|" + user.email() + "|" + str(quote_id), vote.vote) db.run_in_transaction(txn) _set_progress_hasVoted(user)
Note that we need to specify the parent of the vote when querying for it, and we also need to specify the parent when creating a Vote.
Decay
The value of the
Quote.rank property is what we are focused on now. The
rank
is what we will sort by to show the most popular items and it will need
to be calculated in a way that allows newer items to eventually float
to the top of the list even though older items may have received more
votes, otherwise our site will become very boring very fast. We don't
have background tasks that can go back and adjust the current rankings
of quotes over time, so we need a way to rank quotes that puts fresher
quotes higher in the ranking in a scalable way that will work for a
long period of time.
The insight here is that we can add
weight to a vote based on
when the Quote was added to the system. The rank for each quote is
calculated as:
rank = created * DAY_SCALE + votesum
Where the variables have the following meanings:
created
- Number of days after 1/1/2008 that the Quote was created.
votesum
- Sum of all +1 and -1 votes for a quote.
DAY_SCALE
- This is a constant that determines how quickly votes should decay (defaults to 4). Another way to think about this is how many votes one more day is worth.
For 'created' we just pick a date in the past as our day zero and
start counting forward from there.
DAY_SCALE with a value of four means
that a vote for a Quote one day fresher will be worth four more votes.
That is, if Quote 1 and 2 have the same number of votes but Quote 2 was
added a day later then its rank will be 4 larger.
Does this work? Presume the following scenario:
Day 1
Quote 0 and 1 are added on Day 1 and get 5 and 3 votes respectively. Order by rank is [Quote 0, Quote 1]. Quote Votes Rank -------------------------------- 0 (5) 1 * 4 + 5 = 9 1 (3) 1 * 4 + 3 = 7
Day 2
Quote 0 and 1 get 3 and 0 more votes respectively. Quote 2 is added and gets 3 votes. Order by rank is now [Quote 0, Quote 2, Quote 1] Quote Votes Rank -------------------------------------- 0 (5) + (3) 1 * 4 + 8 = 12 1 (3) + (0) 1 * 4 + 3 = 7 2 (3) 2 * 4 + 3 = 11
Day 3
Quote 2 gets two more vote. Quote 3 is added and gets 5 votes. Order by rank is [Quote 3, Quote 2, Quote 0, Quote 1] Quote Votes Rank ------------------------------------------- 0 (5) + (3) 1 * 4 + 8 = 12 1 (3) + (0) 1 * 4 + 3 = 7 2 (3) + (2) 2 * 5 + 4 = 14 3 (5) 3 * 4 + 5 = 17
Note that ties are possible, which means that rank for quotes will have to be disambiguated since the application allows paging of ranked quotes. That means for each rank we need to append information that will make it unique. In this case we will keep one counter per user and increment it each time that user adds a new quote to the system. The rank plus the user id and counter value is guaranteed to be unique for each quote.
Here is the code for generating a unique value based on the user:
models._unique_user()
def _unique_user(user): """ Creates a unique string by using an increasing counter sharded per user. The resulting string is hashed to keep the users email address private. """ def txn(): voter = _get_or_create_voter(user) voter.count += 1 voter.hasAddedQuote = True voter.put() return voter.count count = db.run_in_transaction(txn) return hashlib.md5(user.email() + "|" + str(count)).hexdigest()
For more information on paging see the article "How-To Do Paging on App Engine."
Contention
One of the most important design principles to keep in mind in building a performant App Engine application is to avoid contention, trying to update a single entity or entity group too quickly. Any single entity or entity group can only be updated about five times a second. Since a single quote and its associated votes form a single entity group we only need to consider how often any one quote is updated when looking for contention. In this application we'll assume that on the high side there will be a couple thousand votes per quote over the course of a day, which averages out to much less than five votes per second, so we are in good shape.
Using memcache
There is a memcache API that is very useful for speeding up an application and avoiding hitting the datastore. One of the most common queries in the Overhead application is pulling out each user's votes for a list of quotes so they are reflected in the user interface. We can cache the results in memcache and once there we avoid a datastore hit as long as the data is available in the cache. Here is the code that handles looking up votes and caching the results:
def voted(quote, user): """Returns the value of a users vote on the specified quote, a value in [-1, 0, 1].""" val = 0 if user: memcachekey = "vote|" + user.email() + "|" + str(quote.key().id()) val = memcache.get(memcachekey) if val is not None: return val vote = Vote.get_by_key_name(key_names = user.email(), parent = quote) if vote is not None: val = vote.vote memcache.set(memcachekey, val) return val
AJAX Libraries API
There are other optimizations that you can also do to save your application bandwidth. One of the easiest is to have Google host your Javascript library for you. The interactive part of the web pages for Overheard is done using jQuery and instead of adding the jQuery source to the application I employed Google's AJAX Libraries API. The AJAX Libraries API is a content distribution network and loading architecture for the most popular, open source JavaScript libraries. While this application uses jQuery you can also benefit if you use Prototype, script.aculo.us, Dojo, or any of the other JavaScript libraries in the growing list that the AJAX Libraries API supports.
HTML5
The last optimization you can make is to create a clean user interface for your application in HTML 5. Doing so will allow your application to run not only on desktops but also on the latest mobile devices. That saves you effort from having to build a custom client for multiple mobile devices, and that should be a huge time savings.
Summary
The Apache 2 licensed source for this application is available in the appengine-overheard-python project on GitHub. A live version of this sample application is running at. | https://developers.google.com/appengine/articles/overheard | CC-MAIN-2014-15 | refinedweb | 1,849 | 72.66 |
This chapter describes how to call programs. It provides information on writing subprograms and passing parameters between them.
The COBOL system enables you to design applications as separate programs at source level. Each program can then be called dynamically from the main application program without first having to be linked dynamically with the other programs. Figure 2-1 shows an example of an application divided up in this way.
Figure 2-1: Application Divided Using CALL
The main program A, which is permanently resident in memory, calls B, C, or H, which are programs within the same application. These programs call other specific functions as follows:
Because the functions B, C and H are standalone they do not need to be permanently resident in memory together. You can call them as they are needed, using the same physical memory when they are called. The same applies to the lower functions at their level in the tree structure.
In the figure, you would have to plan the use of CALL and CANCEL operations so that a frequently called subprogram such as K would be kept in memory to avoid load time. On the other hand, because it is called by C or H, it cannot be initially called without C or H in memory; that is, the largest of C or H should call K initially so as to allow space. It is important also to avoid overflow of programs. At the level of X, Y and Z, the order in which they are loaded does not matter because they do not make calls at a lower level.
It is advantageous to leave called programs in memory if they open files, to avoid having to reopen them on every call. The EXIT statement leaves files open in memory. The CANCEL statement closes the files and releases the memory that the canceled program occupies, provided all other programs in the executable file have been cancelled or never called.
If you use a tree structure of called, independent programs as shown earlier, each program can call the next dynamically by using the technique shown in the following sample coding:
working-storage section. 01 next-prog pic x(20) value spaces. 01 current-prog pic x(20) value "rstprg". procedure division. loop. call current-prog using next-prog cancel current-prog if next-prog = spaces stop run end-if move next-prog to current-prog move spaces to next-prog go to loop.
The programs to be run can then specify their successors as follows:
. . . . . . linkage-section. 01 next-prog pic x(20). . . .
. . . procedure division using next-prog. . . . . . . move "follow" to next-prog. exit program.
In this way, each independent segment or subprogram cancels itself and changes the name in the CALL statement to call the next one with the USING phrase.
The total number of programs which can be loaded in memory as the result of a call is not constant. The number depends on the amount of available memory in your computer and the size of the program being called.
Dynamically called programs have an advantage over programs that have been linked into a single executable file, in that dynamically called programs have their memory freed when they are cancelled while the latter do not.
If a program is called and the program is dynamically loaded, the filename is used to identify it. If the program is statically linked then the Program-Id paragraph can be used. See the section Calling COBOL Subprograms for more details.
You can avoid many "program not found" errors by always using the filename without extensions as the program-name in the Program-Id paragraph. This enables flexibility in constructing your executable programs with statically or dynamically called programs.
For details on the Program-ID paragraph, see your Language Reference.
You can write subprograms or your main programs in the COBOL language or in some other language, such as C. You can mix these subprograms freely in an application. However, before you call a non-COBOL subprogram from a COBOL program, you must link it to either the dynamic loader run-time support module or to your statically or dynamically linked COBOL application.
A COBOL subprogram can be linked, or it can also be dynamically loaded at run time.
A linked program is an executable object module, while a dynamically loadable module is a COBOL intermediate code file (.int file), COBOL generated code file (.gnt file), or a COBOL callable shared object.
A COBOL program can call a COBOL subprogram by using one of the following formats of the CALL statement:
CALL "literal" USING ...
or:
CALL data-name USING ...
For any COBOL programs, the literal string or the contents of the alphanumeric data item must represent the Program-ID, the entry point name, or the basename of the source file (that is, the filename without any extension). The path and filename for a module can also be specified when referencing a COBOL program, but we do not recommend you do this, as unexpected results can occur where the referenced module exists in more than one file, or type of format, or if the application is ported to other environments. For statically linked modules, the native code generator converts calls with literal strings to subroutine calls which refer to external symbols. Server Express automatically creates a routine to define the symbol and to load the associated file if it is entered at run time.
Note: Programs that are called at link time must have names that the system assembler and linker can accept; that is, they must not contain characters other than 0-9, A-Z, a-z, underscore (_), or hyphen (-). You must correct any entry point names that use characters other than these so that they are acceptable to the system assembler and linker.
Use a CALL literal statement to call a linked program directly. If the program is not found a run-time system error is displayed unless the dynamic loader is present, in which case it will attempt to find a dynamically loadable version of the program.
Use either a CALL literal statement, or a CALL data-name statement, to call a dynamically loadable program, and make the dynamic loader run-time support module search for the called program.
You might need to load the dynamic loader using the Cob utility.See the chapter COBOL System Interface (Cob) in your User's Guide for more details of this directive.
The dynamic loader run-time support module follows this search order to find the named file:
If the dynamic loader run-time support module has to search for a file on disk and no path-name has been specified on the call, the search order followed is determined by the program_search_order run-time tunable and by the setting of the COBPATH environment variable. For information on the program_search_order run-time tunable see the chapter Run-time Configuration in your User's Guide. For information on the COBPATH environment variable see the appendix Environment Variables in your User's Guide.
If you specify a directory path on the call, the dynamic loader support module searches for the file only in the named directory.
If you specify a file extension, the dynamic loader run-time support module searches only for a file with a matching extension. However, we recommend that you do not include an explicit extension in the filenames you specify to the CALL statement. If you specify a file without an extension, the dynamic loader run-time support module adds the extension .so to the basename of the file, and searches the disk for the corresponding callable shared object file. If it cannot find the callable shared object the dynamic loader run-time support module adds the extension .int to the basename of the file, and searches the disk for the corresponding intermediate code file. If it cannot find the .int file, the dynamic loader run-time support module adds the extension .gnt to the basename of the file, and searches for the corresponding .gnt file.
The dynamic loader run-time support module always assumes that the first matching program name which it finds is the program you require to call.
If no matching program is found a run-time error occurs.
Note that if the first character of a filename which is to be dynamically loaded at run time is the dollar sign ($), the first element of the filename is checked for filename mapping. The first element of the filename consists of all the characters before the first slash character (/).
See your File Handling for details. For example, if the statement:
CALL "$MYLIB/A"
is found in the source program, the file A is loaded from the path as defined by the MYLIB environment variable at run time.
You can access non-COBOL subprograms using the standard COBOL CALL ... USING statement. The address of each USING BY REFERENCE or USING BY CONTENT parameter is passed to the argument in the non-COBOL subprogram which has the same ordinal position in the formal parameter declarations. You must thus ensure all formal parameter declarations are pointers.
Note that if you use the CALL...USING BY VALUE form of the CALL...USING statement, the USING parameter is not passed BY VALUE if it is larger than four bytes long. If it is larger than this, it can be passed BY REFERENCE, but no warning is output to inform you of this. If you specify a numeric literal with a CALL...USING BY VALUE statement, it is passed BY VALUE as though it were a four-byte COMP-5 item; that is, it appears in machine-order as a data item and not as a pointer to that data item. If you specify a data item with a CALL...USING BY VALUE statement it must be defined as COMP-5.
You might need to specify a particular calling convention when interfacing to non-COBOL programs - see the chapter The COBOL Interfacing Environment for more information.
The following example shows how C functions can be accessed from a COBOL program
$set rtncode-size"4" working-storage section. 01 str. 03 str-text pic x(10). 03 filler pic x value x"00". * Null terminate string for C function 01 counter pic 9(8) comp-5 value zero. procedure division. call-c section. call "cfunc" using str, counter if return-code not = zero * RETURN-CODE set from return () in C display "ERROR" else display "OK" end-if stop run. ------------------------------------------------
cfunc (st, c) char *st; int *c; { ... return(0); }
When you use the CALL statement from within a COBOL program to access a non-COBOL module as described above, you must ensure that the COBOL run environment is not accidentally damaged. This means you must ensure that:
The CANCEL statement has no effect when it references a non-COBOL program .
The Server Express system traps unexpected signals and returns run-time system errors:
114 Attempt to access item beyond bounds of memory
115 Unexpected signal
Where C and COBOL modules are linked, these error messages are usually due to an error in the C code which causes a hardware interrupt for such conditions as segmentation violation. If you do receive these run-time system errors, carefully check the C source routines using the system debugger, paying particular attention to the format and byte ordering of parameters passed between the COBOL and C modules.
COBOL programs can contain ENTRY statements. An ENTRY statement identifies a place where execution can begin as an alternative to the Procedure Division if a calling program so specifies.
COBOL fully supports entry points, but the dynamic call loader presents a potential problem. Because the run-time system typically defaults to looking for called programs dynamically, there is no way for the run-time system to locate a particular entry point embedded in a program on disk. When you execute a call statement like:
call "abc" using ...
the run-time system first looks for a
program or entry point called
abc in all of the programs and libraries that
have already been loaded. If it does not find the program, the run-time system
then looks for a file called
abc.ext where
.ext is an executable file
formats. For details of executable file types see the section
Executable File
Types in the chapter Packaging Applications in your
User's
Guide.
If
abc represents the name of an entry point contained in another
program, the run-time system cannot locate the file on disk, and a
"program not found" message is issued. The run-time system does not
scan through every individual executable file on disk to locate an entry
point.
Therefore, you must load the program containing the called entry point into the run-time system.
One technique that you can use to do this is to create a .lbr file that contains any programs containing entry points that need to be preloaded. You can create the .lbr file (library file), using the Library facility. Once the .lbr file is created, you can issue a call to the .lbr file.
Note: When you call an .lbr file, the run-time system does not load every program in the .lbr into the run-time system. Instead, the run-time system registers the existence of all programs and entry points contained in the called .lbr file, for future reference. Later when one of these programs contained in the .lbr is called, the run-time system notes that it is contained in the .lbr and loads it at that point.
Once a program that contains the entry points is loaded into the run-time system, all entry points contained in the program are identified to the run-time system and are available to be called by any program loaded later. This means that if you need to call entry points in a particular program from another program, you must ensure that the program is loaded first, so the run-time system can register these entry points.
This section describes how you call a program and pass the command line to the main program as a parameter. The main program in a run unit is the first program within it; that is, the program which is called directly by the COBOL system.
As the maximum size, form and contents of the command line vary between operating systems, these issues need to be considered if you want to port your application between environments. For example, to ensure portability, a maximum command line size of 128 characters might be appropriate rather than the system limit. Similarly, only alphabetic and numeric characters with the equals sign (=) and space characters should be used for entering the command line for a program if you want to guarantee portability.
The command line can be accessed from:
The standard COBOL calling convention is:
call progname using ...
or:
call "progname" using ...
where
progname (without quotation marks) is a data item that contains a
valid program-name, and
"progname" (with quotation marks) is the actual name of a
valid program.
A program-name is a character string representing the program or subprogram to be called. In the run-time system, this name is treated as an implicit program-name; that is, there is no filename extension in the program-name.
This means the actual executable file being called might be in any of the following supported executable formats:
When progname.lbr is found, the run-time system opens the .lbr file and locates and loads an executable file with the same program-name, for example progname.gnt, progname.int, or progname (no extension) from the .lbr file.
An explicit program-name can be specified in the call statement as well:
call "progname.gnt" using ....
This forces the run-time system to look for the exact filename specified, in this case progname.gnt. If the exact program-name is not located a "program not found" error message is issued.
Once started, the run-time system loads and manages all called subprograms. When the run-time system locates and loads a a called program, it assigns a unique run-time system identifier to the program. (This identifier is used internally in the run-time system.) The run-time system allocates memory (both real and virtual) for the program, and can swap portions of it out to disk as needed.
The run-time system records the pathname of a program as well. Once loaded into the run-time system, the run-time system uses the same copy of the program unless it is physically canceled. See the description of the l run-time switch in the chapter Descriptions of Run-time Switches in your User's Guide for details of how to specify that programs should be physically canceled.
Whenever a COBOL program running under the run-time system issues a call to a subprogram, the run-time system goes through the following steps:
As described above, the run-time system can search for multiple executable files, and can search for these program files in more than one directory.
Note: The search sequences described below apply to executable files (programs). It does not apply to other file types, for example data files and COBOL source files.
You do not need to be concerned about search conventions if you only have one executable version of your program on disk. This discussion only applies if you have multiple executable files available.
Whenever a COBOL program issues an explicit call to a subprogram, for example:
call "myprog.gnt" using ...
the run-time system searches for a file with the specified extension.
In this case, the run-time system searches for
myprog.gnt. It does not
search for other valid executable formats with the same program-name but
different extensions.
When a program issues an implicit call, that is, a call to a program-name without specifying a file extension, the run-time system searches for the called program in the order listed below.
When a program issues a call like:
call "proga" using ...
the run-time system searches through the following sequence looking for
proga:
If none of the above are found, the run-time system issues the message, "program not found".
You can change the order in which the run-time system searches for files by setting the I1 run-time switch. This causes the run-time system to search for files in the order :
This is useful for testing when you are typically compiling only to intermediate (.int) code.
When the run-time system finds and loads a program, it records the location (drive and path) where the program was first found. If the program issues a later call to another program, the run-time system does not look in the current directory for the new program being called. Instead, it defaults back to the same directory where the calling program was first found.
If the run-time system cannot find the called program in the same directory that the calling program is in, the run-time system begins its standard search sequence to try to locate the called program. This technique, known as inheritance, is the default behavior for the run-time system.
It is also important to understand the way the run-time system searches for various executable files through the multiple directories that can be set in the COBDIR environment variable. For example, if your program issues a call to a program like:
call "myprog" using ...
the run-time system initially searches its active directory to see if myprog has already been loaded (and not subsequently canceled).
If it has been loaded, the run-time system passes control to myprog. It does not refresh the program's Data Division unless:
A later call then forces the run-time system to locate it again and load a fresh copy.
See your Language Reference for details on PROGRAM-ID .
Note: You should be aware of the impact of inheritance on the run-time system search sequence. If you have the same program-name in more than one directory, you can access the wrong version.
Call prototypes are a relatively new feature of the COBOL language. Prototypes enable each CALL statement to be checked for correctness when the program is compiled. Prototypes can help you write multi-program applications that function as you expect. For information on the CALL statement syntax see your Language Reference.
When a COBOL program calls another program there is no validation of the type or the number of parameters provided in the CALL statement. If there is a mismatch between the parameter types provided on the CALL statement's USING clause and those of the called program's Linkage Section as referenced in the USING clause of the Procedure Division, then it is likely that either an application error or a run-time system error will occur.
For example, suppose you had the following program Mymain:
program-id. MYMAIN. working-storage section. 01 . 05 myhandle pic x(4). 05 othervalue pic x(4) value "6x3b". procedure division. call 'MYROUTINE' using myhandle display "Othervalue is " othervalue.
and the subprogram Myroutine:
program-id. MYROUTINE. linkage section. 01 myhandle usage pointer. procedure division using myhandle. set myhandle to null exit program.
The program and its subprogram would work as you expected if compiled
and run on a 32-bit system (where pointers are 4 bytes long), but would corrupt
the value
othervalue on a 64-bit system (where pointers are 8 bytes long):
You could be informed about this kind of problem when you compiled the programs, if the compiler had access to the data-types expected by the called program Myroutine when it compiled the program Mymain. Call prototypes provide this information about called programs, and enable the compiler to check for semantic consistency between the parameters in both the calling program, and in the called subprogram.
A call prototype can be regarded as a cut-down version or model of the code of the called program. The prototype contains:
No code is required in the Procedure Division.
A call prototype is identified by the use of the IS EXTERNAL clause in the PROGRAM-ID paragraph.
If you were to code the calling program above (Mymain) as follows:
program-id. MYROUTINE is EXTERNAL. linkage section. 01 myhandle usage pointer. procedure division using myhandle. end program MYROUTINE. ****************************************************** * Prototypes are usually defined in a copyfile, but * * here it is placed in-line * ****************************************************** program-id. MYMAIN. working-storage section. 01 . 05 myhandle pic x(4). 05 othervalue pic x(4) value "6x3b". procedure division. call 'MYROUTINE' using myhandle display "Othervalue is " othervalue. end program MYMAIN.
when you compiled the program you would receive this warning message:
14 call 'MYROUTINE' using myhandle *1059-E**************************************** ** Parameter is not consistent with that defined in prototype
Coding your programs in this way enables you to recognise programming errors without having to do run-time tests.
Ideally, all programs called from COBOL should be prototyped; however, this is not practical, as there is already a substantial body of COBOL code, and COBOL programmers are not used to type-checking programs. Even if the effort was expended to prototype all calls a program makes, it is likely that strict type-checking would cause a large number of Compiler errors on valid COBOL calls. For this reason, Server Express enables you to prototype called programs using a relaxed form of type-checking, and/or the keyword ANY with a USING statement.
For an extended example of using call prototypes, see the section Call Prototypes in the chapter Examples in your Language Reference - Additional Topics.
You can use the keyword ANY as a USING parameter. This enables any parameter to fill the corresponding parameter position on any CALL statement to the prototyped routine. For example, you can avoid producing the error shown in the example above by using this prototype:
program-id. MYROUTINE is EXTERNAL. procedure division using any. end program MYROUTINE.
For information on the ANY keyword, see your Language Reference.
By default, Server Express performs relaxed type-checking on BY VALUE binary data items. That is, even if binary data items have been defined with different sizes in the calling and called programs, the programs will compile with errors. If you specified a CALL statement that had a data-item defined as PIC X(2) COMP in its USING list, that date-item can correspond to a PIC X(n) COMP data-item in a call prototype, where n on a 32-bit system can be from 1 through 4, and on a 64-bit system can be 1 through 8.
For example, the following program will compile successfully:
program-id. MYROUTINE is EXTERNAL. linkage section. 01 callee-value pic x(2) comp-5. procedure division using by value callee-value. end program MYROUTINE. program-id. MYMAIN. working-storage section. 01 . 05 caller-value pic x(4) value 123. procedure division. call 'MYROUTINE' using by value caller-value end program MYMAIN.
In this example, if the actual value of
caller-value was too big to fit a
data-item defined as PIC X(2) COMP-5, binary truncation would occur. Such
truncations might cause problems with the logic of your program, so you might
want to specify that type-checking is more strict so that you can identify such
potential problems. You can do this by setting the Compiler directive
PROTOTYPE"STRICT". If you were to set PROTOTYPE"STRICT"
when you compiled the above program, the Compiler would produce a message
warning you of the type mismatch. For information on the PROTOTYPE directive,
see the chapter
Directives for Compiler
in your User's
Guide.
The COBOL TYPEDEF facility enables you to use common data description entries for USING parameters in calling and called programs and their prototypes. For detailed information on TYPEDEF, see your Language Reference.
As you saw in the section Call Prototypes, when program prototypes are used an error occurs if there is a mismatch between data-types. To avoid this error, and to code the CALL statement and USING parameters correctly, the data description entry of the USING parameter in the call prototype must be duplicated in the program calling that prototype. If you were to do this manually, such duplication could lead to code maintenance problems, and perhaps lead to inconsistencies when you were creating programs.
To enable easy duplication of data description entries, the call prototype can use a TYPEDEF name to describe the parameter expected. For example:
program-id. MYROUTINE is EXTERNAL. linkage section. 01 callee-value-t pic x(2) comp-5 is typedef. 01 callee-value usage callee-value-t. procedure division using callee-value. end program MYROUTINE. program-id. MYMAIN. working-storage section. 01 . 05 caller-value usage callee-value-t. procedure division. call 'MYROUTINE' using caller-value end program MYMAIN.
TYPEDEF can be used not only for simple data description; it can represent an entire record structure. For example:
program-id. MYROUTINE is EXTERNAL. linkage section. 01 callee-value-t is typedef. 05 callee-value-item-1 pic x(2) comp-5. 05 callee-value-item-2 pic x(4). 01 callee-value usage callee-value-t. procedure division using callee-value. end program MYROUTINE. program-id. MYMAIN. working-storage section. 01 . 05 caller-value usage callee-value-t. procedure division. move 123 to callee-value-item-1 of caller-value move 'abcdef' to callee-value-item-2 of caller-value call 'MYROUTINE' using caller-value end program MYMAIN.
All data-items defined as TYPEDEFs in a call prototype are available to any programs using that prototype.
In Server Express 2.0 the COBOL system library routines are now prototyped, enabling you to ensure that data-items defined in your programs match those expected by the library routines. This is particularly useful if you are porting 32-bit applications to 64-bit systems, and want to ensure that data-items are typed correctly.
For information on the prototypes used by the library routines, see the chapter Library Routines.
This document and the proprietary marks and names used herein are protected by international law. | http://www.emunix.emich.edu/info/cobol/books/prcall.htm | crawl-002 | refinedweb | 4,683 | 54.22 |
specular()
Contents
specular()#
Sets the specular color of the materials used for shapes drawn to the screen, which sets the color of highlights.
Examples#
def setup(): py5.size(100, 100, py5.P3D) py5.background(0) py5.no_stroke() py5.background(0) py5.fill(0, 51, 102) py5.light_specular(255, 255, 255) py5.directional_light(204, 204, 204, 0, 0, -1) py5.translate(20, 50, 0) py5.specular(255, 255, 255) py5.sphere(30) py5.translate(60, 0, 0) py5.specular(204, 102, 0) py5.sphere(30)
Description#
Sets the specular color of the materials used for shapes drawn to the screen, which sets the color of highlights. Specular refers to light which bounces off a surface in a preferred direction (rather than bouncing in all directions like a diffuse light). Use in combination with emissive(), ambient(), and shininess() to set the material properties of shapes.
Underlying Processing method: specular
Signatures#
specular( gray: float, # value between black and white, by default 0 to 255 /, ) -> None specular( rgb: int, # color to set /, ) -> None | https://py5.ixora.io/reference/sketch_specular.html | CC-MAIN-2022-40 | refinedweb | 169 | 61.12 |
hi, im just trying to make a simple program, just to see wat i can do.
i want to no y this code doesnt run as expected, after the last line the program quits, without leaving time to view wat is supposed to be on the screen
help please
Code:#include <iostream> using namespace std; // So we can see cout and endl int main() { int x = 0; // declare variables int answer; int y = 0; while ( x < 100000 ) { // While x is less than 100000 cout<< x <<endl; x++; x++; // Update x so the condition can be met eventually } cout<< "Total files placed in your computer = " ; cout << "99899 \n"; cout << "Happy holidays!.\n"; cout<< "Do you think im telling the truth?\n"; cout<< "1 = yes\n2 = no\n" ; cin>> answer; //stores variable in answer if (answer = 0) { cout<< "Well if your not going to believe me......\n maybe i should add some more... would you like that? \n"; } //program should wait here, waiting for an input or enter stroke to quit cin.get();} | http://cboard.cprogramming.com/cplusplus-programming/65383-simple-question-not-ruinning-expected.html | CC-MAIN-2014-23 | refinedweb | 171 | 81.56 |
CodePlexProject Hosting for Open Source Software
path.py
easy_install -h
In VS, if you go to Tools->Python Tools you'll see an item called Diagnostic Info. Can you share that info with us (either put it online somewhere or email an attachment to
ptvshelp@microsoft.com)? It includes some of our logs that may reveal what's going wrong.
If you type "import pa", do you see "path" appear in that list? What about "test_path"? According to the logs, you should see both of those.
from path import path
import sys
def getDirStats(myPath):
d=path(myPath)
path.path
path.Path
from path import Path as path
path = Path
If you write from path import Path as path then you'll get identical behaviour and you should get better completions.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://pytools.codeplex.com/discussions/573373 | CC-MAIN-2016-50 | refinedweb | 167 | 84.78 |
Deadbolt makes it very easy to add authorization to your Play! application. However, until now, it’s been harder to add the same constraints to web services and AJAX-invoked methods – which is to say, the mechanism worked, but when access failed the response was always HTML. Less, in this asynchronous world, than useful..
@With(Deadbolt.class) public class Foo extends Controller { @Restrict("bar") @XML public static void getSomeXml() { // render some XML } @Restrict("bar") @JSON public static void getSomeJSON() { // render some JSON } }.
2 thoughts on “Secure your web services and AJAX calls with Deadbolt”
Hi Steve,
Nice blog! Is there an email address I can contact you in private? | https://www.objectify.be/wordpress/2012/02/21/secure-your-web-services-and-ajax-calls-with-deadbolt/ | CC-MAIN-2021-21 | refinedweb | 109 | 62.48 |
Fixtures.getDeleteTableStmt() should escape table names
Reported by Jan Tammen | June 25th, 2011 @ 01:14 PM | in 1.4.x
Framework version: 1.2.1
Platform you're using: Mac OS X (though the problem is not connected to a specific platform)
Details:
I have a model class declared as follows:
@Entity @Table(name = "`user`") public class User extends ...
The escaped table name is necessary because I am using PostgreSQL and "user" is a reserved word there. I a unit test I want to use Fixtures.deleteDatabase() to flush the entire in memory test database in a @Before handler method. The problem is that the table "user" cannot be cleared, because the generated statement does not correctly escape the table name. Resulting in the following error:
org.h2.jdbc.JdbcSQLException: Tabelle "USER" nicht gefunden Table "USER" not found; SQL statement: DELETE FROM user; [42102-149] at org.h2.message.DbException.getJdbcSQLException(DbException.java:327) ...
Thanks and greets,
Jan.
Nicolas Leroux October 28th, 2011 @ 08:26 PM
- Assigned user set to Nicolas Leroux
- State changed from new to confirmed
- Milestone set to 1.3
- Milestone order changed from 644 to 0
notalifeform (at gmail) April 21st, 2014 @ 07:55. | https://play.lighthouseapp.com/projects/57987/tickets/937-fixturesgetdeletetablestmt-should-escape-table-names | CC-MAIN-2019-26 | refinedweb | 198 | 56.66 |
Bugzilla Status UpdateZach Lipton and The Bugzilla Team
Saturday, July 10th, 2004
Introduction and Updates
Welcome to the new Bugzilla status update, covering the four months since our last update and the release of Bugzilla 2.17.7. In this update, the Bugzilla Team is pleased to announce the release of Bugzilla 2.18, Release Candidate 1 (rc1), and Bugzilla 2.16.6, the latest maintenance release in the current stable series.
We are also pleased to announce the new Bugzilla Website, thanks to the efforts of Mike Morgan and the Bugzilla Team. The new site is designed to more closely match the look and feel of the mozilla.org website and is standards-compliant..
New Releases
2.18rc1
This release is a developers' release and is not recommended for production use, but all existing users of the 2.17 development branch are strongly encouraged to upgrade to 2.18rc1, both for the increased stability and new features, and for the security updates described below. 2.18rc1 is the first Bugzilla release to support operation on Microsoft Windows servers with no modifications to Bugzilla itself.
2.16.5
All users of the 2.16 stable branch are encouraged to update their production installations to 2.16.6 for security reasons. More details on the security vulnerabilities fixed in this update are available in the 2.16.5 Security Advisory. See the check-in manifest at the bottom of this status update for a list of changes.
They are also requested to test their installations with 2.18rc1 using a backup copy of their database, in order to help us make the best 2.18 final release. Since 2.16 was originally released, Bugzilla has come a long way. This list shows many of the major new features that have been added to the 2.17 development branch. Those using 2.16 should take a look at this list for an indication of what will be new in 2.18.
The 2.16 branch will be retired with the release of Bugzilla 2.22, scheduled for approximately April 2005. Administrators using the 2.16 branch are encouraged to investigate migration to the 2.18 stable branch when 2.18 is released.
2.14
We would like to remind all administrators running Bugzilla instances from the old 2.14 branch that this branch has been retired, and is no longer being supported actively by the team. We strongly recommend upgrading to a stable version (either 2.16.5, or 2.18 when it is released) to ensure security and proper operation, and for the new features provided by this branch.
New Features Since the Last Status Update
Several new features are available for testing in our release candidate, 2.18rc1. The following items describe the most important of these changes since the previous status update, and the manifest at the end of this document describe the full list of changes.
- All remaining static HTML pages (with the exception of QuickSearch) have been converted to template files processed by page.cgi. This feature allows all pages in Bugzilla to be localized (bug 170213).
- A preference panel for the management of saved searches was added to the User Preferences page (bug 232176).
- Buglists can now be exported as calendars in the icalendar format (bug 235459).
- The "noresolveonopenblockers" parameter was added to allow administrators to prevent a bug being closed when it has open dependencies (bug 24496).
Major New Features Since 2.16
Users upgrading from 2.16 may be interested in a list of major new features since the 2.16 release.
Date-Based Releases and More
An update from Dave Miller, Bugzilla project leader on the new date-based release scheme:
Well, today we're finally releasing our first release candidate for Bugzilla 2.18.
It's been a long time coming. It's been just shy of 2 years since Bugzilla 2.16 was released. This is a contributing factor to why this release is just now coming, even after our feature freeze on March 15th has now passed us by almost 4 months.
There are a lot of new features in 2.18. Large substantial humungous chunks (am I repeating myself?) of Bugzilla code have been reorganized and rewritten since 2.16. Bugzilla's underpinning now features substantial amounts of well-organized object-oriented Perl code. We're not there, yet, though. There's still a pretty good chunk of it (post_bug, process_bug, and the administrative utilities) that are still the old code that's had extra stuff hacked into it for years. :) And therein lies our challenge for the next few releases.
There are quite a number of new features that are almost ready to land on the trunk. Several of them have been put off for the last 4 months because they would violate our feature freeze to check them in. Those will start landing over the next few weeks, now that what will become 2.18 is living on a branch in CVS.
We announced a while back that the 2.18 Release would start us on a 6-month release cycle. Following that schedule, our feature freeze for 2.20 will be on September 15th, 2004. Yes, that's only 2 months from now. I don't expect the freeze to last 4 months again like it did for 2.18. For 2.18 we had 2 years worth of cleaning up to do. :) Since we only have 2 months of development time between now and the 2.20 freeze, it can't get that bad. So we should be able to expect to see Bugzilla 2.20 in final release form by mid-October.
Even with all of that going on, we're not done with 2.18 yet. Today's release is just a candidate. It will evolve with your help, as you test it and point out any regressions we need to fix. There will be a second release candidate in a week or two, after we knock off any major regressions anyone reports. The second candidate will also get a week or two of testing before being declared the final release.
We have a few flags on the bugs for dealing with this. If a bug you report is something that you think is important to have fixed in 2.18, set the "blocking2.18" flag to the question mark ("?") setting. This will send a message to me asking me to evaluate it. If I (or Myk) set it to "+", that means we've agreed, and attempts will be made to get it fixed on the 2.18 branch so it can be included in the final 2.18 release. Similarly, once a patch is ready to go, it must get a "+" on the "approval2.18" flag (set by Myk or myself) before it can be checked in on the branch. Please do request that if you have something blocking 2.18 after you get it reviewed.
Before I sign off here, I want to take a moment to profusely thank Mike Morgan for the work he's done on our website over the last couple months. This is a really wonderful new website he cooked up for us! :) If you have any feedback on the new site design, or find any dead links that need to be fixed, please post on the mozilla-webtools mailing list. (See the support page to find out where to subscribe).)
- Oracle support. (Bug 189947)
- Ability to add generic customized fields to bugs. (Bug 91037)
- Customized 2004/03/03 to 2004/07/8. This list was generated by filtering Bonsai's output on that query.
Checkins that don't refer to a specific bug number have been omitted, and were a small minority. Bold bugs are security bugs.
Checkin manifest:
- Bug 236296 - Fix Build Identifier on guided entry form
- Bug 236567 - Update the documentation describing the Perl modules installation on Windows using ppm
- Bug 236019 - Make request.cgi use $cgi->param instead of %::FORM
- Bug 236443 - Respect customization of customized words in create.html.tmpl
- Bug 234879 - Remove %FORM from editkeywords.cgi
- Bug 234875 - Use ->param in quips.cgi
- Bug 220814 - Add to FAQ: How to upgrade Bugzilla from CVS
- Bug 236634 - Move colon out of anchor text in "Target Milestone:" in show_bug
- Bug 235278 - Eliminate %::FORM from userprefs.cgi
- Bug 236652 - Fix libgdi typo in section 2.4.2 of the docs
- Bug 232141 - All all saved searches to footer until linkinfooter UI returns
- Bug 170213 - Make static HTML files into page.cgi pages. This does votehelp.html (-> id=voting.html), bug_status.html (-> id=fields.html) and bugwritinghelp.html (-> id=bug-writing.html)
- Bug 232176 - Add a preferences panel for saved searches, to allow management all in one place
- Bug 143490 - Eliminate unsupported calls from checksetup.pl when running in Windows
- Bug 236322 - Trivial inaccuracy in description of "find a specific bug" search corrected (the search doesn't really search summaries, so I've removed the text that says it does).
- Bug 178162 - Move the vote checkbox to the left
- Bug 236664 - Make checksetup.pl print good install instructions for Perl modules on win32
- Bug 232491 - Try harder to avoid parameterless searches (either saved or otherwise)
- Bug 237540 - Remove unused hidden field from edit-multiple
- Bug 235459 - Add icalendar output format in buglist
- Bug 237646 - Fix for regression in userprefs.cgi that disallowed users to change their password via this page
- Bug 236424 - Allow showdependencies trees to collapse. Adds [optional] Javascript-enabled +/- controls that allow branches in the dependency tree to collapse.
- Bug 232397 - .bz_obsolete shouldn't specify "underline". Define specific bz_obsolete/closed/inactive classes (that don't specify underline, but line-through instead) and additional Template filters for conveniently applying them
- Bug 237757 - Resolved bugs are no longer struck out on dependency trees. Includes a global CSS file that defines the relevant bz_* classes and adds a link to it from the global header template
- Bug 192516 - Moving the loose .pm files into the Bugzilla directory, where they belong. These files pre-date the Bugzilla directory, and would have gone there had it existed at the time. The four files in question were copied on the CVS server to preserve CVS history in the files.
- Bug 24496 - Adds a parameter "noresolveonopenblockers" which when enabled, prevents bugs from being closed if there are any bugs blocking it which are still open.
- Bug 132066 - Add a note to the login page about needing cookies for a good user experience
- Bug 237864 - Clean up leftover issues from the bug 192516 checkin (some occurances of Token got missed)
- Bug 203869 - Update documentation to better describe group controls
- Bug 237513 - Change password uses semi empty field
- Bug 237514 - Confirmed email address is missing
- Bug 237517 - Inconsistent spelling of cancelled or canceled
- Bug 237772 - Instances of "a terms.bug" should be replaced with "terms.abug" also fix the spelling of decipher
- Bug 234293 - Complete the conversion from "query" terminology to "search" terminology
- Bug 238025 - Generate HTML table header in editkeywords.cgi even when there are no keywords defined
- Bug 179351 - Improve variable scoping issues in order to fix a bug causing oddly formatted dependency emails
- Bug 228423 - Document adjustment of MySQL 4GB default table size limit
- Bug 232338 - Make the footer wrap cleanly, so it doesn't over-widen the page
- Bug 238033 - Eliminate HTML closing tags that haven't been opened and fix an indentation issue
- Bug 126252 - Add the gnatsparse Python script to the contrib directory
- Bug 207039 - Add documentation explaining how to install bugzilla under regular user privileges
- Bug 233246 - Improve documentation on enter_bug comment formatting templates.
- Bug 224420 - Documentation for new reporting and charting systems.
- Bug 237515 - Change 'also' to 'too' in the watching help page
- Bug 237840 - Eliminate case sensitivity for "attachment N" linkification
- Bug 238282 - An incorrect bugword
- Bug 236650 - Clarify choice of install directory in docs
- Bug 238396 - Update the README file for the gnatsparse project
- Bug 238506 - Fix checksetup.pl so that it does not fail if an upgrading site never changed a groupset
- Bug 218206 - Document ft_min_word_len MySQL param for indexing small words in full-text indexes and fix several typos in documentation
- Bug 127862 - Have sanitycheck.cgi use perl to evaluate email regexp
- Bug 238669 - Add a space between 'entered' and '(' in illegal_email_address error
- Bug 238656 - Reword the "Account self-creation" error message
- Bug 238673 - Add missing article in change email address page
- Bug 238677 - Fix wording of the "require_new_password" message
- Bug 238683 - Fix for usage of uninitialized value in concatenation in Bugzilla/CGI.pm
- Bug 238693 - Replace depreciated v-strings with calls to the pack() function
- Bug 177224 - Update installation docs to note XUL and RDF MIME types
- Bug 181589 - Add mass-remove to editgroups
- Bug 232097 - Use an entity reference for the landfill base URL in the demos, to make it easy to change each release.
- Bug 237369 - Implement relatively simple changes from %FORM to $cgi->param variable
- Bug 226764 - 226754 - 234175 - Remove deprecated ConnectToDatabase() and quietly_check_login()/confirm_login() calls. Cleans up callsites (consisting of most of our CGIs), swapping (where appropriate) for calls to Bugzilla->login
- Bug 235265 - Getting rid of some unwanted form value dumps.
- Bug 233962 - UserInGroup() should not accept a second parameter any longer
- Bug 238860 - Remove %FORM from editversions.cgi
- Bug 237778 - Update filter list in t/004template
- Bug 238867 - Remove one last %FORM from quips.cgi
- Bug 238650 - Reword duplicate of self error message
- Bug 237508 - Have checksetup.pl specify which perl to use (the same one it's running under) when giving instructions how to use CPAN to install needed modules.
- Bug 189156 - Explain quip moderation in documentation.
- Bug 146087 - Set the default of the sendmailnow param to ON on the trunk as well
- Bug 236926 - Supply a missing a $cgi-header in buglist.cgi
- Bug 232554 - Fix SQL queries in Flag.pm in order to fix a bug that causes flags to remain set but inaccessible when product changes.
- Bug 220817 - Add to FAQ documentation for 'Why do I have to log in every time I access a page?'.
- Bug 238874 - Remove %FORM and %COOKIE from colchange.cgi. Does precisely that, swapping them for references to cgi->param/cookie.
- Bug 233295 - Document terminology customization feature
- Bug 238352 - Remove alphabetical sorting from some fields in reports (e.g. priority) and keep them in a sensible order instead
- Bug 239346 - Add hook at end of comments
- Bug 239255 - Update docs in order to specify that $webservergroup is the group of the webserver, not the user
- Bug 14887 - Put <label> tags in forms
- Bug 239576 - Make sure detaint_natural is always called with a defined value in editkeywords.cgi
- Bug 230293 - Send CSV buglists with "Content-Disposition: attachment"
- Bug 237176 - Allows power users to display relevance values as a column in the search results for a fulltext search
- Bug 238862 - Remove %FORM and %COOKIE from enter_bug.cgi
- Bug 238864 - Remove %FORM and %COOKIE from move.pl
- Bug 192775 - Rearrange parameter order in token URLs to make them always fully linked in some MUAs
- Bug 233245 - Update documentation of formats to include ctypes as well
- Bug 239885 - Don't display the sendmail message if the current platform is Windows
- Bug 239912 - Make bug_email.pl work with useqacontact
- Bug 239826 - Support closing resolved bugs when changing multiple bugs
- Bug 224698 - Remove localconfig variable mysqlpath
- Bug 87770 - Make attachment.cgi work with no parameters
- Bug 240228 - Improve the format of the error message displayed by checksetup.pl when the MySQL requirements are not satisfied
- Bug 238865 - Remove %FORM from page.cgi. Does so, fixing the linked page template and adding a code error for the "bad id provided" case
- Bug 194332 - Fix spelling that caused error message mismatch for the "invalid_maxrows" error message
- Bug 233245 - Replace "variable" with "constant" since there is no contenttypes variable in Constants.pm.
- Bug 240219 - Display valid PPM commands when using PPM version 2
- Bug 240060 - Stop yelling at people about the minimum sendmail version
- Bug 224477 - Make webservergroup default to apache on new installs
- Bug 238869 - Remove %FORM from votes.cgi.
- Bug 240439 - "Edit user again" link didn't work if the user had a + in their email address
- Bug 240434 - Replace increased with improved on the login page
- Bug 237638 - Make bugzilla_email_append.pl work with BugMail.pm instead of processmail
- Bug 192571 - Empty default owner (assignee or QA) causes "Reassign bug to owner and QA contact of selected component to NOOP
- Bug 240004 - Limit the password generation subroutine to nice characters only
- Bug 241516 - Remove possible namespace conflicts in the additional CSS classes for bugid, component, and status on show_bug
- Bug 234540 - "Take bug" on create attachment screen missed an API change to BugMail which caused it not to mail the previous bug owner about the change.
- Bug 237838 - Make sure CheckCanChangeField() always gets correct resolution
- Bug 241259 - Add a CSS tag for 'Additional Comments'
- Bug 242740 - URL to Bug Writing Help document changed
- Bug 204042 - Taint issues in perl 5.6.0 that were causing an Internal Error to ocurr after adding an attachment.
- Bug 240486 - Makes the banner template CSS friendly
- Bug 231975 - Avoid naming new product groups the same as existing groups and do not rename product groups on product rename.
- Bug 240036 - Unlock tables after address error before attempting to process footer
- Bug 227785 - Add navigation/summary/last-modified after modifying a bug
- Bug 232861 - Prevent references to bugs or comments from being expanded in attachment links
- Bug 226477 - Fix undefined method call in Bugzilla::User->in_group
- Bug 226411 - Make DiffStrings handle fields with duplicate values
- Bug 238675 - Improved wording for the reassign-to-entry error message
- Bug 239263 - User.pm should always use the main database to avoid a potential error
- Bug 244053 - Improve grammar in checksetup.pl
- Bug 244045 - --no-silent option for checksetup.pl
- Bug 217627 - Fixes error that occured with bug aliases starting with zero
- Bug 208847 - Fixes taint errors in editgroups.cgi
- Bug 141006 - Runs all edit* cgi scripts in taint mode
- Bug 244650 - Fix searches on commentatators when searching for other email addresses
- Bug 227172 - Fixes a potential race codition when users change their email address
- Bug 243351 - Prevents an issue of MySQL version sensitivity in case sensitive searches
- Bug 183753 - Make collectstats.cgi work on Win32
- Bug 179671 - Fix boolean charts
- Bug 223541 - Make flags appear correctly in "view all attachments" mode
- Bug 240079 - Improved wording in README file
- Bug 242161 - Adds a patchviewer("diff") link to process_bug.cgi
- Bug 240252 - Improved wording in editproducts.cgi
- Bug 245976 - Fixes an error that occured when trying to add a milestone
- Bug 240325 - Update regexp-based groups
- Bug 160210 - Fixes Mac OS X detection and adds 10.1 and 10.2 to the OS list
- Bug 246599 - Adds Mac OS 10.3 (Panther) to the OS list
- Bug 142744 - Makes the test suite work on Win32
- Bug 246328 - Make editmilestone.cgi check for invalid sortkeys
- Bug 246778 - Fixes an error that occured with ThrowUserError and timetracking
- Bug 247209 - Improves OS detection for Solaris
- Bug 247192 - Improves OS detection for StarOffice on Solaris SPARC
- Bug 225359 - Allows dependency graphs to work on Win32
- Bug 245924 - Uses HTML 4 and CSS formatting for the Bugzilla footer
- Bug 248685 - Fixes the lack of terms in the header of showdependencytree.cgi
- Bug 248001 - Converts boolean conditions in SQL statements to improve database independence
- Bug 245101 - Fixes warnings that occured from upgrades from 2.14.x without going through a 2.16.x version
- Bug 239343 - Adds the sendbugmail.pl script to contrib/ for external scripts that need processmail's functionality
- Bug 243463 - Use a param to prevent charts from leaking secure information
- Bug 223878 - Avoids problems that occur when changing a deleted flag
- Bug 249802 - Document granting of permissions to a MySQL user for MySQL 4
- Bug 245077 - The "find a specific bug" tab is now the default when loading query.cgi, the script will remember the previously selected tab and display it when query.cgi is loaded again.
- Bug 248988 - Prevents a possible error with attachments on Win32
- Bug 249863 - Fix invalid HTML in create.html.tmpl
- Bug 190432 - Avoids using non-ANSI SQL when saving a named query
- Bug 250265 - Fix taint errors with vote fields when editing products
- Bug 227191 - Prevents the database password from being disclosed when the SQL server is halted and the webserver is left running in 2.17.x releases.
- Bug 233486 - Fixes a privilege escalation in 2.17.x releases where auser with privileges to grant membership to one or more individual groups (i.e. usually an administrator) can trick the administrative controls into granting membership in groups other than the ones he has privileges for.
- 235510 - Avoids a potential user password comprimise in versions 2.17.5 through 2.17.7 where the user password could be visible in web server logs when accessing a chart.
- Bug 244272 - Fixes an issue where a user with permission to grant membership to any group (i.e. usually an administrator) could cause editusers.cgi to execute arbitrary SQL. 2004/03/03 to 2004/07/08. This list was written from Bonsai's output on that query.
Bold bugs are security bugs.
Checkin manifest:
- Bug 236567 - Update the documentation for installing perl modules with PPM
- Bug 220814 - Update the FAQ to explain how to update Bugzilla from CVS
- Bug 207039 - Improve documentation on installing Bugzilla with regular user privlieges
- Bug 237591 - Allows XML import to function when there are regexp metacharacters in product names
- Bug 220817 - Update the FAQ to include information on why Bugzilla may request a username and password every time a page is accessed
- Bug 238628 - Adjust the database schema chart to fit on an 8.5X11 inch page
- Bug 239912 - Allows the bug_email.pl contrib script to work with useqacontact
- Bug 240228 - Improves the error message used by checksetup.pl when the MySQL requirements are not met
- Bug 240060 - Elimnates a warning in checksetup.pl about the minimum sendmail version
- Bug 224477 - Makes webservergroup default to group 'apache' in new installations
- Bug 117297 - Fixes an error where a bugmail message could be sent twice to a user on the CC list
- Bug 240079 - Improves the wording in the README
- Bug 249802 - Document how to create a MySQL user with permissions using MySQL 4
- 244272 - Fixes an issue where a user with permission to grant membership to any group (i.e. usually an administrator) could cause editusers.cgi to execute arbitrary SQL. | https://www.bugzilla.org/status/2004-07-10.html | CC-MAIN-2016-18 | refinedweb | 3,743 | 61.87 |
AMR Grids¶
AMR grids are specified by nested objects in the Python, with a layout described in Coordinate grids and physical quantities. These objects can be built in several ways:
Programmatically¶
The following example demonstrates how an AMR grid can be built programmatically from scratch:
from hyperion.grid import AMRGrid amr = AMRGrid() for ilevel in range(nlevels): level = amr.add_level() for igrid in range(ngrids): grid = level.add_grid() grid.xmin, grid.xmax = ..., ... grid.ymin, grid.ymax = ..., ... grid.zmin, grid.zmax = ..., ... grid.nx, grid.ny, grid.nz = ..., ..., ... grid.quantities['density'] = np.array(...)
where
nlevels is the number of levels in the AMR grid, and
ngrids is the number of grids each each level. The dimensions of the
np.array(...) on the last line should be
(nz, ny, nx).
Requirements¶
The following geometrical requirements have to be respected:
- In a given level, all grids should have the same x, y, and z resolutions, i.e. the resolution in each direction can be different, but the resolution along a particular direction has to be the same for all grids in the level.
- In a given level, the edges of all grids have to line up with a common grid defined by the widths in each direction. For example, if the cell width is
1.0in the x direction, one cannot have a grid with
xmin=0.0and one with
xmin=0.5since the cell walls in the x direction for these two grids do not line up on a common grid.
- The refinement ratio between two levels (the ratio of widths of cells in a direction from one level to the next) should be a whole number. The refinement ratio can be different for different directions, and can be greater than 2.
- The boundaries of grids in a given level have to line up with cell walls in the parent level.
If these conditions are not met, then the Fortran Hyperion code will raise an error.
From simulation output¶
Importing functions are available in
hyperion.importers to convert simulation output to the AMR structure required. At this time, only output from the Orion code can be read in. If the output is contained in a directory
directory, then the AMR structure can be retrieved with:
from hyperion.importers import parse_orion amr, stars = parse_orion('directory')
The
stars variable is a list of
Star instances. These
Star instances have several attributes, which include:
x,
y, and
z- the position of the star
m,
r- the mass and radius of the star
mdot- the infall rate onto the star
These can be used for example to set up sources of emission in the model:
# Set up the stars for star in stars: source = m.add_point_source() source.luminosity = lsun source.position = (star.x, star.y, star.z) source.temperature = 6000.
The above just creates sources with equal temperatures and luminosities, but these can also be set depending on
m,
r, and
mdot. | http://docs.hyperion-rt.org/en/stable/advanced/indepth_amr.html | CC-MAIN-2021-17 | refinedweb | 485 | 62.38 |
tell application "Adium" set x to 0 repeat with theChat in (every chat) set x to x + (unread message count of theChat) end repeat say "You have " & x & " unread messages"end tell
import com.apple.cocoa.foundation.*;void setup() { size(400,400); int adiumUnread = runAS(); println(adiumUnread);}void draw() { }public int runAS() { String script = "tell application \"Adium\"\n" +" set x to 0\n" +" repeat with theChat in (every chat)\n" +" set x to x + (unread message count of theChat)\n" +" end repeat\n" +" end tell\n" +" x"; NSAppleScript myScript = new NSAppleScript(script); NSMutableDictionary errors = new NSMutableDictionary(); NSAppleEventDescriptor result = myScript.execute(errors); return result.int32Value();}
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=38695.msg285657 | CC-MAIN-2015-11 | refinedweb | 139 | 51.18 |
10 January 2013 19:04 [Source: ICIS news]
(updates with Canadian and Mexican data)
HOUSTON (ICIS)--Chemical shipments on Canadian railroads rose by 14.9% year on year in the week ended 5 January, according to data released by a rail industry association on Thursday.
Canadian chemical railcar loadings for the week totalled 9,673, compared with 8,419 in the same week in 2012, the Association of American Railroads (AAR) said. ?xml:namespace>
US chemical railcar traffic for the week ended 5 January fell by 3.8% year on year to 25,903 loadings.
Overall US weekly railcar loadings for the week ended 5 January in the freight commodity groups tracked by the AAR fell by 12.1% year on year to 241,682 | http://www.icis.com/Articles/2013/01/10/9630808/canada-weekly-chemical-railcar-traffic-rises-14.9.html | CC-MAIN-2014-35 | refinedweb | 125 | 54.83 |
About This Project. Yay
The settings/how to run it are as follows:
Buttons
- Arm - resets all counts & starts recording event counts for motion & sound. Both mics must detect the sound at once for it to register as a bark.
- Notify - turns on text messaging & will send a text when motion is detected.
- Raw Values? - This live updates the raw values to the dashboard - This WILL slow down polling interval of the mics/motion substantially possibly missing barks or motion events. Just to test & see your average levels
After some playing around with the threshold settings I got it pretty tuned in to identifying when he is barking or not. Turns out overall he is a good dog.
What's Connected
This project currently used: Arduino Uno R3 ESP8266-01S 2x Analog sound microphones Motion Detector HC-SR501 plus some small parts- AMS1117, capacitors, etc...
Triggers & Alerts
I didn't use too much for alerts or triggers with this project. Just one trigger that is used for notifying me, if intrusion/motion is detected & I have the "notify me" button enabled. I may add a LED on the board to indicate when motion is detected or bark detected. Maybe a Neopixel strip that also counts the events?
Scheduling
I have the device arm itself everyday at 9am and disarm at 4pm otherwise I always forget to turn it on and then it won't keep count.
Dashboard Screenshots
Photos of the Project
Video
no video yet...
Code
#include <CayenneESP8266Shield.h> char token[] = "your token here"; char ssid[] = "your wifi"; char password[] = "your wifi password here"; #define EspSerial Serial #define ESP8266_BAUD 115200 ESP8266 wifi(EspSerial); const int barkPin1 = A1; const int barkPin2 = A0; const int motionPin = 3; int barkLevel1; int barkLevel2; int threshold1; int threshold2; int armed; int barking1 = 0; int barking2 = 0; int trueBark = 0; int showRaw; int motion = 0; int notify; int prevMotion = 0; int motionDetects = 0; void setup() { EspSerial.begin(ESP8266_BAUD); delay(10); // Serial1.begin(9600); Cayenne.begin(token, wifi, ssid, password); Cayenne.virtualWrite(V13, 0); Cayenne.virtualWrite(V11, 0); pinMode(barkPin1, INPUT); pinMode(barkPin2, INPUT); pinMode(motionPin, INPUT); } void loop() { Cayenne.run(); prevMotion = motion; barkLevel1 = 530 - analogRead(barkPin1); //set your mics values here barkLevel2 = 1023 - analogRead(barkPin2); //set your mics values here motion = digitalRead(motionPin); if (motion != prevMotion) { Cayenne.virtualWrite(V10, motion); if (armed == 1) { if (prevMotion == 0) { motionDetects++; Cayenne.virtualWrite(V11, motionDetects); } if (notify == 1) { Cayenne.virtualWrite(V13, 1); } else { Cayenne.virtualWrite(V13, 0); } } } if (showRaw == 1) { Cayenne.virtualWrite(V8, barkLevel1); Cayenne.virtualWrite(V9, barkLevel2); } if (armed == 1) { if (barkLevel1 > threshold1) { barking1++; Cayenne.virtualWrite(V2, barking1); } if (barkLevel2 > threshold2) { barking2++; Cayenne.virtualWrite(V5, barking2); } if (barkLevel1 > threshold1 && barkLevel2 > threshold2) { trueBark++; Cayenne.virtualWrite(V6, trueBark); } // Serial1.print(barkLevel1); // Serial1.print(" "); // Serial1.println(threshold2); } } CAYENNE_IN(V1) { armed = getValue.asInt(); if (armed == 1) { barking1 = 0; barking2 = 0; trueBark = 0; motionDetects = 0; Cayenne.virtualWrite(V2, 0); Cayenne.virtualWrite(V5, 0); Cayenne.virtualWrite(V6, 0); Cayenne.virtualWrite(V11, 0); } } CAYENNE_IN(V3) { threshold1 = (getValue.asLong() / 1023); } CAYENNE_IN(V4) { threshold2 = (getValue.asLong() / 1023); } CAYENNE_IN(V7) { showRaw = getValue.asInt(); } CAYENNE_IN(V12) { notify = getValue.asInt(); }
vapor83
| https://www.hackster.io/vapor83/barkbox-simple-noise-intrusion-detection-device-652d27 | CC-MAIN-2018-26 | refinedweb | 511 | 51.55 |
Kotlin and MongoDB, a Perfect Match
Posted on Sep 25, 2018. Updated on May 1, 2020
MongoDB’s dynamic schema is powerful and challenging at the same time. In Java, a common approach is to use an object-document mapper to make the schema explicit in the application layer. Kotlin takes this approach even further by providing additional safety and conciseness. This post shows how the development with MongoDB can benefit from Kotlin and which patterns turned out to be useful in practice. We’ll also cover best practices for coding and schema design.
TL;DR
- MongoDB’s dynamic schema is powerful, but it can lead to more mistakes. In order to maintain safety, it’s even more important to make the schema explicit and enforced in the application layer by:
- Using a statically typed language
- Using object-document mapping (ODM)
- Kotlin nicely completes this approach:
- Null-aware types to model optional fields
- Powerful means to easily handle null/optional fields
- Immutable properties. So we can’t forget to provide required fields.
- Increased awareness in the team for optional fields
- Data classes to easily create immutable and maintainable data structures for the object-document-mapper
- Coroutines enable using the non-blocking driver without fiddling with callbacks
- The existing object-document mappers are seamlessly supporting immutable data classes
- Best Practices:
- Use type-safe queries based on Kotlin’s properties to avoid fiddling around with strings.
- When adding or removing a field it’s usually better to update all documents in order to avoid nullable types.
- Use tailored data classes for projections.
- Wrap optional fields in an additional optional data class. This way, the fields within the data class can be non-nullable.
The Status Quo of Dealing with MongoDB’s Dynamic Schema in Java
MongoDB is not schemaless. There is always a schema, but it’s dynamic and not enforced by the database. This makes MongoDB very flexible and adaptive. However, there is the danger of losing track of the schema and its variations. We may end up in “field undefined” errors, error-prone string concatenations, wrong types, and typos. What’s the solution?
A statically typed language and object mapping.
We map the documents to objects which are instances of a class with a statically defined structure. This way, the compiler guides us during reading and writing the values. This approach provides a (type-)safe way of using MongoDB and makes the schema explicit, enforced, (kind of) validated and documented in the application layer.
So that’s all great but nothing new. We’re already using this approach in Java for a while now. However, Kotlin can extend and improve this approach even further!
Data Classes
Powerful Data Structure Definition
The strict usage of object-document mapper requires you to write a corresponding class for each document. Fortunately, that’s where Kotlin’s data classes are a huge relief in contrast to Java.
data class Design( val name: String, val dateCreated: Instant, val statistics: Statistics? ) data class Statistics( val likeCount: Int, val dislikeCount: Int )
That’s it. I can’t imagine how the definition of data structures could be more concise. Additional benefits are:
- High safety due to immutable properties.
hashCode(),
equals()and
toString()are generated and (more important) don’t have to be maintained.
- Readability due to named arguments.
Kotlin-Friendly Object-Document-Mapper
The existing object-document mapper for MongoDB works nicely with Kotlin’s immutable data classes. We should not take that for granted. Just take a look at Hibernate and the pull-ups that are required to make it work together with Kotlin. Still, it’s not possible to benefit from data classes.
Here’s an overview over some ODMs:
- We mainly use Spring Data MongoDB in our projects. We use the more low-level MongoTemplate most of the time. Fortunately, Spring Data MongoDB has dedicated Kotlin support built-in.
- The lightweight and Kotlin-native KMongo also looks pretty promising. But I haven’t used it in production yet. Check it out.
Side note: Since we have less impedance mismatch between the object-oriented and the document world, the object-document mapping is much simpler (compared to ORMs). Less complexity usually leads to less trouble. In fact, we never had any mapping issue or debugging sessions in our mapping framework (I’m looking at you, Hibernate!). It just works out of the box.
Tailored Data Classes for Projections
In many situations, we only need some fields and not the whole document. Fetching the whole document and mapping it to the complete data class leads to higher query times and a waste of memory. Fortunately, Kotlin makes it easy to define tailored data classes for that query:
import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.mapping.Field @Document(collection = "designs") data class DesignWithLikeCount( val name: String, @Field("statistics.likeCount") val likeCount: Int )
Now, we only have to add the required projection to the query and we are done.
// Usage: projection and mapping to a tailored class query.fields() .include("name") .include("statistics.likeCount") val entities = mongoTemplate.find<DesignWithLikeCount>(query)
The above snippets are using plain strings to refer to the fields. We’ll talk about better approaches in the next section.
Type-Safe Queries and Updates
Today’s ODMs are leveraging Kotlin’s language features to allow writing type-safe queries and updates.
Queries
Usually, we have to refer to the field name with strings.
val query = Query().addCriteria(Criteria.where("name").isEqualTo(name)) val designs = mongoTemplate.find<Design>(query)
Fiddling around with strings like
"name" is error-prone. Using constants is an obvious solution. Still, we have to fiddle around with strings and keep the data class property names in sync with the constants. Both are error-prone.
Fortunately, Spring’s MongoTemplate (and KMongo) support type-safe queries. First, the ODM derives the field name from the property of the data class (
Design::name). Second, there are extension functions on Kotlin’s properties that directly creates a
Criteria object (
isEqualTo()). Even better: They are infix function. So, we can write something like this:
val query = Query().addCriteria(Design::name isEqualTo name)
Note that the
/ operator is used to refer to nested properties
// refers to "statistics.likeCount" val query = Query().addCriteria(Design::statistics / Statistics::likeCount gt 10 )
Updates
As of Spring Data MongoDB 2.2.6, type-safe updates are not supported yet. However, we can easily add this feature:
fun Update.set(property: KProperty<*>, value: Any?): Update { return set(property.name, value) }
Usage:
val update = Update().set(Design::name, "Dog") mongoTemplate.updateMulti<Design>(query, update)
Nullability
Null-Aware Types
Even when we use Java and object mapper, we still have the challenge to keep track of the optional fields. Especially after the database model has grown over some years and same team member have left and a new one joined.
// Java public class Design { private String name; // can name be null? private Statistics statistics; // can statistics be null? // getter & setter boilerplate }
It’s likely to run into the infamous NullPointerExceptions:
int likes = design.getStatistics().getLikeCount() // NPE because statistics is null in some cases!
Annotations like
@Nullable help here, but they are not enforced by the compiler and maintaining them is easy to forget.
The point is that Java’s type system doesn’t distinguish between nullable and non-nullable types. Fortunately, Kotlin does. We just have to add a
? behind the type.
// Kotlin data class Design( val name: String, // name can never be null val statistics: Statistics? // statistics are optional/nullable )
Hence, our Kotlin classes also document which fields can be null and which not. And even better: The compiler enforces the handling of null values before we can access the value. This avoids the annoying NullPointerExceptions.
val likes = design.statistics.likeCount // Compile Error! // We are not allowed to access likeCount directly, because statistics can be null.
Another point: Let’s assume that the field
name of a
Design document is used everywhere in the code base. Let’s further assume that we decide to make this field optional. In Kotlin, we just add a
? and the compiler points us to every access to the
name property that has to be adjusted in order to handle null values. This is so powerful.
For me, Kotlin’s nullability is the missing part for making MongoDB’s dynamic schema explicit and documented in the application code. Besides, it significantly improves the safety.
Powerful Means for Handling Optional Fields
Let’s assume we are aware that a field can be null. Then, it’s still cumbersome in Java to do the actual null checking.
// Java int likes; if (design != null && design.getStatistics() != null) { likes = design.getStatistics().getLikeCount(); } else { like = 0; }
These nested null-checks are easy to forget. Fortunately, Kotlin has powerful and concise means to handle nullable fields.
val likes = design?.statistics?.likeCount ?: 0
Enforce Required Fields with Immutable Properties
If we stricly use immutable properties in data classes and object mapper, we have another benefit: We can’t forget to set a required (= non-nullable) field.
val newDesign = Design() // compile error! The non-nullable property `name` is missing. mongoTemplate.insert(newDesign)
This removes a really big source of errors and keeps the schema consistent.
Increased Awareness for Optional Fields
“Ok, we have to add a
statisticsfield in the design document”
“Can the field be null?”
After using the combo MongoDB + Kotlin for a while, we discovered the following effect in our team: Every time we introduce a new field, we automatically start discussing its nullability. It’s impressive. The type system forces us to decide on the nullability at the moment we add the property to the corresponding data class. That shaped our awareness of the required and optional fields and becomes one of the first questions we ask when it comes to new fields.
Schema Design
Avoid Nullability with Nesting
We should pay attention to nullability when it comes to the schema design. An example:
data class Design( val name: String, val likeCount: Int?, val vectorDesign: Bool?, val dislikeCount: Int? )
There are two things wrong here:
- First, there are many nullable fields. We should strive to reduce nullability in our schema in order to make it simpler and less error-prone.
- Second, this schema doesn’t tell us, if there are fields that belong semantically together. Just look at the field
likeCountand
dislikeCount. Let’s assume that these fields are either set together or none of them. This is not obvious by looking at the schema/data class.
A solution is to wrap that group of fields together into a new data class
Statistics:
data class Design( val name: String, val vectorDesign: Bool?, val statistics: Statistics? ) data class Statistics( val likeCount: Int, // non-nullable val dislikeCount: Int // non-nullable )
This way, the schema states clearly: If a
statistics field exists, all of its subfields are never null.
Side note: By the way, I like the impact that object mapping has on the schema design. It impedes a highly variable schema (many nullable fields or complete arbitrary field names), which in turn is harder to understand, more error-prone and harder to process. My rule of thumb: If we can’t easily map a schema to classes, it’s usually not a good one.
New Fields: Migration instead of Nullable Types
Let’s assume we have to add the new field
dateCreated to the Design document. Is this field nullable or not? At the first glance, yes, because at the time of releasing the new application version (that starts writing this field) none of the existing documents have this field.
data class Design( val name: String, // is the new field `dateCreated` nullable? val dateCreated: Instant? // Well, there are existing documents without this field... )
In MongoDB, we often change the schema because we have to align it to the changing access pattern of the application. However, this may lead to a schema consisting of many nullable fields because some documents fulfill the new schema and some the old.
We don’t know if
dateCreated is nullable/optional by design or because it was added later (being a side-effect of a changed schema). That makes the schema ambiguous and harder to grasp. That’s why I strongly recommend performing a real schema migration by setting this field in every document via a dedicated migration script.
db.designs.updateMany({}, { $set: { "dateCreated": ISODate() } })
So we can safely mark the new field
dateCreated as non-nullable. The bottom line is: Consequently and permanently clean up your schema. Make it as consistent as possible by doing complete schema migrations. Try to use nullable fields by design, not for schema changes.
Misc
Coroutines: Asynchronous Driver Without Callbacks
The asynchronous MongoDB driver allows the efficient usage of threads. However, this usually leads to a more complex code because we have to deal with callbacks or stream-based APIs. Fortunately, Spring’s MongoTemplate and KMongo provides a coroutine-based wrapper around MongoDB’s asynchronous driver. So we can write code that looks synchronous but is asynchronous and non-blocking under the hood.
Don’t Use Fongo for Testing
This point is not Kotlin related, but a matter close to my heart. I highly recommend using a real MongoDB for your tests instead of the in-memory database Fongo. That’s a breeze with Testcontainers.
- For more details about the reasons, check out my post “Don’t use In-Memory Databases for Tests”.
- Besides, my post “Best Practices for Unit Testing in Kotlin” shows how we can reuse a single MongoDB container for each test class in an idiomatic way without any test framework integration. | https://phauer.com/2018/kotlin-mongodb-perfect-match/ | CC-MAIN-2021-49 | refinedweb | 2,265 | 58.28 |
Managing activity between pages can be quite easy in React if you know how to keep things in good order. The go-to way of passing props down and back up every time there’s a change makes sense, but can easily get messy.
And slow.
By breaking out your components into two simple categories and separating each page’s responsibility, you can take out the need to pass down so many props (and keep many of them up in the address bar).
Page components vs. block components
Let’s start by breaking out an application into blocks of HTML that relate to functions of the application itself. If you’ve ever used any CMS, you’re likely already familiar with the concept of managing “pages” separate from “blocks” of content.
Example:
An application has a blog post object. There is a page specific to that single blog post, but there are also individual representations of that blog in short-form. Maybe there’s a blog main page with a list of 10 per page, maybe there’s a “newest posts” section of the homepage, maybe there is an author page with every post they have authored.
The blog page is all about the content of the individual blog post, but the blog block is something that can be used wherever we want, regardless of context. To separate out your functionality into pages in React without sacrificing the ability to pass information between, it’s important that your app is structured with many page components that can use any number of block components.
More on this in a moment.
Tying pages to URLs
There are a few ways to do this and none of them come out-of-the-box with React. There are many great options of how to do it, but my favorite is react-router. Because I’m doing this example for the web, we’ll use
react-router-dom, but there are options for React Native as well. Here are the basics of how that works.
- One component (usually called
App) is the top-level that owns the router and manages the history object* as part of its state and props.
- Multiple (page) components or render functions choose what to put on the page based on the URL in the address bar currently.
- The rest of your functionality is put into the pages on an as-needed basis.
- This is the important bit.
Did you know that the DOM already has an object that contains all of the properties of the pieces of the URL? Do me a favor, go into your console in this browser tab, type in
window.history and check that out.
Pretty cool, right? What’s great about it is that it manages where you’re at and where you’ve been using… (drumroll) state! Check out the docs when you have a minute because there are really cool things you can do with the history object.
The way that most routing works is by tying your top-level component to the history and managing its state with your browser history. It also contains a lot of cool abilities to break out URL segments, and params.
OK, so seriously, what do I do with that?
Here’s where this gets cool. By passing the history object into props on page components, you maintain state variables (even if they change at the top level) down into each page and even between them. Leverage that with the ability to put other block components wherever you want, and you have a tidy way to manage whatever information is relevant for the page of the app.
Step 1: Pages
Let’s go back to our blog example. Without a router, you would need to create a separate file with a separate state between the homepage and the blog post page, but with a router, you can pass params into the URL, even using that to dynamically set URLs.
Check it out:
import React, { Component } from "react" import { BrowserRouter as Router, Route } from "react-router-dom" component App extends Component { render () { return ( <div className="app"> <Router> <Route path="/" exact component={HomePage} /> <Route path="/blog" exact component={BlogPage} /> <Route path="/blog/:id" exact component={BlogPostPage} /> </Router> </div> ) } }
With three lines, you have set up three separate pages, all that share content of the blog posts and can render the same component without having to pass a load of props. You’ll even notice, that I’ve included URL parameter for the blog post ID called
id.
Step 2: Mapping the history
By taking the dynamic piece of the URL(the blog post’s ID) and moving it into a parameter, we can avoid the need for the application to have any knowledge of the blog database whatsoever.
This has huge processing savings implications. If there’s a CRUD interface inside that
/blog URL,
BlogPostPage can manage all of that. Even better yet, you can rely on a reducer through Redux to manage all of the local stores so that
App is only responsible for making sure the right page shows.
This is what the start of
BlogPostPage probably looks like:
import React, { Component } from "react" component BlogPostPage extends Component { state = { postId: this.props.match.params.id } componentDidMount () { // database call to get other attributes for state } render () { ... } }
Step 3: The fun stuff
By default
react-router includes the ability to pick up on parameters, hashes, or anything else you may want to check in the URL. Every one of these is immediately available for the page component:
Parameters (for named variables):
this.props.match.params
Hash (great for anchor links):
this.props.location.hash
Query params (for search or other queries):
this.props.location.search
All URL segments (if you need even more granular control over the path):
this.props.location.pathname
This even works if you nest paths within each other:
return ( <div className="app"> <Router> <Route path="/" exact component={HomePage} /> <Route path="/blog" exact component={BlogPage} /> <Route path="/blog/:id" exact component={BlogPostPage} /> <Route path="/user" exact component={UserProfile} /> <Route path="/user/settings" exact component={UserSettings} /> </Router> </div> )
Conclusion
After some refactoring, you can think of each page of your application as separate mini-apps only responsible for their own features and break out features repeated between pages into block components that get used on each page. That keeps your state and props few and responsibilities small.. | https://blog.logrocket.com/react-url-state/ | CC-MAIN-2021-39 | refinedweb | 1,070 | 59.23 |
Fixed various bugs related to builddir!=srcdir prims2x0.6.2.fs is now installed avoid extra make for check updated testdist and testall
\ definitions needed for interpreter only \ Copyright (C) 1995-2000,2004. \ \ Revision-Log \ put in seperate file 14sep97jaw \ \ input stream primitives 23feb93py require ./basics.fs \ bounds decimal hex ... require ./io.fs \ type ... require ./nio.fs \ . <# ... require ./errore.fs \ .error ... require kernel/version.fs \ version-string-obsolete s-word \G Parses like @code{word}, but the output is like @code{parse} output. \G @xref{core-idef}. \ this word was called PARSE-WORD until 0.3.0, but Open Firmware and \ dpANS6 A.6.2.2008 have a word with that name that behaves \ differently (like NAME). source 2dup >r >r >in @ over min /string rot dup bl = IF drop (parse-white) ELSE (word) THEN [ has? new-input [IF] ] 2dup input-lexeme! [ [THEN] ] 2dup + r> - 1+ r> min >in ! ; : word ( char "<chars>ccc<char>-- c-addr ) \ core \G Skip leading delimiters. Parse @i{ccc}, delimited by \G @i{char}, in the parse area. @i{c-addr} is the address of a \G transient region containing the parsed string in \G counted-string format. If the parse area was empty or \G contained no characters other than delimiters, the resulting \G string has zero length. A program may replace characters within \G the counted string. OBSOLESCENT: the counted string has a \G trailing space that is not included in its length. sword here place bl here count + c! here ; : ( c-addr1 u1 ) over swap r> scan >r over - dup r> IF 1+ THEN >in +! [ has? new-input [IF] ] 2dup input-lexeme! [ [THEN] ] ; \ name 13feb93py [IFUNDEF] (name) \ name might be a primitive : (name) ( -- c-addr count ) \ gforth source 2dup >r >r >in @ /string (parse-white) [ has? new-input [IF] ] 2dup input-lexeme! [ [THEN] ] 0A , 10 , 2 , 0A , \ 10 16 2 10 \ !! protect BASE saving wrapper against exceptions : getbase ( addr u -- addr' u' ) 2dup s" 0x" string-prefix? >r 2dup s" 0X" string-prefix? r> or base @ &34 < and if hex 2 /string endif over c@ [char] # - dup 4 u< IF cells bases + @ base ! 1 /string ELSE drop THEN ; : sign? ( addr u -- addr1 u1 flag ) over c@ [char] - = dup >r IF 1 /string THEN r> ; : ?dnegate ( d1 f -- d2 ) if dnegate then ; has? os 0= [IF] : x@+/string ( addr u -- addr' u' c ) over c@ >r 1 /string r> ; [THEN] : s'>unumber? ( addr u -- ud flag ) \ convert string "C" or "C'" to character code dup 0= if false exit endif x@+/string 0 s" '" 2rot string-prefix? ; : s>unumber? ( c-addr u -- ud flag ) \ gforth \G converts string c-addr u into ud, flag indicates success dpl on over c@ '' = if 1 /string s'>unumber? exit endif base @ >r getbase sign? >r rdrop false ELSE rdrop 2drop r> ?dnegate true THEN r> base ! ; \ ouch, this is complicated; there must be a simpler way - anton : s>number? ( addr u -- d f ) \ gforth \G converts string addr u into d, flag indicates success sign? >r s>unumber? 0= IF rdrop false ELSE \ no characters left, all ok r> ?dnegate has? ec [IF] AVariable forth-wordlist : find-name ( c-addr u -- nt | 0 ) \ gforth \g Find the name @i{c-addr u} in the current search \g order. Return its @i{nt}, if found, otherwise 0. forth-wordlist (f83find) ; [ELSE] \ \ has? f83headerstring [IF] : f83find ( addr len wordlist -- nt / false ) wordlist-id @ (f83find) ; [ELSE] : f83find ( addr len wordlist -- nt / false ) wordlist-id @ (listlfind) ; [THEN] :) ; [THEN] \ \ header, finding, ticks 17dec92py \ The constants are defined as 32 bits, but then erased \ and overwritten by the right ones has? f83headerstring [IF] \ to save space, Gforth EC limits words to 31 characters $80 constant alias-mask $40 constant immediate-mask $20 constant restrict-mask $1f constant lcount-mask [ELSE] [ has? rom [IF] ] 0= [ [THEN] ] if drop ['] compile-only-error else (cfa>int) then ; has? f83headerstring [IF] : name>string ( nt -- addr count ) \ gforth name-to-string \g @i{addr count} is the name of the word represented by @i{nt}. cell+ count lcount-mask and ; : ((name>)) ( nfa -- cfa ) name>string + cfaligned ; : (name>x) ( nfa -- cfa w ) \ cfa is an intermediate cfa and w is the flags cell of nfa dup ((name>)) swap cell+ c@ dup alias-mask and 0= IF swap @ swap THEN ; [ELSE] : name>string ( nt -- addr count ) \ gforth name ; [THEN] : name>int ( nt -- xt ) \ gforth name-to-int name-question-int \G Like @code{name>int}, but perform @code{-2048 throw} if @i{nt} \G has no interpretation semantics. (name>x) restrict-mask and [ has? rom [IF] ] 0= [ [THEN] ] [ has? rom [IF] ] 0= [ [THEN] ] flag-sign ; : (name>intn) ( nfa -- xt +-1 ) (name>x) tuck (x>int) ( w xt ) swap immediate-mask and [ has? rom [IF] ] 0= [ [THEN] ] @ [ has? float [IF] ] float+ [ [ELSE] ] cell+ [ [THEN] ] to-body ; has? prims [IF] : flash! ! ; : flashc! c! ; [THEN] has? flash [IF] ' flash! [ELSE] ' ! [THEN]>}. [ has? flash [IF] ] dodoes: over flash! cell+ flash! [ [ELSE] ] dodoes: over ! cell+ ! [ [THEN] ] ; ' parse1 ( c-addr u -- ... xt) \ "... xt" is the action to be performed by the text-interpretation of c-addr u : parser ( c-addr u -- ... ) \ text-interpret the word/number c-addr u, possibly producing a number parser1 execute ; has? ec [IF] ' (name) Alias parse-name : no.extensions 2drop -&13 throw ; ' no.extensions Alias compiler-notfound1 ' no.extensions Alias interpreter-notfound1 [ELSE] Defer parse-name ( "name" -- c-addr u ) \ gforth \G Get the next word from the input buffer ' (name) IS parse-name ' parse-name alias parse-word ( -- c-addr u ) \ gforth-obsolete \G old name for @code{parse-name} ' parse-name alias name ( -- c-addr u ) \ gforth-obsolete \G old name for @code{parse-name} Defer compiler-notfound1 ( c-addr count -- ... xt ) Defer interpreter-notfound1 ( c-addr count -- ... xt ) : no.extensions ( addr u -- ) 2drop -&13 throw ; ' no.extensions IS compiler-notfound1 ' no.extensions IS interpreter-notfound1 Defer before-word ( -- ) \ gforth \ called before the text interpreter parses the next word ' noop IS before-word [THEN] has? backtrace [IF] : interpret1 ( ... -- ... ) rp@ backtrace-rp0 ! BEGIN ?stack [ has? EC 0= [IF] ] before-word [ [THEN] ] parse-name dup WHILE parser1 execute REPEAT 2drop ; : interpret ( ?? -- ?? ) \ gforth \ interpret/compile the (rest of the) input buffer backtrace-rp0 @ >r ['] interpret1 catch r> backtrace-rp0 ! throw ; [ELSE] : interpret ( ... -- ... ) BEGIN ?stack [ has? EC 0= [IF] ] before-word [ [THEN] ] parse-name dup WHILE parser1 execute REPEAT 2drop ; [THEN] \ interpreter 30apr92py \ not the most efficient implementations of interpreter and compiler : interpreter1 ( c-addr u -- ... xt ) 2dup find-name dup if nip nip name>int else drop 2dup 2>r snumber? IF 2rdrop ['] noop ELSE 2r> interpreter-notfound1 THEN then ; ' interpreter1 IS parser1 \ \ Query Evaluate 07apr93py has? file 0= [IF] : sourceline# ( -- n ) 1 ; [ELSE] has? new-input 0= [IF] Variable #fill-bytes \G number of bytes read via (read-line) by the last refill [THEN] [THEN] has? new-input 0= [IF] : input-start-line ( -- ) >in EXIT THEN [ [THEN] ] tib /line [ has? file [IF] ] loadfile @ ?dup IF (read-line) throw #fill-bytes ! ELSE [ [THEN] ] sourceline# 0< IF 2drop false EXIT THEN accept eof @ 0= [ has? file [IF] ] THEN 1 loadline +! [ [THEN] ] swap #tib ! input-start-line ; : ! input-start-line [ has? file [IF] ] blk off loadfile off -1 loadline ! [ [THEN] ] ['] interpret catch pop-file [ has? file [IF] ] r>loadfilename [ [THEN] ] throw ; [THEN] \ \ Quit 13feb93py Defer 'quit has? os [IF] Defer .status [ELSE] [IFUNDEF] bye : (bye) ( 0 -- ) \ back to DOS drop 5 emit ; : bye ( -- ) 0 (bye) ; [THEN] [THEN] : prompt state @ IF ." compiled" EXIT THEN ." ok" ; : (quit) ( -- ) \ exits only through THROW etc. BEGIN [ has? ec [IF] ] cr [ [ELSE] ] .status ['] cr catch if [ has? OS [IF] ] >stderr [ [THEN] ] cr ." Can't print to stdout, leaving" cr \ if stderr does not work either, already DoError causes a hang 2 (bye) endif [ [THEN] ] refill WHILE interpret prompt REPEAT bye ; ' (quit) IS 'quit \ \ DOERROR (DOERROR) 13jun93jaw has? os [IF] 8 Constant max-errors 5 has? file 2 and + Constant /error Variable error-stack 0 error-stack ! max-errors /error * cells allot \ format of one cell: \ source ( c-addr u ) \ last parsed lexeme ( c-addr u ) \ line-number \ Loadfilename ( addr u ) : error> ( -- c-addr1 u1 c-addr2 u2 line# [addr u] ) -1 error-stack +! error-stack dup @ /error * cells + cell+ /error cells bounds DO I @ cell +LOOP ; : >error ( c-addr1 u1 c-addr2 u2 line# [addr u] -- ) error-stack dup @ dup 1+ max-errors 1- min error-stack ! /error * cells + cell+ /error 1- cells bounds swap DO I ! -1 cells +LOOP ; : input-error-data ( -- c-addr1 u1 c-addr2 u2 line# [addr u] ) \ error data for the current input, to be used by >error or .error-frame source input-lexeme 2@ sourceline# [ has? file [IF] ] sourcefilename [ [THEN] ] ; : dec. ( n -- ) \ gforth \G Display @i{n} as a signed decimal number, followed by a space. \ !! not used... base @ decimal swap . base ! ; : dec.r ( u n -- ) \ gforth \G Display @i{u} as a unsigned decimal number in a field @i{n} \G characters wide. base @ >r decimal .r r> base ! ; : hex. ( u -- ) \ gforth \G Display @i{u} as an unsigned hex number, prefixed with a "$" and \G followed by a space. \ !! not used... [char] $ emit base @ swap hex u. base ! ; : ; : umin ( u1 u2 -- u ) 2dup u> if swap then drop ; Defer mark-start Defer mark-end :noname ." >>>" ; IS mark-start :noname ." <<<" ; IS mark-end : part-type ( addr1 u1 u -- addr2 u2 ) \ print first u characters of addr1 u1, addr2 u2 is the rest over umin 2 pick over type /string ; : .error-line ( c-addr1 u1 c-addr2 u2 -- ) \ print error in line c-addr1 u1, where the error-causing lexeme \ is c-addr2 u2 >r 2 pick - part-type ( c-addr3 u3 R: u2 ) mark-start r> part-type mark-end ( c-addr4 u4 ) type ; : .error-frame ( throwcode addr1 u1 addr2 u2 n2 [addr3 u3] -- throwcode ) \ addr3 u3: filename of included file - optional \ n2: line number \ addr2 u2: parsed lexeme (should be marked as causing the error) \ addr1 u1: input line error-stack @ IF ( throwcode addr1 u1 n0 n1 n2 [addr2 u2] ) [ has? file [IF] ] \ !! unbalanced stack effect over IF cr ." in file included from " type ." :" 0 dec.r 2drop 2drop ELSE 2drop 2drop 2drop drop THEN [ [THEN] ] ( throwcode addr1 u1 n0 n1 n2 ) ELSE ( throwcode addr1 u1 n0 n1 n2 [addr2 u2] ) [ has? file [IF] ] cr type ." :" [ [THEN] ] ( throwcode addr1 u1 n0 n1 n2 ) dup 0 dec.r ." : " 5 pick .error-string IF \ if line# non-zero, there is a line cr .error-line ELSE 2drop 2drop THEN THEN ; : (DoError) ( throw-code -- ) [ has? os [IF] ] >stderr [ [THEN] ] input-error-data .error-frame error-stack @ 0 ?DO error> .error-frame LOOP drop [ has? backtrace [IF] ] dobacktrace [ [THEN] ] normal-dp dpp ! ; ' (DoError) IS DoError [ELSE] : dec. base @ >r decimal . r> base ! ; : DoError ( throw-code -- ) cr source drop >in @ type ." <<< " dup -2 = IF "error @ type drop EXIT THEN .error ; [THEN] :] ] \ stack depths may be arbitrary here ['] 'quit CATCH dup WHILE <# \ reset hold area, or we may get another error DoError \ stack depths may be arbitrary still (or again), so clear them clearstacks [ has? new-input [IF] ] clear-tibstack [ [ELSE] ] r@ >tib ! r@ tibstack ! [ [THEN] ] REPEAT drop [ has? new-input [IF] ] clear-tibstack [ [ELSE] ] r> >tib ! [ [THEN] ] ; \ \ Cold Boot 13feb93py : (bootmessage) ( -- ) ." Gforth " version-string type ." , Copyright (C) 1995-2008 Free Software Foundation, Inc." cr ." Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license'" [ has? os [IF] ] cr ." Type `bye' to exit" [ [THEN] ] ; defer bootmessage ( -- ) \ gforth \G Hook (deferred word) executed right after interpreting the OS \G command-line arguments. Normally prints the Gforth startup \G message. has? file [IF] defer process-args [THEN] ' (bootmessage) IS bootmessage has? os [IF] Defer 'cold ( -- ) \ gforth tick-cold \G Hook (deferred word) for things to do right before interpreting the \G OS command-line arguments. Normally does some initializations that \G you also want to perform. ' noop IS 'cold [THEN] : cold ( -- ) \ gforth [ has? backtrace [IF] ] rp@ backtrace-rp0 ! [ [THEN] ] [ has? file [IF] ] os-cold [ [THEN] ] [ has? os [IF] ] set-encoding-fixed-width 'cold [ [THEN] ] [ has? file [IF] ] process-args loadline off [ [THEN] ] bootmessage quit ; has? new-input 0= [IF] : clear-tibstack ( -- ) [ has? glocals [IF] ] lp@ forthstart 7 cells + @ - [ [ELSE] ] [ has? os [IF] ] r0 @ forthstart 6 cells + @ - [ [ELSE] ] sp@ cell+ [ [THEN] ] [ [THEN] ] dup >tib ! tibstack ! #tib off input-start-line ; [THEN] : boot ( path n **argv argc -- ) [ has? no-userspace 0= [IF] ] main-task up! [ [THEN] ] [ has? os [IF] ] os-boot [ [THEN] ] [ has? rom [IF] ] ram-shadow dup @ dup -1 <> >r u> r> and IF ram-shadow 2@ ELSE ram-mirror ram-size THEN ram-start swap move [ [THEN] ] sp@ sp0 ! [ has? peephole [IF] ] \ only needed for greedy static superinstruction selection \ primtable prepare-peephole-table TO peeptable [ [THEN] ] [ has? new-input [IF] ] current-input off [ [THEN] ] clear-tibstack 0 0 includefilename 2! rp@ rp0 ! [ has? floating [IF] ] fp@ fp0 ! [ [THEN] ] [ has? os [IF] ] handler off ['] cold catch dup -&2049 <> if \ broken pipe? DoError cr endif [ [ELSE] ] cold [ [THEN] ] [. | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/kernel/int.fs?rev=1.165;sortby=rev;f=h;only_with_tag=v0-7-0 | CC-MAIN-2021-10 | refinedweb | 2,127 | 76.42 |
Copyright ©2003 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.
This document contains a list of requirements and desiderata for version 1.1 of XML Schema. its publication does not imply endorsement by the W3C membership..
The requirements included in this document were culled from public and member-only messages sent to the XML Schema Working Group. Each message was acknowledged. The requirements were then discussed by the Working Group and accepted requirements were classified into the three categories described in 1 Introduction.
It is the intention of the Working Group that this requirement gathering and classification should continue and that updated versions of this document should be published from time to time. This is not a Last-Call publication of this Working Draft.
This document has been produced by the W3C XML Schema Working Group as part of the W3C XML Activity. The authors of this document are the members of the XML Schema Working Group.
Patent disclosures relevant to this specification may be found on the XML Schema Working Group's patent disclosure page at.
Please report comments on this document to www-xml-schema-comments@w3.org (archive). A list of current W3C Recommendations and other technical documents can be found at.
1 Introduction
2 Structures Requirements and Desiderata
2.1 Complex Types
2.1.1 Requirements
2.1.2 Desiderata
2.1.3 Opportunistic Desiderata
2.2 Constraints and Keys
2.2.1 Requirements
2.2.2 Desiderata
2.2.3 Opportunistic Desiderata
2.3 PSVI
2.3.1 Requirements
2.3.2 Desiderata
2.4 Restrictions
2.4.1 Requirements
2.5 Structures (General)
2.5.1 Desiderata
2.5.2 Opportunistic Desiderata
2.6 Substitution Groups
2.6.1 Requirements
2.6.2 Desiderata
2.7 Wildcards
2.7.1 Requirements
2.7.2 Opportunistic Desiderata
3 Datatypes Requirements and Desiderata
3.1 Datatypes (General)
3.1.1 Requirements
3.1.2 Desiderata
3.1.3 Opportunistic Desiderata
3.2 Date and Time Types
3.2.1 Requirements
3.2.2 Desiderata
3.3 Numeric Types
3.3.1 Requirements
3.3.2 Desiderata
3.3.3 Opportunistic Desiderata
This document contains a list of requirements and desiderata for XML Schema 1.1.:
A requirement must be met in XML Schema 1.1.
A desideratum should be met in XML Schema 1.1.
An opportunistic desideratum may be met in XML Schema 1.1.
Clarify the expected processor behavior if an attribute has both use="prohibited", and a fixed value specified.
See (member-only link) .
We need to be clear where the XML Schema spec depends on component identity. We need a language to talk about identity of types, in general, and particularly with respect to anonymous types. Can an inherited type have an anonymous type? Are anonymous types that appear multiple types in a model group the same type?
See (member-only link) minutes of 10/24 telcon .
Clean up named model group syntax and component.
See .
Change the XML representation (and possibly the component structure) of local element declarations to at least allow, if not require, all particles to be references, with scope, i.e. put the local declarations directly under <complexType>
Proposal
Asir Vedamuthu (member-only link)
Provide a [schema normalized value] for all valid element infoitems, not just those of simple type, and address the question of typing the characters in mixed content.
Relax the constraint that a complex type may contain at most one attribute of type ID.
See .
Proposal
Henry Thompson. (member-only link)
The XML representation for field and selector allows an annotation, but there is no schema component to which this annotation can adhere. This inconsistency must be resolved.
See : R-46.
Resolve the issues associated with restricting types whose elements include identity constraints. Specifically, (1) the rule must changed to state that the restricted type must have a superset rather than a subset of identity constraints, (2) the term superset must be clearly defined, and (3) there must be a way to redefine identity constraints in the restricted type without causing duplicate name problems.
See : R-94.
Add the ability to define and enforce co-constraints on attribute values, or on attribute values and sub-elements. For example, if attribute a has value foo, the attribute b must have one of the values fuzz, duz, or buzz; but if attribute a has value bar, the attribute b must have one of the values car, far, or tar. Or: if attribute href occurs, the element must be empty; if it does not occur, then it must have type phrase-level-content.
See : LC-193 Response.
Key constraints to restrict which element types can be pointed to: Allow a schema author use key constaints to specify that a value (which otherwise behaves like an SGML or XML ID) is restricted to pointing at one (or more) particular element type(s)?
See (member-only link) : LC-151.
Revise the derivation of complex-type restriction so as to eliminate the problems with pointless occurrences. Currently, it eliminates some derivations that should otherwise be valid.
See : R-24.
Proposal
Microsoft proposals, item 1.2 (member-only link)
Revise the particle derivation rules so as to eliminate the problems with choice/choice rules.
See : R-42.
Remove the current rules on derivation by restriction; define legal restrictions in terms of their effect on the language, not in terms of a structural relationship between the base type and the derived type.
See (member-only link) ..
See .
Address localization concerns regarding Part 1: Structures.
See (member-only link) : LC-206.
Specify a manner in which schema documents can be included in-line in instances.
See (member-only link) : Issue 42.
Improve interaction between substitution group exclusions and disallowed substitutions in the element component.
See (member-only link) .
Allow an element declaration to be in more than one substitution group.
See (member-only link) .
Address problems with the interaction between wildcards and substitution groups. Specifically, resolve the bug where if complex type A has a wildcard, and B restricts A, then it can restrict the wildcard to a set of elements that match the wildcard. Not all elements in the substitution groups of those elements necessarily match the wildcard - so B is not a subset of A.
See (member-only link) .
The namespace constraints on wildcards must be more expressive in order to be able to express the union or intersection of any two wildcards. Specifically, it must be possible to express "any namespace except those in the following list."
See : CR-20.
Proposals
Microsoft proposals, item 1.3 (member-only link)
Asir Vedamuthu (member-only link)
Allow a wildcard to indicate that it will allow any element that conforms to a specified type.
See .
Proposal
Xan Gregg (member-only link)
Address localization concerns regarding Part 2: Datatypes.
See (member-only link) : LC-207.
Unit of length must be defined for the all primitive types, including anyURI, QName, and NOTATION.
See .
See (member-only link) .
Proposal
Dave Peterson and subsequent thread (member-only links)
Provide regular expressions or BNF productions to express (1) the valid lexical representations and (2) the canonical lexical representation of each primitive built-in type.
Proposal
Alexander Falk (member-only link).
Interaction between uniqueness and referential integrity constraints on legacy types and union types.
See : CR-50 (broken link).
XML Schema Part 1 (Structure) and XML Schema Part 2 (Datatypes) have different notions of "derived" for simple types, specifically with regard to list and union types.
See .
Proposal
Allow abstract simple types.
See : CR-47.
Proposals
Dave Peterson (member-only link)
Microsoft proposals, item 2.2 (member-only link)
Add a "URI" type that allows only a URI, not a URI reference. The current anyURI type allows a URI reference.
See .
Support for extensible enumerations such as allowed in Java.
See .
There must be a canonical representation of duration, and a process for calculating the canonical representation from any other lexical representation. Currently, a period of one day and a period of 24 hours are considered two different values in the value space. They should be considered two different lexical representations of the same value.
See (member-only link) . See also : R-170.
Proposals
Microsoft proposals, item 1.1 (member-only link)
Michael Kay (member-only link)
Address localization concerns regarding the date and time types.
See (member-only link) : LC-221.
Resolve the issue that relates to timezone normalization resulting in a time crossing over the date line.
See .
The definition of the dateTime value space does not reference a part of ISO 8601 that defines dateTime values, only lexical representations. The reference should be corrected, and the recommendation should explain or fix the fuzziness and/or gaps in the definitions referenced.
See (member-only link) .
Proposal
Dave Peterson erratum for R-120 (member-only link)
The year 0000 should be allowed in the types date, dateTime, gYear and gYearMonth.
See (member-only link) .
Proposal
Dave Peterson erratum for R-120 (member-only link)
Provide totally ordered duration types, specifically one that is expressed only in years and months, and one that is expressed only in days, hours, minutes, and seconds (ignoring leap seconds.) Possibly define other totally ordered duration types such as day/hour/minute and hour/minute/second duration.
Proposal
yearMonthDuration and dayTimeDuration as defined in XQuery and XPath Function and Operators
The canonical representation of float and double must be refined because it currently maps several lexical representations into a single legal value. Specifically, the description of the canonical representation must address (1) signed exponents, and (2) trailing zeroes in the mantissa.
See (member-only link) .
Proposal
Ashok Malhotra and subsequent thread (member-only links)
Provide a datatype which retains trailing zeroes in the lexical representation of decimal numbers.
See : CR-42.
Proposals
Dave Peterson and Mike Cowlishaw (member-only link)
Latest from Dave Peterson (member-only link)
Allow scientific notation for decimals.
See : CR-23.
Allow negative values for the fractionDigits facet.
See : CR-22. | http://www.w3.org/TR/xmlschema-11-req/ | CC-MAIN-2015-14 | refinedweb | 1,669 | 51.24 |
Hex editors routinely deal with fairly big files. Unfortunately when I tried to load big files into ours, it took forever to start.
It was actually very responsive after it got started, so the startup performance was the only problematic area.
Sample files
I prepared a bunch of files in
samples/ with various files, and selected different one in
preload.js like this:
let fs = require("fs") let { contextBridge } = require("electron") let data = fs.readFileSync(`${__dirname}/samples/1024.bin`) contextBridge.exposeInMainWorld( "api", { data } )
As our app loads all files equally, except for some logic changes depending on printable vs non-printable characters, I simply copied over our original 4kB sample required number of times to get size I wanted.
Performance measuring code
Svelte makes it fairly easy to measure when it started, and when it's done updating the DOM. The
tick callback happens once Svelte is done.
From what I've seen this is not quite when browser shows the content, but it covers most of the wait time.
import { tick } from "svelte" let t0 = performance.now() tick().then(() => { let t1 = performance.now() console.log(`Loaded ${Math.round(data.length / 1024)}kB in ${t1 - t0}ms`) })
performance.now is recommended over
Date due to potentially better accuracy.
How slow is it?
What we got right now is nowhere close to what we want (some representative rounded numbers from a few tries):
- Loaded 4kB in 180ms
- Loaded 16kB in 570ms
- Loaded 64kB in 1850ms
- Loaded 256kB in 7625ms
- Loaded 1024kB in 42135ms
Taking 42s to load 1MB file is definitely not acceptable.
What is taking all that time?
The best dataset to test performance on is one big enough to not be too affected by noise and small stuff, and one small enough that you can iterate without feeling temptation to open TikTok while you wait.
For a quick tests I used 64kB. I had some ideas what might be slow, so I tried commenting out some code. Here's what happens (some representative rounded numbers from a few tries):
- Baseline: Loaded 64kB in 1990ms
- No ASCII: Loaded 64kB in 1440ms
- No Hex: Loaded 64kB in 1130ms
- No mouseover events: Loaded 64kB in 2000ms
- Replaced
printfby
.toString(16)(which doesn't do zero padding) in Hex: Loaded 64kB in 2250ms
That gives us some idea what to do optimize, and what to leave for now.
In the next episode we'll see how far we can get optimizing the code.
As usual, all the code for the episode is here.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/taw/electron-adventures-episode-64-measuring-performance-3ph8 | CC-MAIN-2021-49 | refinedweb | 422 | 71.04 |
Drools 5.1 Expands Spring Support, Adds CXF, Camel, and JMX Monitoring
Drools 5.1 Expands Spring Support, Adds CXF, Camel, and JMX Monitoring
Join the DZone community and get the full member experience.Join For Free
How to Transform Your Business in the Digital Age: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.
Drools provides a unified, integrated platform for Workflow, Rules, and Event Processing. Each aspect of the platform is designed as a first class citizen. The five sub projects include:
- Drools Guvnor (BRMS/BPMS)
- Drools Expert (rule engine)
- Drools Flow (process/workflow)
- Drools Fusion (event processing/temporal reasoning)
- Drools Planner
Drools Intro Video
What's New?Since Drools 5.0, you've been able to configure a KnowledgeBase with an XML change-set instead of programatically. In the 5.1 API the change-set namespace is versioned, meaning the 1.0.0 xsd should be referenced.
The core additions to Drools 5.1 include JMX monitoring, expanded Spring support, Camel support, CXF support, a Session Inspection and Reporting Framework, and Knowledge Agent Incremental Change Support.
For Spring, the XSD can be found in the drools-spring jar. "" is the namespace:
<>
Drools Expert includes a differential update which has reduced memory consumption and increased scalability. Exit points have been replaced by channels and live queries are now supported.
Implementation of the BPMN 2.0 specification has expanded in Drools Flow as well as throughout the entire Drools tool chain. Drools Flow also includes a new web-based management console, pluggable variable persistence, improved process instance migration, and an installer that simplifies installation of Drools Guvnor, the Eclipse plugin, and the GWT console.
Drools Guvnor now has a cleaner appearance and adds several new features:
- Discussions
- Inbox for monitoring changes
- Bulk Importer
- Built in Selector
- Rule Templates
- Fact Constraints
- Guided editor improvements
- Working Sets
- Oryx integration for web based BPMN2 editing
For the full rundown of Drools 5.1's many new features, check out this section of the Drools Docs. }} | https://dzone.com/articles/drools-51-expands-spring | CC-MAIN-2019-09 | refinedweb | 342 | 56.05 |
Tell me, how do you deploy your code? If you still GIT pull on your servers, you are surely doing something wrong. How will you scale that process? How will you eliminate the chance of human failure? Let me help you; I really want to. Have you heard that Pinterest open sourced its awesome deployment system called Teletraan? If not, read this post. If yes, read it still, and maybe you can learn from the way we use it in production at endticket.
What is Teletraan?
It is a deployment system that consists of 3 main pieces:
- The deploy service is a Dropwizard-based Java web service that provides the core deploy support. It's actually an API, the very heart and brain of this deployment service.
- The deploy board is a Django-based web UI used to perform day-to-day deployment works. Just an amazing user interface for Teletraan.
- The deploy agent is the Python script that runs on every host and executes the deploy scripts.
Is installing it a pain? Not really; the setup is simple. But if you're using Chef as your configmanagement tool of choice, take thesesince they might prove helpful: chef-teletraan-agent, chef-teletraan.
Registering your builds
Let the following snippet speak for itself.
import requests headers = {'Content-type': 'application/json'} r = requests.post("%s/v1/builds" % teletraan_host, data=json.dumps({'name': teletraan_name, 'repo': name, 'branch': branch, 'commit': commit, 'artifactUrl': artifact_base_url + '/' + artifact_name, 'type': 'GitHub'}), headers=headers )
I've got the system all set up.What now?
Basically, you have to make your system compatible with Teletraan. You must have an aritfact repository available to store your builds, and add deploy scripts to your project. Create a directory called "teletraan" in your project root. Add the following scripts to it:
- POST_DOWNLOAD
- POST_RESTART
- PRE_DOWNLOAD
- PRE_RESTART
- RESTARTING
Although referred as Deploy Scripts, they can be written in any programming language as long as they are executable.
Sometimes, the same build artifact can be used to run different services based on different configurations. In this case, create different directories under the top-level teletraan with the deploy environment names, and put the corresponding deploy scripts under the proper environment directories separately. For example:
- teletraan/serverx/RESTARTING
- teletraan/serverx/POST_RESTART
- teletraan/servery/RESTARTING
What do these scripts do?
The host level deploy cycle looks the following way:
UNKNOWN->PRE_DOWNLOAD->[DOWNLOADING]->POST_DOWNLOAD->[STAGING]->PRE_RESTART->RESTARTING->POST_RESTART->SERVING_BUILD
Autodeploy?
You can define various environments. In our case, every successful master build ends up on the staging cluster automatically. It is powered by Teletraan’s autodeploy feature. It works nicely. Whenever Teletraan detects a new build, it gets automatically pushed to the servers.
Manual control
We don’t autodeploy the code to the production cluster. Teletraan offers a feature called "Promoting builds". Whenever a build proves to be valid at the staging cluster (some Automated end-to-end testing; and of course, manual testing is involved in the process) the developer has the ability to promote a build to production.
Oh noes!Things went wrong. Is there a way to go back?
Yes there is a way! Teletraan gives you the ability to roll back any build which happens to be failing. And this can happen instantly. Teletraan keeps a configurable numberof builds on the server of every deployed project; an actual deploy is just a symlink being changed to the new release.
Rolling deployments, oh the automation!
Deploy scripts should always run flawlessly. But let's say they do actually fail. What happens then? You can define it. There are three policies in Teletraan:
- Continue with the deployment.Move on to the next host as ifnothing happened.
- Roll back everything to the previous version. Make sure everything is fine; it's more important than a hasty release.
- Remove the failing node from production. We have enough capacity left anyway, so let's just cut off the dead branches!
This gives you all the flexibility and security you need when deploying your code to any HA environment.
Artifacts?
Teletraan just aims to be a deployment system, and nothing more. And it does its purpose amazingly well. You just have to notify it about builds. Also you just have to make sure that your tarballs are available to every node where deploy agents are running.
Lessons learned from integrating Teletraan into our workflow
It was acutally a pretty good experience even when I was fiddling with the Chef part. We use Drone as our CI server, and there was no plugin available for Drone, so thathad to be done also. Teletraan is a new kid on the block, so you might have to write some lines of code to make it apart of your existing pipeline. But I think that if you're willing to spend a day or two on integrating it, it will pay off for you.
About the author
BálintCsergő is a software engineer from Budapest, currently working as an infrastructure engineer at Hortonworks. He loves Unix systems, PHP, Python, Ruby, the Oracle database, Arduino, Java, C#, music, and beer. | https://www.packtpub.com/books/content/deployment-done-right-teletraan | CC-MAIN-2017-17 | refinedweb | 842 | 67.55 |
okay so i am working on this very basic game to help cement some programming information i going over into my brain. i can't figure out what is wrong with my loop.
the code gets to the while loop and the gets stuck.. anyone know whats going on?
thanks in advance!thanks in advance!Code:#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]){ int GameEnd =0; int Option; int RockysPow =3; int ApollosPow =10; cout<<"Welcome to Rockys Punch Out Adventure!\n" "created by sean wilson.\n"; system("PAUSE"); while (GameEnd != 1);{ cout<<"would your like to..\n"; cout<< "1: train to fight\n"; cout<< "2: take on Apollo Creed\n"; cin>> Option; if (Option == 1){ RockysPow++; cout<<RockysPow; } else {if (Option == 2){cout<<"option 2\n";} else {cout<< Option <<" is not a valid entry.";} } } system("PAUSE"); return EXIT_SUCCESS; } | http://cboard.cprogramming.com/cplusplus-programming/110615-loop-not-initializing.html | CC-MAIN-2014-35 | refinedweb | 145 | 77.64 |
Ian Lynagh wondered: | is there a nicer way to do something like | | #ifdef __GLASGOW_HASKELL__ | #include "GHCCode.hs" | #else | > import HugsCode | #endif I usually make two directories: Hugs/ Ghc/ That contain files with the same names but different compiler-dependent implementations. Then it is just a question of setting the PATHs right. I hate using C preprocessor stuff for this. I think the directory solution is nice because it forces you to concentrate all the compiler-dependent stuff into a few modules, which are distinct from the rest of the implementation. /Koen. -- Koen Claessen phone:+46-31-772 5424 mailto:koen@cs.chalmers.se ----------------------------------------------------- Chalmers University of Technology, Gothenburg, Sweden | http://www.haskell.org/pipermail/haskell-cafe/2001-February/001498.html | CC-MAIN-2014-42 | refinedweb | 109 | 57.16 |
Kate
#include <katetemplatehandler.h>
Detailed Description
Inserts a template and offers advanced snippet features, like navigation and mirroring.
For each template inserted a new KateTemplateHandler will be created.
The handler has the following features:
- It inserts the template string into the document at the requested position.
- When the template contains at least one variable, the cursor will be placed at the start of the first variable and its range gets selected.
- When more than one variable exists,TAB and SHIFT TAB can be used to navigate to the next/previous variable.
- When a variable occurs more than once in the template, edits to any of the occurrences will be mirroed to the other ones.
- When ESC is pressed, the template handler closes.
- When ALT + RETURN is pressed and a
%{cursor}variable exists in the template,the cursor will be placed there. Else the cursor will be placed at the end of the template.
- See also
- KateDocument::insertTemplateTextImplementation(), KTextEditor::TemplateInterface
Definition at line 73 of file katetemplatehandler.h.
Constructor & Destructor Documentation
Setup the template handler, insert the template string.
NOTE: The handler deletes itself when required, you do not need to keep track of it.
we always need a view
TODO: maybe use Kate::CutCopyPasteEdit or similar?
bail out if we can't insert text
now there must be a range
TODO: maybe support delayed actions, i.e.:
- create doc
- insert template
- create view => ranges are added for now simply "just insert" the code when we have no active view
Definition at line 60 of file katetemplatehandler.cpp.
Cancels the template handler and cleans everything up.
Definition at line 175 of file katetemplatehandler.cpp.
Member Function Documentation
Provide keyboard interaction for the template handler.
The event filter handles the following shortcuts:
TAB: jump to next editable (i.e. not mirrored) range. NOTE: this prevents indenting via TAB. SHIFT + TAB: jump to previous editable (i.e. not mirrored) range. NOTE: this prevents un-indenting via SHIFT + TAB. ESC: terminate template handler (only when no completion is active). ALT + RETURN: accept template and jump to the end-cursor. if %{cursor} was given in the template, that will be the end-cursor. else just jump to the end of the inserted text.
Reimplemented from QObject.
Definition at line 263 of file katetemplatehandler.cpp.
Definition at line 1018 of file katetemplatehandler.cpp.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2020 The KDE developers.
Generated on Wed May 20 2020 22:13:03 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/4.14-api/applications-apidocs/kate/part/html/classKateTemplateHandler.html | CC-MAIN-2020-24 | refinedweb | 433 | 59.7 |
MicroPlode – Implementing the first Microservice
11/30/15
Content
Context: Where am I here and why is it so dark :-)?
Getting started: Setting up a new project for our first Microservice implementation.
Message for you: Doing the hard things first.
Conclusion and Outlook: Some thoughts on the progress of the project and how to continue.
Context
If you are wondering what is going on here you probably missed the first blog post in this series. I could sum up things here, but I believe it makes more sense to read that first blog post to really understand the idea of this.
After doing this – and hopefully there is still interest to continue 🙂 – we are getting started right away.
Getting started
One good thing I understood from Microservices so far is that I am quite free in choosing my technology stack. Of course all Microservices that are forming the application must support the underlying communication platform and must be deployable to the target system. Here this means support for the used messaging platform and executable under Linux/Mac OS/Windows. Apart from that everything else regarding used technologies would be up to me (the team so to say :-)). This would include the programming language and the used IDE as well as the used build system. Somehow that sounds and is pretty cool. Even though some colleagues already made fun on me that I will probably do the whole thing in Perl. Of course this would be tempting, but I decided to go for Spring Boot.
And how cool is this I have to say. It is really good to every now and then stick the head out of the ongoing-project-world-window so to say and see what has happended outside in the meantime. It took me roughly 5 minutes (and this is no exaggeration) to setup the project using Spring Initializer. This way it was also really straightforward to implement a first Web Service.
Building the whole thing with Maven creates an executable JAR that can be started right away … as the first Microservice.
That is really pretty amazing. Now what I would like to have is a simple WebService to trigger some action in the whole application. Later on these WebService calls will probably be triggered by the frontend. But of course it is also a nice and easy way to start playing around with the application and potentially do some automated tests later on. The class implementing the WebService is really straightforward.
package de.codecentric.microplode.controller; import de.codecentric.microplode.messaging.MessageSender; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/trigger-action") public class TriggerActionController { @Autowired private MessageSender messageSender; @RequestMapping(method=RequestMethod.GET) public @ResponseBody String triggerAction() throws Exception{ messageSender.sendMessage("Trigger Action"); return "TriggerAction Called"; } }
One can see already here that a MessageSender class is injected and used to obviously send a message :-). More on the messaging is soon to come, but in general to follow the progress of this project also later on I am doing GIT tags with every “milestone” reached. Currently this means with every new blogpost :-).
Game Service Repository (1.0.0)
Playing Field Service Repository (1.0.0)
Computer Player Service Repository (1.0.0)
Documentation Repository (1.0.0)
It is really not a lot of code yet, but nevertheless it contains a WebService to trigger sending a message in the GameService. This message is then received in both – the PlayingFieldService and the ComputerPlayerService – microservices. The documentation-repository is intended to serve as a minimal documentation which I think is even useful if working on the project alone. But luckily a codecentric colleague of mine (hello Jonas :-)) is right now joining the project. Beside the fact that it is more fun, this way we can of course better judge the impact of using Microservices on working on an application in a team.
Message for you
As this is a playground project we are using messaging no matter if that is really 100% required or not. Probably we could survive as well using synchronous REST calls for example. But as said earlier I want to see where this whole messaging solution leads us and thus gain some insight in advantages and potential problems using messaging.
In the first post of this series I was still thinking to use Kafka as the messaging platform for this project. For me it turned out – after some further evaluation – that this is too complicated for this project or – more probably – my understanding of it is too limited. Thus I switched to RabbitMQ. This has been working like a charm from the very beginning. My proof-of-concept implementation is thereby mainly based on the following Spring tutorial:
Starting with the messaging for me is a quite natural thing to do as the motto is “doing the hard things first”. And of course getting the messaging straight is important as this is the foundation to enable the communication between the individual services. Maybe for someone who has done half a dozen projects in this setup it will no longer be a big deal, but I think currently this is not really a mainstream approach to do things yet.
Switching to the technical aspects using RabbitMQ things have become really straightforward. Installation on Windows is simply done with an installer. Only thing is that you need to install Erlang first. Afterwards the RabbitMQ server can simply be started as an executable which I found a bit more straightforward than what was needed for Kafka. Of course I cannot judge at all any other technical advantages/disadvantages of the two systems, but in ease of use RabbitMQ simply made it for me.
The above figure is a slightly updated version of the one shown in the first blog post of this series. Not too much has changed beside the fact that the PlayerService is now the ComputerPlayerService and also REST calls and the used messaging platform are integrated into the figure. The code for sending/receiving a message can be seen from the GIT repositories linked earlier. Probably the only special thing to mention is the use of the Fanout Exchange to be able to send the same message to different queues and thus to different consumers. For sure we will also check out Topic Exchange for this in the near future, but for the time being this is a solution that seems to work good enough for our requirements.
Conclusion and Outlook
This series of blog posts is driven by two major ideas:
- Gaining first hand experiences with technologies used in a Microservices ecosystem.
- But for sure as important getting a “feeling” what it means to work on Microservices instead of a monolithic application.
The first part has been covered by using SpringBoot to create individual services and by implementing a first solution for the messaging infrastructure. The second part is gaining more momentum now that a colleague has joined the project as mentioned above.
Of course the whole application is not too complicated, but splitting up responsibilities, now that Jonas is joining the project, was really easy. Jonas is simply taking over the development of the GameService microservice. We only needed to share a bit of documentation to get this started, like how to identify fields on the board and how to identify players in messages. Furthermore at least for the time being all communication to the – or better a potential – frontend is encapsulated in that service. So Probably I will implement some hook to trigger certain actions on “my” microservices, but otherwise we are totally seperated. We are not even sharing the popular “commons” project. Our interfaces are defined by the queue names and the format of the JSON strings and I would really not mind (nor notice until I look into the code) if that GameService gets now rewritten from scratch in Python as an example.
What is the downside to this approach then? When talking about the board there will be a need to repeat the implementation for the representation of that board in different services for sure. Especially as handling the board will be one of the more complex parts of the application. But then again the complexity will differ probably between different services. The same is true for storing player information. Parts of those will be duplicated to the different services and must be kept there.
Nevertheless currently I think this duplication of data might also be a chance. How often have you ended up in a project with overly complex “domain objects” that might be hard to change and maintain in the end. The important thing is of course that there is always one service that has the final responsibility on certain data. For the board this obviously is the PlayingFieldService and for the players it is the GameService.
What next then? I say a first working version where two human players can play against each other. Of course everything without a GUI, but playable by doing the corresponding REST calls to start a new game and to make a move. The current state can then be printed out for debugging purposes anyway and basically that is all that is required (beside some minor things like calculating the explosions and detecting game-ended-situations :-)). That is a plan!
So the next blog post will hopefully show that result and will be written as some kind of dialogue between Jonas and me sharing our experiences and learnings from working in a Microservices project setup.
Comment | https://blog.codecentric.de/en/2015/11/microplode-implementing-the-first-microservice/ | CC-MAIN-2017-17 | refinedweb | 1,612 | 54.32 |
W. Richard Stevens, Bill Fenner, Andrew M. Rudoff
Mentioned 53
* .:
Tornadoweb and Nginx are popular web servers for the moment and many benchmarkings show that they have a better performance than Apache under certain circumstances. So my question is:
Is 'epoll' the most essential reason that make them so fast? And what can I learn from that if I want to write a good socket server?
If you're looking to write a socket server, a good starting point is Dan Kegel's C10k article from a few years back:
I also found Beej's Guide to Network Programming to be pretty handy:
Finally, if you need a great reference, there's UNIX Network Programming by W. Richard Stevens et. al.:
Anyway, to answer your question, the main difference between Apache and Nginx is that Apache uses one thread per client with blocking I/O, whereas Nginx is single-threaded with non-blocking I/O. Apache's worker pool does reduce the overhead of starting and destorying processes, but it still makes the CPU switch between several threads when serving multiple clients. Nginx, on the other hand, handles all requests in one thread. When one request needs to make a network request (say, to a backend), Nginx attaches a callback to the backend request and then works on another active client request. In practice, this means it returns to the event loop (
epoll,
kqueue, or
select) and asks for file descriptors that have something to report. Note that the system call in main event loop is actually a blocking operation, because there's nothing to do until one of the file descriptors is ready for reading or writing.
So that's the main reason Nginx and Tornado are efficient at serving many simultaneous clients: there's only ever one process (thus saving RAM) and only one thread (thus saving CPU from context switches). As for epoll, it's just a more efficient version of select. If there are N open file descriptors (sockets), it lets you pick out the ones ready for reading in O(1) instead of O(N) time. In fact, Nginx can use select instead of epoll if you compile it with the
--with-select_module option, and I bet it will still be more efficient than Apache. I'm not as familiar with Apache internals, but a quick grep shows it does use select and epoll -- probably when the server is listening to multiple ports/interfaces, or if it does simultaneous backend requests for a single client.
Incidentally, I got started with this stuff trying to write a basic socket server and wanted to figure out how Nginx was so freaking efficient. After poring through the Nginx source code and reading those guides/books I linked to above, I discovered it'd be easier to write Nginx modules instead of my own server. Thus was born the now-semi-legendary Emiller's Guide to Nginx Module Development:
(Warning: the Guide was written against Nginx 0.5-0.6 and APIs may have changed.) If you're doing anything with HTTP, I'd say give Nginx a shot because it's worked out all the hairy details of dealing with stupid clients. For example, the small socket server that I wrote for fun worked great with all clients -- except Safari, and I never figured out why. Even for other protocols, Nginx might be the right way to go; the eventing is pretty well abstracted from the protocols, which is why it can proxy HTTP as well as IMAP. The Nginx code base is extremely well-organized and very well-written, with one exception that bears mentioning. I wouldn't follow its lead when it comes to hand-rolling a protocol parser; instead, use a parser generator. I've written some stuff about using a parser generator (Ragel) with Nginx here:
All of this was probably more information than you wanted, but hopefully you'll find some of it useful.
I will do a few small projects over the next few months and need some books (preferably) or URLs to learn some basic concepts.
In general one PC or embedded device (which varies by project) collects some user input or data from an external hardware device and transmits it to a remote PC which will enter it into a database.
The back-end will be coded in Delphi using Indy socket components. The front-end might be a PC running a Delphi app using the same Indy sockets, but it might equally be a small controller board, probably programmed in C (with neither Windows nor Linux as an o/s, but with some unforeseeable socket support).
So, what I need is
Any recommendations to get me up to speed, at least enough for a small project which would allow me to learn on the job.
Thanks in advance
Out of online resources, Beej's Guide to Network Programming tops the list.
On most UNIX systems passing an open file between processes can be easily done for child/parent processes by fork(); however I need to share a fd "after" the child was already forked.
I've found some webpages telling me that sendmsg() may work for arbitary processes; but that seems very OS dependent and complex. The portlisten seems like the best example I can find, but I'd prefer a good wrapper library like libevent that hides all the magic of kqueue, pool, ....
Does anyone know if there's some library (and portable way) to do this?
There is a Unix domain socket-based mechanism for transferring file descriptors (such as sockets - which cannot be memory mapped, of course) between processes - using the
sendmsg() system call.
You can find more in Stevens (as mentioned by Curt Sampson), and also at Wikipedia.
You can find a much more recent question with working code at Sending file descriptor by Linux socket.
Over the years I've developed a small mass of C++ server/client applications for Windows using WinSock (Routers, Web/Mail/FTP Servers, etc... etc...).
I’m starting to think more and more of creating an IPv6 version of these applications (While maintaining the original IPv4 version as well, of course).
Questions:
For a reference (or for fun), you can sneek a peak of the IPv4 code at the core of my applications.
Ulrich Drepper, the maintainer of glibc, has a good article on the topic,
But don't forget Richard Steven's book, Unix Network Programming, Volume 1: The Sockets Networking API for good practice.
Think MUDs/MUCKs but maybe with avatars or locale illustrations. My language of choice is ruby.
I need to handle multiple persistent connections with data being asynchronously transferred between the server and its various clients. A single database must be kept up-to-date based on activity occurring in the client sessions. Activity in each client session may require multiple other clients to be immediately updated (a user enters a room; a user sends another user a private message).
This is a goal project and a learning project, so my intention is to re-invent a wheel or two to learn more about concurrent network programming. However, I am new to both concurrent and network programming; previously I have worked almost exclusively in the world of non-persistent, synchronous HTTP requests in web apps. So, I want to make sure that I'm reinventing the right wheels.
Per emboss's excellent answer, I have been starting to look at the internals of certain HTTP servers, since web apps can usually avoid threading concerns due to how thoroughly the issue is abstracted away by the servers themselves.
I do not want to use EventMachine or GServer because I don't yet understand what they do. Once I have a general sense of how they work, what problems they solve and why they're useful, I'll feel comfortable with it. My goal here is not "write a game", but "write a game and learn how some of the lower-level stuff works". I'm also unclear on the boundaries of certain terms; for example, is "I/O-unbound apps" a superset of "event-driven apps"? Vice-versa?
I am of course interested in the One Right Way to achieve my goal, if it exists, but overall I want to understand why it's the right way and why other ways are less preferable.
Any books, ebooks, online resources, sample projects or other tidbits you can suggest are what I'm really after.
The way I am doing things right now is by using
IO#select to block on the list of connected sockets, with a timeout of 0.1 seconds. It pushes any information read into a thread-safe read queue, and then whenever it hits the timeout, it pulls data from a thread-safe write queue. I'm not sure if the timeout should be shorter. There is a second thread which polls the socket-handling thread's read queue and processes the "requests". This is better than how I had it working initially, but still might not be ideal.
I posted this question on Hacker News and got linked to a few resources that I'm working through; anything similar would be great:
Although you probably don't like to hear it I would still recommend to start investigating HTTP servers first. Although programming for them seemed boring, synchronous, and non-persistent to you, that's only because the creators of the servers did their job to hide the gory details from you so tremendously well - if you think about it, a web server is so not synchronous (it's not that millions of people have to wait for reading this post until you are done... concurrency :) ... and because these beasts do their job so well (yeah, I know we yell at them a lot, but at the end of the day most HTTP servers are outstanding pieces of software) this is the definite starting point to look into if you want to learn about efficient multi-threading. Operating systems and implementations of programming languages or games are another good source, but maybe a bit further away from what you intend to achieve.
If you really intend to get your fingers dirty I would suggest to orient yourself at something like WEBrick first - it ships with Ruby and is entirely implemented in Ruby, so you will learn all about Ruby threading concepts there. But be warned, you'll never get close to the performance of a Rack solution that sits on top of a web server that's implemented in C such as thin.
So if you really want to be serious, you would have to roll your own server implementation in C(++) and probably make it support Rack, if you intend to support HTTP. Quite a task I would say, especially if you want your end result to be competitive. C code can be blazingly fast, but it's all to easy to be blazingly slow as well, it lies in the nature of low-level stuff. And we haven't discussed memory management and security yet. But if it's really your desire, go for it, but I would first dig into well-known server implementations to get inspiration. See how they work with threads (pooling) and how they implement 'sessions' (you wanted persistence). All the things you desire can be done with HTTP, even better when used with a clever REST interface, existing applications that support all the features you mentioned are living proof for that. So going in that direction would be not entirely wrong.
If you still want to invent your own proprietary protocol, base it on TCP/IP as the lowest acceptable common denominator. Going beyond that would end up in a project that your grand-children would probably still be coding on. That's really as low as I would dare to go when it comes to network programming.
Whether you are using it as a library or not, look into EventMachine and its conceptual model. Overlooking event-driven ('non-blocking') IO in your journey would be negligent in the context of learning about/reinventing the right wheels. An appetizer for event-driven programming explaining the benefits of node.js as a web server.
Based on your requirements: asynchronous communication, multiple "subscribers" reacting to "events" that are centrally published; well that really sounds like a good candidate for an event-driven/message-based architecture.
Some books that may be helpful on your journey (Linux/C only, but the concepts are universal):
(Those were the classics)
Projects you may want to check out:
Are there any libraries or guides for how to read and parse binary data in C?
I am looking at some functionality that will receive TCP packets on a network socket and then parse that binary data according to a specification, turning the information into a more useable form by the code.
Are there any libraries out there that do this, or even a primer on performing this type of thing?
The standard way to do this in C/C++ is really casting to structs as 'gwaredd' suggested
It is not as unsafe as one would think. You first cast to the struct that you expected, as in his/her example, then you test that struct for validity. You have to test for max/min values, termination sequences, etc.
What ever platform you are on you must read Unix Network Programming, Volume 1: The Sockets Networking API. Buy it, borrow it, steal it ( the victim will understand, it's like stealing food or something... ), but do read it.
After reading the Stevens, most of this will make a lot more sense.
Basically suggestions about casting to
struct work but please be aware that numbers can be represented differently on different architectures.
To deal with endian issues network byte order was introduced - common practice is to convert numbers from host byte order to network byte order before sending the data and to convert back to host order on receipt. See functions
htonl,
htons,
ntohl and
ntohs.
And really consider kervin's advice - read UNP. You won't regret it!
I'm a beginning C++ programmer / network admin, but I figure I can learn how to do this if someone points me in the right direction. Most of the tutorials are demonstrated using old code that no longer works for some reason.
Since I'm on Linux, all I need is an explanation on how to write raw Berkeley sockets. Can someone give me a quick run down?
Read Unix Network Programming by Richard Stevens. It's a must. It explains how it all works, gives you code, and even gives you helper methods. You might want to check out some of his other books. Advanced Programming In The Unix Enviernment is a must for lower level programming in Unix is general. I don't even do stuff on the Unix stack anymore, and the stuf from these books still helps how I code.
For TCP client side:
Use gethostbyname to lookup dns name to IP, it will return a hostent structure. Let's call this returned value host.
hostent *host = gethostbyname(HOSTNAME_CSTR);
Fill the socket address structure:
sockaddr_in sock; sock.sin_family = AF_INET; sock.sin_port = htons(REMOTE_PORT); sock.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
Create a socket and call connect:
s = socket(AF_INET, SOCK_STREAM, 0); connect(s, (struct sockaddr *)&sock, sizeof(sock))
For TCP server side:
Setup a socket
Bind your address to that socket using bind.
Start listening on that socket with listen
Call accept to get a connected client. <-- at this point you spawn a new thread to handle the connection while you make another call to accept to get the next connected client.
General communication:
Use send and recv to read and write between the client and server.
Source code example of BSD sockets:
You can find some good example code of this at wikipedia.
Further reading:
I highly recommend this book and this online tutorial:
I want to create an extremely simple iPhone program that will open a telnet session on a lan-connected device and send a sequence of keystrokes. Most of the code I've seen for sockets is overwhelming and vast overkill for what I want to do:
Any simple code examples out there I can play with?
What are Async Sockets? How are they different from normal sockets (Blocking and Non-Blocking)?
Any pointers in that direction or any links to tutorials will be helpful.
Thanks.
Comparison of the following five different models for I/O in UNIX Network Programming: The sockets networking API would be helpful:
Blocking
Nonblocking
I/O multiplexing
Signal-driven I/O
Asynchronous I/O
I'm just cleaning up some code we wrote a while back and noticed that for a udp socket, 0 is being treated as the connection closed.
I'm quite sure this was the result of porting the same recv loop from the equivalent tcp version. But it makes me wonder. Can recv return 0 for udp? on tcp it signals the other end has closed the connection. udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning?
Note: the man page in linux does not distinguish udp and tcp for a return code of zero which may be why we kept the check in the code.
udp doesn't have the concept of a connection so can it return 0? and if it can, what is it's meaning
It means a 0-length datagram was received. From the great UNP:
Writing a datagram of length 0 is acceptable. In the case of UDP, this results in an IP datagram containing an IP header (normally 20 bytes for IPv4 and 40 bytes for IPv6), an 8-byte UDP header, and no data. This also means that a return value of 0 from recvfrom is acceptable for a datagram protocol: It does not mean that the peer has closed the connection, as does a return value of 0 from read on a TCP socket. Since UDP is connectionless, there is no such thing as closing a UDP connection.
I am trying to send some file descriptor by linux socket, but it does not work. What am I doing wrong? How is one supposed to debug something like this? I tried putting perror() everywhere it's possible, but they claimed that everything is ok. Here is what I've written:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/types.h> #include <fcntl.h> void wyslij(int socket, int fd) // send fd by socket { struct msghdr msg = {0}; char buf[CMSG_SPACE(sizeof fd)];; // why does example from man need it? isn't it redundant? sendmsg(socket, &msg, 0); } int odbierz(int socket) // receive fd from socket { struct msghdr msg = {0}; recvmsg(socket, &msg, 0); struct cmsghdr * cmsg = CMSG_FIRSTHDR(&msg); unsigned char * data = CMSG_DATA(cmsg); int fd = *((int*) data); // here program stops, probably with segfault return fd; } int main() { int sv[2]; socketpair(AF_UNIX, SOCK_DGRAM, 0, sv); int pid = fork(); if (pid > 0) // in parent { close(sv[1]); int sock = sv[0]; int fd = open("./z7.c", O_RDONLY); wyslij(sock, fd); close(fd); } else // in child { close(sv[0]); int sock = sv[1]; sleep(0.5); int fd = odbierz(sock); } }
Stevens (et al) UNIX® Network Programming, Vol 1: The Sockets Networking API describes the process of transferring file descriptors between processes in Chapter 15 Unix Domain Protocols and specifically §15.7 Passing Descriptors. It's fiddly to describe in full, but it must be done on a Unix domain socket (
AF_UNIX or
AF_LOCAL), and the sender process uses
sendmsg() while the receiver uses
recvmsg().
I got this mildly modified (and instrumented) version of the code from the question to work for me on Mac OS X 10.10.1 Yosemite with GCC 4.9.1:
)); struct iovec io = { .iov_base = "ABC", .iov_len = 3 };; if (sendmsg(socket, &msg, 0) < 0) err_syserr("Failed to send message\n"); } static int odbierz(int socket) // receive fd from socket { struct msghdr msg = {0}; char m_buffer[256];); unsigned char * data = CMSG_DATA(cmsg); err_remark("About to extract fd\n"); int fd = *((int*) data);; }
The output from the instrumented but unfixed version of the original code was:
$ ./fd-passing fd-passing: pid=1391: Parent at work fd-passing: pid=1391: Failed to send message error (40) Message too long fd-passing: pid=1392: Child at play $ fd-passing: pid=1392: Failed to receive message error (40) Message too long
Note that the parent finished before the child, so the prompt appeared in the middle of the output.
The output from the 'fixed' code was:
$ ./fd-passing fd-passing: pid=1046: Parent at work fd-passing: pid=1048: Child at play fd-passing: pid=1048: About to extract fd fd-passing: pid=1048: Extracted fd 3 Read 3! This is the file z7.c. It isn't very interesting. It isn't even C code. But it is used by the fd-passing program to demonstrate that file descriptors can indeed be passed between sockets on occasion. Done! fd-passing: pid=1046: Parent exits $
The primary significant changes were adding the
struct iovec to the data in the
struct msghdr in both functions, and providing space in the receive function (
odbierz()) for the control message. I reported an intermediate step in debugging where I provided the
struct iovec to the parent and the parent's "message too long" error was removed. To prove it was working (a file descriptor was passed), I added code to read and print the file from the passed file descriptor. The original code had
sleep(0.5) but since
sleep() takes an unsigned integer, this was equivalent to not sleeping. I used C99 compound literals to have the child sleep for 0.5 seconds. The parent sleeps for 1.5 seconds so that the output from the child is complete before the parent exits. I could use
wait() or
waitpid() too, but was too lazy to do so.
I have not gone back and checked that all the additions were necessary.
The
"stderr.h" header declares the
err_*() functions. It's code I wrote (first version before 1987) to report errors succinctly. The
err_setlogopts(ERR_PID) call prefixes all messages with the PID. For timestamps too,
err_setlogopts(ERR_PID|ERR_STAMP) would do the job.
Nominal Animal suggests in a comment:
May I suggest you modify the code to copy the descriptor
intusing
memcpy()instead of accessing the data directly? It is not necessarily correctly aligned — which is why the man page example also uses
memcpy()— and there are many Linux architectures where unaligned
intaccess causes problems (up to SIGBUS signal killing the process).
And not only Linux architectures: both SPARC and Power require aligned data and often run Solaris and AIX respectively. Once upon a time, DEC Alpha required that too, but they're seldom seen in the field these days.
The code in the manual page
cmsg(3) related to this is:;
The assignment to
fdptr appears to assume that
CMSG_DATA(cmsg) is sufficiently well aligned to be converted to an
int * and the
memcpy() is used on the assumption that
NUM_FD is not just 1. With that said, it is supposed to be pointing at the array
buf, and that might not be sufficiently well aligned as Nominal Animal suggests, so it seems to me that the
fdptr is just an interloper and it would be better if the example used:
memcpy(CMSG_DATA(cmsg), myfds, NUM_FD * sizeof(int));
And the reverse process on the receiving end would then be appropriate. This program only passes a single file descriptor, so the code is modifiable to:
memmove(CMSG_DATA(cmsg), &fd, sizeof(fd)); // Send memmove(&fd, CMSG_DATA(cmsg), sizeof(fd)); // Receive
I also seem to recall historical issues on various OSes w.r.t. ancillary data with no normal payload data, avoided by sending at least one dummy byte too, but I cannot find any references to verify, so I might remember wrong.
Given that Mac OS X (which has a Darwin/BSD basis) requires at least one
struct iovec, even if that describes a zero-length message, I'm willing to believe that the code shown above, which includes a 3-byte message, is a good step in the right general direction. The message should perhaps be a single null byte instead of 3 letters.
I've revised the code to read as shown below. It uses
memmove() to copy the file descriptor to and from the
cmsg buffer. It transfers a single message byte, which is a null byte.
It also has the parent process read (up to) 32 bytes of the file before passing the file descriptor to the child. The child continues reading where the parent left off. This demonstrates that the file descriptor transferred includes the file offset.
The receiver should do more validation on the
cmsg before treating it as a file descriptor passing message.
)); /* On Mac OS X, the struct iovec is needed, even if it points to minimal data */ struct iovec io = { .iov_base = "", .iov_len = 1 };)); memmove(CMSG_DATA(cmsg), &fd, sizeof(fd)); msg.msg_controllen = cmsg->cmsg_len; if (sendmsg(socket, &msg, 0) < 0) err_syserr("Failed to send message\n"); } static int odbierz(int socket) // receive fd from socket { struct msghdr msg = {0}; /* On Mac OS X, the struct iovec is needed, even if it points to minimal data */ char m_buffer[1];); err_remark("About to extract fd\n"); int fd; memmove(&fd, CMSG_DATA(cmsg), sizeof(fd));); /* Read some data to demonstrate that file offset is passed */ char buffer[32]; int nbytes = read(fd, buffer, sizeof(buffer)); if (nbytes > 0) err_remark("Parent read: [[%.*s]]\n", nbytes, buffer);; }
And a sample run:
$ ./fd-passing fd-passing: pid=8000: Parent at work fd-passing: pid=8000: Parent read: [[This is the file z7.c. It isn't ]] fd-passing: pid=8001: Child at play fd-passing: pid=8001: About to extract fd fd-passing: pid=8001: Extracted fd 3 Read 3! very interesting. It isn't even C code. But it is used by the fd-passing program to demonstrate that file descriptors can indeed be passed between sockets on occasion. And, with the fully working code, it does indeed seem to work. Extended testing would have the parent code read part of the file, and then demonstrate that the child codecontinues where the parent left off. That has not been coded, though. Done! fd-passing: pid=8000: Parent exits $
I recently started attending two classes in school that focus on networking, one regarding distributed systems and another regarding computer networks in general. After completing the first labs for the two classes, I now have a pretty good understand of network protocol and socket concepts with both C and Java.
Now I'm trying to move beyond the basic concepts and become better at communication class and object design, network design patterns, intermediate socket/stream management conventions, important libraries, and general *nix network programming intermediate techniques in either C or OO languages.
Can you suggest any resources that you've had success with?
Unix network programming by Richard Stevens is a must-have book which discusses many advanced network programming techniques. I've been doing network programming for years, and even now hardly a day goes by without me looking up something in this great reference.
Steven's Know it all book about Network Programming is too detailed to start with and contains library to encapsulate the real socket programming.
I would recommend to start with the Beej's Guide to Network Programing and then move to the TCP/IP Sockets in C. They give a a lot good basics about the network programming and provide a platform to finally go through the Stevens book.
Stevens others books like TCP/IP illustrated series covers all the conceptual part of networks.
I learned network programming from the Linux Socket Programming By Example book by Warren W. Gray.):
How to migrate to *nix platform after spending more than 10 years on windows? Which flavor will be easy to handle to make me more comfortable and then maybe I can switch over to more stadard *nix flavors? I have been postponing for a while now. Help me with the extra push.
Linux is the most accessible and has the most mature desktop functionality. BSD (in its various flavours) has less userspace baggage and would be easier to understand at a fundamental level. In this regard it is more like a traditional Unix than a modern Linux distribution. Some might view this as a good thing (and from certain perspectives it is) but will be more alien to someone familiar with Windows.
The main desktop distributions are Ubuntu and Fedora. These are both capable systems but differ somewhat in their userspace architecture The tooling for the desktop environment and default configuration for system security works a bit differently on Ubuntu than it does on most other Linux or Unix flavours but this is of little relevance to development. From a user perspective either of these would be a good start.
From a the perspective of a developer, all modern flavours of Unix and Linux are very similar and share essentially the same developer tool chain. If you want to learn about the system from a programmer's perspective there is relatively little to choose.
Most unix programming can be accomplished quite effectively with a programmer's editor such as vim or emacs, both of which come in text mode and windowing flavours. These editors are very powerful and have rather quirky user interfaces - the user interfaces are ususual but contribute significantly to the power of the tools. If you are not comfortable with these tools, this posting discusses several other editors that offer a user experience closer to common Windows tooling.
There are several IDEs such as Eclipse that might be of more interest to someone coming off Windows/Visual Studio.
Some postings on Stackoverflow that discuss linux/unix resources are:
What are good linux-unix books for an advancing user
What are some good resources for learning C beyond K&R
Resources for learning C program design
If you have the time and want to do a real tour of the nuts and bolts Linux From Scratch is a tutorial that goes through building a linux installation by hand. This is quite a good way to learn in depth.
For programming, get a feel for C/unix from K&R and some of the resources mentioned in the questions linked above. The equivalent of Petzold, Prosise and Richter in the Unix world are W Richard Stevens' Advanced Programming in the Unix Environment and Unix Network Programming vol. 1 and 2.
Learning one of the dynamic languages such as Perl or Python if you are not already familiar with these is also a useful thing to do. As a bonus you can get good Windows ports of both the above from Activestate which means that these skills are useful on both platforms.
If you're into C++ take a look at QT. This is arguably the best cross-platform GUI toolkit on the market and (again) has the benefit of a skill set and tool chain that is transferrable back into Windows. There are also several good books on the subject and (as a bonus) it also works well with Python.
Finally, Cygwin is a unix emulation layer that runs on Windows and gives substantially unix-like environment. Architecturally, Cygwin is a port of glibc and the crt (the GNU tool chain's base libraries) as an adaptor on top of Win32. This emulation layer makes it easy to port unix/linux apps onto Cygwin. The platform comes with a pretty complete set of software - essentially a full linux distribution hosted on a Windows kernel. It allows you to work in a unix-like way on Windows without having to maintain a separate operating system installations. If you don't want to run VMs, multiple boots or multiple PCs it may be a way of easing into unix.
I was just thrust into Linux programming (Red Hat) after several years of C++ on Win32. So I am not looking for the basics of programming. Rather I am looking to get up to speed with things unique to the Linux programming world, such as packages, etc. In other words, I need to know everything in without spending 3K. Any ideas of how I can acquire that knowledge quickly (and relatively cheaply)?
Update: The things that I am used to doing on Windows like building .exe and dlls using VC++, creating install scripts etc are just done differently on Linux. They use things like yum, make and make install, etc. Things like dependency walker that I take for granted in the windows world constantly send me to google while doing linux. Is there a 'set' of new skills somewhere that I can browse or is this more of a learn as you go?
The primary problem is this: As a very experienced programmer in Windows,I am having to ask simple questions like what's the difference between usr\bin and usr\local\bin and I would like to be prepared.
For POSIX and such I can recommend Advanced Programming in the UNIX Environment and having a bookmark to The single UNIX Specification.
For GCC/GDB and those tools I'm afraid I can't give you any good recommendation.
Hope that helps anyway.
Edit: Duck was slightly faster.
Edited because I had to leave a meeting when I originally submitted this, but wanted to complete the information
Half of that material is learning about development in a Unix-like environment, and for that, I'd recommend a book since it's tougher to filter out useful information from the start.
I'd urge you to go to a bookstore and browse through these books:
Unix/Linux System Administration - This book covers the more system administrator side of stuff, like directory structure of most Unix and Linux file systems (Linux distributions are more diverse than their Unix-named counterparts in how they might structure their file system)
Other information accessible online:
GCC Online Manual - the comprehensive GNU GCC documentation
winsock, this should be mostly familiar to you.
make- Wikipedia article that will have links to the various
makedocumentation out there
Additionally, you will want to learn about
ldd, which is like dependency walker in Windows. It lists a target binary's dependencies, if it has any.
And for Debugging, check out this StackOverflow thread which talks about a well written GDB tutorial and also links to an IBM guide.
Happy reading.
Recently I started taking this guide to get myself started on downloading files from the internet. I read it and came up with the following code to download the HTTP body of a website. The only problem is, it's not working. The code stops when calling the recv() call. It does not crash, it just keeps on running. Is this my fault? Am I using the wrong approch? I intent to use the code to not just download the contents of .html-files, but also to download other files (zip, png, jpg, dmg ...). I hope there's somebody that can help me. This is my code:
#include <stdio.h> #include <sys/socket.h> /* SOCKET */ #include <netdb.h> /* struct addrinfo */ #include <stdlib.h> /* exit() */ #include <string.h> /* memset() */ #include <errno.h> /* errno */ #include <unistd.h> /* close() */ #include <arpa/inet.h> /* IP Conversion */ #include <stdarg.h> /* va_list */ #define SERVERNAME "developerief2.site11.com" #define PROTOCOL "80" #define MAXDATASIZE 1024*1024 void errorOut(int status, const char *format, ...); void *get_in_addr(struct sockaddr *sa); int main (int argc, const char * argv[]) { int status; // GET ADDRESS INFO struct addrinfo *infos; struct addrinfo hints; // fill hints memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; // get address info status = getaddrinfo(SERVERNAME, PROTOCOL, &hints, &infos); if(status != 0) errorOut(-1, "Couldn't get addres information: %s\n", gai_strerror(status)); // MAKE SOCKET int sockfd; // loop, use first valid struct addrinfo *p; for(p = infos; p != NULL; p = p->ai_next) { // CREATE SOCKET sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if(sockfd == -1) continue; // TRY TO CONNECT status = connect(sockfd, p->ai_addr, p->ai_addrlen); if(status == -1) { close(sockfd); continue; } break; } if(p == NULL) { fprintf(stderr, "Failed to connect\n"); return 1; } // LET USER KNOW char printableIP[INET6_ADDRSTRLEN]; inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), printableIP, sizeof(printableIP)); printf("Connection to %s\n", printableIP); // GET RID OF INFOS freeaddrinfo(infos); // RECEIVE DATA ssize_t receivedBytes; char buf[MAXDATASIZE]; printf("Start receiving\n"); receivedBytes = recv(sockfd, buf, MAXDATASIZE-1, 0); printf("Received %d bytes\n", (int)receivedBytes); if(receivedBytes == -1) errorOut(1, "Error while receiving\n"); // null terminate buf[receivedBytes] = '\0'; // PRINT printf("Received Data:\n\n%s\n", buf); // CLOSE close(sockfd); return 0; } void *get_in_addr(struct sockaddr *sa) { // IP4 if(sa->sa_family == AF_INET) return &(((struct sockaddr_in *) sa)->sin_addr); return &(((struct sockaddr_in6 *) sa)->sin6_addr); } void errorOut(int status, const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); exit(status); }
If you want to grab files using HTTP, then libcURL is probably your best bet in C. However, if you are using this as a way to learn network programming, then you are going to have to learn a bit more about HTTP before you can retrieve a file.
What you are seeing in your current program is that you need to send an explicit request for the file before you can retrieve it. I would start by reading through RFC2616. Don't try to understand it all - it is a lot to read for this example. Read the first section to get an understanding of how HTTP works, then read sections 4, 5, and 6 to understand the basic message format.
Here is an example of what an HTTP request for the stackoverflow Questions page looks like:
GET HTTP/1.1\r\n Host: stackoverflow.com:80\r\n Connection: close\r\n Accept-Encoding: identity, *;q=0\r\n \r\n
I believe that is a minimal request. I added the CRLFs explicitly to show that a blank line is used to terminate the request header block as described in RFC2616. If you leave out the
Accept-Encoding header, then the result document will probably be transfered as a gzip-compressed stream since HTTP allows for this explicitly unless you tell the server that you do not want it.
The server response also contains HTTP headers for the meta-data describing the response. Here is an example of a response from the previous request:
HTTP/1.1 200 OK\r\n Server: nginx\r\n Date: Sun, 01 Aug 2010 13:54:56 GMT\r\n Content-Type: text/html; charset=utf-8\r\n Connection: close\r\n Cache-Control: private\r\n Content-Length: 49731\r\n \r\n \r\n \r\n <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ... 49,667 bytes follow
This simple example should give you an idea what you are getting into implementing if you want to grab files using HTTP. This is the best case, most simple example. This isn't something that I would undertake lightly, but it is probably the best way to learn and appreciate HTTP.
If you are looking for a simple way to learn network programming, this is a decent way to start. I would recommend picking up a copy of TCP/IP Illustrated, Volume 1 and UNIX Network Programming, Volume 1. These are probably the best way to really learn how to write network-based applications. I would probably start by writing an FTP client since FTP is a much simpler protocol to start with.
If you are trying to learn the details associated with HTTP, then:
telnet server 80and typing in requests by hand
--verboseand
--includecommand line options so that you can see what is happening
Just don't plan on writing your own HTTP client for enterprise use. You do not want to do that, trust me as one who has been maintaining such a mistake for a little while now...
Could anyone give me some pointers as to the best way in which to learn how to do very low latency programming? I have many programming books but I've never seen one which focused (or helped) on writing extremely fast code. Or are books not the best way forward?
Some advice from an expert would be really appreciated!
EDIT: I think I'm referring more to CPU/Memory bound.
[C++ programmer]:
Ultra-low-latency programming is hard. Much harder than people suspect when they first start down the path. There are some techniques and "tricks" you can employ. Like IO Completion ports, multi core utilization, highly optimized synchronization techniques, shared memory. The list goes on forever. (edit) It's not as simple as "code-profile-refactor-repeat" because you can write excellent code that is robust and fast, but will never be truly ultra-low latency code.
Unfortunately there is no one single resource I know of that will show you how it's done. Programmers specializing in (and good at) ultra low-latency code are among the best in the business and the most experienced. And with good reason. Because if there is a silver bullet solution to becoming a good low-latency programmer, it is simply this: you have to know a lot about everything. And that knowledge is not easy to come by. It takes years (decades?) of experience and constant study.
As far as the study itself is concerned, here's a few books I found useful or especially insightful for one reason or another:
I'm writing a concurrent TCP server that has to handle multiple connections with the 'thread per connection' approach (using a thread pool). My doubt is about which is the most optimal way for every thread to get a different file descriptor.
I found that the next two methods are the most recommended:
accepts()all the incoming connections and stores their descriptors on a data structure (e.g.: a
queue). Then every thread is able to get an fd from the queue.
Problems I find to each of them:
mutex_lock) before a thread can read from it, so in the case that a considerable number of threads wants to read in exactly the same moment I don't know how much time would pass until all of them would get their goal.
accept()calls has not been totally solved on Linux yet, so maybe I would need to create an artificial solution to it that would end up making the application at least as slow as with the approach 1.
Sources:
(Some links talking about approach 2: does-the-thundering-herd-problem-exist-on-linux-anymore - and one article I found about it (outdated) : linux-scalability/reports/accept.html
And an SO answer that recommends approach 1: can-i-call-accept-for-one-socket-from-several-threads-simultaneously
I'm really interested on the matter, so I will appreciate any opinion about it :)
As mentioned in the StackOverflow answer you linked, a single thread calling accept() is probably the way to go. You mention concerns about locking, but these days you will find lockfree queue implementations available in Boost.Lockfree, Intel TBB, and elsewhere. You could use one of those if you like, but you might just use a condition variable to let your worker threads sleep and wake one of them when a new connection is established.
As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
Chapter 30 of Unix Network Programming introduce the alternatives of client/server design. The UNP book is the best start of network programming.
I am trying to make a simple client-server chat program. On the client side I spin off another thread to read any incomming data from the server. The problem is, I want to gracefully terminate that second thread when a person logs out from the main thread. I was trying to use a shared variable 'running' to terminate, problem is, the socket read() command is a blocking command, so if I do while(running == 1), the server has to send something before the read returns and the while condition can be checked again. I am looking for a method (with common unix sockets only) to do a non-blocking read, basically some form of peek() would work, for I can continually check the loop to see if I'm done.
The reading thread loop is below, right now it does not have any mutex's for the shared variables, but I plan to add that later don't worry! ;)
void *serverlisten(void *vargp) { while(running == 1) { read(socket, readbuffer, sizeof(readbuffer)); printf("CLIENT RECIEVED: %s\n", readbuffer); } pthread_exit(NULL); }
This may not be the specific answer you're looking for, but it may be the place you could find it. I'm currently reading:
Unix Network Programming, Volume 1: The Sockets Networking API, 3rd Edition
And there are a lot of examples of multi-threaded, non-blocking servers and clients. Also, they explain a lot of the reasoning and trade-offs that go between the different methods.
Hope that helps...
I would like to implement a telnet server in C. How would I proceed with this? Which RFCs should I look at? This is important to me, and I would appreciate any help.
If you are serious about network programming I would highly recommend Richard W. Stevens' "UNIX Network Programming Vol 1" - it's much better reading than RFCs with great examples.
It is very expensive book but there are cheap paperback edition available on eBay. Even if you get expensive hard-cover edition it worth every penny you paid.
I don't quite understand the purpose of the first argument in the
select function. Wikipedia describes it as the maximum file descriptor across all the sets, plus 1 . Why +1 and why does
select need this information ?
This is a happenstance detail of the (original) Berkeley sockets implementation. Basically, the implementation used the number of file descriptors as a sizing variable for some temporary internal bit arrays. Since Unix descriptors start with zero, the largest descriptor would be one less than the size of any array with a one-slot-per-descriptor semantic. Hence the "largest-plus-one" requirement. This plus-1 adjustment could have been absorbed into the system call itself, but wasn't.
Ancient history, that's all. The result is that the correct interpretation of the first argument has less to do with descriptor values than with the number of them (i.e. the maximum number of descriptors to be tested). See Section 6.3 of Stevens et al (This is a revised and updated version of Rich Stevens' classic text. If you don't have it, get it!)
I'm thinking of purchasing this book to learn more on C/C++ networking programming:
I was just wondering is there/do I need a windows equivalent book (I do plan to code on both OS'). I'm not sure of the difference in the evolution regarding BSD sockets the windows.
I'm mainly buying this to eventually write code which will stream data between computers.
For my application, I need to have a central process responsible for interacting with many client processes. The client processes need a way to identify and communicate with the central process. Additionally, the central process may not be running, and the client process needs a way to identify that fact. This application will be running on a Unix-like system, so I'd thought about using
named pipes sockets for the task. How would I, specifically, go about using named pipes sockets for this task (actual code would be greatly appreciated!)? If named pipes sockets are not ideal, are there better alternatives?
You need to read one of the standard text books on the subject - probably Stevens 'UNIX Network Programming, Vol 1, 3rd Edn'.
You have to make a number of decisions, including:
These decisions radically impact the code that's required. If the process is dealing with one short message at a time, it might be appropriate to consider UDP instead of TCP. If the process is dealing with extended conversations with several correspondents and is not forking a child to handle them, then you can consider whether threaded programming is appropriate. If not, you need to consider timeliness and whether the central process can be held up indefinitely.
As indicated in a comment, you also need to consider how a process should deal with the central process not running - and you need to consider how fast that response should be. You also have to protect against the central process being so busy that it looks like it is not running, even though it is running but is just very busy dealing with other connections. How much trouble do you get into if the process that can't connect to the central process tries to kick off a new copy of it.
I am new to IOS Swift. I want to develop UDP client and send data in Swift.
I have reference the following link:
Swift: Receive UDP with GCDAsyncUdpSocket
Retrieving a string from a UDP server message
But I could not find a good way to implement
UDP in
Swift.
Does someone can teach me How to implement UDP client and send data in Swift in iPhone?
Thanks in advance.
This looks like a dupe to Swift UDP Connection.
Refactoring the example a little bit:
let INADDR_ANY = in_addr(s_addr: 0) udpSend("Hello World!", address: INADDR_ANY, port: 1337) func udpSend(textToSend: String, address: in_addr, port: CUnsignedShort) { func htons(value: CUnsignedShort) -> CUnsignedShort { return (value << 8) + (value >> 8); } let fd = socket(AF_INET, SOCK_DGRAM, 0) // DGRAM makes it UDP var addr = sockaddr_in( sin_len: __uint8_t(sizeof(sockaddr_in)), sin_family: sa_family_t(AF_INET), sin_port: htons(port), sin_addr: address, sin_zero: ( 0, 0, 0, 0, 0, 0, 0, 0 ) ) textToSend.withCString { cstr -> Void in withUnsafePointer(&addr) { ptr -> Void in let addrptr = UnsafePointer<sockaddr>(ptr) sendto(fd, cstr, strlen(cstr), 0, addrptr, socklen_t(addr.sin_len)) } } close(fd) }
If you have the target IP as a string, use inet_pton() to convert it to an in_addr. Like so:
var addr = in_addr() inet_pton(AF_INET, "192.168.0.1", &buf)
Feel free to steal code from over here: SwiftSockets
Oh, and if you plan to do any serious network programming, grab this book: Unix Network Programming
I have a network application that I need to convert so that it works for ipv6 network. Could you please let me know what I need to do (replace socket APIs)?
One more thing, how can I test my application?
Thanks.
3rd edition of "Unix Network Programming" has numerous examples and a whole chapter in IPv4/IPv6 interoperability.
I've just been looking at the following books: -K&R C -The Complete Reference C++ -The Complete Reference C -Deitel How to Program C -Deitel How to Program C++
and not one of them contains any networking, how to create sockets etc. Is there any 'definitive' reference for C network programming? Google wasn't particularly helpful.
I'm probably considering windows and unix platforms
Recently, one of my work is to write network stacks using C++ in an OS developed by my team which is totally different from linux. However, I think how a deep understanding of linux network stacks may be helpful to design and implementation a well one.
Any advice or helpful material?
Unix Network Programming by W. Richard Stevens
I'd like to do some hobby development of command line applications for UNIX in C. To narrow that down, I'd like to focus on the BSD family, specifically FreeBSD as my development machine is a Mac OS X 10.7 Lion box.
Searches for UNIX development have returned some from Addison Wesley, but I cannot find adequate documentation for FreeBSD. If there is a good general book on developing for either BSD or AT&T UNIX, I would be interested in that. please note I prefer books as I learn best that way.
Thanks,
Scott
Stevens "Advanced Programming in the Unix Environment". It covers FreeBSD but it's not FreeBSD specific. It is Unix specific, and covers all the bases you require.
I guess you could take a look at these:
Programming with POSIX Threads
The sockets Networking API
Interprocess Communications
Advanced Programming in the UNIX environment
The first three are very specific and would serve only if you need to focus on that particular subject. The last link is a highly rated book on Amazon that you may be interested in.
All in all, if you already have a grip of threads, IPC, networking, filesystem, all you need is the internet because there is widely available documentation about the POSIX API.
I'm going to graduate soon in electronics and tlc engineering and I have some decent OO programming experience with PHP and Java.
Now I would like to try starting a career as a C programmer.
I'm interested in C since this is, I think, the most suited language, without considering Assembly, to develop device drivers, firmwares and other low-level softwares in. In particular I hope to be able to work on network related topics. I want to work quite close to the hardware since I suppose this is the only way I'll be able to fruitfully spend my degree while at the same time finding gratification in being a programmer.
So I'd like to ask what you think I should read considering that I can already write something in C, nothing fancy though, and that I've read a couple of times the K&R.
If you know of any tools or libraries (like libevent and libev) that are de facto standards in the field of low-level, network related, C programming that would be nice to know as well.
In chapter 5 in the book Unix Network Programming by Stevens et al, there are a server program and a client program as follows:
server
mysignal(SIGCHLD, sig_child); for(;;) { connfd = accept(listenfd, (struct sockaddr *)&ca, &ca_len); pid = fork(); if(pid == 0) { //sleep(60); close(listenfd); str_echo(connfd); close(connfd); exit(0); } close(connfd); }
function sig_child works to handle signal SIGCHLD; the code is as follows:
void sig_child(int signo) { pid_t pid; int stat; static i = 1; i++; while(1) { pid = wait(&stat); if(pid > 0) { printf("ith: %d, child %d terminated\n", i, pid); } else { break; } } //pid = wait(&stat); return; }
client
for(i = 0 ; i < 5; i++) { sockfd[i] = socket(AF_INET, SOCK_STREAM, 0); if(sockfd[i] < 0) { perror("create error"); exit(-1); } memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(5900); if(inet_pton(AF_INET, argv[1], &sa.sin_addr) != 1) { perror("inet_pton error"); exit(-1); } connect(sockfd[i], (struct sockaddr *)&sa, sizeof(sa)); } str_cli(sockfd[0], stdin); exit(0);
As you can see in the source code of the client, the program will establish five connections to the server end, but only one connection is used in the program; after
str_cli is finished,
exit(0) is called. And all the connections should be closed, then the five child processes in the server will exit, and SIGCHLD is sent to the parent process, which uses function
sig_child to handle the SIGCHLD. Then the
while loop will confirm all the child processes will be waited by parent process correctly. And I test the program for a couple of times; it works well, all the children will be cleaned.
But in the book, the authors wrote that "wait could not work properly, because function wait may become blocked before all the child processes exit". So is the statement right in the book? If it's right, could you please explain it in more detail. (PS: I think
wait in a
while statement would properly handle the exit of all the child processes.)
The problem is not with
wait, but with signal delivery. The
sig_chld function in the book doesn't have the
while loop, it only waits for one child
void sig_child(int signo) { pid_t pid; int stat; pid = wait(&stat); printf("child %d terminated\n", pid); return; }
When the client exits, all connections are closed and all the children eventually terminate. Now, the first
SIGCHLD signal is delivered and upon entering the signal handler, the signal is blocked. Any further signal won't be queued and is therefore lost, causing zombie children in the server.
You can fix this by wrapping
wait in some loop, as you did. Another solution is to ignore
SIGCHLD explicitly, which is valid when you don't need the exit status of your children.
While
wait in a loop finally waits for all children, it has the drawback, that
wait blocks, if there are still children running. This means the process is stuck in the signal handler until all children are terminated.
The solution in the book is to use
waitpid with option
WNOHANG in a loop
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) printf("child %d terminated\n", pid);
This loop waits for all terminated children, but exits as soon as possible, even if there are running children.
To reproduce the server hanging in the signal handler, you must do the following
Is there a good book for ruby sockets programming or we have to rely on Unix C books for theory and source ?.
If the goal is to learn socket programming I would recommend using C and reading through some Unix system programming books. The books will probably be much better and go into more detail than a sockets book that is Ruby specific (mainly because C, Unix and sockets have been around much longer than Ruby and my quick Googling didn't find a Ruby specific book).
Books I would recommend:
After getting a handle on the sockets in general (even if you don't write any C) the Ruby API for sockets will make much more sense.
The Tcp server need to serve many clients, If one client one server port and one server thread to listen the port, I want to know weather it is faster ?
If one port is good, could someone explain the different between one port and multiple ports in this case, thanks!
The problem with using multiple ports to achieve this is that each of your clients will each have a specific port number. Depending on the number of clients there could be a tremendous amount of bookkeeping involved.
Typically, for a tcp server that is to serve multiple clients, you have a "main" thread which listens to a port and accepts connections on that port. That thread then passes the connected socket off to another thread for processing and goes back to listening.
For a wealth of Unix network programming knowledge check out "The Stevens Book"
What is the best way to coordinate the accepts of a listenning socket between multiple processes?
I am thinking of one of the two ways:
Have a "Master" process that will send a message to each process when it is its turn to start accepting connections.
So the sequence will be:
Master process gives token to Worker A. Worker A accepts connection, gives token back to Master process. Master process gives token to Worker B. etc.
Each process will have an accepting thread that will be spinning around a shared mutex. Lock the mutex, accept a connection, free the lock.
Any better ideas?
1) I'm not sure why you wouldn't want multiple "threads" instead of "processes".
But should you require a pool of worker processes (vs. "worker threads"), then I would recommend:
2) The master process binds, listens ... and accepts all incoming connections
3) Use a "Unix socket" to pass the accepted connection from the master process to the worker process.
4) As far as "synchronization" - easy. The worker simply blocks reading the Unix socket until there's a new file descriptor for it to start using.
5) You can set up a shared memory block for the worker to communicate "busy/free" status to the master.
Here's a discussion of using a "Unix domain socket":
Sending file descriptor over UNIX domain socket, and select()
Stevens "Network Programming" is also an excellent resource:
Environment: a RedHat-like distro, 2.6.39 kernel, glibc 2.12.
I fully expect that if a signal was delivered while accept() was in progress, accept should fail, leaving errno==EINTR. However, mine doesn't do that, and I'm wondering why. Below are the sample program, and strace output.
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <signal.h> #include <errno.h> #include <arpa/inet.h> #include <string.h> static void sigh(int); int main(int argc, char ** argv) { int s; struct sockaddr_in sin; if ((s = socket(AF_INET, SOCK_STREAM, 0))<0) { perror("socket"); return 1; } memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; if (bind(s, (struct sockaddr*)&sin, sizeof(struct sockaddr_in))) { perror("bind"); return 1; } if (listen(s, 5)) { perror("listen"); } signal(SIGQUIT, sigh); while (1) { socklen_t sl = sizeof(struct sockaddr_in); int rc = accept(s, (struct sockaddr*)&sin, &sl); if (rc<0) { if (errno == EINTR) { printf("accept restarted\n"); continue; } perror("accept"); return 1; } printf("accepted fd %d\n", rc); close(rc); } } void sigh(int s) { signal(s, sigh); unsigned char p[100]; int i = 0; while (s) { p[i++] = '0'+(s%10); s/=10; } write(1, "sig ", 4); for (i--; i>=0; i--) { write(1, &p[i], 1); } write(1, "\n", 1); }
strace output:
execve("./accept", ["./accept"], [/* 57 vars */]) = 0 <skipped> socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3 bind(3, {sa_family=AF_INET, sin_port=htons(0), sin_addr=inet_addr("0.0.0.0")}, 16) = 0 listen(3, 5) = 0 rt_sigaction(SIGQUIT, {0x4008c4, [QUIT], SA_RESTORER|SA_RESTART, 0x30b7e329a0}, {SIG_DFL, [], 0}, 8) = 0 accept(3, 0x7fffe3e3c500, [16]) = ? ERESTARTSYS (To be restarted) --- SIGQUIT (Quit) @ 0 (0) --- rt_sigaction(SIGQUIT, {0x4008c4, [QUIT], SA_RESTORER|SA_RESTART, 0x30b7e329a0}, {0x4008c4, [QUIT], SA_RESTORER|SA_RESTART, 0x30b7e329a0}, 8) = 0 write(1, "sig ", 4sig ) = 4 write(1, "3", 13) = 1 write(1, "\n", 1 ) = 1 rt_sigreturn(0x1) = 43 accept(3, ^C <unfinished ...>
Within Unix Network Programming book, there is a section which says:
We used the term "slow system call" to describe
accept, and we use this term for any system call that can block forever. That is, the system call need never return. Most networking functions fall into this category. For example, there is no guarantee that a server's call to
acceptwill ever return, if there are no clients that will connect to the server. Similarly, our server's call to
readin Figure 5.3 will never return if the client never sends a line for the server to echo. Other examples of slow system calls are reads and writes of pipes and terminal devices. A notable exception is disk I/O, which usually returns to the caller (assuming no catastrophic hardware failure).
The basic rule that applies here is that when a process is blocked in a slow system call and the process catches a signal and the signal handler returns, the system call can return an error of
EINTR. Some kernels automatically restart some interrupted system calls. For portability, when we write a program that catches signals (most concurrent servers catch
SIGCHLD), we must be prepared for slow system calls to return
EINTR. Portability problems are caused by the qualifiers "can" and "some," which were used earlier, and the fact that support for the POSIX
SA_RESTARTflag is optional. Even if an implementation supports the
SA_RESTARTflag, not all interrupted system calls may automatically be restarted. Most Berkeley-derived implementations, for example, never automatically restart select, and some of these implementations never restart
acceptor
recvfrom.
I am trying to set up multicast sources for an application on linux using source specific multicast (SSM) and the code is going ok (using the C interface) but I would like to verify that the system will behave as I expect it to.
Setup:
Multicast address - 233.X.X.X:9876
Source1 - 192.X.X.1
Source2 - 192.X.X.2
Interface1 - 192.X.X.100
Interface1 - 192.X.X.101
Steps
Desired Outcome:
Reader1 can see the data from the multicast.
Reader2 can't see the data from the multicast.
I am concerned that the above will not be the case as in my testing using non source specific multicast an IP_ADD_MEMBERSHIP has global effect. So reader2's socket sees data because it is bound to the unique multicast address which has been joined to an interface seeing data. The info at this link under "Joining a Multicast" matches up with my observations.
It may well be that IP_ADD_SOURCE_MEMBERSHIP behaves differently to IP_ADD_MEMBERSHIP but the documentation is sparse and not specific in this regard.
Specific questions:
I am inexperienced with network programming so please forgive any shortcomings in my understanding.
Thanks for any assistance.
I've worked through this and after obtaining a copy of Unix Network Programming the behaviour at least seems clear and understandable.
The answer is yes all multicast joins are global whether they be SSM or otherwise. The reason for this is that the join actually takes effect a couple of layers down from a process issuing a join request. Basically, it tells the IP layer to accept multicast packets from the source specified and provide them to any process bound to the socket with the multicast address.
SSM was actually introduced because of the limited address space of IPv4. When using multicast on the internet there are not nearly enough unique multicast addresses such that each person who want to use one could have a unique address. SSM pairs a source address with a multicast address which as a pair form a globally unique identifier i.e. shared multicast address e.g. 239.10.5.1 and source 192.168.1.5. So the reason that SSM exists is purely for this purpose of facilitating multicast in a limited address space. In the environment that our software is working in (Cisco) SSM is being used for redundancy and convenience of transmission, stacking multiple streams of data on the same IP:port combo and having downstream clients select the stream they want. This all works just fine until a given host wants access to more than one stream in the multicast, because they're all on the same multicast address all subscribed processes get all the data, and this is unavoidable due to the way the network stack works.
Final solution
Now that the behaviour has been understood the solution is straightforward, but does require additional code in each running process. Each process must filter the incoming data from the multicast address and only read data from the source(s) that they are interested in. I had hoped that there was some "magic" in built into SSM to do this automatically, but there is not.
recvfrom() already provides the senders address so doing this is relatively low cost.
I am wondering if there is a simpler way to broadcast my own IP to all devices on my network on a specific port using C or C++
I don't know too much about socket programming just cause most of my applications don't need a network. I looked into it and I found one piece of code that looks promising although it doesn't exactly broadcast since it sends to specific IP addresses.
Is there a way to broadcast to addresses say between 192.168.1.0/255 in one fell swoop or do I need to go through loop through the addresses and then send a packet to them myself?
EDIT: I'm asking about c++ implementation, not network infrastructure. That is why I linked the above link.
This is pretty much what IP multicast was invented for.
Ton of examples on the internet. Just a couple for you:
Many more out there, but if you are any serious about doing network programming, get this book and you'll never regret.
I can either send data throughout the udp protocol with the UdpClient.Send(byte array) or the UdpClient.Client.Send(stream) method. both methods work. the only differences are that on one method I pass a byte array and on the other I pass a stream.
quick example:
UdpClient udpClient = new UdpClient(localEndPoint); // I can eather send data as: udpClient.Send(new byte[] { 0, 1, 2 }, 3); udpClient.Client.Send(new byte[5]);
Also which method will ensure that my data reaches it's destination without loosing information? I have read that the udp protocol does not ensure that all bytes reach it's destination thus is better for streaming video, audio but not for transferring files like I am doing. The reason why I am using udp instead of tcp is because it is very complicated to establish a tcp connection between two users that happen to be behind a router. I know it will be possible if one of the users enables port forwarding on his router. I managed to send data by doing what is called udp punch holing. udp punch holing enables you to establish a connection between two users that are behind a router with the help of a server. It will be long to explain how that work in here you can find lot's of information if you google it. Anyways I just wanted to let you know why I was using udp instead tcp. I don't now if it will be possible to send a file with this protocol making sure that no data is lost. maybe I have to create an algorithm. or maybe the UdpClient.Client.Send method ensures that data will be received and the UdpClient.Send method does not ensure that data will be received.
UDP does not guarantee data delivery or order of them. It only guarantees if you receive packet successfully, the packet is complete. You need to make your network communication reliable with your own implementation. The two functions should not make any difference.
UNIX Network Programming has a chapter for this topic. (22.5 Adding Reliability to a UDP Application). You can also take a look at libginble which supports NAT traversal function (with STUN or relay) and reliability of communication.
This article, Reliability and Flow Control, might also help you to understand one possible way to implement it. Good Luck!
I have a client using select() to check if there is anything to be received, else it times out and the user is able to send(). Which works well enough. However, the program locks up waiting for user input, so it cant recv() again until the user has sent something. I am not having much luck with using threads either, as I cannot seem to find a good resource, which shows me how to use them.
I have tried a creating two threads (using CreateThread) for send and recv functions which are basically two functions using while loops to keep sending and receiving. And then the two CreateThreads() are wrapped up in a while loop, because otherwise it just seemed to drop out.
I have basically no previous experience with threads, so my description of what i've been doing will probably sound ridiculous. But I would appreciate any help, in using them properly for this kind of use, or an alternative method would also be great.
Can't find a good resource on socket programming? Bah. Read the bible:
I have a link error when trying to use
sctp_get_no_strms function. I am running Slackware 14.1 and have lksctp-tools installed.
# ls /var/log/packages | grep sctp lksctp-tools-1.0.16-x86_64-1_SBo
However libsctp symbol list does not include this function.
# nm -D /usr/lib64/libsctp.so | grep sctp_get 0000000000001100 T sctp_getaddrlen 00000000000010e0 T sctp_getladdrs 00000000000010c0 T sctp_getpaddrs
Is
sctp_get_no_strms not supported by lksctp-tools?
The compilation command is as follows:
gcc -o srv sctpserv01.o sctp_wrapper.o -L../lib -lsock -lsctp
When using functions from a library, the appropriate header file needs to be #include'd — for example
#include "unp.h" since the function
sctp_get_no_strms() is described in Stevens Unix Network Programming, Volume 1: The Sockets API, 3rd Edn and is specific to that book.
Note that
unp.h is not a standard system header, which is why I used
"unp.h" rather than
<unp.h> (with angle brackets around the header file name).
I have an IP = '127.0.0.1', port number 'port', and trying
class AClass(asyncore.dispatcher): def __init__(self, ip, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((ip, port)) def handle_connect(self): print 'connected' def handle_read(self): data = self.recv(8192) print data def handle_close(self): self.close()
Nothing is being printed though.
The sending is being handled by another process. How can I check ? Is the above correct ?
Edit: For sending: a different python program, running separately:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((addr, port)) packet="some string" sock.sendall(packet+'\r\n')
Nothing happens
If I put, on server side (!!!)
print sock.recv(4096) I see the packet printed - but still nothing happens from the client side.
I assume that you mean for
AClass to be the server-side. In that case,
AClass should not be doing a
connect(). There are two sides to socket communications. On the server-side, you typically create the socket, bind it to an address and port, set the backlog (via
listen()), and
accept() connections. Typically, when you have a new connection from a client, you spawn off some other entity to handle that client.
This code implements an echo server:
import asyncore import socket class EchoHandler(asyncore.dispatcher_with_send): def handle_read(self): self.out_buffer = self.recv(1024) if not self.out_buffer: self.close() print "server:", repr(self.out_buffer) def handle_close(self): self.close() class EchoServer(asyncore.dispatcher): def __init__(self, ip, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind((ip, port)) self.listen(1) def handle_accept(self): sock, addr = self.accept() print "Connection from", addr EchoHandler(sock) s = EchoServer('127.0.0.1', 21345) asyncore.loop()
Notice that in the
__init__() method, I'm binding the socket, and setting the backlog.
handle_accept() is what handles the new incoming connection. In this case, we get the new socket object and address returned from
accept(), and create a new async handler for that connection (we supply the socket to
EchoHandler).
EchoHandler then does the work of reading from the socket, and then puts that data into
out_buffer.
asyncore.dispatcher_with_send will then notice that data is ready to send and write it to the socket behind the scenes for us, which sends it back to the client. So there we have both sides, we've read data from the client, and then turn around and send the same data back to the server.
You can check this implementation in a couple of ways. Here is some python code to open a connection, send a message, read the response, and exit:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((ip, port)) client.sendall("Hello world!\r\n") print "client:", repr(client.recv(1024)) client.close()
You can also just use telnet as your client using the command
telnet localhost 21345, for this example. Type in a string, hit enter, and the server will send that string back. Here's an example session I did:
:: telnet 127.0.0.1 21345 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello! Hello! aouaoeu aoeu aoeu aouaoeu aoeu aoeu ^] telnet> quit Connection closed.
In the example, the first "Hello!" is the one I typed in my client, the second one is the echo from the server. Then I tried another string, and it was echoed back as well.
If you've not done socket communications before, I really can't recommend Richard Stevens UNIX Network Programming enough. A 3rd edition is now in print and available on Amazon. It doesn't, however, cover using Python or asyncore. And, unfortunately, asyncore is one module that's really not covered very well in the Python documentation. There some examples out there in the wild that are pretty decent though.
Hopefully, this gets you moving in the right direction.
EDIT: here's a asyncore based client:
class Client(asyncore.dispatcher_with_send): def __init__(self, ip, port, message): asyncore.dispatcher_with_send.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((ip, port)) self.out_buffer = message def handle_connect(self): print 'connected' def handle_read(self): data = self.recv(8192) print "client:", repr(data) def handle_close(self): self.close()
I have currently been working on a multiplayer game using Node.js and Socket.io. I've done okay and I understand the basics, but the further I get into it, the more I realize I really don't understand how networking programming works. As the codebase grows and more features are added, my code is starting to become horribly inefficient and very hard to maintain.
The only resources I've really been able to find online cover very small applications and the methods used don't seem to have much scalability to them.
I'm wondering if anyone has a good book, or perhaps some online videos or articles that cover more advanced aspects or best practices of programming a large multiplayer game. I'm not new to game development, however I am new to the multiplayer and networking side of it.
Unix Network Programming, by Stevens is the best I have seen on network programming. It is incredibly complete and thorough and clear. You can go as deep as you want to with this book.
Also check out the excellent Beej's Guide to Network Programming online.
I have two software components working in tandem - a Visual Studio C# chat application I made, which connects via a TCP NetworkStream to a Node.js application which is hosting a very simple TCP server.
The C# application sends messages via the TCP NetworkStream to the server, and everything works well, until I close the application (the actual process is relatively unimportant, but I've listed it here and included a short gif for clarity):
First, I start up the Node.js TCP server
Then the C# Application starts and opens up a TCP NetworkStream to the Node.js server
I type the message 'Hello!' into the C# app's input and hit 'Send'
The message is recieved by the TCP server
However when I close my C# application, I get an
ECONNRESET error
I'm closing the NetworkStream on the client side using
NetworkStream.Close() which, as @RonBeyer pointed out, is ill-advised. According to MSDN it:
Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed.
I assume this is done with the
using keyword in C# (which I am pretty unfamiliar with, given my novice understanding of the language).
BUT I DIGRESS. What I know is that an
ECONNRESET error is caused by an abrupt closure of the socket / stream. The peculiar thing is, disregarding the
ECONNRESET error on the server allows the server to accept new connections seemingly unperturbed.
So my question is:
I say this because the function of the server (to accept new TCP connections) remains uninterrupted, so it seems to make no difference superficially. Any expertise on the subject would be really helpful.
Thanks in advance!
I suggest reading this post and then deciding for yourself based on your own knowledge of your code whether or not it's OK to ignore the ECONNRESET. It sounds like your Node app may be trying to write to the closed connection (heartbeats being sent?). Proper closing of the connection from your C# app would probably take care of this, but I have no knowledge of C#.
You may have a problem if you get lots of users and if ECONNRESET causes the connection to go into TIME_WAIT. That will tie up the port for 1-2 minutes. You would use netstat on Linux to look for that but I'm sure there is an equivalent Windows app.
If you really want to get into the nitty gritty of socket communications I suggest the excellent Unix Network Programming, by Stevens.
I'm coding a TCP Server class based on the I/O multiplexing (select) way. The basic idea is explained in this chunk of code:
GenericApp.cpp
TServer *server = new Tserver(/*parameters*/); server->mainLoop();
For now the behavior of the server is independent from the context but in a way that i nedd to improove.
Actual Status
receive(sockFd , buffer); MSGData * msg= MSGFactory::getInstance()->createMessage(Utils::getHeader(buffer,1024)); EventHandler * rightHandler =eventBinder->getHandler(msg->type()); rightHandler->callback(msg);
At this version the main loop reads from the socket, instantiates the right type of message object and calls the appropriate handler(something may not work properly because it compiles but i have not tested it). As you can notice this allows a programmer to define his message types and appropriate handlers but once the main loop is started nothing can be done. I need to make this part of the server more customizable to adapt this class to a bigger quantity of problems.
MainLoop Code
void TServer::mainLoop() { int sockFd; int connFd; int maxFd; int maxi; int i; int nready; maxFd = listenFd; maxi = -1; for(i = 0 ; i< FD_SETSIZE ; i++) clients[i] = -1; //Should be in the constructor? FD_ZERO(&allset); //Should be in the constructor? FD_SET(listenFd,&allset); //Should be in the constructor? for(;;) { rset = allset; nready = select (maxFd + 1 , &rset , NULL,NULL,NULL); if(FD_ISSET( listenFd , &rset )) { cliLen = sizeof(cliAddr); connFd = accept(listenFd , (struct sockaddr *) &cliAddr, &cliLen); for (i = 0; i < FD_SETSIZE; i++) { if (clients[i] < 0) { clients[i] = connFd; /* save descriptor */ break; } } if (i == FD_SETSIZE) //!!HANDLE ERROR FD_SET(connFd, &allset); /* add new descriptor to set */ if (connFd > maxFd) maxFd = connFd; /* for select */ if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready <= 0) continue; } for (i = 0; i <= maxi; i++) { /* check all clients for data */ if ( (sockFd = clients[i]) < 0) continue; if (FD_ISSET(sockFd, &rset)) { //!!SHOULD CLEAN BUFFER BEFORE READ receive(sockFd , buffer); MSGData * msg = MSGFactory::getInstance()->createMessage(Utils::getHeader(buffer,1024)); EventHandler * rightHandler =eventBinder->getHandler(msg->type()); rightHandler->callback(msg); } if (--nready <= 0) break; /* no more readable descriptors */ } } }
Do you have any suggestions on a good way to do this? Thanks.
Your question requires more than just a stack overflow question. You can find good ideas in these book:
Basically what you're trying to do is a
reactor. You can find open source library implementing this pattern. For instance:
If you want yout handler to have the possibility to do more processing you could give them a reference to your TCPServer and a way to register a socket for the following events:
read, the socket is ready for read
write, the socket is ready for write
accept, the listening socket is ready to accept (read with
close, the socket is closed
timeout, the time given to wait for the next event expired (
selectallow to specify a timeout)
So that the handler can implement all kinds of protocols
half-duplex or
full-duplex:
writeevent to let a handler knows when it can send on the socket.
readevent. It should not be in your main loop but in the socket
readhandler.
timeoutso that you can implement
timersand drop idle connections.
This leads to some problems:
state-machineto react to the network events and update the events it wants to receive.
queueof messages. The queue is needed because the readiness of one socket is independent of the readiness of the other. And you may read something on one and not being ready to send it on the other.
priority queuefor timeouts
As you see this is no simple problem. You may want to reduce the genericity of your framework to simplify its design. (for instance handling only
half-duplex protocols like simple HTTP)
I'm looking for resources and book which one can use to get started with IPv4 and IPv6 network development. The most relevant book I've came up so far is "Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)" which covers both protocols but apart from that I did not find very much.
The information I'm looking for is how both protocols work in detail, how IPv6 and its handling differs to IPv4 and how to use the APIs (Windows or *nix) to set up basic communication between applications across both protocols.
Is above mentioned book already the right starting point or are there other resources and books one can use to get started with this topic?
Douglas Comer
Apart from Programming, if you looking for TCP/IP (v4-6), and other stack related queries and design rationale, his books are the ultimate references. Ofcourse you can dig as much as you want, reading papers online. But from basic to intermediate level his books serves the best.
To start with read
Internetworking with TCP/IP Vol-1, 4e.
This is a must, if i may say. After that, you probably would like to look at the stack details then follow
Internetworking with TCP/IP Vol-2 (ANSCI and BSD)
For programming on *nix machine UNP by stevens, is unbeatable. Underlying concepts are almost same for unix/linux/windowx/mac/ -- mostly everything is based BSD designed Sockets. So i think UNP is best for programming. I think these three books shall solve your purpose. If you like collecting books, then you can add another one to you library by Stevens again
Some excellent video tutorials on networking, excellent resource
I'm new to C programming and Linux at this time, still struggling my way through a whole lot of things. I'm trying understand whether or not there's any official documentation available for all C related structures and methods available for Linux. I'm aware that we have Linux man page for almost everything, however I'm unable to find any structure definition in there.
For eg. I wish to find out more about sockaddr_in and sockaddr structure. When I search google I come with up with a lots of result, including an MSDN documentation page describing this structure. However, I'm looking for something more official (something similar to MSDN) for linux specific C programming (structures, methods etc.). I'm unsure if any such documentation exist, or if I'm misunderstanding something. Please help me find it in case it exists.
Many Thanks in advance !
If you can buy books, here are some books that explain well mostly used structures in C. I would recommend you to start with The Linux Documentation Project so you can start with the basic structures:
The Linux Documentation Project's Programming using C-API
Richars Steven's book Unix Network Programming, Volume 1 The Sockets Networking API
Robert Love's Linux System Programming
Robert Love's Linux Kernel Development, 3rd Edition
Richard Stone's Beginning Linux Programming, 4th Edition
Michael Kerrisk The Linux Programming Interface
Except these books man pages, GNU libc can be read for more information.
I hope that helps. Cheers
I'm new to socket programing, so forgive me if this question is basic; I couldn't find an answer anywhere.
What constitutes requiring a new socket?
For example, it appears possible to send and receive with the same socket fd on the same port. Could you send on port XXXX and receive on port YYYY with one socket? If not, then are sockets specific to host/port combinations?
Thanks for the insight!
A socket establishes an "endpoint", which consists of an IP address and a port:
Yes, a single socket is specific to a single host/port combination.
READING RECOMMENDATION:
Beej's Guide to Network Programming:
Unix Network Programming: Stevens et al:
I'm recently learning how to program a basic webserver in c. My server depending on certain inputs will send various lines of text all which end in a blank line, and I need to recieve them from the client side somehow to display one line at a time.
Right now the server does something like
send(socket, sometext, strlen(sometext), 0) send ... send(socket, "\n", 2, 0); ....
Client:
Currently what I am doing is using fdopen to wrap the socket file descriptor and read with fgets:
FILE *response = fdopen(someSocket, "r"); while(1){ fgets(input, 500, response); if(strcmp(input, "\n") != 0){ //do some stuff } else { // break out of the loop break; } }
This all works well except my program need to fulfil one condition, and that is to not break the socket connection ever. Because I opened a file, in order to stop memory leak the next line after is:
fclose(response);
This however is the root of my problems because it not only closes the file but also closes the socket, which I can't have. Can anyone give me any guidence on simple methods to work around this? I was thinking about maybe using recv() but doesn't that have to take in the whole message all at once? Is there any way to recreate the behavior of fgets using recv?
I'm really a newbie at all this, thanks for all the help!
Your only real alternative is to write a function that:
1) calls recv() with a fixed buffer and a loop,
2) only returns when you get a complete line (or end-of-connection)
3) saves any "leftover characters for the next read of the next line of text
IIRC, Stevens has such a function:
Book:
Example code:
PS: Any self-respecting higher-level web programming library will give you a "getNextLine()" function basically for free.
Just finished self-studying C with "The C Programming Language, 2nd Ed." by Brian Kernighan and Dennis Ritchie, and am looking for a good follow-up book that can kind of pick up where that book left of - specifically pertaining to programming C under Linux (sockets, threading, IPC, etc.). I did the search thing, but there are so many books (some of them quite expensive) that it is hard to pick one.
I know the Kernighan/Ritchie book is frequently used in C programming courses, so I was kind of curious what schools (and other self-learners) have been using after it?
You can read Deep C secrets as a follow-up. But I also strongly recommend you to read comp.lang.c Frequently Asked Questions. As K&R is very old , so you also need to brush up your self with C's new standards, C99/ C11.
For network programming you can follow Unix Network Programming.
Ok so I have been at this bug all day, and I think I've got it narrowed down to the fundamental problem.
I am working on an app that has required me to write my own versions of
NSNetService and
NSNetServiceBrowser to allow for Bonjour over Bluetooth in iOS 5. It has been a great adventure, as I knew nothing of network programming before I started this project. I have learned a lot from various example projects and from the classic Unix Network Programming textbook. My implementation is based largely on Apple's
DNSSDObjects sample project. I have added code to actually make the connection between devices once a service has been resolved. An
NSInputStream and an
NSOutputStream are attained with
CFStreamCreatePairWithSocketToHost( ... ).
I am trying to send some data over this connection. The data consists of an integer, a few
NSStrings and an
NSData object archived with
NSKeyedArchiver. The size of the
NSData is around 150kb so the size of the whole message is around 160kb. After sending the data over the connection I am getting the following exception when I try to unarchive...
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive
After further exploration I have noticed that the received data is only about 2kb.. The message is being truncated, thus rendering the archive "incomprehensible."
The method that sends the data to all connected devices
- (void) sendMessageToPeers:(MyMessage *)msg { NSEnumerator *e = [self.peers objectEnumerator]; //MyMessage conforms to NSCoding, messageAsData getter calls encodeWithCoder: NSData *data = msg.messageAsData; Peer *peer; while (peer = [e nextObject]) { if (![peer sendData:data]) { NSLog(@"Could not send data to peer.."); } } }
The method in the Peer class that actually writes data to the
NSOutputStream
- (BOOL) sendData:(NSData *)data { if (self.outputStream.hasSpaceAvailable) { [self.outputStream write:data.bytes maxLength:data.length]; return YES; } else { NSLog(@"PEER DIDN'T HAVE SPACE!!!"); return NO; } }
NSStreamDelegate method for handling stream events ("receiving" the data)
The buffer size in this code is 32768 b/c that's what was in whatever example code I learned from.. Is it arbitrary? I tried changing it to 200000, thinking that the problem was just that the buffer was too small, but it didn't change anything.. I don't think I fully understand what's happening.
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { case NSStreamEventHasBytesAvailable: { NSInteger bytesRead; uint8_t buffer[32768]; // is this the issue? // uint8_t buffer[200000]; //this didn't change anything bytesRead = [self.inputStream read:buffer maxLength:sizeof(buffer)]; if (bytesRead == -1) ...; else if (bytesRead == 0) ...; else { NSData *data = [NSData dataWithBytes:buffer length:bytesRead]; [self didReceiveData:data]; } } break; /*omitted code for other events*/ } }
NSStream over a network like that will be using a TCP connection. It can vary, but the maximum packet size is often around 2k. As the message you’re sending is actually 160k, it will be split up into multiple packets.
TCP abstracts this away to just be a stream of data, so you can be sure all these packets will receive in the correct order.
However, the
stream:handleEvent: delegate method is probably being called when only the first 2k of data has arrived – there’s no way for it to know that there’s more coming until it does.
Note the method
read:maxLength: doesn’t gauruntee you’ll always get that max length – in this case it seems to be only giving you up to 2k.
You should count up the actual
bytesReceived, and concatenate all the data together until you receive the total amount you’re waiting for.
How does the receiver know how much data it wants? – you might want to design your protocol so before sending data, you send an integer of defined size indicating the length of the coming data. Alternatively, if you’re only ever sending one message over the socket, you could simply close it when finished, and have the receiver only unarchive after the socket is closed.
ansiapacheasynchronousbroadcastcc#c++clientcommand-lineconcurrencyconnectdevelopment-environmentdocumentationdownloaddriversepollfile-descriptorfirmwareforkfreebsdfunction-pointershanghole-punchinghostnamehtmliosios5ipciphoneipv4ipv6javajavascriptlinuxlow-latencylow-levelmudmulticastmultiplayermultithreadingnetwork-programmingnetworkingnginxnode.jsnscodernsstreamobjective-coopparsingportpythonrecvresourcesrubyscadasharesignalssocket.iosocketsstackswifttcptelnetthread-safetytornadoudpunixwinsock | http://www.dev-books.com/book/book?isbn=0131411551&name=UNIX-Network-Programming | CC-MAIN-2019-09 | refinedweb | 15,860 | 61.77 |
Expected number of runs in a random permutation
My last post was about the expected number of cycles in a random permutation. Today, we'll compute the expected number of runs in a random permutation.
Runs in permutations
First of all, we'll consider what we even mean when we talk about runs in a permutation. If we have a certain permutation, say \(2, 6, 3, 1, 7, 9, 4, 5, 8, 10\), i.e. simply written as a sequence of numbers. We can now decompose this sequence of numbers into smaller subsequences such that each subsequence is strictly increasing, thereby, we obtain the following subsequences: \([2,6],[3],[1,7,9],[4,5,8,10]\).
First elements of runs
Now, to compute the expected number of runs if we pick one permutation of the numbers \(\{1,2,3,\dots,n\}\) at random, we can do the following: We do not actually focus on the runs itself, but instead just on the beginning of each run.
The first position in a permutation automatically marks the beginning of a run (namely the beginning of the first run).
Let us now think about whether the second position marks the beginning of a new run. In fact, the second position marks the beginning of a new run with a probability of exactly \(0.5\). This is clear because there can be two cases:
- Either the second number is greater than the first number, which results in no new run beginning at the second position.
- Or the second number is smaller than the first number, which means that the second run starts at the second position of our sequence.
It is clear that both of the above events occur with probability \(0.5\) because for each situation where the second number is greater than the first, we can acchieve the other situation by swapping the first and second element in the permutation.
The same reasoning works for the remaining positions \(3,4,\dots,n\), so that we know that the probability that a new run starts at position \(i\geq 2\), is given by \(0.5\) regardless of the particular value of \(i\).
Expected number of runs
We can now compute the expected number of runs by installing some indicator variables: The variable \(I_i\) (for \(i\geq 2\)) is 1 if the element at position \(i\) marks the beginning of a run, otherwise 0.
We can then compute the number of runs by \(1+\sum_{i=2}^n I_i\) (the constant 1 comes from the fact that the first position always marks the beginning of a run).
So, we obtain that the expected number of runs is (using linearity of expectation) given by \(E[1+\sum_{i=2}^n I_i] = 1 + \sum_{i=2}^n E[I_i] = 1 + \sum_{i=2}^n Pr[I_i = 0] = 1 + \sum_{i=2}^n 0.5 = \frac{n+1}{2}\).
Testing
The following method computes the runs in a permutation:
def runs(p): if len(p)==0: return [] r = [[p[0]]] for x in p[1:]: if x > r[-1][-1]: r[-1].append(x) else: r.append([x]) return r
We can verify our results by running:
for i in xrange(1,10): a = list(range(i)) s = 0 for p in itertools.permutations(a): s = s + len(runs(p)) avg = Fraction(s, factorial(i)) print "%d : %f"%(i, avg) | http://phimuemue.com/posts/2014-03-27-expected-number-runs-in-random-permutations.html | CC-MAIN-2017-34 | refinedweb | 563 | 58.21 |
Suggestions welcome!
There is online documentation (within ANU only) for JOGL and GLUT.
Sample questions and the ANU has copies of exam papers from previous years.
Simple 3D programs like the cube exercise may show multiple images in the window at once. This happens because the nVidia graphics cards are really fast and screen updates are not being limited to one per LCD/CRT frame. You can synchronise drawing by setting an environment variable from your terminal.
$ setenv __GL_SYNC_TO_VBLANK 1
You need to add JOGL to your classpath with
$ setenv CLASSPATH ".:/usr/local/java/jre/lib/jogl.jar"
The R105 server is ephebe.anu.edu.au. You can ssh or scp to ephebe from inside or outside the ANU.
and the C code:and the C code:import java.util.*; // Initialise static long Start; Date now = new Date(); Start = now.getTime(); ... // Current time Date now = new Date(); float seconds; seconds = (float)(now.getTime() - Start) / 1000.0f;
#include <sys/time.h> ... /* Initialise */ static long Start; struct timeval now; gettimeofday(&now, NULL); Start = now.tv_sec; ... /* Current time */ struct timeval now; float seconds; gettimeofday(&now, NULL); seconds = (float)(now.tv_sec - Start) + (float)now.tv_usec / 1000000.0;
Geometry drawings
OpenGL Lighting
Virtual Reality System Development | http://cs.anu.edu.au/student/comp4610.2007/2006/hints/index.html | crawl-003 | refinedweb | 201 | 61.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.