Question:
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...

At a core level, what does bit-shifting (<<, >>, >>>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.

Answer:
Let's say we have a single byte:
```
```
0110110
```
```
Applying a single left bitshift gets us:
```
```
1101100
```
```
The leftmost zero was shifted out of the byte, and a new zero was appended to the right end of the byte.
The bits don't rollover; they are discarded. That means if you left shift 1101100 and then right shift it, you won't get the same result back.
Shifting left by N is equivalent to multiplying by 2
N
.
Shifting right by N is (if you are using
ones' complement
) is the equivalent of dividing by 2
N
and rounding to zero.
Bitshifting can be used for insanely fast multiplication and division, provided you are working with a power of 2. Almost all low-level graphics routines use bitshifting.
For example, way back in the olden days, we used mode 13h (320x200 256 colors) for games. In Mode 13h, the video memory was laid out sequentially per pixel. That meant to calculate the location for a pixel, you would use the following math:
```
```
memoryOffset = (row * 320) + column
```
```
Now, back in that day and age, speed was critical, so we would use bitshifts to do this operation.
However, 320 is not a power of two, so to get around this we have to find out what is a power of two that added together makes 320:
```
```
(row * 320) = (row * 256) + (row * 64)
```
```
Now we can convert that into left shifts:
```
```
(row * 320) = (row << 8) + (row << 6)
```
```
For a final result of:
```
```
memoryOffset = ((row << 8) + (row << 6)) + column
```
```
Now we get the same offset as before, except instead of an expensive multiplication operation, we use the two bitshifts...in x86 it would be something like this (note, it's been forever since I've done assembly (editor's note: corrected a couple mistakes and added a 32-bit example)):
```
```
mov ax, 320; 2 cycles
mul word [row]; 22 CPU Cycles
mov di,ax; 2 cycles
add di, [column]; 2 cycles
; di = [row]*320 + [column]

; 16-bit addressing mode limitations:
; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov
```
```
Total: 28 cycles on whatever ancient CPU had these timings.
Vrs
```
```
mov ax, [row]; 2 cycles
mov di, ax; 2
shl ax, 6;  2
shl di, 8;  2
add di, ax; 2    (320 = 256+64)
add di, [column]; 2
; di = [row]*(256+64) + [column]
```
```
12 cycles on the same ancient CPU.
Yes, we would work this hard to shave off 16 CPU cycles.
In 32 or 64-bit mode, both versions get a lot shorter and faster.  Modern out-of-order execution CPUs like Intel Skylake (see
http://agner.org/optimize/
) have very fast hardware multiply (low latency and high throughput), so the gain is much smaller.  AMD Bulldozer-family is a bit slower, especially for 64-bit multiply.  On Intel CPUs, and AMD Ryzen, two shifts are slightly lower latency but more instructions than a multiply (which may lead to lower throughput):
```
```
imul edi, [row], 320    ; 3 cycle latency from [row] being ready
add  edi, [column]      ; 1 cycle latency (from [column] and edi being ready).
; edi = [row]*(256+64) + [column],  in 4 cycles from [row] being ready.
```
```
vs.
```
```
mov edi, [row]
shl edi, 6               ; row*64.   1 cycle latency
lea edi, [edi + edi*4]   ; row*(64 + 64*4).  1 cycle latency
add edi, [column]        ; 1 cycle latency from edi and [column] both being ready
; edi = [row]*(256+64) + [column],  in 3 cycles from [row] being ready.
```
```
Compilers will do this for you: See how
GCC, Clang, and Microsoft Visual C++ all use shift+lea when optimizing
```
return 320*row + col;
```
.
The most interesting thing to note here is that
x86 has a shift-and-add instruction (
```
LEA
```
)
that can do small left shifts and add at the same time, with the performance as an
```
add
```
instruction.  ARM is even more powerful: one operand of any instruction can be left or right shifted for free.  So scaling by a compile-time-constant that's known to be a power-of-2 can be even more efficient than a multiply.
OK, back in the modern days... something more useful now would be to use bitshifting to store two 8-bit values in a 16-bit integer. For example, in C#:
```
```
// Byte1: 11110000
// Byte2: 00001111

Int16 value = ((byte)(Byte1 >> 8) | Byte2));

// value = 000011111110000;
```
```
In C++, compilers should do this for you if you used a
```
struct
```
with two 8-bit members, but in practice they don't always.


Question:
Let's say I have a class that has a member called data which is a list.

I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.

What's your technique for doing this?

Do you just check the type by looking at __class__?

Is there some trick I might be missing?

I'm used to C++ where overloading by argument type is easy.

Answer:
A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:
```
```
def __init__ (self, filename):
    if isinstance (filename, basestring):
        # filename is a string
    else:
        # try to convert to a list
        self.path = list (filename)
```
```


Question:
I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project.

I am not asking for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?).

Thank you, and I will edit the question for clarity if anyone needs it.

Answer:
This is going to be a streaming endeavor.
If you can, do not use transactions here. The transactional cost will simply be too great.
So what you're going to do is read the file a line at a time and insert it in a line at a time. You should dump failed inserts into another file that you can diagnose later and see where they failed.
At first I would go ahead and try a bulk insert of a couple of hundred rows just to see that the streaming is working properly and then you can open up all you want.


Question:
I can select all the distinct values in a column in the following ways:

SELECT DISTINCT column_name FROM table_name;

SELECT column_name FROM table_name GROUP BY column_name;

But how do I get the row count from that query? Is a subquery required?

Answer:
```
```
select Count(distinct columnName) as columnNameCount from tableName
```
```


Question:
What I would like is be able to generate a simple report that is the output of svn log for a certain date range.  Specifically, all the changes since 'yesterday'.

Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?

Example:

svn -v log -d 2008-9-23:2008-9:24 > report.txt

Answer:
Very first hit by google for "svn log date range":
http://svn.haxx.se/users/archive-2006-08/0737.shtml
So
```
svn log <url> -r
  {2008-09-19}:{2008-09-26}
```
will get
  all changes for  the past week,
  including today.
And if you want to generate reports for a repo, there's a solution:
Statsvn
.
HTH


Question:
I have an Enum like this

package com.example;

public enum CoverageEnum {

    COUNTRY,
    REGIONAL,
    COUNTY
}

I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:

<c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
    ${type}
</c:forEach>

But can I achieve the same thing without scriptlets?

Cheers,
Don

Answer:
If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:
```
```
<c:forEach var="type" items="${myprefix:getValues()}">
```
```
EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:
```
```
public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
    try {
        Method m = klass.getMethod("values", null);
        Object obj = m.invoke(null, null);
        return (Enum<T>[])obj;
    } catch(Exception ex) {
        //shouldn't happen...
        return null;
    }
}
```
```


Question:
I've been working with Perl long enough that many of its idiosyncracies have become second nature to me.  When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary).  I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java).

A few things occur to me:

The proper use of sigils

Referencing/Dereferencing

Use of list functions like map,
grep, sort

Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl?  Do you stress the similarities or the differences, or both in equal measure?

Answer:
I'm a java programmer who recently had to pick up Perl.  The part I found hardest to get used to were all the special built in variables like $_ $~ $' and so on.  Until you get used to them it's hard to keep track of which one does what.
And, of course, the use of regular expressions.
For example, I have to maintain code and when I saw the line below for the first time it was a little confusing.  As a java programmer it looks like gibberish.
```
```
next unless "$_" !~ /^#/;
```
```


Question:
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.

Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.

Seeing a code example for a concrete limitation would be great.

Related questions:

Can you explain closures (as they relate to Python)?

What is a ‘Closure’?

How does a javascript closure work ?

Answer:
The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:
```
```
def outer ():
    x = 1
    def inner ():
        print x
        x = 2
    return inner
outer () ()
```
```
Usually just pointing out that a function has its own local variables is enough to deter such silliness.


Question:
I've seen the other post about this, but is there a clean way of doing this in Haskell?

As a 2nd part, can it also be done without making the function monadic?

Answer:
If your arguments are going to be natural numbers, you can do simply:
```
```
memo f = let values = map f [0..]
     in \n -> values !! n
```
```
However, that doesn't really help you with the stack overflowing, and it doesn't work with recursive calls. You can see some fancier solutions at
http://www.haskell.org/haskellwiki/Memoization
.


Question: How do I tar a list of files and folders (all in the same directory) with the exclusion of a single directory (which contains a huge amount of data)

Answer:
```
tar --exclude=PATTERN xvzf nameof.tar.gz ./*
```
PATTERN can be the directory name. GNU tar.


Question:
If I do not specify the following in my web.xml file:

<session-config>
    <session-timeout>10</session-timeout>
</session-config>

What will be my default session timeout? (I am running Tomcat 6.0)

Answer: I'm sure it depends on your container. Tomcat is 30 minutes.


Question:
I have a Python application in a strange state.  I don't want to do live debugging of the process.  Can I dump it to a file and examine its state later?  I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.

(This is a variation on my question about debugging memleaks in a production system.)

Answer:
There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it.
As for handling the corefile of a Python process, the
Python source has a gdbinit file
that contains useful macros. It's still a lot more painful than somehow getting into the process itself (with pdb or the interactive interpreter) but it makes life a little easier.


Question:
I know a Haskell module name, but I can't figure out in what package it is defined. This is bad because I can't compile without a package exposing this module.

Specificaly it is Text.Regex that I can't locate, but I would like to know how to solve that problem in general.

Answer:
http://www.haskell.org/ghc/docs/latest/html/users_guide/packages.html
ghc-pkg find-module Text.Regex
But that only works for (a) recent GHCs, and (b) packages installed on your system.
You can also grep through the package file (e.g. /usr/lib/ghc-6.8.2/package.conf) to see what's installed.
You can also use either the haskell API search engines
hoogle
or the
hackage
search engine
hayoo
.
Text.Regex is in the package regex-base, and a few others built on top of it.


Question:
Motivation

I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.

Possibility 1

Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?

Possibility 2

My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?

Answer:
I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL:
from the "Fundamentals of Computer Graphics"
some sourcecode in C#
- should be easy to adapt to other programming languages.


Question:
I've looked at the java documentation and scoured the net for information on java's support for international characters with specific fonts (such as Monospace), but haven't been able to get a clear concrete answer.

There has been a change between java 1.4 and java 1.5/1.6. For example, in java 1.4 if you set the font on a JTextArea to Monospace, it won't be able to handle foreign characters (get rectangles instead), but in java 1.5/1.6 it seems to work fine.

Are these differences/improved support clearly documented anywhere?

Thanks

Answer:
From
Internationalization Enhancements
:
Multilingual Text Rendering
To render multilingual text, using logical fonts, 2D now takes advantage of installed host OS fonts for all supported writing systems. For example, if you run in a Thai locale environment, but have Korean fonts installed, both Thai and Korean are rendered. The JRE now also automatically detects physical fonts that are installed into its lib/fonts/fallback directory and adds these physical fonts to all logical fonts for 2D rendering.
Use of Unicode APIs on Windows
AWT now uses the Unicode APIs on Windows 2000/XP. As a result, some of its components can handle text without being restricted by Windows locale settings.
For example, AWT text components can accept and display text in the Devanagari writing system regardless of the Windows locale settings.
(emphasis mine)


Question:
What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:

number: (MONTH|INT);

It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:

date: month '/' day ( '/' year )? -> ^('DATE' year month day);

I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:

foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');

Answer:
The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser.  It's a common mistake, and something that is only possible in very simple languages.
What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks.  How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs.  I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates.  The first approach:
```
```
INT: '0'..'9'+;
```
```
The second approach:
```
```
DATENUM: '0' '1'..'9';
INT: '0' | SIGN? '1'..'9' '0'..'9'*;
```
```
After accepting using these rules in the lexer, your date field would be either:
```
```
date: INT '/' INT ( '/' INT )?
```
```
or:
```
```
date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?
```
```
After that, you would perform a semantic run over your AST to make sure that your dates are valid.
If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:
```
```
date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}
```
```
When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.


Question:
The following snippet is supposed to take the value of PROJECT (defined in the Makefile)
and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR

I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?

#define PROJECT classifier

#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)

#include PROJECTINCSTR

Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.

Answer: That barebone example works with gcc (v4.1.2) and tries to include "PROJECT_ir.h"


Question:
This must be a classic .NET question for anyone migrating from Java.

.NET does not seem to have a direct equivalent to java.io.StreamTokenizer, however the JLCA provides a SupportClass that attempts to implement it.  I believe the JLCA also provides a Tokenizer SupportClass that takes a String as the source, which I thought a StreamTokenizer would be derived from, but isn't.

What is the preferred way to Tokenize both a Stream and a String? or is there one? How are streams tokenized in .Net?  I'd like to have the flexibility that java.io.StreamTokenizer provides.  Any thoughts?

Answer:
To tokenize a string, use
```
string.Split(...)
```
.


Question:
I have been used to working with VS2005 and 2008 - using msbuild, etc, but I have inherited a set of projects that have to remain in vc6.0 for now.  I don't like opening each project in the developer studio and building.  I prefer to build form command line (I am automating the builds).  Is this possible?

I have tried the nmake utility, but I still need to open up the projects and save/export the make file.  This is tedious if the project changes - each time I have to save the make file.  nmake seems to work, but it had a problem when I changed the location of the project in my directory tree (I checked out of svn into a new clean dir to try the build).  It seemed to have hard coded paths in it, but I will have to check on that - it might have been a different problem.

Any alternatives out there?

Eventually I will migrate these to 2008, but for now that is not an option.

Answer:
We use automated builds at my work place. Essentially just a batch file i fire off from the command line. Let me make sure i am allowed to post some sample code before i go ahead and post it. But yes, it IS possible to automate the build.
Sample Code:
:::::::: CompileSolution :::::::::::::::::::::::::
call X:\BuildTools\bin\BuildVbProj.bat
%COMPONENTNAME% %SOLUTIONDIR%
%PROJFILE% %BUILDOUTPUTFILE%
%PREBUILDFILE% if %ERRORLEVEL% NEQ 0
goto BuildErrors
goto Cleanup
EDIT:
The BuildVbProj.bat file ultimately calls VB6.exe in the Program Files\MS Visual Studio\VB98\ folder. Try calling it with "VB6.exe /?" or "VB6.exe -?" and it will show you a list of options. You can basically automate your process using those options.
There should be a similar exe for VC in the VC98 folder as well.


Question: What are the alternative "design methods" to the Model View Controller? MVC seems to be popular (SO was built with it, I know that much) but is it the only method used?

Answer:
There are many others:
Model View Presenter (MVP)
Supervising Controller
Passive View
Model View ViewModel (MVVM)
This is common in WPF applications (though
Prism
uses the MVP pattern (usually))


Question:
I'm parsing XML results from an API call using PHP and xpath.

 $dom = new DOMDocument();
 $dom->loadXML($response->getBody());

 $xpath = new DOMXPath($dom);
 $xpath->registerNamespace("a", "http://www.example.com");

 $hrefs = $xpath->query('//a:Books/text()', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookTitle[$i] = $hrefs->item($i)->data;
 }

 $hrefs = $xpath->query('//a:Books', $dom);

 for ($i = 0; $i < $hrefs->length; $i++) {
      $arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
 }

This works but is there a way I can access both the text and the attribute from one query?  And if so how do you get to those items once query is executed?

Answer:
Could you query for the concatenation?
```
```
$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);
```
```
XSLT is an expression language in itself, and you can construct whatever specific format of return value you want from within the expression.


Question:
I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting

./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj

Which c++filt describes as

std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&)

I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including -lstdc++.

Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?

EDIT: After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.

Answer:
```
std::_Rb_Tree
```
might be a red-black tree, which would most likely be from using
```
map
```
. It should be part of
```
libstdc++
```
, unless your library is linking against a different version of
```
libstdc++
```
than the application, which from what you've said so far seems unlikely.
EDIT: Just to clarify, the red-black tree is the underlying data structure in
```
map
```
. All that
```
hash_map
```
does is hash the key before using it, rather than using the raw value.


Question:
Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to?  I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working.  Examples would be much appreciated.  Thanks.

EDIT:  Here is what I have unsuccessfully tried:

class Comment(db.Model):
    series = db.ReferenceProperty(reference_class=Series);

    def series_id(self):
        return self._series

And in my template:

<a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>

The result:

<a href="games/view-series.html?series=#comm59">more</a>

Answer:
You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.
Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.


Question: How do the full text search systems of PostgreSQL and MySQL compare? Is any clearly better than the oder? In which way are they different?

Answer:
Update:
Starting in MySQL 5.6, InnoDB
supports fulltext search
I'm not well versed in PostgreSQL unfortunately, but if you use the FULL TEXT search in MySQL you're immediately tied to MyISAM. If you want to use InnoDB (and if ACID compliance means anything to you, you should be using InnoDB) you're stuck using other solutions.
Two popular alternatives that are often rolled out are
Lucene
(an apache project with a Zend module if you're using PHP) and
Sphinx
.


Question:
Say I have the following XML...

<root>
  <base>
    <tent key="1" color="red"/>
    <tent key="2" color="yellow"/>
    <tent key="3" color="blue"/>
  </base>
  <bucket>
    <tent key="1"/>
    <tent key="3"/>
  </bucket>
</root>

...what would the XPath be that returns that the "bucket" contains "red" and "blue"?

Answer:
I think this will work:
```
```
/root/base/tent[/root/bucket/tent/@key = @key ]/@color
```
```


Question:
I'm looking for a piece of code that can tell me the offset of a field within a structure without allocating an instance of the structure.

IE: given

struct mstct {
    int myfield;
    int myfield2;
};

I could write:

mstct thing;
printf("offset %lu\n", (unsigned long)(&thing.myfield2 - &thing));

And get offset 4 for the output. How can I do it without that mstct thing declaration/allocating one?

I know that &<struct> does not always point at the first byte of the first field of the structure, I can account for that later.

Answer:
How about the standard offsetof() macro (in stddef.h)?
Edit: for people who might not have the offsetof() macro available for some reason, you can get the effect using something like:
```
```
#define OFFSETOF(type, field)    ((unsigned long) &(((type *) 0)->field))
```
```


Question:
I am looking for an app that will let me type in code ON my cellphone. I don't need to compile or anything, and its not to program for the cellphone. Just something nice to have when an idea pops in my head.

Am I completely overlooking a simple code editor for Symbian S60v3 phones?

I am looking for something similar to CEdit which is for Windows Mobile.

Answer:
You can use visual studio :
http://wiki.forum.nokia.com/index.php/Using_Visual_Studio_6.0_with_S60_3rd_Edition


Question:
I'm looking to create an ValidationRule class that validates properties on an entity type object.  I'd really like to set the name of the property to inspect, and then give the class a delegate or a lambda expression that will be evaluated at runtime when the object runs its IsValid() method.  Does anyone have a snippet of something like this, or any ideas on how to pass an anonymous method as an argument or property?

Also, I'm not sure if I'm explaining what I'm trying to accomplish so please ask questions if I'm not being clear.

Answer:
```
```
class ValidationRule {
    public delegate bool Validator();

    private Validator _v;

    public ValidationRule(Validator v) { _v = v; }

    public Validator Validator {
        get { return _v; }
        set { _v = value; }
    }

    public bool IsValid { get { return _v(); } }
}

var alwaysPasses = new ValidationRule(() => true);
var alwaysFails = new ValidationRule(() => false);

var textBoxHasText = new ValidationRule(() => textBox1.Text.Length > 0);
```
```
That should get you started. But, really, inheritance is far more appropriate here. The problem is simply that the
```
Validator
```
doesn't have access to any state that it doesn't close over, this means that it isn't as reusable as say
```
ValidationRules
```
that contain their own state. Compare the following class to the previous definition of
```
textBoxHasText
```
.
```
```
interface IValidationRule {
    bool IsValid { get; }
}

class BoxHasText : IValidationRule {
    TextBox _c;

    public BoxHasText(TextBox c) { _c = c; }

    public bool IsValid {
        get { return _c.Text.Length > 0; }
    }
}
```
```


Question:
Basically I want to know how to set center alignment for a cell using VBScript...

I've been googling it and can't seem to find anything that helps.

Answer:
There are many ways to select a cell or a range of cells, but the following will work for a single cell.
```
```
'Select a Cell Range
Range("D4").Select

'Set the horizontal and vertical alignment
With Selection
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
End With
```
```
The HorizontalAlignment options are xlLeft, xlRight, and xlCenter


Question: Is there a query in SQL Server 2005 I can use to get the server's IP or name?

Answer:
```
```
select @@servername
```
```


Question:
I'm an experienced programmer but just starting out with Flash/Actionscript. I'm working on a project that for certain reasons requires me to use Actionscript 2 rather than 3.

When I run the following (I just put it in frame one of a new flash project), the output is a 3 rather than a 1 ? I need it to be a 1.

Why does the scope of the 'ii' variable continue between loops?

var fs:Array = new Array();

for (var i = 0; i < 3; i++){

    var ii = i + 1;
    fs[i] = function(){
        trace(ii);
    }
}

fs[0]();

Answer:
Unfortunately Actionscript 2.0 does not have a strong scope... especially on the time line.
```
```
var fs:Array = new Array();

for (var i = 0; i < 3; i++){

    var ii = i + 1;
    fs[i] = function(){
        trace(ii);
    }
}

fs[0]();
trace("out of scope: " + ii + "... but still works");
```
```


Question:
How do I locate resources on the classpath in java?
Specifically stuff that ends in .hbm.xml.

My goal is to get a List of all resources on the classpath that end with ".hbm.xml".

Answer:
You have to get a
classloader
, and test whether it's a URLClassLoader. If so, downcast and
get its URLs
. From there, open each as a JarFile and look at its
entries
. Apply a
regex
to each entry and see if it's one that interests you.
Clearly, this isn't fast. It's best to be given a name to be looked up in the classpath, perhaps listed in a standard file name in the META-INF directory of each classpath element, similar to the technique used by the
ServiceProvider facility
. Note that you can
list all files
with a given name on the classpath.


Question: I wonder if They can work perfectly together...

Answer: The simple answer is yes - I have both installed on the machine I'm replying to this question from. :=)


Question:
This code works (C# 3)

double d;
if(d == (double)(int)d) ...;

Is there a better way to do this?

For extraneous reasons I want to avoid the double cast so; what nice ways exist other than this? (even if they aren't as good)

Note: Several people pointed out the (important) point that == is often problematic regrading floating point. In this cases I expect values in the range of 0 to a few hundred and they are supposed to be integers (non ints are errors) so if those points "shouldn't" be an issue for me.

Answer:
You don't need the extra (double) in there. This works:
```
```
if (d == (int)d) {
 //...
}
```
```


Question:
Is there a way to get the C/C++ preprocessor or a template or such to mangle/hash the __FILE__ and __LINE__ and perhaps some other external input like a build-number into a single short number that can be quoted in logs or error messages?

(The intention would be to be able to reverse it (to a list of candidates if its lossy) when needed when a customer quotes it in a bug report.)

Answer:
Well, if you're displaying the message to the user yourself (as opposed to having a crash address or function be displayed by the system), there's nothing to keep you from displaying exactly what you want.
For example:
```
```
typedef union ErrorCode {
    struct {
        unsigned int file: 15;
        unsigned int line: 12; /* Better than 5 bits, still not great
                                  Thanks commenters!! */
        unsigned int build: 5;
    } bits;
    unsigned int code;
} ErrorCode;

unsigned int buildErrorCodes(const char *file, int line, int build)
{
    ErrorCode code;
    code.bits.line=line   & ((1<<12) - 1);
    code.bits.build=build & ((1<< 5) - 1);
    code.bits.file=some_hash_function(file) & ((1<<15) - 1);

    return code.code;
}
```
```
You'd use that as
```
```
buildErrorCodes(__FILE__, __LINE__, BUILD_CODE)
```
```
and output it in hex.  It wouldn't be very hard to decode...
(Edited -- the commenters are correct, I must have been nuts to specify 5 bits for the line number.  Modulo 4096, however, lines with error messages aren't likely to collide.  5 bits for build is still fine - modulo 32 means that only 32 builds can be outstanding AND have the error still happen at the same line.)


Question:
If I have a UIView (or UIView subclass) that is visible, how can I tell if it's currently being shown on the screen (as opposed to, for example, being in a section of a scroll view that is currently off-screen)?

To maybe give you a better idea of what I mean, UITableView has a couple of methods for determining the set of currently visible cells. I'm looking for some code that can make a similar determination for any given UIView.

Answer:
Not tried any of this yet. But
```
CGRectIntersectsRect()
```
,
```
-[UIView convertRect:to(from)View]
```
and
```
-[UIScrollView contentOffset]
```
seem to be your basic building blocks here.


Question: I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++.

Answer:
Take a look at
The ADAPTIVE Communication Environment (ACE)
.  It's a library of templates and objects for high performance applications in C++.  It has great cross-platform primitives for threading, networking, etc.


Question:
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?

I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.

Type type = typeof(FooBar)
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
type.GetConstructors(flags)
    .Where(constructor => constructor.GetParameters().Length == 0)
    .First();

Answer:
```
```
type.GetConstructor(Type.EmptyTypes)
```
```


Question: What are the best JVM settings you have found for running Eclipse?

Answer:
Here's what I use (though I have them in the shortcut instead of the settings file):
eclipse.exe -showlocation -vm "C:\Java\jdk1.6.0_07\bin\javaw.exe" -vmargs -Xms256M -Xmx768M -XX:+UseParallelGC -XX:MaxPermSize=128M


Question:
I have a method lets say:

private static String drawCellValue(
    int maxCellLength, String cellValue, String align) { }

and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String, obviously I can pass any string value.. I would like to know if it's possible to have an Enum value as a method parameter, and if so, how?

Just in case someone thinks about this; I thought about using a Boolean value but I don't really fancy it. First, how to associate true/false with left/right ? (Ok, I can use comments but I still find it dirty) and secondly, I might decide to add a new value, like 'justify', so if I have more than 2 possible values, Boolean type is definitely not possible to use.

Any ideas?

Answer:
This should do it:
```
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}
```
```


Question:
I'm setting up a server to offer JIRA and SVN.  I figure, I'll use LDAP to keep the identity management simple.

So, before I write one....  is there a good app out there to let users change their ldap password?  I want something that lets a user authenticate with ldap and update their password.  A form with username, old password, new password and verification would be enough.

I can write my own, but it seems silly to do so if there's already a good app out there that handles this....

Thanks for the help.

Answer:
This should do it:
```
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}
```
```


Question:
There are many scenarios where it would be useful to call a Win32 function or some other DLL from a PowerShell script. to Given the following function signature:

bool MyFunction( char* buffer, int* bufferSize )

I hear there is something that makes this easier in PowerShell CTP 2, but I'm curious how this is best done in PowerShell 1.0. The fact that the function needing to be called  is using pointers could affect the solution (yet I don't really know).

So the question is what's the best way to write a PowerShell script that can call an exported Win32 function like the one above?

Remember for PowerShell 1.0.

Answer:
There isn't any mechanism in PowerShell 1.0 to directly call Win32 API's. You could of course write a C# or VB.NET helper class to do this for you and call that from PowerShell.
Update: Take a look at -
http://blogs.msdn.com/powershell/archive/2006/04/25/583236.aspx
http://www.leeholmes.com/blog/ManagingINIFilesWithPowerShell.aspx


Question:
Is there such a thing as unit test generation? If so...

...does it work well?

...What are the auto generation solutions that are available for .NET?

...are there examples of using a technology like this?

...is this only good for certain types of applications, or could it be used to replace all manually written unit testing?

Answer:
Take a look at
Pex
. Its a Microsoft Research project. From the website:
Pex generates Unit Tests from hand-written Parameterized Unit Tests through Automated Exploratory Testing based on Dynamic Symbolic Execution.
UPDATE for 2019:
As mentioned in the comments, Pex is now called
IntelliTest
and is a feature of Visual Studio Enterprise Edition. It supports emitting tests in MSTest, MSTest V2, NUnit, and xUnit format and it is extensible so you can use it with other unit test frameworks.
But be aware of the following caveats:
Supports only C# code that targets the .NET Framework.
Does not support x64 configurations.
Available in Visual Studio
Enterprise Edition only


Question: What are some methods of utilising Eclipse for Dependency Management?

Answer:
I really like the
The Maven Integration for Eclipse (m2eclipse, Eclipse m2e)
. I use it purely for the dependency management feature. It's great not having to go out and download a bunch of new jars new each time I set up a project.


Question:
I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:

#ifdef OSisWindows
// do Windows-specific stuff
#else
// do Unix-specific stuff
#endif

Is there a way to do this? Is there a better way to do the same thing?

Answer:
Some compilers will generate #defines that can help you with this. Read the compiler documentation to determine what they are.
MSVC
defines one that's
```
__WIN32__
```
,
GCC
has some you can see with
```
touch foo.h; gcc -dM foo.h
```


Question: Is it possible to highlight text inside of a textarea using javascript? Either changing the background of just a portion of the text area or making a portion of the text selected?

Answer:
Try this piece of code I wrote this morning, it will highlight a defined set of words:
```
```

        <title></title>

                <textarea cols="30" rows="10">

                </textarea>

```
```
This was written for another post (http://facebook.stackoverflow.com/questions/7497824/how-to-highlight-friends-name-in-facebook-status-update-box-textarea/7597420#7597420), but it seems to be what you're searching for.


Question:
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?

The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.

Answer:
This sounds like modifying the
```
__builtin__
```
name space.  To do it:
```
```
import __builtin__
__builtin__.foo = 'some-value'
```
```
Do not use the
```
__builtins__
```
directly (notice the extra "s") - apparently this can be a dictionary or a module.  Thanks to ΤΖΩΤΖΙΟΥ for pointing this out, more can be found
here
.
Now
```
foo
```
is available for use everywhere.
I don't recommend doing this generally, but the use of this is up to the programmer.
Assigning to it must be done as above, just setting
```
foo = 'some-other-value'
```
will only set it in the current namespace.


Question: Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface.

Answer:
you can edit the conf/server.xml and add an entry like this pointing to your war directory
```
```
<Context path="/strutsDisplayTag"
        reloadable="true"
        docBase="C:\work\learn\jsp\strutsDisplayTag"
        workDir="C:\work\learn\jsp\strutsDisplayTag\work" />
```
```
ELSE
 you can copy your .WAR file to the webapps directory of tomcat.


Question: I have pushed my .htaccess files to the production severs, but they don't work. Would a restart be the next step, or should I check something else.

Answer:
No
:
Apache allows for decentralized management of configuration via special files placed inside the web tree. The special files are usually called
```
.htaccess
```
, but any name can be specified in the
AccessFileName
directive... Since .htaccess files are read on every request, changes made in these files take immediate effect...


Question:
I have a site, from which you can download an HTML file. This HTML file contains a form with hidden fields, which is right away posted back to the site using JavaScript. This is a way of allowing users to download to their own machine data that they edit on the site.

On some machines, you get an IE "yellow bar" when trying to open the file you saved. The "yellow bar" in IE is warning that the HTML is trying to run an Active X (which it is not, there is only JavaScript doing a submit() on a form). However if you receive the exact same HTML file by email, save it, and open it, you don't have this problem. (It looks like IE is putting some more constraint on what can be done in a HTML file you saved from web site.)

My question is: where can I find documentation on this IE security mechanism, and possibly how can I get around it?

Alex

Answer:
I don't 100% follow what your JavaScript is submitting to, but if you're submitting back to the original site from the downloaded copy you'll have a problem using JavaScript as all browsers treat cross-domain JavaScript as a security violation.
JavaScript isn't allowed to read or write to any site not on the current domain


Question:
I have a Button inside an UpdatePanel.  The button is being used as the OK button for a ModalPopupExtender.  For some reason, the button click event is not firing.  Any ideas?  Am I missing something?

<asp:updatepanel id="UpdatePanel1" runat="server">
    <ContentTemplate>
        <cc1:ModalPopupExtender ID="ModalDialog" runat="server"
            TargetControlID="OpenDialogLinkButton"
            PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton"
            BackgroundCssClass="ModalBackground">
        </cc1:ModalPopupExtender>
        <asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server">
            ...
            <asp:Button ID="ModalOKButton" runat="server" Text="OK"
                        onclick="ModalOKButton_Click" />
        </asp:Panel>
    </ContentTemplate>
</asp:updatepanel>

Answer:
It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click event.  I tested this out by removing the
```
```
OkControlID="ModalOKButton"
```
```
from the ModalPopupExtender tag, and the button click fires.  I'll need to figure out another way to send the data to the server.


Question:
I have  DocumentRoot /var/www/test    in my .htaccess file. This is causing the apache server to give me a 500 internal server error.

The error log file shows:
alert] [client 127.0.0.1] /var/www/.htaccess: DocumentRoot not allowed here

AllowOveride All is set in my conf file.

Any idea why this is happening?

Answer:
The
DocumentRoot
directive cannot appear in a
```
.htaccess
```
file. Put it in
```
httpd.conf
```
instead.


Question:
Are there any unit testing solutions for Flex? or actionscript 3?

If so, what are their features? Any UI testing abilities? Functional testing? Any pointers, examples, libraries or tools that you can share?

Answer:
FlexUnit is pretty awesome -
http://opensource.adobe.com/wiki/display/flexunit/FlexUnit
Also ASUnit -
http://asunit.org
They are both pretty similiar and both haven taken quite a bit from frameworks like JUnit.
FlexMonkey (
http://code.google.com/p/flexmonkey/
) although I haven't used it myself seems to do UI unit testing.


Question:
You know those websites that let you type in your checking account number and the routing number, and then they can transfer money to and from your account?

How does that work?  Any good services or APIs for doing that?  Any gotchas?

Answer:
The banks do have APIs for doing this, but only approved people/companies are allowed to interface with these systems.  Because it actually involves transferring money around, the security requirements are pretty high in terms of how you handle the account numbers on your system.
Many sites that offer this feature for buying goods actually use a third party system to handle the actual money transfer into their account.   This lowers the amount of trouble to implement the API, as well as putting the burden of security on the third party handling the money transfers.
If you are serious about setting up a system where you can accept bank account numbers, and exchange funds, you should contact your bank, and see what the actual requirements for implementing such a system.  Each bank has their own system, along with their own rate regarding the cost of these transactions.
Some third parties I'm aware of are
Moneris
Cactus
Beanstream
I'm in Canada, although I think Moneris and Cactus operate in the US.  I think Beanstream doesn't.  Again, you can talk to your bank, and they can probably get you in touch with a third party who will help you with the transactions.


Question:
A legacy embedded system is implemented using a cooperative multi-tasking scheduler.

The system essentially works along the following lines:

Task A does work

When Task A is done, it yields the processor.

Task B gets the processor and does work.

Task B yields

...

Task n yields

Task A gets scheduled and does work

One big Circular Queue: A -> B -> C -> ... -> n -> A

We are porting the system to a new platform and want to minimize system redesign.

Is there a way to implement that type of cooperative multi-tasking in vxWorks?

Answer:
While VxWorks is a priority based OS, it is possible to implement this type of cooperative multi-tasking.
Simply put all the tasks at the
same
priority.
In your code, where you do your
yield
, simply insert a 'taskDelay(0);'
Note that you have to make sure the kernel time slicing is disabled (kernelTimeSlice(0)).
All tasks at the same priority are in a Queue.  When a task yields, it gets put at the end of the queue.  This would implement the type of algorithm described.


Question:
I've heard that the automotive industry has something called MISRA C.

What are the relevant standards for other high reliability/availability/security industries, such as

Space

Aircraft

Banking/financial

Automotive

Medical

Defense/Military

???

-Adam

Answer:
if you're asking specifically about coding, the MISRA presents some guidelines for avoiding common mistakes in C.
however, there's a lot more to good software than coding. The "bible" of the aviation industry for sw development is DO-178B. It tells you what questions need to be addressed in the various design phases and how the answers should be documented. It's an ENORMOUS amount of paperwork, but if you're trying to keep planes in the air, you want the weakest point to be the human (pilot), not the software.


Question:
I want to do something like the following in spring:

<beans>
    ...
    <bean id="bean1" ... />
    <bean id="bean2">
        <property name="propName" value="bean1.foo" />
...

I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.

Answer:
I think you have to inject bean1, then get
```
foo
```
manually because of a timing issue. When does the framework resolve the value of the target bean?
You could create a pointer bean and configure that.
```
```
class SpringRef {
  private String targetProperty;
  private Object targetBean;

  //getters/setters

  public Object getValue() {
    //resolve the value of the targetProperty on targetBean.
  }
}
```
```
Common-BeanUtils
should be helpful.


Question:
I recently asked a question about tracing Linq-to-Entities

I think that one of the answers was not right, as they refer to using the DataContext. Is there a DataContext for LINQ-to-Entities? If so, how do I get it?

Answer:
Apparently, LinqToEntities uses an
ObjectContext
instead of DataContext.
It is hilarious that the object team made a DataContext and the data team made an ObjectContext (and on to DataQuery vs ObjectQuery, etc.) "Naming is Hard!"
Update, for .net 4 with EF4.1, you might also be interested in
DbContext
when working with LinqToEntities.  See
also
.


Question:
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this.

Thanks
Dirk

Answer:
With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:
First, install 2.6rc2. You can download the source from the
Python website
. Standard
```
./configure && make && sudo make install
```
installation style.
Next, remove the
```
/usr/bin/python
```
symlink. Do
not
remove
```
/usr/bin/python2.5
```
. Add a symlink to 2.6 with
```
ln -s /usr/local/bin/python2.6 /usr/bin/python
```
.
Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish.
Migrating installed libraries is a much longer process. Look in the
```
/usr/lib/python2.5/site-packages/
```
and
```
/usr/local/lib/python2.5/site-packages/
```
directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with
```
sudo easy_install <name>
```
, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library.


Question:
From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story).

I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task.  I just don't understand how they get set up and how they actually work.  Any examples would be appreciated.

Answer:
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function
```
on_event()
```
and data pointers to a framework function
```
watch_events()
```
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The
GTK+ tutorial
has a nice section on the
theory of signals and callbacks
.


Question:
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.

Example:

2748 to "ABC"

Answer:
try
```
```
2748.ToString("X")
```
```


Question:
My zune just updated to 3.0 (didn't even realize they were releasing something new!) and the update came with two games, but the Zune marketplace does not have games.

Where do I go to get started, and what are the capabilities of the Zune in terms of games/apps?

Answer:
Well, first, you must download the Microsoft XNA 3.0 CTP. Read the documentation, which will explain the capabilities. But, from memory:
No hardware accelerated 3d (obviously, you can create a software 3d engine and then render the result to a 2d sprite, but... Don't expect much in terms of performance ;))
No XACT, you must use a new sound API


Question:
I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write

myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction);

this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too.

Answer:
Make sure your events are exposed as public. For example...
```
```
[Browsable(true)]
public event EventHandler MyCustomEvent;
```
```


Question:
I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.

I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework.

Is there any good general purpose way to indefinitely pause a worker thread in C# .NET.

I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case.

Answer:
The
Threading in C#
ebook summarises Thread.Suspend and Thread.Resume thusly:
The deprecated Suspend and Resume methods have two modes – dangerous and useless!
The book recommends using a synchronization construct such as an
AutoResetEvent
or
Monitor.Wait
to perform thread suspending and resuming.


Question:
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.

Is there some kind of configuration that needs to be done somewhere for this work?

Answer:
Sure. From a
mindless technology article called "Make Python Scripts Droppable in Windows"
, you can add a drop handler by adding a registry key:
Here’s a registry import file that you can use to do this. Copy the
  following into a .reg file and run it
  (Make sure that your .py extensions
  are mapped to Python.File).
```
```
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
@="{60254CA5-953B-11CF-8C96-00AA00B8708C}"
```
```
This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with
```
86C86720-42A0-1069-A2E8-08002B30309D
```
.
A comment in that post indicates that one can enable dropping on "no console Python files (
```
.pyw
```
)" or "compiled Python files (
```
.pyc
```
)" by using the
```
Python.NoConFile
```
and
```
Python.CompiledFile
```
classes.


Question: How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that.

Answer:
I assume you're talking about the Apache server that Oracle installs.  Look for the file httpd.conf.
Open this file in a text editor and look for the line
Listen 8080
or
Listen {ip address}:8080
Change the port number and either restart the web server or just reboot the machine.


Question:
I started playing around with Linq today and ran into a problem I couldn't find an answer to. I was querying a simple SQL Server database that had some employee records. One of the fields is the full name (cn). I thought it would be interesting to group by the first name by splitting the full name at the first space. I tried

group by person.cn.Split(separators)[0]

but ran into a lengthy runtime exception (looked a lot like a C++ template instantiation error).

Then I tried grouping by a few letters of the first name:

group by person.cn.Substring(0,5)

and that worked fine but is not what I want.

I'm wondering about two things:

Why does the first example not work when it looks so close to the second?

Knowing that behind the scenes it's SQL stuff going on, what's a good way to do this kind of thing efficiently

Thanks,

Andrew

Answer:
Split has no translation into SQL.
So, how to do this string manipulation without split?  Cheat like hell (untested):
```
```
string oneSpace = " ";
string fiftySpace = "                                                  ";

var query =
  from person in db.Persons
  let lastname = person.cn.Replace(oneSpace, fiftySpace).SubString(0, 50).Trim()
  group person by lastname into g
  select new { Key = g.Key, Count = g.Count };
```
```


Question:
I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?

Or better yet post the algorithm?

Thanks!

Answer:
From the idevkit.com forums:
```
```
#define kFilteringFactor 0.1
static UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    // Calculate low pass values

    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
    rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));
    rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));

    // Subtract the low-pass value from the current value to get a simplified high-pass filter

    float accelX = acceleration.x - rollingX;
    float accelY = acceleration.y - rollingY;
    float accelZ = acceleration.z - rollingZ;

    // Use the acceleration data.

}
```
```


Question:
Functional languages are good because they avoid bugs by eliminating state, but also because they can be easily parallelized automatically for you, without you having to worry about the thread count.

As a Win32 developer though, can I use Haskell for some dlls of my application? And if I do, is there a real advantage that would be taken automatically for me?  If so what gives me this advantage, the compiler?

Does F# parallelize functions you write across multiple cores and cpu's automatically for you?  Would you ever see the thread count in task manager increase?

Basically my question is, how can I start using Haskell in a practical way, and will I really see some benefits if I do?

Answer:
I'm currently learning Haskell myself, when you start out learning it, it doesn't seem very intriguing because the learning experience is NOTHING like learning a language like C#, it's a whole new world, but I noticed I could write very very complex expressions in just a few lines of code, when I looked back at the code it was much more concise, it was small and tight. I'm absolutely loving it! You can indeed write real-world programs that will be smaller, easier to maintain, and much more complex then most other languages allow, I vote for you to learn it!!
Good luck.


Question:
I have a series of ASCII flat files coming in from a mainframe to be processed by a C# application. A new feed has been introduced with a Packed Decimal (COMP-3) field, which needs to be converted to a numerical value.

The files are being transferred via FTP, using ASCII transfer mode. I am concerned that the binary field may contain what will be interpreted as very-low ASCII codes or control characters instead of a value - Or worse, may be lost in the FTP process.

What's more, the fields are being read as strings. I may have the flexibility to work around this part (i.e. a stream of some sort), but the business will give me pushback.

The requirement read "Convert from HEX to ASCII", but clearly that didn't yield the correct values.  Any help would be appreciated; it need not be language-specific as long as you can explain the logic of the conversion process.

Answer:
I apologize if I am way off base here, but perhaps this code sample I'll paste here could help you. This came from VBRocks...
```
```
Imports System
Imports System.IO
Imports System.Text
Imports System.Text.Encoding

'4/20/07 submission includes a line spacing addition when a control character is used:
'   The line spacing is calculated off of the 3rd control character.
'
'   Also includes the 4/18 modification of determining end of file.

'4/26/07 submission inclues an addition of 6 to the record length when the 4th control
'   character is an 8.  This is because these records were being truncated.

'Authored by Gary A. Lima, aka. VBRocks

''' <summary>
''' Translates an EBCDIC file to an ASCII file.
''' </summary>
''' <remarks></remarks>
Public Class EBCDIC_to_ASCII_Translator

#Region " Example"

    Private Sub Example()
        'Set your source file and destination file paths
        Dim sSourcePath As String = "c:\Temp\MyEBCDICFile"
        Dim sDestinationPath As String = "c:\Temp\TranslatedFile.txt"

        Dim trans As New EBCDIC_to_ASCII_Translator()

        'If your EBCDIC file uses Control records to determine the length of a record, then this to True
        trans.UseControlRecord = True

        'If the first record of your EBCDIC file is filler (junk), then set this to True
        trans.IgnoreFirstRecord = True

        'EBCDIC files are written in block lengths, set your block length (Example:  134, 900, Etc.)
        trans.BlockLength = 900

        'This method will actually translate your source file and output it to the specified destination file path
        trans.TranslateFile(sSourcePath, sDestinationPath)

        'Here is a alternate example:
        'No Control record is used
        'trans.UseControlRecord = False

        'Translate the whole file, including the first record
        'trans.IgnoreFirstRecord = False

        'Set the block length
        'trans.BlockLength = 134

        'Translate...
        'trans.TranslateFile(sSourcePath, sDestinationPath)

        '*** Some additional methods that you can use are:

        'Trim off leading characters from left side of string (position 0 to...)
        'trans.LTrim = 15

        'Translate 1 EBCDIC character to an ASCII character
        'Dim strASCIIChar as String = trans.TranslateCharacter("S")

        'Translate an EBCDIC character array to an ASCII string
        'trans.TranslateCharacters(chrEBCDICArray)

        'Translates an EBCDIC string to an ASCII string
        'Dim strASCII As String = trans.TranslateString("EBCDIC String")

    End Sub

#End Region    'Example

    'Translate characters from EBCDIC to ASCII

    Private ASCIIEncoding As Encoding = Encoding.ASCII
    Private EBCDICEncoding As Encoding = Encoding.GetEncoding(37)  'EBCDIC

    'Block Length:  Can be fixed (Ex:  134).
    Private miBlockLength As Integer = 0
    Private mbUseControlRec As Boolean = True        'If set to False, will return exact block length
    Private mbIgnoreFirstRecord As Boolean = True    'Will Ignore first record if set to true  (First record may be filler)
    Private miLTrim As Integer = 0

    ''' <summary>
    ''' Translates SourceFile from EBCDIC to ASCII.  Writes output to file path specified by DestinationFile parameter.
    ''' Set the BlockLength Property to designate block size to read.
    ''' </summary>
    ''' <param name="SourceFile">Enter the path of the Source File.</param>
    ''' <param name="DestinationFile">Enter the path of the Destination File.</param>
    ''' <remarks></remarks>
    Public Sub TranslateFile(ByVal SourceFile As String, ByVal DestinationFile As String)

        Dim iRecordLength As Integer     'Stores length of a record, not including the length of the Control Record (if used)
        Dim sRecord As String = ""         'Stores the actual record
        Dim iLineSpace As Integer = 1    'LineSpace:  1 for Single Space, 2 for Double Space, 3 for Triple Space...

        Dim iControlPosSix As Byte()      'Stores the 6th character of a Control Record (used to calculate record length)
        Dim iControlRec As Byte()          'Stores the EBCDIC Control Record (First 6 characters of record)
        Dim bEOR As Boolean                'End of Record Flag
        Dim bBOF As Boolean = True      'Beginning of file
        Dim iConsumedChars As Integer = 0     'Stores the number of consumed characters in the current block
        Dim bIgnoreRecord As Boolean = mbIgnoreFirstRecord   'Ignores the first record if set.

        Dim ControlArray(5) As Char         'Stores Control Record (first 6 bytes)
        Dim chrArray As Char()              'Stores characters just after read from file

        Dim sr As New StreamReader(SourceFile, EBCDICEncoding)
        Dim sw As New StreamWriter(DestinationFile)

        'Set the RecordLength to the RecordLength Property (below)
        iRecordLength = miBlockLength

        'Loop through entire file
        Do Until sr.EndOfStream = True

            'If using a Control Record, then check record for valid data.
            If mbUseControlRec = True Then
                'Read the Control Record (first 6 characters of the record)
                sr.ReadBlock(ControlArray, 0, 6)

                'Update the value of consumed (read) characters
                iConsumedChars += ControlArray.Length

                'Get the bytes of the Control Record Array
                iControlRec = EBCDICEncoding.GetBytes(ControlArray)

                'Set the line spacing  (position 3 divided by 64)
                '   (64 decimal = Single Spacing; 128 decimal = Double Spacing)
                iLineSpace = iControlRec(2) / 64

                'Check the Control record for End of File
                'If the Control record has a 8 or 10 in position 1, and a 1 in postion 2, then it is the end of the file
                If (iControlRec(0) = 8 OrElse iControlRec(0) = 10) AndAlso _
                    iControlRec(1) = 1 Then

                    If bBOF = False Then
                        Exit Do

                    Else
                        'The Beginning of file flag is set to true by default, so when the first
                        '   record is encountered, it is bypassed and the bBOF flag is set to False
                        bBOF = False

                    End If    'If bBOF = Fals

                End If    'If (iControlRec(0) = 8 OrElse

                'Set the default value for the End of Record flag to True
                '   If the Control Record has all zeros, then it's True, else False
                bEOR = True

                'If the Control record contains all zeros, bEOR will stay True, else it will be set to False
                For i As Integer = 0 To 5
                    If iControlRec(i) > 0 Then
                        bEOR = False

                        Exit For

                    End If    'If iControlRec(i) > 0

                Next    'For i As Integer = 0 To 5

                If bEOR = False Then
                    'Convert EBCDIC character to ASCII
                    'Multiply the 6th byte by 6 to get record length
                    '   Why multiply by 6?  Because it works.
                    iControlPosSix = EBCDICEncoding.GetBytes(ControlArray(5))

                    'If the 4th position of the control record is an 8, then add 6
                    '    to the record length to pick up remaining characters.
                    If iControlRec(3) = 8 Then
                        iRecordLength = CInt(iControlPosSix(0)) * 6 + 6

                    Else
                        iRecordLength = CInt(iControlPosSix(0)) * 6

                    End If

                    'Add the length of the record to the Consumed Characters counter
                    iConsumedChars += iRecordLength

                Else
                    'If the Control Record had all zeros in it, then it is the end of the Block.

                    'Consume the remainder of the block so we can continue at the beginning of the next block.
                    ReDim chrArray(miBlockLength - iConsumedChars - 1)
                    'ReDim chrArray(iRecordLength - iConsumedChars - 1)

                    'Consume (read) the remaining characters in the block.
                    '   We are not doing anything with them because they are not actual records.
                    'sr.ReadBlock(chrArray, 0, iRecordLength - iConsumedChars)
                    sr.ReadBlock(chrArray, 0, miBlockLength - iConsumedChars)

                    'Reset the Consumed Characters counter
                    iConsumedChars = 0

                    'Set the Record Length to 0 so it will not be processed below.
                    iRecordLength = 0

                End If    ' If bEOR = False

            End If    'If mbUseControlRec = True

            If iRecordLength > 0 Then
                'Resize our array, dumping previous data.  Because Arrays are Zero (0) based, subtract 1 from the Record length.
                ReDim chrArray(iRecordLength - 1)

                'Read the specfied record length, without the Control Record, because we already consumed (read) it.
                sr.ReadBlock(chrArray, 0, iRecordLength)

                'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
                sRecord = Join(Array.ConvertAll(chrArray, New Converter(Of Char, String)(AddressOf ChrToStr)), "")

                'If the record length was 0, then the Join method may return Nothing
                If IsNothing(sRecord) = False Then

                    If bIgnoreRecord = True Then
                        'Do nothing - bypass record

                        'Reset flag
                        bIgnoreRecord = False

                    Else
                        'Write the line out, LTrimming the specified number of characters.
                        If sRecord.Length >= miLTrim Then
                            sw.WriteLine(sRecord.Remove(0, miLTrim))

                        Else
                            sw.WriteLine(sRecord.Remove(0, sRecord.Length))

                        End If    ' If sRecord.Length >= miLTrim

                        'Write out the number of blank lines specified by the 3rd control character.
                        For i As Integer = 1 To iLineSpace - 1
                            sw.WriteLine("")

                        Next    'For i As Integer = 1 To iLineSpace

                    End If    'If bIgnoreRecord = True

                    'Obviously, if we have read more characters from the file than the designated size of the block,
                    '   then subtract the number of characters we have read into the next block from the block size.
                    If iConsumedChars > miBlockLength Then
                        'If iConsumedChars > iRecordLength Then
                        iConsumedChars = iConsumedChars - miBlockLength
                        'iConsumedChars = iConsumedChars - iRecordLength

                    End If

                End If    'If IsNothing(sRecord) = False

            End If    'If iRecordLength > 0

            'Allow computer to process  (works in a class module, not in a dll)
            'Application.DoEvents()

        Loop

        'Destroy StreamReader (sr)
        sr.Close()
        sr.Dispose()

        'Destroy StreamWriter (sw)
        sw.Close()
        sw.Dispose()

    End Sub

    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="chr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ChrToStr(ByVal chr As Char) As String
        Dim sReturn As String = ""

        'Convert character into byte
        Dim EBCDICbyte As Byte() = EBCDICEncoding.GetBytes(chr)

        'Convert EBCDIC byte to ASCII byte
        Dim ASCIIByte As Byte() = Encoding.Convert(EBCDICEncoding, ASCIIEncoding, EBCDICbyte)

        sReturn = Encoding.ASCII.GetString(ASCIIByte)

        Return sReturn

    End Function

    ''' <summary>
    ''' Translates an EBCDIC String to an ASCII String
    ''' </summary>
    ''' <param name="sStringToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateString(ByVal sStringToTranslate As String) As String
        Dim i As Integer = 0
        Dim sReturn As New System.Text.StringBuilder()

        'Loop through the string and translate each character
        For i = 0 To sStringToTranslate.Length - 1
            sReturn.Append(ChrToStr(sStringToTranslate.Substring(i, 1)))

        Next

        Return sReturn.ToString()

    End Function

    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateCharacter(ByVal sCharacterToTranslate As Char) As String

        Return ChrToStr(sCharacterToTranslate)

    End Function

    ''' <summary>
    ''' Translates an EBCDIC Character (Char) Array to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterArrayToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks>Remarks</remarks>
    Public Function TranslateCharacters(ByVal sCharacterArrayToTranslate As Char()) As String
        Dim sReturn As String = ""

        'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
        sReturn = Join(Array.ConvertAll(sCharacterArrayToTranslate, _
                            New Converter(Of Char, String)(AddressOf ChrToStr)), "")

        Return sReturn

    End Function

    ''' <summary>
    ''' Block Length must be set.  You can set the BlockLength for specific block sizes (Ex:  134).
    ''' Set UseControlRecord = False for files with specific block sizes (Default is True)
    ''' </summary>
    ''' <value>0</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property BlockLength() As Integer
        Get
            Return miBlockLength

        End Get
        Set(ByVal value As Integer)
            miBlockLength = value

        End Set
    End Property

    ''' <summary>
    ''' Determines whether a ControlKey is used to calculate RecordLength of valid data
    ''' </summary>
    ''' <value>Default value is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property UseControlRecord() As Boolean
        Get
            Return mbUseControlRec

        End Get
        Set(ByVal value As Boolean)
            mbUseControlRec = value

        End Set
    End Property

    ''' <summary>
    ''' Ignores first record if set (Default is True)
    ''' </summary>
    ''' <value>Default is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property IgnoreFirstRecord() As Boolean
        Get
            Return mbIgnoreFirstRecord

        End Get

        Set(ByVal value As Boolean)
            mbIgnoreFirstRecord = value

        End Set
    End Property

    ''' <summary>
    ''' Trims the left side of every string the specfied number of characters.  Default is 0.
    ''' </summary>
    ''' <value>Default is 0.</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property LTrim() As Integer
        Get
            Return miLTrim

        End Get

        Set(ByVal value As Integer)
            miLTrim = value

        End Set
    End Property

End Class
```
```


Question: I am developing a TCP/IP client that has to deal with a proprietary binary protocol. I was considering using user-defined types to represent the protocol headers, and using CopyMemory to shuffle data to and from the UDT and a byte array. However, it appears that VB6 adds padding bytes to align user-defined types. Is there any way to force VB6 to not pad UDT's, similar to the #pragma pack directive available in many C/C++ compilers? Perhaps a special switch passed to the compiler?

Answer:
No.
Your best bet is to write the low level code in C or C++ (where you do have
```
#pragma pack
```
), then expose the interface via COM.


Question:
ToolStripItems show Active highlighting when you mouse over them, even if the form they are in is not in focus.   They do not, however, show their tooltips, unless the form is  focused.   I have seen the ToolStrip 'click-though' hack.  Anyone know how to make a ToolStripButton show its tooltip when its parent form is not in focus?

Thanks!

Answer:
Perhaps one of the two approaches in this code will kick you off in the right direction...
```
```
public Form1()
{
    InitializeComponent();

    tooltip = new ToolTip();
    tooltip.ShowAlways = true;
}

private ToolTip tooltip;
private void toolStripButton_MouseHover(object sender, EventArgs e)
{
    if (!this.Focused)
    {
        ToolStripItem tsi = (ToolStripItem)sender;
        tooltip.SetToolTip(toolStrip1, tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text);
        /*tooltip.Show(tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text, this,
            new Point(toolStrip1.Left, toolStrip1.Bottom));*/
    }
}

private void toolStripButton_MouseLeave(object sender, EventArgs e)
{
    tooltip.RemoveAll();
}
```
```
The problem with the first is you can't set it to the button directly, it doesn't inherit from Control, and the tooltip won't show up unless you're over the strip but not over a button.
The problem with the second (commented out way) is it doesn't display at all. Not quite sure why, but maybe you can debug it out.


Question:
I've recently seen the light of EventWaitHandle's powerful behavior in C# and decided to move some functionality in a sister application to do the same. The only problem is that the sister app is written in C.

No big deal, I'm using pthreads, which have a pthread_cond_t datatype that allows for signalling. My only question is, is it possible for a cond to be 'signalled' before something is waiting on it?

Right now my testing says no. That is, if ThreadA fires a signal before ThreadB is waiting, ThreadB will wait indefinately. Is there another pthread type that I can use that behaves closer to the functionality of the EventWaitHandle in C#? An object is signalled, meaning that the first thread to wait on it, will pass immediately, and set it to unsignalled.

Wrapping the pthread_cond into another data structure wouldn't be too hard to achieve this. But again, is this functionality already available in the pthread library?

Answer:
If you're using condition variables correctly, this won't matter.
The basic flow of your code should be (in pseudocode):
```
```
lock(lockobj);
while (!signalled) {
    wait(condvar);
}
signalled = false;
unlock(lockobj);
```
```
on the waiting side, and:
```
```
lock(lockobj);
signalled = true;
notify(condvar);
unlock(lockobj);
```
```
on the signalling side. (Of course, the lock object and condition variable used have to be the same on both sides.) Hope this helps!


Question:
Possible Duplicate:

  Emacs, switch to previous window

other-window advances me to the next window in the current frame, but I also want a way to move back to the previous window.

Emacs has next-buffer and previous-buffer, but no analogous interactive functions for window navigation.  Just other-window.

Answer:
Put this in your .emacs, and bind it to whatever key you like
```
(defun back-window ()
  (interactive)
  (other-window -1))
```


Question:
Windbg fans claim that it is quite powerful and I tend to agree. But when it comes to debugging STL containers, I am always stuck. If the variable is on the stack, the !stl extension sometimes figures it out, but when a container with a complex type (e.g. std::vector<TemplateField, std::allocator<TemplateField> >) is on the heap or part of some other structure, I just don't know how to view its contents.

Appreciate any tips, pointers.

Answer:
I often find debugger support for STL data types inadequate.  For this reason I'm increasingly using
logging frameworks and logging statements
.  I used to think that these are for people who can't use a debugger, but I now realize that they offer real value.  They allow you to embed portable debugging knowledge in your code and maintain it together with the code.  In contrast, work you do in the debugger is typically ephemeral.


Question:
I'm trying to print out the date in a certain format:

NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateStr = [dateFormatter stringFromDate:today];

If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it:

20080927030337 PM

Am I doing something wrong or is this a bug with firmware 2.1?

Edit 1: Made description clearer

Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "":

[dateFormatter setAMSymbol:@""];
[dateFormatter setPMSymbol:@""];

Answer:
Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never had an AM/PM appended to dateStr when I do:
```
```
NSLog(@"%@", dateStr);
```
```
Are you doing anything else with dateStr that you didn't post here? How are you checking the value?
Follow up
Try turning the am/pm setting on then off. I didn't have the problem either, until I did that. I am printing it out the same way you are.
Okay, I see it when I do this also. It's gotta be a bug. I recommend you
file a bug report
and just check for and filter out the unwanted characters in the meantime.


Question:
Is it possible to use PHP's SimpleXML functions to create an XML object from scratch?  Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that?

I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded.

I've done it using the DOMDocument functions, although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-)

Answer:
Sure you can.  Eg.
```
```
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
```
```
Output
```
```
<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>
```
```
Have fun.


Question: Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method.  What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character?

Answer:
BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example:
```
```
#define MY_BUFFER_SIZE 1024

char mybuffer[MY_BUFFER_SIZE];
int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);
```
```


Question:
My company has a subsidiary with a slow Internet connection. Our developers there suffer to interact with our central Subversion server. Is it possible to configure a slave/mirror  for them? They would interact locally with the server and all the commits would be automatically synchronized to the master server.

This should work as transparently as possible for the developers. Usability is a must.

Please, no suggestions to change our version control system.

Answer:
You should try
The SVK version control system
SVK
is a decentralized version control system built with the robust Subversion filesystem. It supports repository mirroring, disconnected operation, history-sensitive merging, and integrates with other version control systems, as well as popular visual merge tools.
On this link there is text about
Using SVK to Synchronize SVN Repositories


Question:
Can anyone tell me, where on the web I can find an explanation for Bron-Kerbosch algorithm for clique finding or explain here how it works?

I know it was published in "Algorithm 457: finding all cliques of an undirected graph" book, but I can't find free source that will describe the algorithm.

I don't need a source code for the algorithm, I need an explanation of how it works.

Answer:
Try finding someone with an ACM student account who can give you a copy of the paper, which is here:
http://portal.acm.org/citation.cfm?doid=362342.362367
I just downloaded it, and it's only two pages long, with an implementation in Algol 60!


Question:
I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names.  When I try to string together find and grep with xargs, I get the following error:

find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/bar
xargs: unterminated quote

Any suggestions for a more robust usage of xargs?

This is on Mac OS X 10.5.3 (Leopard) with BSD xargs.

Answer:
```
find . -print0 | grep --null 'FooBar' | xargs -0 ...
```
I don't know about whether
```
grep
```
supports
```
--null
```
, nor whether
```
xargs
```
supports
```
-0
```
, on Leopard, but on GNU it's all good.


Question:
If you have a project, that releases a library and an application, how you handle version-numbers between the two.

Example: Your project delivers a library, that convert different file-formats into each other. The library is released for inclusion into other applications. But you also release a command-line-application, that uses this library and implements an interface to the functionality.

New releases of the library lead to new releases of the application (to make use of all new features), but new releases of the application may not trigger new releases of the library. Now how are the versions numbers handled: Completely independent or should library- and application-version be dependent in some way?

Answer:
Completely independent version numbers, but the command line (or any other dependent) app should say which version of the library it was compiled against in the help section or a banner.
That way you will be able to tell which functionality will the apps have and reduce potential confusion, especially given that somebody could compile a newer app version against an old library for any reason. Also, you decouple them and can add features on the library without depending on release of a new app version and so on.
If you are sure you will always want all the apps and library to go in lockstep then you could use same numbers, but that's adding a constraint for not a strong reason.


Question:
Do you do automated testing on a complex workflow system like K2?

We are building a system with extensive integration between Sharepoint 2007 and K2. I can't even imagine where to start with automated testing as the workflow involves multiple users interacting with Sharepoint, K2 workflows and custom web pages.

Has anyone done automated testing on a workflow server like K2? Is it more effort than it's worth?

Answer:
I'm having a similar problem testing workflow-heavy MOSS-based application. Workflows in our case are based on WWF.
My idea is to mock pretty much everything that you can't control from unit tests - documents storage, authentication, user rights and actions, sharepoint-specific parts of workflows for sharepoint (these mocks should be thoroughly tested to mirror behavior of real components).
You use inversion of control to make code choose which component to use at runtime - real or mock.
Then you can write system-wide tests to test workflows behavior - setting up your own environment, checking how workflow engine reacts. These tests are too big to call them unit-tests, still it is automated testing.
This approach seems to work on trivial cases, but I still have to prove it is worthy to use in real-world workflows.


Question:
I have a pretty complicated Linq query that I can't seem to get into a LinqDataSsource for use in a GridView:

IEnumerable<ticket> tikPart = (
    from p in db.comments where
        p.submitter == me.id &&
        p.ticket.closed == DateTime.Parse("1/1/2001") &&
        p.ticket.originating_group != me.sub_unit
    select p.ticket
    ).Distinct();

How can I get this into a GridView?  Thank you!

Answer:
```
```
gridview.DataSource = tikPart.ToList();
gridview.DataBind();
```
```


Question: I want to obtain the current number of window handles and the system-wide window handle limit in C#. How do I go about this?

Answer:
As Raymond Chen put it some time ago, if you're thinking about window handle limits, you're probably doing something wrong :)
Anyway, I bet there's no special C# way to do it, because it's very system-specific. You can use the same functions that you would use in a C++ application. Call the functions using P/Invoke. To learn how to write the imports, go to
pinvoke.net
.
Edit: As I understand your question, I assume you already know how to do that in a Win32 application.


Question:
I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?

example:

-(void)drawRect:(CGRect)rect
{
  // Drawing code
  CGContextRef  context = UIGraphicsGetCurrentContext();
  CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific);
  CGContextSetTextPosition(context,80,80);
  CGContextShowText(context, "hello", 6);
  //not even this works
  CGContextShowTextAtPoint(context, 1,1, "hello", 6);
}

Answer:
Here is a fragment of code that I'm using.
```
```
UIColor *mainTextColor = [UIColor whiteColor];
[mainTextColor set];
drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16);
```
```
And:
```
```
static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,
                          int maxFontSize, int minFontSize) {
    CGPoint point = CGPointMake(left, y);
    UIFont *font = [UIFont systemFontOfSize:maxFontSize];
    [text drawAtPoint:point forWidth:right - left withFont:font
       minFontSize:minFontSize actualFontSize:NULL
       lineBreakMode:UILineBreakModeTailTruncation
       baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
}
```
```


Question:
The heart of any good web app is it's offline capability and JavaScript functionality. Currently what tools and wrappers are availability for the desktop web app maker to cross over to the mobile market? What would be the necessary read ups for such a team?

Clarifications:
I am searching for information on how much offline capabilities and JavaScript functionality has improved on the Mobile phones. I know that the term 'mobile phones' are too broad. I am aware of offline solutions like Gears, Adobe AIR, Silverlight etc. But are these really for mobile phones?

How much has JavaScript improved on Mobile Webkit Browsers such as iPhone and Symbians? OperaMini also claims some JavaScript functionality.

Answer:
I'm not totally sure I understand your question, but you'll probably want to take a look at the
iPhone Dev Center
and the
Google Android SDK
to start.
Blackberry
also has a Development Program. Beyond that, you may want to look into
WAP and WML
.
Google Gears
,
Adobe Air
, and
Mozilla's XUL
will give you some offline capability, but to my knowledge they won't wrap an existing desktop app and make it available for the web.


Question:
I have a flash application running Flash 9 (CS3).  Application is able to control the Softkeys when this flash application is loaded in the supported mobile device.  But, the application doesn't have control when the same is embedded in HTML page and browsed via supported mobile device.  Any ideas how to make this work?

Thanks
Keerthi

Answer:
There is no special way to receive soft key events when embedded in HTML - if the browser/OS gives the events to Flash, then you can catch them like any other key event:
```
```
var myListener = new Object();
myListener.onKeyDown = function() {
    var code = Key.getCode();
    if (code==ExtendedKey.SOFT1) {
        trace("I got a soft key event");
    }
}
Key.addListener(myListener);
```
```
However, you'll find that most phones/browsers will not give you soft key events when your SWF is embedded in HTML. This isn't part of the Flash Lite spec - strictly speaking I believe they could give you those events if they wanted to, but most phones simply use those keys for browser functions, and consume them before they get to Flash.
Note that you can check at runtime whether or not softkeys are available:
```
```
trace(System.capabilities.hasMappableSoftKeys);
trace(System.capabilities.softKeyCount);
```
```


Question: As per the title. For those who don't know, it's basically Ada for .Net.

Answer:
According to [wikipedia](
http://en.wikipedia.org/wiki/A_Sharp_(.NET))
, A#.Net has been folded into "GNAT for .Net" for future releases
AdaCore
has taken over this development, and announced "GNAT for .NET", which is a fully supported .NET product with all of the features of A# and more.


Question: One of the stated goals of the PureMVC framework is to avoid platform dependencies in order to be portable. Considering that because of language and API differences application code will always be heavily dependent on the platform, and that avoiding platform dependencies makes the framework reinvent the wheel and/or only provide a least-common-denominator feature set, in what way does the portability of the framework benefit me as an application developer?

Answer:
I've worked with PureMVC. They're trying to implement their stuff in quite a lot of languages. You may be right about the least common denominator, but overall, it's not a bad framework, and I've seen a really nice AS3 app in PureMVC.
I don't think they're talking about portability in terms of porting actual code. The idea there is more that you're using a generalized MVC architecture, which you could apply to other projects and other languages.
They're trying to say that if you become familiar with the PureMVC pattern, you could potentially come into a new PureMVC codebase, even if it's another language, and you would already know the lay of the land.
You might also say that developers who develop good PureMVC skills are likely to develop good habits which will translate as they go from language to language.  But then again, maybe not.. for the reasons you mentioned.