Thursday, May 29, 2008

alloca()

alloca()

allocate space in the stack frame

Function
SYNOPSIS

#include

void *alloca(size_t size);
DESCRIPTION

The alloca() function allocates space in the stack frame of the caller, and returns a pointer to the allocated block. This temporary space is automatically freed when the function from which alloca() is called returns.
PARAMETERS

size

Specifies the size of the allocated block of memory.

RETURN VALUES

The alloca() function returns a null pointer if there is insufficient memory.

Wednesday, May 28, 2008

STOPPED JOBS and job control...

When you try to exit a window or logout, you may get a message:

There are stopped jobs.

This means that a program you were running has been suspended (usually by
typing Ctrl-Z) and has not been properly terminated. If you just try to exit
again, the system will automatically terminate those jobs. If you want to see
what those jobs are, use the 'jobs' command. Just type:

jobs

You will see a listing, which may look like this:

[1] - Stopped foo
[2] + Stopped bar

If you want to continue using one of the jobs in the list, use the 'fg'
command. For example, if you wanted to continue using 'foo' in the above
listing, type this:

fg %1

Actually, the 'fg' part is optional. So, you could just type:

%1

...and get the same effect. If instead you want to just terminate a job, use
the 'kill' command. For example, if you wanted to kill 'bar' in the above
listing, type this:

kill %2

The information below describes jobs in much more detail, if you're
interested.

The shell associates a job with each pipeline (most often a single
command/program) It keeps a table of current jobs, printed by the "jobs"
command, and assigns them small integer numbers. When a job is started
asynchronously with '&' (started in the background), the shell prints a line
which looks like:

[1] 1234

indicating that the job that was started asynchronously was job number 1 and
had one (top-level) process, whose process ID number was 1234.

If you are running a job and wish to do something else, you may type Ctrl-Z,
which sends a STOP signal to the current job. The shell will then normally
indicate that the job has been 'Stopped', and print another prompt. You can
then manipulate the state of this job, putting it in the background with the
'bg' command, or run some other commands and then eventually bring the job
back into the foreground with the foreground command 'fg'. A Ctrl-Z takes
effect immediately and is like an interrupt in that pending output and unread
input are discarded when it is typed. There is another special key, Ctrl-Y,
which does not generate a STOP signal until a program attempts to read(2) it.
This can be typed ahead when you have prepared some commands for a job which
you wish to stop after it has read them.

A job being run in the background will stop if it tries to read from the
terminal. Background jobs are normally allowed to produce output, but this
can be disabled by giving the command 'stty tostop'. If you set this tty
option, then background jobs will stop when they try to produce output like
they do when they try to read input.

There are several ways to refer to jobs in the shell. The character '%'
introduces a job name. If you wish to refer to job number 1, you can name it
as '%1'. Just naming a job brings it to the foreground; thus '%1' is a
synonym for 'fg %1', bringing job 1 back into the foreground. Similarly
saying '%1 &' resumes job 1 in the background. Jobs can also be named by
prefixes of the string typed in to start them, if these prefixes are
unambiguous, thus '%ex' would normally restart a suspended ex(1) job, if there
were only one suspended job whose name began with the string 'ex'. It is also
possible to say '%?string' which specifies a job whose text contains string,
if there is only one such job.

The shell maintains a notion of the current and previous jobs. In output
pertaining to jobs, the current job is marked with a '+' and the previous job
with a '-'. The abbreviation '%+' refers to the current job and '%-' refers
to the previous job. For close analogy with the syntax of the history
mechanism, '%%' is also a synonym for the current job.

Tuesday, May 27, 2008

Writing Technical Articles!!

Writing Technical Articles

The notes below apply to technical papers in computer science and electrical engineering, with emphasis on papers in systems and networks.

Read Strunk and White, Elements of Style. Again.

Give the paper to somebody else to read. If you can, find two people: one person familiar with the technical matter, another only generally familiar with the area.

Papers can be divided roughly into two categories, namely original research papers and survey papers. There are papers that combine the two elements, but most publication venues either only accept one or the other type or require the author to identify whether the paper should be evaluated as a research contribution or a survey paper. (Most research papers contain a "related work" section that can be considered a survey, but it is usually brief compared to the rest of the paper and only addresses a much narrower slice of the field.)

Research Papers


A good research paper has a clear statement of the problem the paper is addressing, the proposed solution(s), and results achieved. It describes clearly what has been done before on the problem, and what is new.

The goal of a paper is to describe novel technical results. There are four types of technical results:

  1. An algorithm;
  2. A system construct: such as hardware design, software system, protocol, etc.;
    One goal of the paper is to ensure that the next person who designs a system like yours doesn't make the same mistakes and takes advantage of some of your best solutions. So make sure that the hard problems (and their solutions) are discussed and the non-obvious mistakes (and how to avoid them) are discussed. (Craig Partridge)
  3. A performance evaluation: obtained through analyses, simulation or measurements;
  4. A theory: consisting of a collection of theorems.
A paper should focus on
  • describing the results in sufficient details to establish their validity;
  • identifying the novel aspects of the results, i.e., what new knowledge is reported and what makes it non-obvious;
  • identifying the significance of the results: what improvements and impact do they suggest.

Paper Structure

  • Typical outline of a paper is:
    • Abstract, typically not more than 100-150 words;
    • Introduction (brief!): introduce problem, outline solution; the statement of the problem should include a clear statement why the problem is important (or interesting).
    • Related Work (or before summary). Hint: In the case of a conference, make sure to cite the work of the PC co-chairs and as many other PC members as are remotely plausible, as well as from anything relevant from the previous two proceedings. In the case of a journal or magazine, cite anything relevant from last 2-3 years or so volumes.
    • Outline of the rest of the paper: "The remainder of the paper is organized as follows. In Section 2, we introduce ..Section 3 describes ... Finally, we describe future work in Section 5." [Note that Section is capitalized. Also, vary your expression between "section" being the subject of the sentence, as in "Section 2 discusses ..." and "In Section, we discuss ...".]
    • Body of paper
      • problem
      • approach, architecture
      • results

      The body should contain sufficient motivation, with at least one example scenario, preferably two, with illustrating figures, followed by a crisp generic problem statement model, i.e., functionality, particularly emphasizing "new" functionality. The paper may or may not include formalisms. General evaluations of your algorithm or architecture, e.g., material proving that the algorithm is O(log N), go here, not in the evaluation section.

      Architecture of proposed system(s) to achieve this model should be more generic than your own peculiar implementation. Always include at least one figure.

      Realization: contains actual implementation details when implementing architecture isn't totally straightforward. Mention briefly implementation language, platform, location, dependencies on other packages and minimum resource usage if pertinent.

      Evaluation: How does it really work in practice? Provide real or simulated performance metrics, end-user studies, mention external technology adoptors, if any, etc.

    • Related work, if not done at the beginning
    • Summary and Future Work
      • often repeats the main result
    • Acknowledgements
    • Bibliography
    • Appendix (to be cut first if forced to):
      • detailed protocol descriptions
      • proofs with more than two lines
      • other low-level but important details

It is recommended that you write the approach and results sections first, which go together. Then problem section, if it is separate from the introduction. Then the conclusions, then the intro. Write the intro last since it glosses the conclusions in one of the last paragraphs. Finally, write the abstract. Last, give your paper a title.

Title

  • Avoid all but the most readily understood abbreviations.
  • Avoid common phrases like "novel", "performance evaluation" and "architecture", since almost every paper does a performance evaluation of some architecture and it better be novel. Unless somebody wants to see 10,000 Google results, nobody searches for these types of words.

    Use adjectives that describe the distinctive features of your work, e.g., reliable, scalable, high-performance, robust, low-complexity, or low-cost. (There are obviously exceptions, e.g., when the performance evaluation is the core of the paper. Even in that case, something more specific is preferable, as in "Delay measurements of X" or "The quality of service for FedEx deliveries".)

  • If you need inspiration for a paper title, you can consult the Automatic Systems Research Topic or Paper Title Generator.

Authors

The IEEE policies (Section 6.4.1) used to state the following about authorship:
The IEEE affirms that authorship credit must be reserved for individuals who have met each of the following conditions: 1) made a significant intellectual contribution to the theoretical development, system or experimental design, prototype development, and/or the analysis and interpretation of data associated with the work contained in the manuscript, 2) contributed to drafting the article or reviewing and/or revising it for intellectual content, and 3) approved the final version of the manuscript, including references.

This has now moved to the IEEE PSPB Operations Manual, Section 8.2.1.

Abstract

  • The abstract must not contain references, as it may be used without the main article. It is acceptable, although not common, to identify work by author, abbreviation or RFC number. (For example, "Our algorithm is based upon the work by Smith and Wesson.")
  • Avoid use of "in this paper" in the abstract. What other paper would you be talking about here?
  • Avoid general motivation in the abstract. You do not have to justify the importance of the Internet or explain what QoS is.
  • Highlight not just the problem, but also the principal results. Many people read abstracts and then decide whether to bother with the rest of the paper.
  • Since the abstract will be used by search engines, be sure that terms that identify your work are found there. In particular, the name of any protocol or system developed and the general area ("quality of service", "protocol verification", "service creation environment") should be contained in the abstract.
  • Avoid equations and math. Exceptions: Your paper proposes E = m c 2.

Introduction

  • Avoid stock and cliche phrases such as "recent advances in XYZ" or anything alluding to the growth of the Internet.
  • Be sure that the introduction lets the reader know what this paper is about, not just how important your general area of research is. Readers won't stick with you for three pages to find out what you are talking about.
  • The introduction must motivate your work by pinpointing the problem you are addressing and then give an overview of your approach and/or contributions (and perhaps even a general description of your results). In this way, the intro sets up my expectations for the rest of your paper -- it provides the context, and a preview.
  • Repeating the abstract in the introduction is a waste of space.
  • Example bad introduction:

    Here at the institute for computer research, me and my colleagues have created the SUPERGP system and have applied it to several toy problems. We had previously fumbled with earlier versions of SUPERGPSYSTEM for a while. This system allows the programmer to easily try lots of parameters, and problems, but incorporates a special constraint system for parameter settings and LISP S-expression parenthesis counting.

    The search space of GP is large and many things we are thinking about putting into the supergpsystem will make this space much more colorful.

  • A pretty good introduction, drawn from Eric Siegel's class:

    Many new domains for genetic programming require evolved programs to be executed for longer amounts of time. For example, it is beneficial to give evolved programs direct access to low-level data arrays, as in some approaches to signal processing \cite{teller5}, and protein segment classification \cite{handley,koza6}. This type of system automatically performs more problem-specific engineering than a system that accesses highly preprocessed data. However, evolved programs may require more time to execute, since they are solving a harder task.

    Previous or obvious approach:
    (Note that you can also have a related work section that gives more details about previous work.)) One way to control the execution time of evolved programs is to impose an absolute time limit. However, this is too constraining if some test cases require more processing time than others. To use computation time efficiently, evolved programs must take extra time when it is necessary to perform well, but also spend less time whenever possible.
    Approach/solution/contribution:
    The first sentence of a paragraph like this should say what the contribution is. Also gloss the results.

    In this chapter, we introduce a method that gives evolved programs the incentive to strategically allocate computation time among fitness cases. Specifically, with an aggregate computation time ceiling imposed over a series of fitness cases, evolved programs dynamically choose when to stop processing each fitness case. We present experiments that show that programs evolved using this form of fitness take less time per test case on average, with minimal damage to domain performance. We also discuss the implications of such a time constraint, as well as its differences from other approaches to {\it multiobjective problems}. The dynamic use of resources other than computation time, e.g., memory or fuel, may also result from placing an aggregate limit over a series of fitness cases.

    Overview:
    The following section surveys related work in both optimizing the execution time of evolved programs and evolution over Turing-complete representations. Next we introduce the game Tetris as a test problem. This is followed by a description of the aggregate computation time ceiling, and its application to Tetris in particular. We then present experimental results, discuss other current efforts with Tetris, and end with conclusions and future work.

Body of Paper

Hints and common mistakes

Bibliography

  • Avoid use of et al. in a bibliography unless list is very long (five or more authors). The author subsumed into et al. may be your advisor or the reviewer... Note punctuation of et al..
  • If writing about networks or multimedia, use the network bibliography. All entries not found there should be sent to me. A listing of frequently-used references for networks is available.
  • Internet drafts must be marked ``work in progress''. Make sure that they have been replaced by newer versions or RFCs. Any Internet Draft reference older than six months should automatically be suspicious since Internet Drafts expire after that time period.
  • Book citations include publication years, but no ISBN number.
  • It is now acceptable to include URLs to material, but it is probably bad form to include a URL pointing to the author's web page for papers published in IEEE and ACM publications, given the copyright situation. Use it for software and other non-library material. Avoid long URLs; it may be sufficient to point to the general page and let the reader find the material. General URLs are also less likely to change.
  • Leave a space between first names and last name, i.e., "J. P. Doe", not "J.P.Doe".
  • References such as
    John Doe, "Some paper on something", technical report.
    are useless. Cite the source, date and other identifying information.
  • For conference papers, you MUST name the conference location, month and the full conference name, not just some abbreviation. Page numbers are nice, but optional. All of this information is readily available via the IEEE or ACM digital libraries.
  • Check if Internet drafts have been published as RFCs or if there's a newer version.
  • Having a citation
    Jane Doe, "Some random paper", to be published, 2003.
    is useless, as the paper has presumably been published by now. Google or the ACM or IEEE digital libraries will help you find it.

Acknowledgements

  • Acknowledge your funding sources. Some sources have specific wording requirements and may prefer that the grant number is listed. The NSF requires text like "This work was supported by the National Science Foundation under grant EIA NN-NNNNN."
  • Generally, anonymous reviewers don't get acknowledged, unless they really provided an exceptional level of feedback or insight. Rather than "We thank X for helping us with Y", you might vary this as "X helped with Y.".

Reporting Numerical Results and Simulations

In all but extended abstracts, numerical results and simulations should be reported in enough detail that the reader can duplicate the results. This should include all parameters used, indications of the number of samples that contributed to the analysis and any initial conditions, if relevant.

When presenting simulation results, provide insight into the statistical confidence. If at all possible, provide confidence intervals. If there's a "strange" behavior in the graph (e.g., a dip, peak or change in slope), this behavior either needs to be explained or reasons must be given why this is simply due to statistical aberration. In the latter case, gathering more samples is probably advised.

Figures should be chosen wisely. You can never lay out the whole parameter space, so provide insight into which parameters are significant over what range and which ones are less important. It's not very entertaining to present lots of flat or linear lines.

The description of the graph should not just repeat the graphically obvious such as "the delay rises with the load", but explain, for example, how this increase relates to the load increase. Is it linear? Does it follow some well-known other system behaviors such as standard queueing systems?

LaTeX Considerations

  • There's no need to enclose numbers in $$ (math mode).
  • Use \cite{a,b,c}, not \cite{a} \cite{b} \cite{c}.
  • Use the \usepackage{times} option for LaTeX2e - it comes out much nicer on printers with different resolutions. Plus, compared to cmr, it probably squeezes an extra 10% of text out of your conference allotment.
  • Multi-letter subscripts are set in roman, not italics. For example,
    x_{\mathrm max}
  • For uniformity, use the LaTeX2e graphics set, not the earlier psfigure set:
    \usepackage{graphics}
    ...
    \begin{figure}
    \resizebox{!}{0.5\textheight}{\includegraphics{foo.eps}}
    \caption{Some figure}
    \label{fig:figure}
    \end{figure}

Things to Avoid

Too much motivational material
Three reasons are enough -- and they should be described very briefly.
Describing the obvious parts of the result
"Obvious" is defined as any result that a graduate of our program would suggest as a solution if you pose the problem that the result solves.
Describing unnecessary details
A detail is unnecessary, if its omission will not harm the reader's ability to understand the important novel aspects of the result.
Spelling errors
With the availability of spell checkers, there is no reason to have spelling errors in a manuscript. If you as the author didn't take the time to spell-check your paper, why should the editor or reviewer take the time to read it or trust that your diligence in technical matters is any higher than your diligence in presentation? Note, however, that spell checkers don't catch all common errors, in particular word duplication ("the the"). If in doubt, consult a dictionary such as the (on line) Merriam Webster.
Text in Arial:
Arial and other sans-serif fonts are fine for slides and posters, but are harder to read in continuous text. Use Times Roman or similar serif fonts. Unusual fonts are less likely to be available at the recipient and may cause printing or display problems.

Guidelines for Experimental Papers

"Guidelines for Experimental Papers" set forth for researchers submitting articles to the journal, Machine Learning.
  1. Papers that introduce a new learning "setting" or type of application should justify the relevance and importance of this setting, for example, based on its utility in applications, its appropriateness as a model of human or animal learning, or its importance in addressing fundamental questions in machine learning.
  2. Papers describing a new algorithm should be clear, precise, and written in a way that allows the reader to compare the algorithm to other algorithms. For example, most learning algorithms can be viewed as optimizing (at least approximately) some measure of performance. A good way to describe a new algorithm is to make this performance measure explicit. Another useful way of describing an algorithm is to define the space of hypotheses that it searches when optimizing the performance measure.
  3. Papers introducing a new algorithm should conduct experiments comparing it to state-of-the-art algorithms for the same or similar problems. Where possible, performance should also be compared against an absolute standard of ideal performance. Performance should also be compared against a naive standard (e.g., random guessing, guessing the most common class, etc.) as well. Unusual performance criteria should be carefully defined and justified.
  4. All experiments must include measures of uncertainty of the conclusions. These typically take the form of confidence intervals, statistical tests, or estimates of standard error. Proper experimental methodology should be employed. For example, if "test sets" are used to measure generalization performance, no information from the test set should be available to the learning process.
  5. Descriptions of the software and data sufficient to replicate the experiments must be included in the paper. Once the paper has appeared in Machine Learning, authors are strongly urged to make the data used in experiments available to other scientists wishing to replicate the experiments. An excellent way to achieve this is to deposit the data sets at the Irvine Repository of Machine Learning Databases. Another good option is to add your data sets to the DELVE benchmark collection at the University of Toronto. For proprietary data sets, authors are encouraged to develop synthetic data sets having the same statistical properties. These synthetic data sets can then be made freely available.
  6. Conclusions drawn from a series of experimental runs should be clearly stated. Graphical display of experimental data can be very effective. Supporting tables of exact numerical results from experiments should be provided in an appendix.
  7. Limitations of the algorithm should be described in detail. Interesting cases where an algorithm fails are important in clarifying the range of applicability of an algorithm.

Other Hints and Notes

From Bill Stewart (Slashdot, May 7, 2006), edited

  • Write like a newspaper reporter, not a grad student.
  • Your objective is clear communication to the reader, not beauty or eruditeness or narration of your discoveries and reasoning process. Don't waste their time, or at least don't waste it up front.
  • Hit the important conclusions in the first few sentences so your reader will read them. If you'd like to wrap up with them at the end of your memo, that's fine too, in case anybody's still reading by then, but conclusions come first.
  • If you're trying to express something complex, simplify your writing so it doesn't get in the way. For something simple, 10th grade language structures will do, but if it's really hairy stuff, back down to 8th grade or so.
  • Think about what your audience knows and doesn't know, and what they want and don't want. Express things in terms of what they know and want, not what you know.

From MarkusQ, Slashdot, May 7, 2006

  • Top down design Starting with an outline and working out the details is the normal way of tackling an engineering problem.
  • Checking your facts Engineers should be used to checking anything that is even remotely doubtful before committing to it. So should writers.
  • Failure mode analysis For each sentence ask yourself, could it be misread? How? What is the best way to fix it?
  • Dependency analysis Are the ideas presented in an order that assures that each point can be understood on the basis of the readers assumed knowledge and the information provided by preceding points?
  • Optimization Are there any unnecessary parts? Does the structure require the reader to remember to many details at once, before linking them?
  • Structured testing If you read what you have written assuming only the knowledge that the reader can be expected to have, does each part work the way you intended? If you read it aloud, does it sound the way you intended?

The Conference Review Process

It is hard to generalize the review process for conferences, but most reputable conferences operate according to these basic rules:

  1. The paper is submitted to the technical program chair(s). Many current conferences require electronic submission, in either PostScript or PDF formats, occasionally in Word.
  2. The technical program chair assigns the paper to one or more technical program committee members, hopefully experts in their field. The identity of this TPC member is kept secret.
  3. The TPC member usually provides a review, but may also be asked to find between one and three reviewers who are not members of the TPC. They may be colleagues of the reviewer at the same institution, his or her graduate students or somebody listed in the references. The graduate student reviews can be quite helpful, since these reviewers often provide more detailed criticism rather than blanket dismissal. Any good conference will strive to provide at least three reviews, however, since conferences operate under tight deadlines and not all reviewers deliver as promised, it is not uncommon that you receive only two reviews.
  4. In some conferences, there is an on-line discussion of papers among the reviewers for a particular paper. Usually, a lead TPC member drives the discussion and then recommends the paper for acceptance, rejection or discussion at the TPC meeting.
  5. The technical program chair then collects the reviews and sorts the papers according to their average review scores.
  6. The TPC (or, rather, the subset that can make the meeting), then meets in person or by phone conference. Usually, the bottom third and the top third are rejected and accepted, respectively, without (much) further discussion. The papers discussed are those in the middle of the range, or where a TPC member feels strongly that the paper ended up in the wrong bin, or where the review scores differ significantly. Papers that only received two reviews are also often discussed, maybe with a quick review by one of the TPC members as additional background. The rigor of the TPC meeting depends on the size and reputation of the conference. In some workshops and conferences, the TPC chairs may well make the final decision themselves, without involving the whole TPC.

Other References

Talks

Friday, May 23, 2008

__fastcall

__fastcall (Microsoft Specific)

The __fastcall calling convention specifies that arguments to functions are to be passed in registers, when possible. The following list shows the implementation of this calling convention.
Element Implementation
Argument-passing order The first two DWORD or smaller arguments are passed in ECX and EDX registers; all other arguments are passed right to left.
Stack-maintenance responsibility Called function pops the arguments from the stack.
Name-decoration convention At sign (@) is prefixed to names; an at sign followed by the number of bytes (in decimal) in the parameter list is suffixed to names.
Case-translation convention No case translation performed.

Note Future compiler versions may use different registers to store parameters.

Using the /Gr compiler option causes each function in the module to compile as fastcall unless the function is declared with a conflicting attribute, or the name of the function is main.
Example

In the following example, the function named DeleteAggrWrapper is passed arguments in registers:
Copy Code

// Example of the __fastcall keyword
#define FASTCALL __fastcall

void FASTCALL DeleteAggrWrapper(void* pWrapper);
// Example of the __ fastcall keyword on function pointer
typedef BOOL (__fastcall *funcname_ptr)(void * arg1, const char * arg2, DWORD flags, ...);

Thursday, May 22, 2008

Callback Functions!!

What Is a Callback Function?
The simple answer to this first question is that a callback function is a function that is called through a function pointer.
If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function
it points to it is said that a call back is made.

Why Should You Use Callback Functions?
Because they uncouple the caller from the callee. The caller doesn't care who the callee is; all it knows is that there
is a callee with a certain prototype and probably some restriction (for instance, the returned value can be int,
but certain values have certain meanings).

If you are wondering how is that useful in practice, imagine that you want to write a library that provides implementation
for sorting algorithms (yes, that is pretty classic), such as bubble sort, shell short, shake sort, quick sort, and others.
The catch is that you don't want to embed the sorting logic (which of two elements goes first in an array) into your functions,
making your library more general to use. You want the client to be responsible to that kind of logic. Or, you want it to be used
for various data types (ints, floats, strings, and so on). So, how do you do it? You use function pointers and make callbacks.

A callback can be used for notifications. For instance, you need to set a timer in your application.
Each time the timer expires, your application must be notified. But, the implementer of the time'rs mechanism doesn't know
anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it
makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback
function to notify that the timer has expired (and, in case there is no callback function provided, it posts a message to the
application's queue).

Another example from WinAPI functions that use callback mechanism is EnumWindow(), which enumerates all the top-level windows
on the screen. EnumWindow() iterates over the top-level windows, calling an application-provided function for each window,
passing the handler of the window. If the callee returns a value, the iteration continues; otherwise, it stops.
EnumWindows() just doesn't care where the callee is and what it does with the handler it passes over.
It is only interested in the return value, because based on that it continues its execution or not.

However, callback functions are inherited from C. Thus, in C++, they should be only used for interfacing C code and existing
callback interfaces. Except for these situations, you should use virtual methods or functors, not callback functions.


A Simple Implementation Example

Now, follow the example that can be found in the attached files. I have created a dynamic linked library called sort.dll. It exports a type called CompareFunction:

typedef int (__stdcall *CompareFunction)(const byte*, const byte*);

which will be the type of your callback functions. It also exports two methods, called Bubblesort() and Quicksort(), which have the same prototype but provide different behavior by implementing the sorting algorithms with the same name.

void DLLDIR __stdcall Bubblesort(byte* array,
int size,
int elem_size,
CompareFunction cmpFunc);

void DLLDIR __stdcall Quicksort(byte* array,
int size,
int elem_size,
CompareFunction cmpFunc);

These two functions take the following parameters:

The implementation of these two functions performs a sorting of the array. But, each time there is a need to decide which of two elements goes first, a callback is made to the function whose address was passed as an argument. For the library writer, it doesn't matter where that function is implemented, or how it is implemented. All that matters it is that it takes the address of two elements (that are the two be compared) and it returns one of the following values (this is a contract between the library developers and its clients):

With this contract explicitly stated, the implementation of the Bubblesort() function is this (for Quicksort(), which a little bit more complicated, see the attached files).

void DLLDIR __stdcall Bubblesort(byte* array,
int size,
int elem_size,
CompareFunction cmpFunc)
{
for(int i=0; i < size; i++)
{
for(int j=0; j < size-1; j++)
{
// make the callback to the comparison function
if(1 == (*cmpFunc)(array+j*elem_size,
array+(j+1)*elem_size))
{
// the two compared elements must be interchanged
byte* temp = new byte[elem_size];
memcpy(temp, array+j*elem_size, elem_size);
memcpy(array+j*elem_size,
array+(j+1)*elem_size,
elem_size);
memcpy(array+(j+1)*elem_size, temp, elem_size);
delete [] temp;
}
}
}
}
Note: Because the implementation uses memcpy(), these library functions should not be used for types other than POD (Plain-Old-Data).

On the client side, there must be a callback function whose address is to be passed to the Bubblesort() function. As a simple example, I have written a function that compares two integer values and one that compares two strings:

int __stdcall CompareInts(const byte* velem1, const byte* velem2)
{
int elem1 = *(int*)velem1;
int elem2 = *(int*)velem2;

if(elem1 < elem2)
return -1;
if(elem1 > elem2)
return 1;

return 0;
}

int __stdcall CompareStrings(const byte* velem1, const byte* velem2)
{
const char* elem1 = (char*)velem1;
const char* elem2 = (char*)velem2;

return strcmp(elem1, elem2);
}

To put all these to a test, I have written this short program. It passes an array with five elements to Bubblesort() or Quicksort() along with the pointer to the callback functions.

int main(int argc, char* argv[])
{
int i;
int array[] = {5432, 4321, 3210, 2109, 1098};

cout << "Before sorting ints with Bubblesort\n";
for(i=0; i < 5; i++)
cout << array[i] << '\n';

Bubblesort((byte*)array, 5, sizeof(array[0]), &CompareInts);

cout << "After the sorting\n";
for(i=0; i < 5; i++)
cout << array[i] << '\n';

const char str[5][10] = {"estella",
"danielle",
"crissy",
"bo",
"angie"};

cout << "Before sorting strings with Quicksort\n";
for(i=0; i < 5; i++)
cout << str[i] << '\n';

Quicksort((byte*)str, 5, 10, &CompareStrings);

cout << "After the sorting\n";
for(i=0; i < 5; i++)
cout << str[i] << '\n';

return 0;
}

If I decide that I want the sorting to be done descending (with the biggest element first), all I have to do is to change the callback function code, or provide another that implements the desired logic.

Calling Conventions

In the above code, you can see the word __stdcall in the function's prototype. Because it starts with a double underscore, it is, of course, a compiler-specific extension, more exactly a Microsoft-specific one. Any compiler that supports development of Win32-based applications must support this or an equivalent one. A function that is marked with __stdcall uses the standard calling convention so named because all Win32 API functions (except the few that take variable arguments) use it. Functions that follow the standard calling convention remove the parameters from the stack before they return to the caller. This is the standard convention for Pascal. But in C/C++, the calling convention is that the caller cleans up the stack instead of the called function. To enforce that a function uses the C/C++ calling convention, __cdecl must be used. Variable argument functions use the C/C++ calling convention.

Windows adopted the standard calling convention (Pascal convention) because it reduces the size of the code. This was very important in the early days of Windows, when it ran on systems with 640 KB RAM.

If you don't like the word __stdcall, you can use the CALLBACK macro, defined in windef.h, as

Tuesday, May 13, 2008

21st century bride !!

A newly wed girl was being welcomed at the husband's home in a traditional manner.

She was asked to give a little speech. She addressed as follows:

"My dear family members, I thank you for welcoming me in my new home and family",

she said "Firstly, with my presence I would not want to create any inconveniences by my being here. I mean that I don't want you all to change your way of life, your routine."

"What do you mean my child?" asked the patriarch of the family.

What I mean dad is:

Those who used to wash dishes must carry on washing them.
Those who used to do the laundry must carry on doing it.
Those who cooked shouldn't stop on my account.
Those who used to clean should clean.

As for me, I am here just to control your son!

********

This is called bride from 21st Century!!!!

Who needs prayers ??

A lady approaches a priest and tells him, "Father, I have a problem. I have these two talking female parrots, but they only know how to say one thing. They keep saying "Hi, we're hot. Do you want a date?"


"That's terrible!" the priest exclaimed. "But I do have a solution to your problem. Bring your two parrots over to my house and I will put them with my two male talking parrots to whom I have taught to pray and read the bible.

My parrots will then teach your parrots to stop saying that terrible phrase, and your female parrots will learn to pray and worship."


So the next day, the lady brings her female parrots to the priest's house. The priest's two male parrots are holding rosary beads and praying in their cage. The lady puts her female talking parrots in with the male alking Parrots, and the female parrots say, "Hi, we're hot. Do you want a date?"


One male parrot looks over at the other male parrot and screams, "Put your Bible away Idiot, our prayers have been answered!!!!!!!"

~~~~~~~~

Funny Management Lessons...

Lesson 1:

A man is getting into the shower just as his wife is finishing up her shower, when the doorbell rings.
The wife quickly wraps herself in a towel and runs downstairs. When she opens the door, there stands Bob, the next-door neighbor.
Before she says a word, Bob says, "I'll give you $800 to drop that towel, "
After thinking for a moment, the woman drops her towel and stands naked in front of Bob After a few seconds, Bob hands her $800 and leaves.
The woman wraps back up in the towel and goes back upstairs.
When she gets to the bathroom, her husband asks, "Who was that?"
"It was Bob the next door neighbor," she replies.
"Great," the husband says, "did he say anything about the $800 he owes me?"

Moral of the story
If you share critical information pertaining to credit and risk with your shareholders in time,you may be in a position to prevent avoidable exposure.


*********

Lesson 2:

A priest offered a Nun a lift. She got in and crossed her legs, forcing her gown to reveal a leg. The priest nearly had an accident. After controlling the car, he stealthily slid his hand up her leg.
The nun said, "Father, remember Psalm 129?"
The priest removed his hand. But, changing gears, he let his hand slide up her leg again.
The nun once again said, "Father, remember Psalm 129?"
The priest apologized "Sorry sister but the flesh is weak."
Arriving at the convent, the nun sighed heavily and went on her way.
On his arrival at the church, the priest rushed to look up Psalm 129 It said, "Go forth and seek, further up, you will find glory."


Moral of the story
If you are not well informed in your job, you might miss a great opportunity.


*********

Lesson 3:

A sales rep, an administration clerk, and the manager are walking to lunch when they find an antique oil lamp. They rub it and a Genie comes out.
The Genie says, "I'll give each of you just one wish."
"Me first! Me first!" says the admin clerk. "I want to be in the Bahamas, driving a speedboat, without a care in the world."
Puff! She's gone.
"Me next! Me next!" says the sales rep. "I want to be in Hawaii, relaxing on the beach with my personal masseuse, an endless supply of Pina Coladas and the love of my life."
Puff! He's gone.
"OK, you're up," the Genie says to the manager.
The manager says, "I want those two back in the office after lunch."

Moral of the story
Always let your boss have the first say.


*********

Lesson 4:

An eagle was sitting on a tree resting, doing nothing. A small rabbit saw the eagle and asked him, "Can I also sit like you and do nothing?"
The eagle answered: "Sure , why not."
So, the rabbit sat on the ground below the eagle and rested. All of a sudden, a fox appeared, jumped on the rabbit and ate it.

Moral of the story
To be sitting and doing nothing, you must be sitting very, very high up.


*********

Lesson 5:

A turkey was chatting with a bull. "I would love to be able to get to the top of that tree," sighed the turkey,"but I haven't got the energy."
"Well, why don't you nibble on some of my droppings?" replied the bull.
They're packed with nutrients."
The turkey pecked at a lump of dung, and found it actually gave him enough strength to reach the lowest branch of the tree.
The next day, after eating some more dung, he reached the second branch.
Finally after a fourth night, the turkey was proudly perched at the top of the tree. He was promptly spotted by a farmer, who shot him out of the tree.

Moral of the story
BullShit might get you to the top, but it won't keep you there.


*********

Lesson 6:

A little bird was flying south for the Winter.It was so cold the bird froze and fell to the ground into a large field. While he was lying there, a cow came by and dropped some dung on him. As the frozen bird lay there in the pile of cow dung, he began to realize how warm he was.
The dung was actually thawing him out! He lay there all warm and happy, and soon began to sing for joy.
A passing cat heard the bird singing and came to investigate.
Following the sound, the cat discovered the bird under the pile of cow dung, and promptly dug him out and ate him.

Morals of this story

(1) Not everyone who shits on you is your enemy.


(2) Not everyone who gets you out of shit is your friend.

(3) And when you're in deep shit, it's best to keep your mouth
shut!

Friday, May 09, 2008

cron job details...

To see all the Cron jobs aunder one user use command ..
>>> crontab -l

To add a new Cron job for a user u can use the command...
>>>> crontab -e

While adding one job to the crontab u have to follow following format...

Syntax of crontab

Your cron job looks like as follows:
1 2 3 4 5 /path/to/command arg1 arg2

Where,

  • 1: Minute (0-59)
  • 2: Hours (0-23)
  • 3: Day (0-31)
  • 4: Month (0-12 [12 == December])
  • 5: Day of the week(0-7 [7 or 0 == sunday])
  • /path/to/command - Script or command name to schedule

Same above five fields structure can be easily remembered with following diagram:

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Use of operators

An operator allows you to specifying multiple values in a field. There are three operators:

  1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".
  3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing "5,6,7,8,9,....,13,14,15" using the comma operator.


one example :
55 00 * * * env OMC_TOP=/usr/omc /usr/omc/sbin/maintain_script -r -d 7 /usr/omc/logs gpomcaudit\* #MOMC42 parser audit files +7 days