q:
My account is in the securityadmin role and I cannot grant myself sysadmin permission. I wish to gain access to a database so I can add my account to a particular role within it.

As I don't yet have access to the database I can't use the UI.

Does anyone know if this is possible and what SQL commands will achieve this in SQL Server 2005?
Thanks!

[A]
The
sysadmin role
, as the name implies, can do anything within SQL Server. It has complete rights over the SQL Server. It is the only role that can add others to the sysadmin role. There isn’t anything within SQL Server a sysadmin role member can’t do.
You could use the system stored procedure
add_srvrolemember
to assign users to this role.
Example:
```
```
EXEC sp_addsrvrolemember 'BUILTIN\Administrators', 'sysadmin'
```
```


q:
There is div named "dvUsers". there is an anchor tag "lnkUsers".

When one clicks on anchortag, the div must open like a popup div just below it.

Also the divs relative position should be maintained at window resize and all.
How to do that using javascript/jquery?

[A]
```
```
$(document).ready(function(){ $("#lnkUsers").click(function(){ $("#dvUser").show("slow"); });
```
```
style="display: none" should be applied to dvUser at the first place to make it invisible.

s: huggingface

c: devops

d: intermediate


q:
Recently I've been seeing a lot of this:

<a href='http://widget-site-example.com/example.html'>
    <img src='http://widget-site-example.com/ross.jpg' alt='Ross&#39;s Widget' />
</a>

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

[A]
It's certainly valid to use single quotes (
HTML 4.01, section 3.2.2
). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.


q:
How can I create an Oracle stored procedure which accepts a variable number of parameter values used to feed a IN clause?

This is what I am trying to achieve. I do not know how to declare  in PLSQL for passing a variable list of primary keys of the rows I want to update.

FUNCTION EXECUTE_UPDATE
  ( <parameter_list>
   value IN int)
  RETURN  int IS
BEGIN
    [...other statements...]
    update table1 set col1 = col1 - value where id in (<parameter_list>)

    RETURN SQL%ROWCOUNT ;
END;

Also, I would like to call this procedure from C#, so it must be compatible with .NET capabilities.

Thanks,
Robert

[A]
I've not done it for Oracle, but with SQL Server you can use a function to convert a CSV string into a table, which can then be used in an IN clause. It should be straight-forward to re-write this for Oracle (I think!)
```
```
CREATE Function dbo.CsvToInt ( @Array varchar(1000))
returns @IntTable table
    (IntValue nvarchar(100))
AS
begin

    declare @separator char(1)
    set @separator = ','

    declare @separator_position int
    declare @array_value varchar(1000)

    set @array = @array + ','

    while patindex('%,%' , @array) <> 0
    begin

      select @separator_position =  patindex('%,%' , @array)
      select @array_value = left(@array, @separator_position - 1)

        Insert @IntTable
        Values (Cast(@array_value as nvarchar))

      select @array = stuff(@array, 1, @separator_position, '')
    end

    return
end
```
```
Then you can pass in a CSV string (e.g. '0001,0002,0003') and do something like
```
```
UPDATE table1 SET
       col1 = col1 - value
WHERE id in (SELECT * FROM csvToInt(@myParam))
```
```


q:
I need to write a regular expression that finds javascript files that match

<anypath><slash>js<slash><anything>.js

For example, it should work for both :

c:\mysite\js\common.js (Windows)

/var/www/mysite/js/common.js (UNIX)

The problem is that the file separator in Windows is not being properly escaped :

pattern = Pattern.compile(
     "^(.+?)" +
     File.separator +
     "js" +
     File.separator +
     "(.+?).js$" );

Throwing

java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence

Is there any way to use a common regular expression that works in both Windows and UNIX systems ?

[A]
Does
```
Pattern.quote(File.separator)
```
do the trick?
EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char:
```
```
"\\" + File.separator
```
```
Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change them to their special meaning or lead to a
PatternSyntaxException
.
(Thanks
Alan M
for pointing this out in the comments!)


q:
console.log("double"); vs. console.log('single');

I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?

I thought they're pretty much interchangeable.

[A]
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
```
```
alert('Say "Hello"');
alert("Say 'Hello'");
```
```
This can get complicated:
```
```
alert("It's \"game\" time.");
alert('It\'s "game" time.');
```
```
Another option, new in ECMAScript 6, is
template literals
which use the
backtick
character:
```
```
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
```
```
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that
JSON
is formally specified to use double quotes, which may be worth considering depending on system requirements.


q:
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)

I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.

If there is injection WHERE 1 = 1 AND injected OR 1=1 would have the same result as injected OR 1=1.

Later edit: What about the usage in a view definition?

Thank you for your answers.

Still,
I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.

Take this for example:

CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 AND table.Field=Value

[A]
If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:
```
```
and <condition>
```
```
and concatenate them all together. With the
```
1=1
```
at the start, the initial
```
and
```
has something to associate with.
I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I
have
seen it used as an implementation convenience. The SQL query engine will end up ignoring the
```
1=1
```
so it should have no performance impact.


q:
We are developing a new web service and are looking into the "best practice" for returning errors in the soap response.

We were looking into creating a error response object which every response would contain as a property.  This seems a little heavy however and are wondering if it is possible to use the SOAP header to carry this information?  How do you normally deal with custom errors using SOAP?

[A]
Soap already uses custom headers for error info, all you need to do is throw an exception on the server side, and exception is raised on the client side as a
SoapException
.
You can thrown SoapExceptions on the serverside if you want more control over the exception message/info.
Edit:
For extra information along with the request, custom soap headers can be used. Here's an
example article on CodeProject
that used custom soap headers for authentication, but custom soap headers can be used for other purposes like sending extra info that is not necessarily an error condition (can be business logic info)


q:
I know that there has been a couple questions about tutorials on moq. But I am wondering if there are any sample apps out there that use moq in the context of an n-tier business application using ado.net.

I find the tutes good, but they don't seem to bring everything all together into the big picture. Thus, I am looking for a sample app that brings the full picture together.

Also, I think there is a little bit of a lack of examples which specifically deal with mocking and testing the logic in the data access layer.

Cheers
Anthony

[A]
Moq, like all unit testing frameworks, should not have much a concept of n-tier-ness about it.
One would typically use unit testing to test each individual class one-at-a-time. When a particular class is a little more complex and relies on having references to component classes and calling methods on these component classes, one might use a mocking framework such as Moq to create these constituent components, and to have the class-under-test use these mocked components instead of the real deals.
It looks like you are looking for how to use Moq in integration testing, where you bring all the components together and test the whole shebang all at once, including the data-access components. For doing whole-shebang tests, typically you need the real components, not mocked versions of them.


q:
We have an application that use MSSQL, when we move to 2005, basically we recommend to our client to apply the backward compatibility package and that’s it, but somebody ask me what to do to be 100% compatible on 2005.
I was thinking on
1. Compatibility level: SQL Server 2005 (90)
2. Remove any DMO reference, and replaced by SMO
3. Connect using ADO

I am not sure if this is the correct answer.

[A]
Actually you are talking about two different things.
One is to update the database to SQL 2005 level, to be able to use the functions only available there. It can be done easily by setting the compatibility level. However in this case SQL 2000 clients can have problems with it.
Second is to upgrade your application to use only SQL 2005 related libraries. This is also easy, basically the steps what you have written. In this case your application can also work with SQL 2000 databases (except if you use some SQL 2005 specific feature) because the libraries are backward compatible.
End words: you are either way
compatible
with SQL 2005, the only difference is that you can use SQL 2005
specific features
or not.
Why not change to SQL 2008 already?
Here is a thread
about this topic.


q: I want my application to clean all the temp files it used, the problem is that not all the  temp files are under my control, so I just want to "brutally" unlock them in order to delete them programatically.

[A]
Surely, of your application is wanting to clean up the temp files it owns, then you have full control to unlock these files and delete them!
If you're wanting to delete all TEMP files, whether owned by your application or otherwise, you should be VERY careful.  The original application probably applied the lock because it wants to use the file!
If you truly need to, you could always spawn a command-line application rather than trying to replicate the functionality of existing tools which will be difficult in C#.


q:
Currently I use the "One Page Project Manager" Excel Template for project status reports. It contains a summary of last week's work and a forecast for the next week. For all important tasks we track, if they are comleted or not. Everything on one page. I send this report every week to all participants/stakeholders. (hint: I do not work in an agile environment)

How do you report your project status?

[A]
Status reporting should be brief (nobody likes to sit there for ages while every member of the team goes on and on about their status) so I'm a big fan of SOFT reports:
Successes
- what have you achieved since the last status meeting: tasks directly off the project schedule. If possible I tried to avoid reporting x% done -- it's either done, or it's not. Reporting by % means that tasks will sit at 95% for
weeks
. This also encourages the project manager/tech lead to break down the work breakdown structure into tasks that are no longer than a few days.
Opportunities
- have you identified any opportunities: things that will help the project that aren't being considered yet (e.g.: found a better way to script something, a library that will save the project from implementing something themselves, etc)
Future Work
- what are you working on between now and the next status meeting: again, directly off the project schedule.
Threats
- have you identified anything that will impact your ability to get your scheduled work done? e.g.: a previously-unidentified hole in the requirements, support calls are taking a big chunk of your time, implementing something turns out to be harder than expected, etc.
Ideally I would try and avoid doing this stuff in a big project meeting since 90% of the material is irrelevant to half the people in the room. I like to collect SOFT reports before the meeting, spend some time looking at them before the meeting and then discuss specific issues that are probably relevant to everybody during the actual meeting.


q:
Due to the nature of the live server I deploy to, my mail settings are using deliveryMethod="PickupDirectoryFromIis". I'm using log4net to send logs via email and I need find a way of getting it to do the same thing.

I can see from the docs that there is an SmtpPickupDirAppender, which has a pickupDir setting. If I set this to whatever pickup directory IIS uses, I'm sure everything will work OK. However what I really want is to just tell log4net to use IIS's setting and leave it there. That way if it ever changes we won't have to change the log4net config too, something we're likely to forget. Is there a way to do this?

[A]
AFAIK, that's not possible. Although it sounds like a good idea.
One of the greatest things about log4net is that you can change your configuration without having to restart or recompile the application (check the
FAQ
), so you don't need to worry about having a downtime in your logging.
I don't know if you can query the IIS for the SMTP pick up directory, maybe if this is possible you can add some background job that queries the IIS for this information?


q:
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison.

I think the most interesting frameworks are CppUnit, Boost and the new Google testing framework. Has anybody done any comparison yet?

[A]
See this question
for some discussion.
They recommend the articles:
Exploring the C++ Unit Testing Framework Jungle
, By Noel Llopis.
And the more recent:
C++ Test Unit Frameworks
I have not found an article that compares googletest to the other frameworks yet.


q:
I have a problem, and was hoping I could rely on some of the experience here for advice and a push in the right direction. I have an MS Access file made by propietary software. I only want to take half the columns from this table, and import into new(not yet setup)mysql database.

I have no idea how to do this or what the best way is. New data will be obtained each night, and again imported, as an automatic task.

One of the columns in the access database is a url to a jpeg file, I want to download this file and import into the database as a BLOB type automatically.

Is there a way to do this automatically? This will be on a windows machine, so perhaps it could be scripted with WSH?

[A]
This is a bash script
linux
example using
mdbtools
for automatic extraction and import from a mdb file to mysql.
```
```
#!/bin/bash

MDBFILE="Data.mdb"

OPTIONS="-H -D %y-%m-%d"
mdb-export $OPTIONS $MDBFILE  TableName_1 >  output_1.txt
mdb-export $OPTIONS $MDBFILE  TableName_2 >  output_2.txt

mdb-export $OPTIONS $MDBFILE  TableName_n >  output_n.txt

MYSQLOPTIONS=' --fields-optionally-enclosed-by=" --fields-terminated-by=, -r '
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_1.txt
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_2.txt
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_n.txt
```
```
You can use some others mysqlimport options:
--delete: to delete previous Data from the target mysql table.
--ignore: ignore duplicates
--replace: replace if a duplicate is found
It's not a windows solution but i Hope it helps.


q:
How can I add a plaintext into encrypted ciphertext?

For example, I would like to add number 4 into encrypted(5)

[A]
@Bill the lizard:
Well you can, if you are using ECB or any other block mode where the n+1 block doesn't require much knowledge about block n you can chain on an extra block (or even insert a block as in the case of ecb).
However this leaves you open to mitm-attacks and so on...


q: Does the HTML "select" element have an on select event? what exactly is the name of the event?

[A]
Is
```
onchange
```
what you're looking for?


q:
I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.

EDIT:
To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.

[A]
Try this
```
```
SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM
  (SELECT product_id, sum(quantity) as inventory_total
   FROM inventory
   GROUP BY product_id) inv_t LEFT OUTER JOIN
  (SELECT product_id, count(*) AS sales_total
   FROM sales
   GROUP BY product_id) sale_t
  ON (inv_t.product_id = sale_t.product_id)
```
```
This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table.  You want to make sure that such products also show up in the results.
NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument.  There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.


q:
What does Java do with long variables while performing addition?

Wrong version 1:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??

Wrong version 2:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??

Correct version:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct

I don't get it, why Java concatenate them.

Can anybody help me, why two primitive variables are concatenated?

Greetings, guerda

[A]
I suspect you're not seeing what you think you're seeing. Java doesn't do this.
Please try to provide a
short but complete program
which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample).
```
```
import java.util.*;

public class Test
{
    public static void main(String[] args)
    {
        Vector speeds = new Vector();
        speeds.add("x");
        speeds.add("y");

        long estimated = 1l;
        long time = speeds.size() + estimated;
        System.out.println(time); // Prints out 3
    }
}
```
```


q:
I'm using a Response.Redirect to redirect users to another server to download a file, and the other server is checking the header to ensure it came from the correct server... however it seems Response.Redirect strips the headers from the Response.

Does anybody know how i can add the headers back?  I've tried:

Response.AddHeader("Referer", "www.domain.com");

But the receiving page tests false when i check if the Referrer header is set.

Any suggestions how i can get this working, other than displaying a button for the user to click on (i'd like to keep the url hidden from the user as much as possible).

[A]
I don't think it's possible.  What you are sending back to the client is a Location header that tells the client to load the page referred to instead of the page it originally requested.  In this case the client is not coming from a link and thus does not set the referrer header.  It's basically as if the user typed the redirect url in the location bar in his browser.
You may be able to save the referrer in the session, or encode it in the URL as a query parameter.  Like the Forms login does with ReturnUrl.


q:
Any links/Turorials avalable? I want to write a simple ISAPI plugin for IIS6.0.

Prefered language c++

[A]
Below is a quick (and simple) ISAPI Filter example. I found it very useful when trying to write my first ISAPI plugin.
http://blogs.msdn.com/rakkimk/archive/2007/03/01/writing-a-simple-isapi-filter.aspx
Best of luck.


q:
Is it possible to get a list of control events that are going to fire before they happen, say inside the Page_Load handler?

For example if a button was clicked can I figure this out before the button_click event handler is called?

[A]
The following contains the mangled id for a button when clicked.
```
```
Page.Request.Form["__EVENTTARGET"]
```
```


q:
On a website, everything is tagged with keywords assigned by the staff (it's not a community driven site, due to its nature). I am able to determine which tags a user is most active in (or, what tags they view the most). However, I'm not sure how to choose the list. A few options present themselves, but they don't seem right to me.

Take the top n (or m < n if they have fewer than n viewed tags) tags

Take the top n tags where n is a percentage of the total tags viewed

Take the top n tags with m views where n and m are percentages of total tags viewed and total page views

Take all of the tags, regardless of views

The goal is to identify what is most interesting to the user and show them other things that they might be interested in, with respect to the tags that are assigned to the content.

[A]
You could look at machine learning algorithms to find algorithms with which to evaluate the effectiveness of your choice.
Like for instance:
http://en.wikipedia.org/wiki/Supervised_learning#Approaches_and_algorithms
Stuff like nearest neighbour and bayes could help you improve your suggestions.
This is however overkill for just suggesting "Would you like to look at this too?", but it's an interesting approach to providing better tie-ins. It would, however require some method to figure out whether or not your users value your suggestions (e.g. "I like this!"-links or log-analysis based on time spent on links, etc.)


q:
I have a key that appears to be an empty string, however using unset($array[""]); does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.

The line for the element on a print_r is [] => 1, which indicates to me that the key is the empty string.

Using var_export, the element is listed as '' => 1.

Using var_dump, the element is listed as [""]=>int(1).

So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried unset($array[""]);, unset($array['']);, and unset($array[null]); with no luck.

[A]
My guess is that it's not an empty string.  Try the following to see what you get:
```
```
foreach ($array as $index => $value) {
    echo $index;
    echo ' is ';
    echo gettype($index);
    echo "\n";
}
```
```


q:
The thing is I've been using the lock statement to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met.

Is there a way to condition the lock?

[A]
```
```
Action doThatThing = someMethod;

if (condition)
{
  lock(thatThing)
  {
     doThatThing();
  }
}
else
{
  doThatThing();
}
```
```


q:
From what I understand, if you have multiple web servers, then you need some kind of load balancer that will split the traffic amongst your web servers.

Does this mean that the load balancer is the main connecting point on the network? ie. the load balancer has the IP address of the domain name?

If this is the case, it makes it really easy to add new hardware since you don't have to wait for any dns propogation right?

[A]
There are several solutions to this "problem".
You could round-robin at the DNS-level. I.e. have www.yourdomain.com point to several IP-addresses (well all your servers).
This doesn't give you any intelligence in the load balancing, but the load will be more or less randomly distributed, but you wouldn't be resilient to hardware failures as they would still require changes to DNS.
On the other hand you could use a proxy or a loadbalancing proxy that has a single IP but then distributes the traffic to several back-end boxes. This gives you a single point of failure (the proxy, you could of course have several proxies to defeat that problem) and would also give you the added bonus of being able to use some metric to divide the load more evenly and intelligently than with just round-robin dns.
This setup can also handle hardware failure in the back-end pretty seamlessly. The end user never sees the back-end, just the front-end.
There are other issues to think about as well, if your page uses sessions or other smart logic, you can run into synchronisation problems when your user (potentially) hits different servers on every access.


q:
I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly.

I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up).

Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.

[A] I personally would have the SSIS-fed tables in one database (set to simple recovery mode) and the other tables in a separate database on the same server which is set to full recovery mode,. Then I would set up backups on the second datbase on a regular schedule. A typical backup schedule would be full backup once a week, differntials nightly  and transaction backups every 15-30 minutes depending on how much data is being input.) Be sure to periodically test recovering the backups, learning how to do that when the customer is screaming becasue the datbase is down isn;t a good thing.


q:
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.

Some examples:

Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php

if ( count($arrayName) ) // handles $arrayName being unset or empty

Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);

[A]
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
```
```
ini_set('display_errors', '1');
error_reporting(E_ALL);
```
```
Never use
automagic
. Stuff like autoLoad may bite you in the future.
Always require dependent classes using
```
require_once
```
. That way you can be sure you'll have your dependencies straight.
Use
```
if(isset($array[$key]))
```
instead of
```
if($array[$key])
```
. The second will raise a warning if the key isn't defined.
When defining variables (even with
```
for
```
cycles) give them verbose names (
```
$listIndex
```
instead of
```
$j
```
)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using
Zend Framework's naming conventions
because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the
full backtrace
.


q:
Does anyone have experience with developing for Sharepoint 2003 using Visual Studio 2008?

I need to upgrade to VS2008 because of Vista issues but need to support Sharepoint 2003 webparts. The webparts are all pretty simple. Will I be able to support those webparts using VS2008?

[A]
I've created .net 2.0 assemblies using vs2008, and linked with sharepoint 2007 libraries and then deployed on sharepoint servers.  You won't be able to create .net 1.1 assemblies with vs2008 out of the box - so if you need to target .net 1.1 your best bet is to stick with a virtual server setup.
Developing for sharepoint on vista (or xp for that matter) is challenging because you can't debug line by line unless you attach remotely to server2k3.  My recommendation for sharepoint developers is to install virtual server on vista, and then install vstudio on the virtual server with sharepoint.  If you are going to do this, you can stick with your current version of visual studio, and then debugging is much easier than from vista.
Depending on whether your company has an msdn subscription, this can be more costly if you have to buy a virtual server license, etc...  but it is well worth it to make development easier, in my opinion.


q:
Did someone ever used a BIRT report in a desktop application. I'm comming from the .NET environment and there you can use Crystal Reports to show reports in desktop apps. Is this possible with BIRT too, without having to set up a server environment?

Can you give me some advice how to reach this goal?

Thanks in advance.

[A]
Yes, it is possible. I used it in a project I did about 1-2 years ago so I'll have to get back to you with the details. (Though things might have changed since then)
Here are the plugins
I
needed:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="var" path="JUNIT_HOME/junit.jar" sourcepath="JUNIT_SRC_HOME/junitsrc.zip"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.14.jar"/>
    <classpathentry kind="lib" path="lib/swt.jar"/>
    <classpathentry kind="con" path="SWT_CONTAINER"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.device.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.device.swt_2.1.1.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.engine_2.1.2.v20070205-1728.jar" sourcepath="C:/Programme/eclipse/plugins/org.eclipse.birt.chart.source_2.2.0.v20070209/src"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.engine.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.runtime_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.core_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.common_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.ecore_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.ecore.xmi_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="js.jar"/>
    <classpathentry kind="lib" path="com.ibm.icu_3.4.5.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.ui_2.1.1.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.ui.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="lib/hsqldb.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>
```
```


q:
I remember hearing Joel say he has 2 different locations where the servers are located, each location has 2 front end servers and 1 back end server.

If a one of the hosting facilities goes down, how can he switch over to the other one?  (Or is it just going to be a DNS change that will take 24-72 hours to propagate?).

How can a single SQL Server instance have so many databases on it?  FB has a completely separate database per account.  I can't see a single SQL Server instance having more than say 200-250 databases on it!  And I'm sure they have more customers than that.

[A]
They talked about this in one of the Stack Overflow podcasts, but I can't find it in the transcripts.
1) Each of the two centers handles approximately 1/2 of the users. Fairly often (hourly, I think Joel said) they ship transaction logs to the other site. If site A goes down, they bring up the db backups on site B, and do the DNS switchover. It won't be instantaneous or automated, nor do they want it to be, because they'll be coming up with slightly stale data, and want to avoid that if it's at all possible to bring the broken site back up.
I'm not sure how they handle the DNS situation, but you can set the TTL on DNS records to mere seconds to limit caching, and have failover occur very quickly.
2) Why not? I'm not sure of the hard limit of databases per instance, but there's also nothing keeping you from running multiple instances of SQL Server on your box. I would imagine you're more limited by hardware than software. (You can also run Fogbugz with a MySQL database backend).


q: I am using a ASP/.Net webpage and i want to upload a pdf file into a SQL Database as a binary    I am uping the build in upload control, can you please suggest a way of doing this. I also need to no how to read the pdf back and display it in a web browser. I will be using linq to upload and query my sql database.

[A]
You can use the
```
VARBINARY(MAX)
```
type in your database, create a LINQ to SQL mapping and use the
```
Binary
```
type with the
```
byte[]
```
type containing your PDF file's content.


q:
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening .  I can't find in the documentation how this is done - can someone point me in the right direction?

We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.

[A]
I'm just guessing here, but I'd imagine it is
CWaitCursor
.  Basically, you just create one on the stack, it appears, and disapppears when it is destructed as it goes out of scope e.g.
```
```
void DoSomethingSlow()
{
  CWaitCursor cw;
.
.
.
.
}
```
```


q:
I was wondering how to unit test abstract classes, and classes that extend abstract classes.

Should I test the abstract class by extending it, stubbing out the abstract methods, and then test all the concrete methods? Then only test the methods I override, and test the abstract methods in the unit tests for objects that extend my abstract class?

Should I have an abstract test case that can be used to test the methods of the abstract class, and extend this class in my test case for objects that extend the abstract class?

Note that my abstract class has some concrete methods.

[A]
I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.
As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.


q: I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?

[A]
Did you try to launch your eclipse with java.exe instead of javaw.exe (in your
eclipse.ini
) ?
That might give you the console you need, as described in
this bug
and in
this message
.
Other ideas (in term of java options) could be derived from this
other SO question
.


q: Does everyone just use XML in the message? Are there any good alternatives to XML?  If you do use XML, do you define an XML Schema so clients know how to send messages to your service?

[A]
We use XML, but I think the important thing is to tailor the solution to the problem.  The reason we use XML is that we are basically sending an object across in the message.  There's no reason it can't be plain text, if applicable for the message you are sending, using headers to send along properties if appropriate.
We haven't defined an XSD or DTD for our XML messages, but we do have a formal document describing their composition so that other teams can use our feeds without bugging us.


q:
State should include at least the following:

All settings set via
SetStreamResource()

Indices

I have a class whose Draw() function will call SetStreamResource, set Indices and eventually call DrawIndexedPrimitive(). I would like to restore the device state before Draw() returns.

I am looking for something along the lines of GDI's SaveDC()/RestoreDC().

[A]
Looks like these will do it:
```
```
Microsoft::DirectX::Direct3D::Device::BeginStateBlock
Microsoft::DirectX::Direct3D::Device::EndStateBlock
```
```


q:
I launch my program in C#, which then calls some unmanaged C++.

When I break on a line in the unmanaged C++, the 'New Data Breakpoint' menu item is grayed out.

Is there anyway around this?

[A]
To set a data breakpoint in the native portion of a mixed mode process, see the
answer posted by jyoung
.
Visual Studio disables data breakpoints when running anything but pure, native code. See
this
post for a partial explanation why from a VS Program Manager.


q:
Is it ever OK to use Environment.TickCountto calculate time spans?

int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");

Because TickCount is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful.

I'm using DateTime.Now instead. Is this the best way to do this?

DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");

[A]
Use Stopwatch class. There is a decent example on msdn:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
```
```
Stopwatch stopWatch = Stopwatch.StartNew();
    Thread.Sleep(10000);
    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
```
```


q:
Is there a way to quickly list which sites are on which IP address in IIS 7?

If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.

[A]
You can try this script:
```
```
MachineName = "localhost"
IIsObjectPath = "IIS://" & MachineName & "/w3svc"

WScript.Echo "Checking : " & IISObjectPath

Set IIsObject = GetObject(IIsObjectPath)
for each obj in IISObject
    if (Obj.Class = "IIsWebServer") then
        BindingPath = IIsObjectPath & "/" & Obj.Name

        Set IIsObjectIP = GetObject(BindingPath)
        wScript.Echo BindingPath & " - " & IISObjectIP.ServerComment

        ValueList = IISObjectIP.Get("ServerBindings")
                ValueString = ""
        For ValueIndex = 0 To UBound(ValueList)
            value = ValueList(ValueIndex)
            Values = split(value, ":")
            IP = values(0)
            if (IP = "") then
                IP = "(All Unassigned)"
            end if
            TCP = values(1)
            if (TCP = "") then
                TCP = "80"
            end if
            HostHeader = values(2)

            if (HostHeader <> "") then
                    wScript.Echo "    IP = " & IP & " TCP/IP Port = " & TCP & ", HostHeader = " & HostHeader
            else
                    wScript.Echo "    IP = " & IP & " TCP/IP Port = " & TCP
            end if
                Next
        wScript.Echo ""
        set IISObjectIP = Nothing
    end if
next
set IISObject = Nothing
```
```
(source www.iisfaq.com)


q:
How do I programmatically reset the Excel Find and Replace dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?

I am using Application.FindFormat.Clear and Application.ReplaceFormat.Clear to reset find and replace cell formats.

Interestingly, after using expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords), the FindWhat string shows in the Find and Replace dialog box but not the ReplaceWhat parameter.

[A]
You can use the following command to open the "Replace" dialog with fields filled:
Application.Dialogs(xlDialogFormulaReplace).Show -arguments here-
the argument list is
find_text, replace_text, look_at, look_by, active_cell, match_case, match_byte
So far, the only way I've found to 'click' the buttons is with SendKey.
After much research and testing, I now know exactly what you want to do, but don't think it can be done (without SendKey).  It appears that there is a bug in Excel, that won't reset the replacement value (from VBA), no matter what you try and set it to.
I did find this 'faster' way someone posted on MSDN, so you might give it a try.
Faster than Replace


q: Is there anything I should know before converting a large C++ program from VS2005 to VS2008?

[A] Is there a difference in the syntax that you can't just simply recompile? VS will convert the .sln and vcproj files for you automatically. The rest is just code, and unless you are doing something really strange, it should just recompile as-is.


q:
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page:

Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++.

Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers?

Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞).

[A]
There is an interesting thread on
Lambda the Ultimate
that discusses the
LALR grammar for C++
.
It includes a link to a
PhD thesis
that includes a discussion of C++ parsing, which states that:
"C++ grammar is ambiguous,
  context-dependent and potentially
  requires infinite lookahead to resolve
  some ambiguities".
It goes on to give a number of examples (see page 147 of the pdf).
The example is:
```
```
int(x), y, *const z;
```
```
meaning
```
```
int x;
int y;
int *const z;
```
```
Compare to:
```
```
int(x), y, new int;
```
```
meaning
```
```
(int(x)), (y), (new int));
```
```
(a comma-separated expression).
The two token sequences have the same initial subsequence but different parse trees, which depend on the last element. There can be arbitrarily many tokens before the disambiguating one.


q:
I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.

Currently, I have something like:

Session s = HibernateUtil.getSessionFactory().openSession();
MyClass c = (MyClass)session.get(MyClass.class, myClassID);

[A]
You could try something like this: (code off the top of my head)
```
```
Criteria crit = session.createCriteria(MyClass.class);
crit.add(Restrictions.eq("id", myClassId));
crit.setFetchMode("myProperty", FetchMode.EAGER);
MyClass myThingy = (MyClass)crit.uniqueResult();
```
```
I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.


q:
How would I expose an Objective-C method within JavaScript when using the iPhone SDK when using the UIWebView?

Any help would be appreciated!

[A]
The best way to do this would be through a custom link, and then use the UIWebView delegate method
```
-webView:shouldStartLoadWithRequest:navigationType:
```
to trap requests. When you see a request come through with your link in it, you know your action has been triggered.


q:
I was mapping a relation using something like the following

<map name="Foo" cascade="all-delete-orphan" lazy="false">
  <key column="FooId"/>
  <index column="FooType" type="Domain.Enum.FooType, Domain"/>
  <element column ="FooStatus" type="Domain.Enum.FooStatus, Domain"/>
</map>

The class is like this

namespace Domain {
    public class Enum {
        public enum FooType {
            Foo1,
            Foo2,
            ...
      Foo50}
       public enum FooStatus {
           NotNeeded,
           NeededFor1,
           NeededFor2,
      NeededFor3,
      NiceToHave}
    }
}

Can I do this using Fluent Nhibernate?
If not can I map a class mixing Fluent and XML?

[A]
Forget to add
```
```
namespace Domain
{
public virtual IDictionary<FooType, FooStatus> MyFoo { set; get; }
}
```
```


q: I have a .Net app that will allow the users to attach files to a SQL Server 2005 database.  I want to limit the filesize to 10MB, so from what I can tell, I have to declare the datatype varbinary(max), since the max size I can actually specify is 8000 bytes.  But the ~2GB filesize varbinary(max) allows seems like overkill.  Is there a way for me to limit it at 10MB in the database, or do I just need to check that they're not trying to attach something larger on the frontend.

[A]
I think you need to make it in the frontend. You can limit the HTTP request size in the web.config like that:
```
```
</configuration>
   </system.web>
      <httpRuntime maxRequestLength="60000"/>
   </system.web>
</configuration>
```
```
You may also need to explicitly check the posted file size when the user try to upload a file more than the specified threshold.


q:
How would one go about capturing users keystrokes in the SMS composer on the Symbian OS, specifically for a Nokia N73 (or any of the symbian supported devices http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS)? I'm new to symbian development and I'm trying to write an application to analyse writing styles of those who send SMSs. Any information (or push in the right direction) would be great.

Many Thanks,

A

[A]
Well, there are several levels to answering to your question.
The keystrokes are actually captured by the message editor application. So, either it provides an API to feed you all its keystrokes (you can look for one on
http://forum.nokia.com
. You'll find the message editor API but it will be mostly about re-using GUI controls and not what you're looking for) or you would need a transparent application of your own that stays in the foreground and captures keystrokes before feeding them back to whatever application happens to be right behind. Fortunately (for obvious security reasons), Symbian OS will not allow you to do the later.
You can, however, have your own application read messages when they are saved in the  phone memory: when they are saved in the Draft folder or in the SMS Outbox.
The obligatory shameless plug: I would advise reading the messaging chapter of
http://www.quickrecipesonsymbianos.com
in order to understand how to use the Symbian Message Store
The classes of interest in your case are : CmsvEntry, CMsvSession, MMsvSessionObserver, CMsvOperation and CSmsClientMtm.


q:
Does anyone know what is wrong with this query?

 SELECT DISTINCT c.CN as ClaimNumber,
         a.ItemDate as BillReceivedDate, c.DTN as
 DocTrackNumber
         FROM ItemData a,
         ItemDataPage b,
         KeyGroupData c
         WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
         AND a.ItemNum = b.ItemNum
         AND b.ItemNum = c.ItemNum
         ORDER BY a.DateStored DESC;

I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.

Thanks!

[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression"

[A]
Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:
```
```
SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate,
c.DTN as DocTrackNumber,
a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
```
```


q: How can I find out which row in a JTable the user just clicked?

[A]
Try this:
```
aJTable.rowAtPoint(evt.getPoint());
```


q:
The database type is PostGres 8.3.

If I wrote:

SELECT field1, field2, field3, count(*)
FROM table1
GROUP BY field1, field2, field3 having count(*) > 1;

I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.)

Example:

1-2-3
1-2-3
1-2-3
2-3-4
4-5-6

Should become :

1-2-3
2-3-4
4-5-6

The only answer I found is there but I am wondering if I could do it without hash column.

Warning
I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.

[A]
One possible answer is:
```
```
CREATE <temporary table> (<correct structure for table being cleaned>);
BEGIN WORK;   -- if needed
INSERT INTO <temporary table> SELECT DISTINCT * FROM <source table>;
DELETE FROM <source table>
INSERT INTO <source table> SELECT * FROM <temporary table>;
COMMIT WORK;  -- needed
DROP <temporary table>;
```
```
I'm not sure whether the 'work' is needed on transaction statements, nor whether the explicit BEGIN is necessary in PostgreSQL.  But the concept applies to any DBMS.
The only thing to beware of is referential constraints and in particular triggered delete operations.  If those exist, this may prove less satisfactory.


q:
consider this code block

public void ManageInstalledComponentsUpdate()
        {
            IUpdateView view = new UpdaterForm();
            BackgroundWorker worker = new BackgroundWorker();
            Update update = new Update();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(update.DoUpdate);
            worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);
            worker.RunWorkerAsync();
            Application.Run(view as UpdaterForm);
        }

It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected

[A]
Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited.
Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached.
[edit]
As has also been noted; the event handlers on the worker (in your code) will keep the "view" and "update" objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the "view" and "update", you don't need to get paranoid about unsubscribing the events. I've edited the code to include a "SomeTarget" object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker).
Re worker getting collected when the thread dies: here's the proof; you should see "worker finalized" after the worker reports exit:
```
```
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
class Demo : Form
{
    class ChattyWorker : BackgroundWorker
    {
        ~ChattyWorker()
        {
            Console.WriteLine("Worker finalized");
        }
    }
    class SomeTarget
    {
        ~SomeTarget()
        {
            Console.WriteLine("Target finalized");
        }
        public SomeTarget()
        {
            Console.WriteLine("Target created");
        }
        public void Foo(object sender, EventArgs args)
        {
            Console.WriteLine("Foo");
        }
    }
    static void Collect(object sender, EventArgs args)
    {
        Console.WriteLine("Collecting...");
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Interval = 100;
        timer.Tick += Collect;
        timer.Start();

        ChattyWorker worker = new ChattyWorker();
        worker.RunWorkerCompleted += new SomeTarget().Foo;
        worker.DoWork += delegate
        {
            Console.WriteLine("Worker starting");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(250);
                Console.WriteLine(i);
            }
            Console.WriteLine("Worker exiting");
        };
        worker.RunWorkerAsync();
    }
    [STAThread]
    static void Main()
    { // using a form to force a sync context
        Application.Run(new Demo());
    }
}
```
```


q:
I have currently more than 100 connections in Sleep state.

Some connection must stay in Sleep state (and don't close) because it's permanent connection but some others (with a different user name) are from some php script and I want them to timeout very fast.

Is it possible to setup a wait_timeout per user? and if yes, How?


q:
I had svnserve configured to look at directory "Foo" for the repository it served. Now I changed the configuration from one repository to multiple repositories, all contained in one directory "Bar". I reconfigured svnserve to look at "Bar", but now my client can't find any repositories. What am I doing wrong? Do I need one service for each repository?

Thanks, Miel.

[A]
Did you configure your client to use svn://svn-server/Foo ? (Assuming Foo and Foo2 are repositories in directory Bar, which you're serving)
Since you're serving "Bar" now ("svnserve -r /repositories/Bar" instead of "svnserve -r /repositories/Bar/Foo") you should make a change on your client-side repository URL.
Another solution would be to fire up multiple SVN servers with different ports using the --listen-port parameter. That would also change your URL.
Yet another alternative is just adding new projects to your single existing repository; note that you'll have a single repository configuration this way -- and that means a single set of users, simpler access control, etc.


q:
I am using UIImagePicker to take photo and save the photo. But appears the photo it takes was truncated on top and bottom, which was top and bottom menu when UIImagePicker taking the photo. I am wondering how to take the whole screen of the photo.

Thanks.

[A]
Look in the "editingInfo" dictionary that you get back in the didFinishPickingImage: method, if there's a value for the @"Original" key then it's the real, uncropped image (stored as a UIImage object).
From there you can look at the other editingInfo values to see if the user cropped that image, which you can then apply (or take the UIImage passed to you which is the cropped verson).  If you are getting an image back from the photo library, the original is not in the dictionary and you only have the image passed in.


q:
[Error] WARNING. Duplicate resource(s):
[Error] Type  2 (BITMAP), ID TWWDBRICHEDITMSWORD:
[Error] File C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource kept;
           file C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource discarded.
I have searched the code for same named objects, like objects.
Can anyone give me a clue what else I can look for.

[A]
Two units both using the same resource file. Probably looks like this:
```
```
{$R wwrichsp.RES}
```
```


q:
How long does it take for an experienced Windows programmer to learn writing simple software for Mac OS X?

Where does one start and what tools will be necessary?

[A]
THIS
.  I came from a Win32 API background programming lately a lot in C# and I was able to pick up on Objective-C and Cocoa very quickly by working through the book.  You will be pleasantly surprised, the APIs are very rich and just wonderful.  Reflection is a first class citizen which makes things very easy.
Xcode is of course free and available on your Mac OS X installation disk.
Edit: it took me about 2 weeks to come up to speed and write simple applications.  I think this is because the language and API are easy to learn and use and
Aaron Hillegass
's
book
was a big help.


q: I'd like to check a few queries generated by ActiveRecord, but I don't need to actually run them.  Is there a way to get at the query before it returns its result?

[A]
Both of these articles should help you do what you want.
http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing
http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord


q: How can I get data from a database that I can only access through an ODBC Data Source (DSN) in T-SQL MS SQL Server, any version?

[A]
The selecting is the easy part, but the real question is how do you connect to the datasource.
First, where are you selecting data from?  Are you writing code, or just using the Query analyzer tool (2000) or Management Studio (2005)?
You'll need to setup your connection to the database regardless.  If you need help with the connectionstrings to a DSN, the site www.connectionstrings.com is very helpful.  Otherwise, from a query tool there will be dialog boxes or wizards to help you.


q:
Hey! I was looking at this code at http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html

I noticed that in some situations they used hex numbers, like in line 134:

for (j = 1; val && j <= 0x80; j <<= 1, q++)

Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80.

Also before line 134, on line 114 they have this:

small_n = (n & 0xffff0000) == 0;

The hex to decimal gave me 4294901760 for that hex number.
So here in this line they are making a bit AND and comparing the result to 0??

Why not just use the number?
Can anyone please explain and please do give examples of other situations.

Also I have seen large lines of code where it's just hex numbers and never really understood why :(

[A]
In both cases you cite, the bit pattern of the number is important, not the actual number.
For example,
In the first case,
```
j
```
is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses.
In binary, that is,
```
0000:0001
```
,
```
0000:0010
```
,
```
0000:0100
```
,
```
0000:1000
```
,
```
0001:0000
```
,
```
0010:0000
```
,
```
0100:0000
```
and
```
1000:0000
```
.
There's no option for binary constants in C (until C23) or C++ (until C++14), but it's a bit clearer in Hex:
```
0x01
```
,
```
0x02
```
,
```
0x04
```
,
```
0x08
```
,
```
0x10
```
,
```
0x20
```
,
```
0x40
```
, and
```
0x80
```
.
In the second example,
the goal was to remove the lower two bytes of the value.
So given a value of 1,234,567,890 we want to end up with 1,234,567,168.
In hex, it's clearer: start with
```
0x4996:02d2
```
, end with
```
0x4996:0000
```
.


q: I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?

[A]
You should be able to specify your own EntityResolver, or use specific features of your parser? See
here
for some approaches.
A more complete example:
```
```
<?xml version="1.0"?>
<!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd">
<foo>
    <bar>Value</bar>
</foo>
```
```
And xpath usage:
```
```
import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                System.out.println("Ignoring " + publicId + ", " + systemId);
                return new InputSource(new StringReader(""));
            }
        });
        Document document = builder.parse(new File("src/foo.xml"));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        String content = xpath.evaluate("/foo/bar/text()", document
                .getDocumentElement());
        System.out.println(content);
    }
}
```
```
Hope this helps...


q:
I am trying to compile a labview CIN using visual studio 2003.

I have followed the tutorial located here to the letter, but am getting the following error:

Project : error PRJ0019: A tool returned an error code from "Performing Custom Build Step"

Does anyone know what is causing this? I tried this link found at an expert's exchange question but it does not seem relevant.

Is there an easier way to build a CIN using visual studio?

[A]
Please post the entire error.  It appears that the custom build step defined in your link does not work.
On the Custom Build Step->General page, type:
```
```
"$(CINTOOLS_DIR)\lvsbutil" "$(TargetName)" -d "$(ProjectDir)$(OutDir)"
```
```
in the commandline field and type
```
$(OutDir)$(TargetName).lsb
```
in the output field.
Try pasting that into a commandline and running it. I suspect you have not got the env variables set or they are not pointing to the right places.


q:
Is there any sort of "out of the box" system within SharePoint (i.e. MOSS 2007) that is useful for tracking/managing permissions.  We've got a relatively small installation, but I can easily see special permissions for special users/sites getting out of hand.  I'm hoping there's something pre-baked into SharePoint that will help with this, but if there is, I don't know where.

If this isn't available from SharePoint, are there any 3rd party tools people would recommend?

[A]
Unfortunately, I haven't found anything that great out of the box in SharePoint for managing or tracking user permissions. You always have an opportunity for customizations. There are some third party tools, however. The best tool I've found for simple management of SharePoint is the Universal SharePoint Manager v2007.
This app has some stellar tools for analyzing security and information about permissions.
Here's a link directly to the feature that might interest you the most:
http://www.idevfactory.com/products/uspm2007/features/sharepoint%20user%20site%20security%20analyzer.aspx
I haven't used the USPM myself. I have used the SWAT tool which has a subset of features. iDevFactory does do a good job with their apps and I've found that it's fairly decent ant getting what you want.
Good luck!


q:
In our Sharepoint implementation users have been granted site collection admin rights. On a few occasions they've managed to delete a subsite or even the entire site collection. I'd like to be able to block this but not being a developer I'm finding it pretty tricky.

I've had a look at the MSIT site delete capture tool to try to understand how that's working and it seams fairly straight forward. I want to override the delete function and either block it entirely or have the user type a password. What I can't see is any way to fully override the default behavior as it looks like the MSIT tool simply adds some functionality (backs up the site) then falls back into the default behavior.

So my question is, can I prevent the default behavior or can I only add actions before or after it fires?

Thanks in advance

[A]
Two answers:
You cannot prevent site deletes without either coding up something yourself, or buying a product to help you with "site lifecycle management" or "site governance" or some other vague term they use to describe this sort of thing.
The Site Delete Capture Tool may be good enough for you. It doesn't prevent any kind of deletions, but it does take a crude backup that (hopefully) allows you to restore anything they delete. We're using this tool in production and it works.


q:
We use Trac as our bug tracking / development / wiki system and I was wondering if anyone has experience and uses some of the Trac Agile/Scrum plugins or functionalities? Anything you'd recommend?

Or would it be better to duplicate Trac tickets as dead-tree user story index cards and a hand-drawn burndown chart?

Note that I found a similar question here. Though it's specifically about Scrum. They recommend Agilo. Has anyone tried Agilo yet?

[A]
Bitten
is a Trac plugin for continuous integration that can be harnessed to do automatic builds on check-in, which provides a critical part of the Agile process (rapid feedback). I haven't used any other plugins for Trac personally, so I can't comment on them. However, the native Trac functionality of milestones could be leveraged fairly easily, I suspect, to be used as iteration markers (where each milestone represents the end of an iteration). Since milestones can be used to mark a 'due date' for features already, you shouldn't need much in the way of modification to use them as such.
From there, using tickets as user stories, and tying them to milestones (I'm sure this can be done manually at worst) would give you a basic method of tracking velocity and keeping the team aware of progress (and changes that need to be made as well).


q: Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?

[A]
No, there is no way to directly convert the list to an observable collection. You must add each item to the collection. However, below is a shortcut to allow the framework to enumerate the values and add them for you.
```
```
Dim list as new List(of string)
...some stuff to fill the list...
Dim observable as new ObservableCollection(of string)(list)
```
```


q: do you know any not strict xpath for java? (I want it to not check dtd and schema) and it would be cool if it dont care about correct xml.

[A]
Ok, first of all, "correct xml" can be interpreted in a couple of ways.  If you mean "non-well-formed" (missing angle brackets, overlapping elements, etc.), no version of xpath would likely do anything useful with that.  You'd be better off with some sort of regular expressions.  If your XML isn't well-formed, I hope you have some clue of how it won't be well-formed, otherwise you have no hope of getting anywhere with it.
If you actually mean "invalid", which simply means it doesn't validate against a schema or DTD, then you can use predicates which compare against the "local-name()" function.  For instance, if you want to find the "/foo/bar" element, ignoring schemas, then your xpath would look like this:
```
```
/*[local-name()='foo']/*[local-name()='bar']
```
```


q:
I've been asked to create a fairly straightforward website for a friend. Essentially a user will log in, fill in a set of information, and submit it. This data will then need to written to a database (and read from/presented at a future point).

I'm not really a web developer (I do mostly Java/C++), but about 3 years ago I worked on a project where we created a site using WAMP (Windows, Apache, MySQL and PHP), with a bit of JavaScript/AJAX thrown in for good measure. I was going to use WAMP again, but am concerned that there might be better tools available now.

So, is the WAMP approach a good one for a straightforward site like this?

If so, what tools would you recommend to use for the development of PHP/Javascript?

Finally, I saw in one of the blog posts that Stack Overflow uses JQuery. Would it be worthwhile to use these libs?

[A]
Assuming that the website you're going to be building is hosted on a WAMP stack, then I'd say continue to use that; otherwise, you may wanna stick with Windows/IIS/PHP/MySQL or SQL Server. I always try to make sure my development environment mirrors production as much as possible.
Secondly, if the user is simply logging in, submitting a form, and is then considered to be done, then using Ajax might be overkill; however, if you're definitely going to be going to Ajax route, then I definitely recommend using a library.
Prototype
or
jQuery
are fine - either one makes Ajax ridiculously simple.
Finally, as far as suggested tools are concerned, find something that fits the bill for what you're developing. If this site is as simple as you claim it is, something like
Notepad++
might be sufficient. Another option for the WAMP/LAMP stack is
Aptana Studio
. If you're going the Windows/IIS/SQL Server route, then use some of the
Microsoft Express
tools.
I could be way off, but if you're building a really simple site, don't spend more time configuring shiny new tools for something that can be done with the existing toolbox you've got.


q: I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?

[A]
If you're just using an integer for a sequence you could update the id with the rownum.  e.g.
```
```
update
table
set id = rownum
```
```
You then need to reset the sequence to the next valid id.


q:
I'm using the latest version of the jQuery UI tabs. I have tabs positioned toward the bottom of the page.

Every time I click a tab, the screen jumps toward the top.

How can I prevent this from happening?

Please see this example:

http://5bosses.com/examples/tabs/sample_tabs.html

[A]
If you have something along these lines:
```
```
Tab 1
```
```
Try adding
```
return false;
```
after the tab activation command:
```
```
Tab 1
```
```


q:
I'd like to know which method is recommended on Windows C programming: using malloc or the Win32 HeapAlloc (maybe VirtualAlloc?) function.

I've read the MSDN Memory Management Functions article and the MSDN articles regarding malloc and HeapAlloc, but they do not say which one should be used and in what situations.

[A]
Stick with malloc unless you have a compelling reason to use something different.  It will be implemented underneath in terms of the OS memory allocation primitives, but there is no real advantage in diving down to that layer yourself.
A few API calls I believe need a memory block allocated from a Windows heap, but you will know when you come across them.
Or if you want to do something more advanced, like use shared memory, or need to control the permissions on the memory pages directly then you will need to look at the Windows API calls like VirtualAlloc.


q: How to validate iscontrolkeys in textbox keydown event in .net?

[A]
This msdn page should do the trick
- check the keypresseventsargs returned in the keypress or
this keydown page
should allow you to query the control keys (using the relevant .Net enum)


q:
I've been developing a simple website using asp.net MVC and I'm starting to add some JQuery\JSON goodness.

My problem is up until now all my 'Views' have been strongly typed and I've been building the view based on data from ViewData.Model.MyViewsData.  Now once the view has been rendered and I do a Ajax style request I get new data back as JSON and I need to update my view.  Now how can I update my view with the new data when I no longer have access to all the original ViewData?

I'm guessing I need to one of two things, either: always fetch the data back using Jquery\JSON and forget about using ViewData or do some sort of partial rendering of my view?!

Any tutorials or samples would be most appreciated.

Many Thanks

[A]
I use jQuery and Monorail for an MVC framework - and we use both approaches.
Here's an example for the jquery approach
- ignore the fact it's php. The approach is the same, namely in the postback function in the JSON call, the JSON return object is accessed directly to populate front-end controls that are accessed via the css selector.
The alternative is very similar
(archived
here
) - instead of manually setting control contents, simply apply the html returned in the partial view (ensuring the layout is cancelled as you don't want menus etc just a html fragment).


q:
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?

I mean, something like Apache Commons' PropertyUtilsBean.copyProperties()

[A]
If your class does not modify
```
__getitem__
```
or
```
__setitem__
```
for special attribute access all your attributes are stored in
```
__dict__
```
so you can do:
```
```
nobj.__dict__ = oobj.__dict__.copy()    # just a shallow copy
```
```
If you use python properties you should look at
```
inspect.getmembers()
```
and filter out the ones you want to copy.


q: I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?

[A]
Does your code actually need a user logged in via ASP.NET, or does it just need a CurrentPrincipal? I don't think you need to programmatically log in to your site. You can create a
GenericPrincipal
, set the properties you need, and attach it to, for example Thread.CurrentPrincipal or a mocked HttpContext. If your code actually needs RolePrincipal or something then I would change the code to be less coupled to ASP.NET membership.


q:
I am attempting to deploy an ASP.NET 2.0 Web service application on an IIS server that currently serves a large .NET 1.0 web application.

I have set up an appropriate virtual directory and have set the ASP.NET version for the virtual directory to 2.0, when I attempt to browse the site in a web-browser, I am prompted for a password. If I set the ASP.NET version down to 1.0, I am not prompted for a password, but obviously receive a full application error.

How can I configure IIS so that I can have the .NET 2.0 version selected without requiring the password prompt?

I have anonymous access enabled and have the "Authenticated Access" set to integrated windows authentication"

Any help or suggestions is appreciated...

Thanks.

[A] First of all, be sure that you are running two application pools, one for any .Net 1.1 web apps, and another for any .Net 2.0 web apps.


q:
I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1).

What is the right OCaml idiom for this?

[A]
Here you go:
```
```
let rec range i j =
  if i > j then []
  else i :: range (i+1) j
```
```
Note that this is not tail-recursive.  Modern Python versions even have a lazy range.


q:
I have two iterators, a list and an itertools.count object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:

>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c)  # the mythical "imerge"
>>> merged.next()
'foo'
>>> merged.next()
1
>>> merged.next()
'bar'
>>> merged.next()
2
>>> merged.next()
Traceback (most recent call last):
    ...
StopIteration

What is the simplest, most concise way to do this?

[A]
I'd do something like this. This will be most time and space efficient, since you won't have the overhead of zipping objects together. This will also work if both
```
a
```
and
```
b
```
are infinite.
```
```
def imerge(a, b):
    i1 = iter(a)
    i2 = iter(b)
    while True:
        try:
            yield i1.next()
            yield i2.next()
        except StopIteration:
            return
```
```


q:
Besides the CODEX what resources do you recommend to help a person new to creating plugins help create a WordPress plugin. I have an idea, but need a bit better explanation than what is in the CODEX to get started.

UPDATE: Is there a book that I could buy to help me out with this?

[A]
Having written the MyBlogLog plugin (the original one, that is) I found that the Wordpress Hooks list (can't remember the link offhand) was incredibly useful, as was the sample code from the Codex and WP Install files. Reading through other developer's plugins is also a good way to learn, as you can see how they implemented things and use those techniques to save yourself some R&D time.
What are you looking to create, anyways?
Edit:
I posted a comment with this, but just in case it gets lost...
For your specific needs, you're going to want to store data and be able to manage and retrieve it so creating a custom database table in your plugin is something you will want to do. See this codex link:
http://codex.wordpress.org/Creating_Tables_with_Plugins
Then you can just add your management code into the admin screens using the techniques found on this Codex page:
http://codex.wordpress.org/Adding_Administration_Menus
If you want to display the items on a page, you can either write yourself a custom PHP WP Page template to query the DB directly:
http://codex.wordpress.org/Pages#Page_Templates
Or just add a hook filter on your plugin to write the results to the page based on a keyword you specify:
http://codex.wordpress.org/Plugin_API#Filters


q:
Edit: This was accidentally posted twice. Original: VB.NET Importing Classes

I've seen some code where a Class is imported, instead of a namespace, making all the static members/methods of that class available.  Is this a feature of VB?  Or do other languages do this as well?

TestClass.vb

public class TestClass
    public shared function Somefunc() as Boolean
        return true
    end function
end class

MainClass.vb

imports TestClass

public class MainClass
    public sub Main()
        Somefunc()
    end sub
end class

These files are in the App_Code directory.  Just curious, because I've never thought of doing this before, nor have I read about it anywhere.


q:
We use ASP.NET, C#

When making an update to one of our websites, we roll out the entire site rather than updating just the pages or sections that have changed. This scares me.

Is this a good idea? Should I roll out only the changes?

Should I break my site into smaller projects?

What is best practice?

[A]
You should always roll out the entire site.  Because the actually executable code is contained mostly in the DLLs, you can't actually only roll out the pages that changed, like you could with the old ASP. If there are parts of your website that are actually separate, you can break them apart into separate projects, and deploy each entire section separately.
Also, if putting up the whole site scares you, you probably need better testing or quality assurance standards.  There should always be a copy of your entire site that can go live at any time, in case the server dies, and you have to replace it, or something else goes wrong.


q:
I have a variable that is built in loop. Something like:

$str = "";
for($i = 0; $i < 10; $i++) $str .= "something";

If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one?

How do I do this right?

[A]
You get the undefined variable because you're concatenating the value of itself with another value.
The equivalent of
```
$str = $str . "something";
```
So, it can't say what's the initial value is. It's the equivalent of this:
```
$str = [undefined value] . "something";
```
What's the result of a concatenation of
```
[undefined value]
```
and
```
"something"
```
? The interpreter can't say...
So, you have to put
```
""
```
in the variable first to initiate the variable's value, as you did.
HTH


q:
I've seen some code where a Class is imported, instead of a namespace, making all the static members/methods of that class available.  Is this a feature of VB?  Or do other languages do this as well?

TestClass.vb

public class TestClass
    public shared function Somefunc() as Boolean
        return true
    end function
end class

MainClass.vb

imports TestClass

public class MainClass
    public sub Main()
        Somefunc()
    end sub
end class

These files are in the App_Code directory.  Just curious, because I've never thought of doing this before, nor have I read about it anywhere.

[A]
Actually, that function is available because it's a
shared
function. If you were to remove the shared modifier, you would still have to create an instance of the class to access it.
To achieve access to all variables and all functions within a class by default, you would want to inherit it.
To my knowledge
importing
a class is basically tying direct reference to it, not creating any sort of instance of it for you to use.
EDIT for clarity: The links are there are VB specific links, thus, explaining the functionality of this pertaining to VB.NET


q: I see a lot of IoC frameworks for .Net and Java.  Does anyone know why there are no equivalent frameworks for Smalltalk.  This is more a philosophy question than anything else.  I'm wondering if there is something in the Smalltalk way of doing things that precludes the necessity of having an IoC framework.

[A]
MVC
was invented on Smalltalk and is arguably the original
Inversion of Control
framework.  While somewhat more lightweight than its java counterparts, it has the basic concepts of a model holding the data, a view rendering the data in response to events propogated from a controller.
Less flippantly, Java is actually needs a lot of framework support to do a web application without excessive quantities of boilerplate code.  Smalltalk supports programming idioms such as
continuations
, which allow an author to pretend they are not really writing event driven code.
Seaside
works like this, giving the benefits of IoC with a somewhat more flexible development paradigm.
EDIT: MVC is a framework for UI's in Smalltalk (arguably it's not really a framework as such, but the class library has built in support for it).  It has the inversion of control property in that the view and model respond to events dispatched by the controller - the don't call us, we'll call you property.  Inversion of Control is a design pattern within frameworks that's used to reduce the need for extensive boilerplate in java applications.  In some definitions of an application framework, Inversion of Control is the main property that is viewed as distinguishing a framework from a library.


q:
Which Eclipse package should I choose for Python development with PyDev?

Nothing on the Eclipse homepage tells me what to choose, and the PyDev documentation assumes I already have Eclipse installed. Does it matter which Eclipse package I choose?

[A]
If you just plan on doing Python dev, I'd just go with
Platform Runtime Binary
.
After that, I'd follow the instructions
http://pydev.org/download.html
and
http://pydev.org/manual_101_root.html
to install PyDev.
I use the same setup for Python development.  I also have the RadRails plugin for Ruby on Rails development.


q:
I need to send an email to someone and want them to be able to simply reply to the email without having to specify the email address.

Using sp_send_dbmail sets the reply-to address as the name of the profile that it was sent from.

Can this be changed to specify the reply-to so it looks like it came from me.

Thanks.

[A]
Not in sp send dbmail itself
The reply address is just text and can be set up in the profile.
Eg I configure bob@bob.com but the email account is private@isp.com
Hit reply and it goes to bob@bob.com
So, configure your profile used by the sp thus to show this.
The line saying "The e-mail address to show on outgoing e-mail messages." here
sp send dbmail help. no parameter for reply address


q:
What do you think of using a metric of function point to lines of code as a metric?

It makes me think of the old game show "Name That Tune".  "I can name that tune in three notes!"  I can write that functionality in 0.1 klocs!  Is this useful?

It would certainly seem to promote library usage, but is that what you want?

[A]
KLOC is tolerable if you strictly enforce code standards, kind of like using page requirements for a report: no putting five statements on a single line or removing most of the whitespace from your code.
I guess one way you could decide how effective it is for your environment is to look at several different applications and modules, get a rough estimate of the quality of the code, and compare that to the size of the code. If you can demonstrate that code quality is consistent within your organization, then KLOC isn't a bad metric.
In some ways, you'll face the same battle with any similar metric. If you count feature or function points, or simply features or modules, you'll still want to weight them in some fashion. Ultimately, you'll need some sort of subjective supplement to the objective data you'll collect.


q:
When I create a zip Archive via java.util.zip.*, is there a way to split the resulting archive in multiple volumes?

Let's say my overall archive has a filesize of 24 MB and I want to split it into 3 files on a limit of 10 MB per file.

Is there a zip API which has this feature? Or any other nice ways to achieve this?

Thanks
Thollsten

[A]
Check:
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=38&t=004618
I am not aware of any public API that will help you do that.
(Although if you do not want to do it programatically, there are utilities like WinSplitter that will do it)
I have not tried it but, every ZipEntry while using ZippedInput/OutputStream has a compressed size. You may get a rough estimate of the size of the zipped file while creating it. If you need 2MB of zipped files, then you can stop writing to a file after the cumulative size of entries become 1.9MB, taking .1MB for Manifest file and other zip file specific elements.
So, in a nutshell, you can write a wrapper over the ZippedInputStream as follows:
```
```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ChunkedZippedOutputStream {

    private ZipOutputStream zipOutputStream;

    private final String path;
    private final String name;

    private long currentSize;
    private int currentChunkIndex;
    private final long MAX_FILE_SIZE = 16000000; // Whatever size you want
    private final String PART_POSTFIX = ".part.";
    private final String FILE_EXTENSION = ".zip";

    public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException {
        this.path = path;
        this.name = name;
        constructNewStream();
    }

    public void addEntry(ZipEntry entry) throws IOException {
        long entrySize = entry.getCompressedSize();
        if ((currentSize + entrySize) > MAX_FILE_SIZE) {
            closeStream();
            constructNewStream();
        } else {
            currentSize += entrySize;
            zipOutputStream.putNextEntry(entry);
        }
    }

    private void closeStream() throws IOException {
        zipOutputStream.close();
    }

    private void constructNewStream() throws FileNotFoundException {
        zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName())));
        currentChunkIndex++;
        currentSize = 0;
    }

    private String constructCurrentPartName() {
        // This will give names is the form of <file_name>.part.0.zip, <file_name>.part.1.zip, etc.
        return name + PART_POSTFIX + currentChunkIndex + FILE_EXTENSION;
    }
}
```
```
The above program is just a hint of the approach and not a final solution by any means
.


q: I am looking for a way to maintain PHP sessions across multiple domains on the same server. I am going to be integrating my sites with a Simple Machines Forum so I will need to use MySQL based sessions. Thanks!

[A]
Depending upon your preferred method of modifying PHP variables (Apache's config, .htaccess), change the session.cookie_domain value to be a consistent value.
I have multiple sub-domains, and each VirtualHost section in the Apache config file contains the following line:
php_value session.cookie_domain  mydomain.com
The syntax should be similar if you make the changes in a .htaccess file.
Updated for bobert5064's comment:
For multiple domains (ie domain1.com, domain2.org), I think it is only necessary to choose a common domain name (ie domain1.com).  I have never tried this, so I cannot verify that it works, but the logic seems accurate.
There is also a method to set the variables direction in PHP described at
http://us.php.net/manual/en/function.session-set-cookie-params.php
.  The documentation makes no reference to the ability or inability to set cookies on a different domain.


q:
I am trying to insert a time only value, but get the following error

ex  {"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."}  System.Exception

From the front end, the time is selected using the "TimeEdit" control, with the up and down arrows. The table in SQL Server has the fields set as smalldatetime. I only need to store the time. I use the following to return data to the app

select id,CONVERT(CHAR(5),timeFrom,8)as timeFrom,CONVERT(CHAR(5),timeTo,8)as timeTo
FROM dbo.Availability
where id = @id
and dayName = @weekday

How do I pass time only to the table?

Edit ~ Solution
As per Euardo and Chris, my solution was to pass a datetime string instead of a time only string. I formatted my result as per Time Format using "g".

Thanks

[A]
there is no such thing as Time in SQL, there is only DateTime.
For your purpose, I would use something like this to only return the time portion.
```
```
SELECT (GETDATE() - (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))
```
```
where GETDATE() is the datetime you want to filter.
When setting the time in the database, you will have to add '01/01/1901' or '01/01/1753' to the time.
Dont use CAST and Convert to varchar when working with datetime, its slow. Stick to floating numerical operations.


q:
Wanna write a RegEx to validate a driving license.

if it doesn't start with (US, CA, CN) then it has to be followed with XX and after that with any number of Alpha numeric letters.

So for example if the driving license starts with GB then it has to be followed with XX
GBXX12345363
However if it starts with US then we don't care what comes after it.
USLA039247230

[A]
```
```
/^(?:(?:US|CA|CN)\w+|[[:alpha:]]{2}XX\w+)$/
```
```
I'm not sure if there's more validation that can be done, but this is what I get from what you wrote, not your examples (which seem to imply four letters followed by numbers).


q:
I have a <button> with an accesskey assgined to it. The accesskey works fine as long as the button is visible, but when I set display: none or visibility: hidden, the accesskey no longer works.

Also tried without success:

Use a different element type: a, input (various types, even typeless).

Assign the accesskey to a label that wraps the invisible control.

Note, I'm not sure if this is the standard behavior, but prior to Firefox 3 the accesskey seemed to worked regardless of visibility.

[A]
You can apply a negative margin to push the element outsite of the visible page. I think many browsers and text readers ignore elements with
```
display:none
```
and possibly also
```
visibility:hidden
```
.


q:
I'm developing a poker game in C#. At the moment I'm trying to get the players hand score using RegEx. I search the string (composed of the cards suit and number) and look for suits or numbers to match the RegEx. If i get 2 matches then the player has a pair, 3 matches he has 3 of a kind.

I have 3 classes at the moment, a Card class (with number and suit), a Deck class (that contains 52 Cards) and a Hand class that gets five cards from the shuffled deck.

Deck class has a shuffleDeck();
Hand class has the functions to calculate the score (is in these functions that I am using RegEx).

I generate the string on which I use RegEx by adding the 5 suits and numbers that the hand has.

Is this a good idea or should I do it another way, if so, how?

Thank you for your help

PS. I am one of the unexperienced programmers that want to use a newly learned tool for everything

[A]
You have not provided much detail, but what from what I have read, I assume you're not pushing the OOP very far...
I would have a Card class that has a Rank and Suit class instances. I would then have a deck class that handles shuffling / dealing...
I would then have a Hand class that would contain your poker hand of n Card objects...
In this way you can build up rules to evaluate each hand object, thus being more flexible and more extensible in the future...say if you want to make another card game / add support for another variant of poker...
Using Regular expressions to do all of this seems to be a pretty poor choice.


q: Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going about this?

[A]
If I understand your question well then here are two example methods to tokenize a string. You do not even need the Scanner class, only if you want to pre-cast the tokens, or iterate through them more sofistically than using an array. If an array is enough just use String.split() as given below.
Please give more requirements to enable more precise answers.
```
```
import java.util.Scanner;

  public class Main {

    public static void main(String[] args) {

        String textToTokenize = "This is a text that will be tokenized. I will use 1-2 methods.";
        Scanner scanner = new Scanner(textToTokenize);
        scanner.useDelimiter("i.");
        while (scanner.hasNext()){
            System.out.println(scanner.next());
        }

        System.out.println(" **************** ");
        String[] sSplit = textToTokenize.split("i.");

        for (String token: sSplit){
            System.out.println(token);
        }
    }

}
```
```


q:
Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ?

Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace implementations of some methods.

[A]
The
```
java.lang.reflect
```
package classes and methods allow this access, within certain limits.
See
java.lang.reflect


q:
I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file_get_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way.

This is my current code

 $url =  urldecode( $object_list_url );
 $xmlstr = file_get_contents ( $url );
 $obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA );

[A]
The ini var you're referring to is
```
allow_url_fopen
```
. To check, run this script:
```
```
var_dump(ini_get('allow_url_fopen'));
```
```
Ask your host to turn that ini value on (if it's disabled - it's on by default).
You should not be able to access any remote url without that ini setting on.
Also an idea if they won't could be to try
```
copy
```
ing the file to your server. I expect all filesystem functions will be covered by that ini setting but it's always worth a try.


q:
This may sound strange but sometimes when your ASP.NET webapp isn't working and you can't tell why, you call Microsoft, pay them something like $300 and get about 1-3 weeks of 1-3 people looking at your configuration, memory dumps, sometimes code... but usually not the db, and with a fairly good percentage they help you fix your mistakes, without necessarily up-selling you.

I found that Novell would like to offer that for Mono. Everyone knows MySQL offers it for their clients, because it was part of the reason they got a truck of money to swing by one day to change the name-plate on the door.

I'm curious if anyone has found people for the support of these, and how they'd rate their experience:

Django

Rails

Grails

JRuby

Mono [ratings]

add your own.

[A]
I haven't ever looked for paid support for these open source technologies, but in general I would guess until there is significant market penetration there won't be a business case for 'dial in support' of an app built by a third party.
In general, you'll be looking for a niche technology expert consultant that will probably charge you an hourly rate to look at your problem.
For django - look at djangogigs.com, or post on rentacoder.com I suppose.
Each usually has an irc channel - you could also ask general questions there, or try to find someone for hire.