Thursday, September 30, 2010

XML to XLS using java

Programmer Question

How can I map the metadata to data. For example I only want LastName and Email from the xml file into the xls file. How can I select LastName and email from xml file and convert that into two column XLS file columns being Lastname and email. Thank you



XML Document















XXX
xxxx
xxx
xxx
xxx
xx
xx


xxy
xx
xx
xx
xx
xx
xx





Find the answer here

C# Instance Constructor vs Static Constructor

Programmer Question

What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and JAVA.



Thanks



Find the answer here

Wednesday, September 29, 2010

Can you access the actual identifier from an enum element's numerical value?

Programmer Question

Is there a method to return the identifier string for a given element's numerical value? For instance, logging a UITouch's phase returns an int, but having the actual string value would be easier to read.



I suppose I could write my own switch statement to do this, but I'm hoping there's a built-in means.



Find the answer here

BOT/Spider Trap Ideas

Programmer Question

I have a client who's domain seems to be getting hit pretty hard by what appears to be a DDoS. In the logs it's normal looking user agents with random IPs but they're flipping through pages too fast to be human.. also don't appear to be requesting any images. I can't seem to find any pattern and my suspicion is it's a fleet of Windows Zombies.



The clients had issues in the past with SPAM attacks--even had to point MX at Postini to get the 6.7 GB/day of junk to stop server-side.



I want to setup a BOT trap in a directory disallowed by robots.txt... just never attempted anything like this before, hoping someone out there has a creative ideas for trapping BOTs!



EDIT: I already have plenty of ideas for catching one.. it's what to do to it when lands in the trap.



Find the answer here

Monday, September 27, 2010

Framework change causes exception: Cannot marshal '': Invalid managed/unmanaged type combination ... ?

Programmer Question

From my managed code (let's call it MyLib) I am using a library (let's call it OtherLib) that is basically a wrapper around some c++ code (I have never seen the wrapper code or have had access to its source, nor will I have it).



When my calling library is targetting the 3.5 framework all is good and dandy. When I make it target .NET 4.0 I am getting this exception when using a method from OtherLib:



Cannot marshal 'parameter #3': Invalid managed/unmanaged type combination (this value type must be paired with Struct).



This happens, when I am calling a method on one of the types supplied by the wrapper. On line 4 I get above stated exception.



            If results.Compute(coordOrg, True, Nothing) Then
For Each Coord As Coordinate3D In queueDest
resDM(fromIndex, Coord.zMeter, DistanceCostType.CrowFly) = Math.Round(Math.Sqrt(Math.Pow(pointFrom.X - Coord.xMeterOrLongDeg, 2) + Math.Pow(pointFrom.Y - Coord.yMeterOrLatDeg, 2)) / 1000, 6)
resDM(fromIndex, Coord.zMeter, DistanceCostType.Road) = Math.Round(results.GetCost(Coord, m_itiDistance) / 100000, 6)
resDM(fromIndex, Coord.zMeter, DistanceCostType.Time) = Math.Round(results.GetCost(Coord, m_itiTime) / 100 / 60, 4)
Next
End If


Has anyone encountered something similar ?



EDIT:
I have tried switching the targetting from 3.5 to 4.0 and back again. Under 3.5 all work fine under 4.0 it throws this exception.
I have tried creating a wrapper project targetting 3.5, exposing a static class retrieving results from the OtherLib. Again when I call it from project compiled to 4.0 it fails and works when compiled for 3.5



EDIT2: Enum definition



Public Enum DistanceCostType
CrowFly
Road
Time
End Enum


Find the answer here

Sunday, September 26, 2010

Selecting all rows whos foreign key points to a specific primary key?

Programmer Question

I have two tables. One is a 'Users' table. Each row (user) in the table has a unique id (primary key).



The second table is a 'Tasks' table. Each row in the Tasks table has a foreign key which points to the user (in the Users table) that owns that task.



Using SQL Express 2008, what query must I use to obtain a list of all tasks assigned to a user? For example, if I have a user in the Users table with a primary key of 0 and there are 10 rows in the Tasks table with a foreign key value of 0, that means that this user has 10 tasks assigned to him. I need to build a query that gives me these 10 rows from the Tasks table.



Find the answer here

How Do You Manage Your Eclipse Installation

Programmer Question

How do you manage your Eclipse installation, i.e. the basic installation, plug-ins and workspace settings with regard to consistent updates (including major ones, 3.5 => 3.6) and usage on two or more computers (desktop + notebook).



My current setup is to basically manage the installation on several installations in parallel, i.e. manually add new plug-ins I installed on one to the other, and when I haven't used one in a long time to copy the whole directory from one location to the other.
For updates I use run it about once a month to get the latest versions, major updates I do manually by downloading the basic distribution and re-installing all the plug-ins in the matching version for the new major Eclipse version.



However, this approach has some drawbacks:




  • time intensive

  • update inconsistencies (Update sites change location, update doesn't work because of some version inconsistency between plug-ins that requires a lot of manual fixing, etc) (this has gotten better with 3.5 but still bugs me)

  • no "global" update site, I manually have to manage several locations



I tried alternatives like Yoxos for configuration management but there plug-ins were missing and / or not that well tested together as I expected.



I took a look at Idea as an IDE, the one thing I really loved was the update management: centralized and 90% of the functionality I'd be using are provided as a core that is tested and updated as one.



Thus the question: How do you manage your Eclipse installations and deal with updates?



From my experience with other Eclipse users they have at least the same problem with updates, but I haven't heard of a solution yet.



Find the answer here

Saturday, September 25, 2010

How do I use perlbrew to manage perl installations aimed at web applications?

Programmer Question

I have been using perlbrew to manage multiple versions of perl on a Linux Fedora notebook. I have used it with great benefit to run command-line scripts mostly using App::cmd.



I now want to move to running web applications written using CGI::Application using different perls installed in my $HOME. I am familiar with running Perl web applications in $HOMEs using Apache's user_dir or creating Virtual Hosts but I am unable to come up with a clean way of integrating this and the perlbrew managed perls. Specifically I need help in understanding and finding answers to these questions:




  1. How do install mod_perl under perlbrew?

  2. Assuming this is done, how do I configure my VirtualHost so that it picks up the correct perl that is current?

  3. If this is not possible, (which I doubt) can I at least use local installations to run vanilla CGI?



Thank you for your attention.



Find the answer here

pipe a program into less

Programmer Question

Hello,



I'm taking the dive into setting up and learning git and at the same time learning bash. I'm trying to do something simple as view the help section of



$ git config



unfortunately, when I type that the output of the help goes off the screen. Doing some googling I found less to be the program I want to use to scroll.



I tried



$ git config | less



with no success. Any ideas? Thanks!



Find the answer here

Why does open make my file descriptor 0?

Programmer Question

I'm working on a program that is using a pipe and forks and need to change the write end to an output file. But when I open a file the file descriptor is 0 which is usually stdin but which I think is the cause of some of my problems. Here is my code



outputfd = open("file", O_RDWR | O_CREAT | O_TRUNC) == -1)


Can someone let me know why it is 0? Or how to fix it?



Find the answer here

Objective-C appropriate use of autorelease?

Programmer Question

I'm learning Objective-C and I'm trying to write a Vector3D class.



In C++ or Java the function I want to implement would look something like this:



Vector3D
{
Vector3D crossProduct(Vector3D in)
{
Vector3D result;
result = ... // maths involving this classes variables and the input Vectors variables.
return result;
}
}


Now in objective-c I can't return an object, only an object pointer. Would this be an appropriate place to use autorelease (before returning?). This would enable me to chain the methods on the Vector3D class (since many methods return the object itself) but would this be particularly inefficient as compared to manually allocating and releasing the objects? Are there other commonly used patterns used to return objects in objective-c?



example of operations I'd like to do with the class:



Vector3D * vector3D1 = [[Vector3D alloc] init];
Vector3D * vector3D2 = [[Vector3D alloc] init];
Vector3D * vector3D3 = [vector3D1 cross [ [vector3D2 normalize ] multiply 1.43f]];


Thanks.



Find the answer here

HAML on Rails 3 doesn`t work

Programmer Question

Hey there,



i have tried to render some files with HAML in Rails 3. But HAMl doesn`t work.



My testfiles have the extension .html.haml.
In the GEMFile i have written gem 'haml' and executed the bundle install



When i call my testapp i become an error like this:
Template is missing
Missing template posts/index with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:rjs, :rhtml, :rxml, :builder, :erb]} in view paths "/Users/piet/Sites/blog/app/views"



Hope, i become some help here.



Peter



Find the answer here

Thursday, September 23, 2010

multi-dimensional stdClass Object

Programmer Question

I've got a rather large multidimensional stdClass Object being outputted from a json feed with PHP.



It goes about 8 or 9 steps deep and the data that I need is around 7 steps in.



I'm wondering if I can easily grab one of the entires instead of doing this:



echo $data->one->two->anotherone->gettinglong->omg->hereweare;



I'm saying this because the data structure may change over time.



Is this possible?



Find the answer here

Check a varaible after call it PHP

Programmer Question

Hello,



I have a varaible:



$this->valuepicname = isset($_POST['picname'][$numberpicname]) ? $_POST['picname'][$numberpicname] : "";


The varabile $numberpicname is static and each time I call to - it has another value, so, I want to do it too with th varaible $valuepicname - but I can't define it as static ($valuepicname) because its IF statement (i think this is the reason..).



Hope you understand.. (my english is bad)
Thank you.



Find the answer here

Building an expression with maximum value

Programmer Question

Given n integers, is there an O(n) or O(n log n) algorithm that can compute the maximum value of a mathematical expression that can be obtained by inserting the operators -, +, * and parentheses between the given numbers? Assume only binary variants of the operators, so no unary minus, except before the first element if needed.



For example, given -3 -4 5, we can build the expression (-3) * (-4) * 5, whose value is 60, and maximum possible.



Background:



I stumbled upon this problem some time ago when studying genetic algorithms, and learned that it can be solved pretty simply with a classical genetic algorithm. This runs slowly however, and it's only simple in theory, as the code gets rather ugly in practice (evaluate the expression, check for correct placement of brackets etc.). What's more, we're not guaranteed to find the absolute maximum either.



All these shortcomings of genetic algorithms got me wondering: since we can don't have to worry about division, is there a way to do this efficiently with a more classic approach, such as dynamic programming or a greedy strategy?



Find the answer here

Wednesday, September 22, 2010

Updating Button background for a brief time in Android (higlight it)

Programmer Question

Hi,



I have a button and I want to highlight it for a brief time. For e.g. it's a red button and it should be orange for a second and then turn red again.



My code for this looks like the following:



button.setBackgroundResource(R.color.orange);    //highlight value
button.invalidate();
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
}
button.setBackgroundResource(R.color.red); //old value
button.invalidate();


This doesn't work. The current thread pauses for 3 seconds, but the background image is not changed before. In fact it only changes afterwards to the "old value".



How can i build this highlight feature?



Find the answer here

Is it possible to virtualize a console application's disk access when shelled out from a C# application

Programmer Question

I've got application A which runs application B as a console app. I'd like to write unit tests as part of application A which validate the input to/output from application B, but application B uses hard coded paths to look for some of its inputs. I'd like to be able to run the application, but intercept the call to read from c:\wherever\whatever.txt and provide the contents of that file myself.



Any frameworks or pieces which can do this for me?



Find the answer here

How can I take an xml string and display it on my page similiar to how StackOverflow does it with 'insert code'?

Programmer Question

Hi All,



I'm using the DataContractSerializer to convert and object returned from a WCF call to xml. The client would like to see that xml string in a webpage. If I output the string directly to a label, the browser strips out the angle brackets obviously. My question is how can I do something similar to StackOverflow? Are they doing a find & replace to replace angle brackets with their html entities? I see they are doing a code tag inside a pre tag and then making spans with the appropriate class. Is there an existing utility out there I can use to do this instead of writing some kind of parsing routine. I'm sure something free must be out there. If anyone can direct to the right place or some code that can easily accomplish this, I would greatly appreciate it. I apologize if this is more of a meta.stackoverflow question. Thanks for any tips.



Cheers,

~ck in San Diego



Find the answer here

Commercial JMS/MOM implementations with non-Java client support?

Programmer Question

So far I have seen non-Java client support only for open source message brokers like Apache ActiveMQ, JBoss HornetQ and Open Message Queue (OpenMQ).



Are there also closed-source products like WebSphere, WebLogic or Tibco which offer non-Java access to their MOM brokers, using a documented wire protocol (opposite to a closed-source binary client library) which allows to write clients in other languages?



This is getting more interesting as products (like WebLogic) are available in the (EC2) cloud so that developers can use the cloud instance to develop and test a client application without the need to purchase and install the full version.



Find the answer here

controdiction between c-faq and my compiler

Programmer Question

C-faq says:
the code



int i = 7;
printf("%d\n", i++ * i++);


prints 49. Regardless of the order of evaluation, shouldn't it print 56?
But when i ran this code on my turbo C 3.0 compiler it gave me the output 56.Why is there a controdiction?



Find the answer here

Tuesday, September 21, 2010

enabling log in openSSH, Windows 2003 box

Programmer Question

I have 3 files inside OpenSSH\var\log, they are:
lastlog
OpenSSHD.log
wtmp
I changed the sshd_config file's
LogLevel INFO



Then also I am not getting any logs, anywhere.



Can anybody help me to enable the log file.



Any help is appreciated.Thanks



Find the answer here

How to use subqueries in SQLAlchemy to produce a moving average?

Programmer Question

My problem is that I want to retrieve both a list of measurements along with a moving average of those measurements. I can do that with this SQL statement (postgresql interval syntax):



SELECT time, value,                
(
SELECT AVG(t2.value)
FROM measurements t2
WHERE t2.time BETWEEN t1.time - interval '5 days' AND t1.time
) moving_average
FROM measurements t1
ORDER BY t1.time;


I want to have the SQLAlchemy code to produce a similar statement to this effect. I currently have this Python code:



moving_average_days = # configureable value, defaulting to 5
t1 = Measurements.alias('t1')
t2 = Measurements.alias('t2')
query = select([t1.c.time, t1.c.value, select([func.avg(t2.c.value)], t2.c.time.between(t1.c.time - datetime.timedelta(moving_average_days), t1.c.time))],
t1.c.time > (datetime.datetime.utcnow() - datetime.timedelta(ndays))). \
order_by(Weight.c.time)


That however, generates this SQL:



SELECT t1.time, t1.value, avg_1
FROM weight AS t1,
(
SELECT avg(t2.value) AS avg_1
FROM weight AS t2
WHERE t2.time BETWEEN t1.time - %(time_1)s AND t1.time
)
WHERE t1.time > %(time_2)s
ORDER BY weight.time;


That SQL has the subquery as part of the FROM clause where it cannot have scalar access to the column values of the top-level values, i.e. it causes PostgreSQL to spit out this error:



ERROR:  subquery in FROM cannot refer to other relations of same query level
LINE 6: WHERE t2.time BETWEEN t1.time - interval '5 days' AN...


What I would thus like to know is: how do I get SQLAlchemy to move the subquery to the SELECT clause?



Alternatively another way to get a moving average (without performing COUNT(*) queries for each (time,value) pair) would be an option.



Find the answer here

What does sorting mean in double-byte languages?

Programmer Question

I have some code that sorts table columns by object properties. It occurred to me that in Japanese or Chinese (non-alphabetical languages), the strings that are sent to the sort function would be compared the way an alphabetical language would.



Take for example a list of Japanese surnames:



??
??
??
??
??


In English, these would be Suzuki, Matsuzaka, Matsui, Yamada, Fujimoto.



When I sort the above list via Javascript, the result is:



??
??
??
??
??


(Suzuki, Yamada, Matsui, Matsuzaka, Fujimoto) This is different from the ordering of the Japanese syllabary, which would order the list (phonetically) as Suzuki, Fujimoto, Matsui, Matsuzaka, Yamada.



What I want to know is:




  1. Does one double-byte character really get compared against the other in a sort function?

  2. What really goes on in such a sort?

  3. (Extra credit) Does the result of such a sort mean anything at all? Does the concept of sorting really work in Asian (and other) languages? If so, what does it mean and what should one strive for in creating a compare function for those languages?



Find the answer here

When __repr__() is called?

Programmer Question

print OBJECT calls OBJECT.__str__(), then when OBJECT.__repr__() is called? I see that print OBJECT calls OBJECT.__repr__() when OBJECT.__str__() doesn't exist, but I expect that's not the only way to call __repr__().



Find the answer here

Variable Scope: cross-class function call

Programmer Question

I have a vehicle and a product object and I need vehicle to call a function within product.... I can't seem to figure it out, what should I do here?



var vehicle = function () {
return {
init: function () {
var that = this;

jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
e.preventDefault();
that.remove(jQuery(e.currentTarget).parents('.vehicle-year-profile'));
});

jQuery('.vehicle-year-profile .options .edit').bind('click', function (e) {
e.preventDefault();
that.edit(jQuery(e.currentTarget).parents('.vehicle-year-profile').attr('id'));
});

jQuery('#association-detail .save').bind('click', function (e) {
e.preventDefault();
that.save();
});
},
edit: function (id) {},
save: function () {},
remove: function (el) {},
reset: function () {}
}
}();

var product = function () {
return {
refreshHistory: function () {}
};
}();


Find the answer here

Monday, September 20, 2010

Pythonic way to check if a list is sorted or not

Programmer Question

Is there a pythonic way to check if a list is already sorted in AESC or DESC.



listTs=[1,2,3,5,6,7]



something like listTs.isSorted() that returns True or False.



EDIT: I want to input a list of timestamps for some messages and check if the the transactions appeared in the correct order.



and I can write a custom function too :) , Thanks



Find the answer here

Sunday, September 19, 2010

C++ program to count number of objects in a particular Linux directory

Programmer Question

I'm attempting to write a program in Linux using C++ that counts the number of files and folders in a user specified directory, but the more I read, the more confused I get. I'm new to C++ and to programming in general, and I understand that I have a big hurdle to vault at the start, but I'm not entirely sure where to start reading on this one. I've read a bit about forking processes and system calls, but if someone were to briefly outline the process I have to go through to achieve this, then I can do more in depth reading on the various functions myself.



Find the answer here

How to inject a spring's service bean into a JPA Entity ?

Programmer Question

My problem is very similar to this one : Injecting fields via Spring into entities loaded by Hibernate



The difference is that , I am using JPA2 entities , not hibernate . While the underlayer is still hibernate (3.5.5).



My spring version is 3.0.4.



What's the corresponding eventListeners in JPA's world ?



Sample code from the original post :



class Student {
int id; //loaded from DB
String name; //loaded from DB
int injectedProperty; //Inject via Spring
Service serviceImpl; //Inject via Spring
}


I know there may be aspectJ's solutions , but I'd rather like a pure-java solution.
Thanks.



Find the answer here

Is it still possible to develop for older iOS devices?

Programmer Question

A few months ago I got an shocking email from Apple, telling that they will reject every app that is not built against iOS 4.x SDK. Now I wonder if:



1) is this a bad joke?



2) if not: does that mean that my app will only run on the very lates devices like iPhone4, iPod touch 4, or any device that has iOS 4.x installed?



I downloaded the latest iOS SDK and I can only build against 3.2 or 4.1, where I believe 3.2 is only for iPad. Now I can either throw away my 6 iPod touches with older OS installed or I'm lucky and there's still a way to code for them without upgrading them all to 4.1.



What do you think? What's the truth?



Find the answer here

Getting out of a procedural mindset

Programmer Question

I have been programming (as a job) for around 3-4 months now after having graduated from university studying computing.



At university I was taught object orientated programming and I felt I had a good grasp on this until I started working on real problems.



I just cant seem to do anything but come up with procedural code for solutions - although i am using classes and basic oop techniques the code is essentially procedural inside and I know there are better solutions but i just cant seem to match patterns etc up with what i am trying to do.



How long / much practice does it take before you can really start programming properly using oop techniques - as opposed to just using classes filled with procedural code.



Also, are there any advice on how to really progress with being able to design solutions to problems properly?



Find the answer here

how to call .js after page is loaded

Programmer Question

i need to call customFormElements.js js function after aspx page is loaded, after submit button is clicked. can i do this and if yes how?



window.onload option is not good...



i need to call this file after i press submit button becouse aspx ajax library clear my js file logic and i need to reload it again.



Find the answer here

Saturday, September 18, 2010

Dynamic height header in SEO optimized SOC (Source Ordered Content) layout using only CSS, no Javascript?

Programmer Question

Hey,



I want do do a layout that is search engine and speed-browser friendly with content first in source code. Usually this looks like this:



    

i am content, i go first





but I need an dynamic sized header increases the height with its content...
this must be a common problem. is it possible to solve somehow?
any ideas?



Find the answer here

Friday, September 17, 2010

What exactly is a ROM?

Programmer Question

Hello.



I began studying android and became curious what is a ROM. There are many pages that offer to download ROMs but what it is exactly from a developer's point of view is not quite clear.



So what is it?



Thanks!



Find the answer here

.NET - Is it possible to use ASP.NET without MVC using HTML 5?

Programmer Question

A link would be great.
Thanks.



Find the answer here

How to implement a function called in the method "onUpdate" when using sortable.create in Rails

Programmer Question

Hi - I am creating an application using ROR and would like to know how I can implement a function which I want to call when using "sortable.create".



Below is a sample code from my "*.html.erb" file.






Instead of "Alert" I want to call a actual function to which I can pass the parameters in this case the list "table_retain" and implement the function in 'Application Controller".



I would like to know the syntax as to how this can be done. I am new to ROR and any help will be greatly appreciated.



Thanks



Find the answer here

Javascript Object -> SQL, in Javascript

Programmer Question

I have a simple client-side Sqlite database (via. Google Gears) I want to use for persistence of the contents of a javascript object's properties (not methods). I don't really care about normalization since it has lots of potentially disparate fields (primitive types, arrays, objects) that would thwart normalization anyway.



What would be the best way to go about doing this? Or in the worst case, an alternative that at least achieves persistence?



Find the answer here

Crystal Reports alternatives.. and does SQL Reporting Services have field definitions only option?

Programmer Question

Okay, two part question I guess.



I liked Crystal Reports, although now (if I understand correctly) the licensing model means if I deploy Crystal 2010 via say webform within my application, I have to purchase a runtime license of $2000+ ?



I haven't used SSRS (SQL Server Reporting Services), although I gather that you can use the reportviewer with local data..



So two questions in reality:




  1. The FIELD DEFINITIONS ONLY option in Crystal used to be great.. could design the report without the actual datasource needing binding.. DOES SSRS have this concept?


  2. Has anyone come across a good alternative (hopefully cheaper than Crystal Licensing) to provide WEB BASED REPORTING with the ability of export as PDF?




Realise these are two questions.. I guess from my perspective fairly related.



Any help gratefully received!



Find the answer here

Thursday, September 16, 2010

reference data is lost when form fails validation in spring3 annotation based controller

Programmer Question

I'm doing the spring 3 annotation based controller thing. Problem is, when it fails validation, the reference data is lost, namely the countryDivisions stuff. I didn't put it in the form because its not user editable data, and the orthodoxy here is that only user-editable data goes in the form. Do I have any other choice?



@Controller
public class MyInfoController {

@Autowired
private MyInfoFormValidator validator;

private void loadReferenceData(ModelMap model) {
model.put("countryDivisions",countryDivisionService.getCountryDivisionOrderedByCode());
}

@ModelAttribute
private MyInfoForm loadMyInfo() {
MyInfoForm form = new MyInfoForm();
//load it up
return form;
}


@RequestMapping(value="/editMyInfo", method = RequestMethod.GET)
public String editMyInfo(ModelMap model ) {
loadReferenceData(model);
return "contactEdit";
}

@RequestMapping(value="/editMyInfo", method = RequestMethod.POST)
public String saveMyInfo(ModelMap model, MyInfoForm form,BindingResult result ) {
validator.validate (form,result);
if (result.hasErrors()) {
model.put("commandName", "myInfoForm");
return "contactEdit";
}
//save some stuff
return "redirect:viewMyInfo";
}

}


Find the answer here

make: *** No rule to make target `all'. Stop. Eclipse error

Programmer Question

Hi all,
I've just downloaded Eclipse CDT developer kit (87MB) for Windows. I've also installed MinGW, and msys.
I also added this to PATH: C:\msys\1.0\bin;C:\mingw\bin. and restarted computer after that. I've checked by type "make --version" in cmd and it works.



However, for some reason I cannot compile my C project. I don't get binary files and got only the following things in COnsole:



**** Build of configuration Default for project XXX ****

make all
make: *** No rule to make target `all'. Stop.


Could some one help me with this please?



Find the answer here

"The remote host closed the connection" in Response.OutputStream.Write

Programmer Question

This code streams large files to our users:



                // Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);


// Total bytes to read:
dataToRead = iStream.Length;

// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}


Every once and a while we recieve this exception:



The remote host closed the connection. The error code is 0x80072746


Here is the full stack trace:



Stack Trace:
at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async)
at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal)
at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush)
at System.Web.HttpResponse.Flush(Boolean finalFlush)
at System.Web.HttpResponse.Flush()
at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at BIS.DocumentBus.Controls.DocumentViewer.StreamFile(String filepath)


We have never had evidence that users are having trouble downloading our files and plan to simply ignore this exception.



Any idea what the source of this problem is? Is it safe to ignore?



Find the answer here

Is there a way to use the CPU of a remote machine to convert in ffmpeg?

Programmer Question

My site is built in PHP. I have a WWW server, where all the uploads end up for processing, and then they get rsynced to one of the 4 media servers. If there is a slow and steady stream of uploads, the WWW server converts them all reasonably quickly, but if a bunch of people upload something at the same time, they queue up, and it may take several hours for a file to be processed.



The media servers are typically idle, since serving files off SSD drives results in no iowait, so the CPU is just sitting there, and I wanted to utilize it for conversions.



What would be a good (simple) way to do that?



Find the answer here

Netbeans - difference between "Source files" and "Include path" in php project

Programmer Question

Hi,



what is the difference between "Source files" and "Include path" in php project.



Thanx



Find the answer here

Wednesday, September 15, 2010

In the Eclipse text editor, how can I reformat / fill / justify a paragraph to 80 characters wide?

Programmer Question

When editing text files in Eclipse, for instance, a README file, I have not yet found a way to get the editor to reformat paragraphs of text so that they fit in a reasonable width (typically 80 characters). This seems like it should be a very common thing to want to do, but I haven't found it. Can anyone help?



Note that I'm not talking about soft text wrapping here - I want to hit some key combination and have Eclipse insert and remove actual newline characters so that the file looks OK when viewed in a basic text editor. Essentially, the same thing that the 'fill-paragraph' function on Emacs does. I'm aware that certain specific source code editors has intelligent reformatters that work with comments, but the basic text editor doesn't seem to have anything.



If this doesn't exist I may have to go and write something myself...



Find the answer here

Tuesday, September 14, 2010

How to show a message to a django admin after saving a model?

Programmer Question

I want to display a message to admins after they save a particular model, something like "Now enable the series".



I can see how I'd do this if it were a list action (message_user) but I can't see how to do this from the main CRUD form.



Does anyone know how?



Thanks



Find the answer here

Monday, September 13, 2010

proper C refactoring

Programmer Question

I have the following files: a.h, a.c, b1.c, b2.c and in both b1 and b2 I have some macro definitions which are identical.



Is it ok if I move them in a.h or is it more common to leave them in the file where they are being used ? Which way is the proper way to do it in C ?



Find the answer here

How to make eclipse automatically add braces to an IF statement?

Programmer Question

In Java the following is completely valid:



if (x == null)
Y();
else
Z();


I personally don't like it at all. I like all my IF statements to have braces:



if (x == null) {
Y();
} else {
Z();
}


The eclipse formatter is wonderful and can beautify my code in many other ways. Is there a way to have it add the braces to IF statements?



Find the answer here

How to return a complex return value?

Programmer Question

Hi awesomes~



Currently I am writing some assembly language procedures. As some convention says, when I want to return some value to the caller, say an integer, I should return it in the EAX register. Now I am wondering what if I want to return a float, a double, an enum, or even a complex struct. How to return these type of values?



I can think of returning an address in the EAX which points to the real value in memory. But is it the standard way?



Many thanks~~~



Find the answer here

Insert a string into a string given an index

Programmer Question

Hi,



I know this is a really simple question, but I was just wondering if there is a native php method to inject a string into another string. My usual response to a new text manipulation is to consult the manual's listings of string functions. But I didn't see any native methods for explicitly inserting a string into another string so I figured i'd consult SO.



The answer is likely some kind of combination of the php native string functions OR simply regex (which makes my eye's bleed and my brain melt so I avoid it).



EX:
Take a string like some-image.jpg and inject .big before .jpg yielding some-image.big.jpg



Find the answer here

Ruby on Rails: Update page multiple times in controller

Programmer Question

So I have a rather long controller function that performs various tasks, and it takes around 10-15 seconds. I want to be able to update the user on the status of the function as it goes along (progress bar). Ideally, the function is called as an Ajax request, and would then update the page as it goes along. This would work except you can only update the page once per action. Any ideas? Thank you.



This is what I want to do in code:



def long_function
updatePage "Starting long_function"
#some code which take 5 seconds"
updatePage "Finished with first part"
#some more code which takes a while
updatePage "Finished second part"
#last code part
updatePage "Finished!"
end


Find the answer here

Sunday, September 12, 2010

mysql , bigint or decimal for storing > 32 bit values but less than 64 bits

Programmer Question

We're needing to store integer values of up to 2^38 . Are there any reasons to use decimal(12,0) or should we use bigint ?



Find the answer here

How to update Ruby to 1.9.x on Mac?

Programmer Question

I have created a new user account on my mac and I am trying to update to the current version of ruby on it (1.9.2) from the snow leopard default of 1.8.7. Can somebody point me to tutorial or explain the best method to update Ruby on my mac from 1.8 to 1.9.2? Thanks



Find the answer here

What is a "related target" for an event in ExtJS and/or DHTML?

Programmer Question

When using ExtJS I've noticed a property "Related Target" for an event. Googling also reveals that this term is used in other DHTML related contexts, not only ExtJS. So what is this "related target" and how does it differ from the normal target (which is another property of the event object)? On this subject google revealed nothing.



Find the answer here

c# string format

Programmer Question

Hi Guys,



How do I get the output of this to read 0 instead of 00 when the value is 0?



String.Format("{0:0,0}", myDouble);


Find the answer here

grouping strings by similarity

Programmer Question

I have an array of strings, not many (maybe a few hundreds) but often long (a few hundred chars).



Those string are, generally, nonsense and different one from the other.. but in a group of those string, maybe 5 out of 300, there's a great similarity. In fact they are the same string, what differs is formatting, punctuation and a few words..



How can I work out that group of string?



By the way, I'm writing in ruby, but if nothing else an algorithm in pseudocode would be fine.



thanks



Find the answer here

Saturday, September 11, 2010

Beginner Facebook Application Questions

Programmer Question

I'm just getting into Facebook application development. I've got some questions about how the applications are developed.



First, there's the Facebook PHP SDK. You can install this to a web server capable of executing PHP, but does that mean if you went to www.example.com/facebook-php-sdk/examples/example.php that it would look like you're on Facebook.com but with your fully functioning application?



Second, when I configured apache to set the documentroot to /facebook-php-sdk/ I got white screens with every file - even with proper application ID and secret filled in.



Third, how do you set up to develop locally? I would like to have a sandbox where I can mess around, but the instructions are vague about how to get the PHP SDK going, I'm not sure what files I can edit where to get my "Hello, world!" on.



Thank you all for the help! I am very excited to start developing Facebook applications.



Find the answer here

What does the ~> operator mean?

Programmer Question

I often stumble upon the ~= operator.



eg.



gem 'httparty', '~> 0.5.2'


What does it mean?



Find the answer here

HashSet does not seem to realize that two objects are the same.

Programmer Question

I'm trying to use HashSet to store objects of a class that I created, but apparently the same objects seem to have two different hashes, which is why the contains method does not realize that the object is already in the HashSet. This leads to my program running out of heap memory.



I don't think I'm doing anything wrong, but I wanted a second opinion anyway. I've done similar operations before which all worked fine, which makes this particularly annoying. I'd appreciate any help.



Here's my code



move1 = new Move(t,s);
if(move1.hashCode()==new Move(t,s).hashCode())
System.out.println("match");
move2 = new Move(s,t);
moves.add(move1);
moves.add(move2);
if(moves.contains(new Move(t,s)))
System.out.println("match found");


Here's the Move class:



public class Move {
private int move1;
private int move2;

Move(int m1, int m2)
{
move1 = m1;
move2 = m2;
}

public String toString()
{
return String.valueOf(move1)+" "+String.valueOf(move2);
}
}


Here's the output I get




Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.HashMap.addEntry(HashMap.java:797)
at java.util.HashMap.put(HashMap.java:431)
at java.util.HashSet.add(HashSet.java:194)
at makeMove.(makeMove.java:33)




Find the answer here

Thursday, September 9, 2010

programmatically executing and terminating a long-running batch process in python

Programmer Question

Hi guys,



I have been searching for a way to start and terminate a long-running "batch jobs" in python. Right now I'm using "os.system()" to launch a long-running batch job inside each child process. As you might have guessed, "os.system()" spawns a new process inside that child process (grandchild process?), so I cannot kill the batch job from the grand-parent process. To provide some visualization of what I have just described:



Main (grandparent) process, with PID = AAAA
|
|------> child process with PID = BBBB
|
|------> os.system("some long-running batch file)
[grandchild process, with PID = CCCC]


So, my problem is I cannot kill the grandchild process from the grandparent...



My question is, is there a way to start a long-running batch job inside a child process, and being able to kill that batch job by just terminating the child process?
What are the alternatives to os.system() that I can use so that I can kill the batch-job from the main process ?



Thanks !!



Find the answer here

Running Eclipse Scala Plugin with previous version of Scala

Programmer Question

The scala plugin seems to automatically download version 2.8 of Scala. I'l like to try out the Gridgain 3.0-beta, which currently only works with Scala 2.7.7. Since Gridgain 3.0-beta already provides scala-compiler-2.7.7.jar and scala-library-2.7.7.jar, is it possible to get the Eclipse Scala Plugin to compile to Scala 2.7.7?



I tried removing the Scala Library 2.8 from the project build path and added both the 2.7 jars, but this didn't seem to work.



Would this be easier if I switched to Netbeans?



Find the answer here

cast to generic type at runtime

Programmer Question

Ok, i don't think this is possible so i thought i would ask to make sure. I'm in the process of creating a function reflects over the properties in a class and adds them to this data structure i have. Some of the properties are generic types.



So say we have DataType(of T) that as a .Value property of type T:



Dim properties = GetType(GenFormMaintenancePOCO).GetFields(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
For Each prop As fieldinfo In properties
Collection.Add(prop.Name,prop.GetValue(poco))
Next


In The collection.Add for primitive types(int,string,ect...) i just want to add the type...but in the case of generic i want to add the DataType(Of T).Value. I hope there is some work around but i don't think there is a way because the type of T can not be determined at compile time right? Ideally DirectCast(prop.getvalue(poco),DataType(Of T)).Value would be possible.



Find the answer here

How to be downward compatible to a customers old local database when the application is brandnew?

Programmer Question

Hello,



I want that my users can read my sqlite database still in 10 years, because there could be data in it they want to browse.



Well the database file is 10 years old. In the meantime I have upgraded my database structure (additional fields is best example) and my latest version of the application makes use of that new fields.



Now the user wants to load the 10 year old database with the brandnew application version. But that won`t work, because in the old database file there are some fields missing.



How would you deal with such a scenario?



Find the answer here

Text-Based Java Game

Programmer Question

I need to make a text-based RPG game with java. The first part of the assignment is super simple. we just use vertical lines and underscores to make a little rectangle and then add symbols inside the rectangle as things move, act, die, etc.



I've never done this before, so I want to run my idea by you:



What do you think about doing something like angry birds but with flying moving targets? There would be a little "bird tank" at the bottom left of the screen that would shoot birds. Another question: I'm not entirely sure how I would create a gun that shoots at different angles in a text-based format. And how would it work with aiming and shooting and timing, and such?



Thanky.



Find the answer here

Tuesday, September 7, 2010

Calling php code from php code on different server

Programmer Question

Hi,

The situation is following. I have a local (development) PHP server (Win + IIS) on my computer and I would like to call a function on a remote server because there is an executable file on the remote server (linux) that does not run on my local computer.

So on the remote server would be a simple PHP page which calls the executable with given parameters and returns the results.

I can imagine making an ajax call from javascript to this remote PHP page, but in my case I am using PHPUnit locally and at one point I need to call this remote page for specific data (which the executable file provides).

So my question is - how to make a call from PHP (local) to PHP (remote)? Is web-services the way to go or can this be accomplished simpler?



Find the answer here

Monday, September 6, 2010

is there any NETBEANs plugin that can give design view of webpages ?

Programmer Question

i am developing a web application and working with java servlets and JSP i need to view the design of JSP pages in NETBEANS is there any plugin etc. to do so



Find the answer here

cocos2d and MPMoviePlayerController crash

Programmer Question

Hello,



I try to show an intro and replaceScene when the intro has finished. But, when the movie finish, app is crashing on [[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:0.5f scene:[MenuScene scene]]];.



code is;



- (void) moviePlayBackDidFinish {


[self.moviePlayer stop];



[[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:0.5f scene:[MenuScene scene]]];
}



-(id) init
{



// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {
//pencere boyutu elde ediliyor



NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp4"]];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];



// Register to receive a notification when the movie has finished playing.

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(moviePlayBackDidFinish:)

name:MPMoviePlayerPlaybackDidFinishNotification

object:self.moviePlayer];



if ([self.moviePlayer respondsToSelector:@selector(setFullscreen:animated:)]) {

// Use the new 3.2 style API

self.moviePlayer.controlStyle = MPMovieControlStyleNone;

self.moviePlayer.shouldAutoplay = YES;

// This does blows up in cocos2d, so we'll resize manually

// [moviePlayer setFullscreen:YES animated:YES];

[self.moviePlayer.view setTransform:CGAffineTransformMakeRotation((float)M_PI_2)];

CGSize winSize = [[CCDirector sharedDirector] winSize];

self.moviePlayer.view.frame = CGRectMake(0, 0, winSize.height, winSize.width);// width and height are swapped after rotation

[[[CCDirector sharedDirector] openGLView] addSubview:self.moviePlayer.view];

} else {

// Use the old 2.0 style API

self.moviePlayer.movieControlMode = MPMovieControlModeHidden;

[self.moviePlayer play];

}



}



return self;
}



Find the answer here

Slightly non-trivial data structure: is XmlSerializer right for me?

Programmer Question

I'm currently using XmlSerializer to, surprisingly enough :), handle de/serialization of my data structures - I find it wonderfully simple to use, but at the cost of flexibility. At the moment, I'm using it for a tree-based structure; since XmlSerializer doesn't handle cyclic structures, I've added [XmlIgnore] to my Parent property, and do a post-deserialization iteration over the tree to fix up node parents.



Is there a better way to handle this using XmlSerializer, or would it be better to rewrite the code using XmlReader/XmlWriter? I suppose implementing IXmlSerializable would work, but it seems like a fair amount of work, while still retaining the cons of XmlSerializer.



The current post-deserialization step is OK, but I'm adding a data structure that has to be serialized to a separate XML file: basically a flat list of items that need a Parent property referencing a node from the previous tree structure. This would require yet a post-deserialization step, as well as keeping both a Parent attribute as well as as ParentId (or some trickery) in the new data structure.



So, any smart (and non-fragile) ideas? Or XmlReader/XmlWriter it is?



Solution



DataContractSerializer turned out to be a pretty decent solution, with pretty much the same simplicity as XmlSerializer. I opted not to use the automatic cycle handling but instead defining and OnDeserialized decorated method to handle setting the parent node; that way, the generated XML is standard-conforming.



One thing that confused me for a while was that I got crashes on some properties after deserializing, with the backing members set to null - couldn't figure out how this was possible since the backing members were definitely initialized in all possible constructors. Debugging showed constructors were never called, and after some googling I found this SO post with an explanation.



Find the answer here

jQuery is too fast (faster than mysql)

Programmer Question

I am developing a cakephp application that uses jquery and post methods in the background.



When cakephp sends a post request in the background, a div has to refresh (or regenerate), and it has to show new content.



Post method calls other php file that does a MySQL query. The div also call mysql, and select proper data from database.



Problem is that div is refreshed (or regenerated) before the first mysql query. So it works ok, but how can I tell that div to "wait" a bit, until the mysql query is executed?



Find the answer here

Getting selenium request ,response

Programmer Question

i tried the below code but req/response is not captured??



String trafficOutput = selenium.captureNetworkTraffic("xml");
selenium.type("q", "selenium rc");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");

selenium.open("/#hl=en&source=hp&q=selenium+rc&btnG=Google
+Search&aq=f&aqi=&aql=&oq=&gs_rfai=&fp=ff64793e1cab64b9");
selenium.click("//ol[@id='rso']/li[1]/h3/a/em");
selenium.waitForPageToLoad("30000");
selenium.click("link=Selenium Core");
selenium.waitForPageToLoad("30000");
selenium.click("link=our documentation");
selenium.waitForPageToLoad("30000");
selenium.click("link=Projects");
selenium.waitForPageToLoad("30000");
// assertTrue(selenium.isTextPresent("Results * for selenium
rc"));

String resposneText = selenium.getHtmlSource();
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("output", true));

System.out.println("value is-------- "+trafficOutput);
System.out.println("val is "+resposneText);

dos.writeBytes(trafficOutput);
dos.close();


but no req/response this case?? getting value for
System.out.println("val is "+resposneText);



Find the answer here

Sunday, September 5, 2010

WPF TabControl SelectedItem is reset after window has been closed

Programmer Question

I have a problem with the selected item in WPF-TabControl that could be reproduced with the following simplified code:



If a new TabItem is created and selected through the Click-event of the button in the second window, the tab is created, added and selected. When the second window will be closed, the selected item of the tab-control is reset to the last selected item. The problem occurs in my MVVM-app and it is independent of the Items-collection. I can use the ItemsSource or the Items-Collection, it happens always.



Has someone an idea what happens here or has a nice workaround?



TabControl tabControl = new TabControl() ;
tabControl.Items.Add(new TabItem { Header="InitialTabItem"});
((TabItem)tabControl.Items[0]).Focus();
Window mainWindow = new Window() { Content=tabControl,Title="TabControl-Window"};
mainWindow.Show();
Button addButton = new Button() { Content="AddTabItem"};
addButton.Click += (o, e) => {
TabItem newTabItem=new TabItem(){Header=DateTime.Now.ToLongTimeString()};
tabControl.Items.Add(newTabItem);
tabControl.SelectedItem = newTabItem;
};
Window directorWindow = new Window() { Owner = mainWindow ,Content=addButton,Height=80,Width=200,Title="DirectorWindow"};
directorWindow.Show();


Update



It seems to be as always when I have bigger problems with WPF, to be an issue with focus-management. If I change the creation-code as follows, it works:



TabItem newTabItem=new TabItem(){Header=DateTime.Now.ToLongTimeString()};
tabControl.Items.Add(newTabItem);
Dispatcher.BeginInvoke(new Action(delegate{
newTabItem.Focus();
tabControl.SelectedItem = newTabItem;
}), System.Windows.Threading.DispatcherPriority.Input, null);


However it looks not very confidently to me. Some ideas?



Find the answer here

.emacs, automake and cmake.

Programmer Question

A long time ago I wrote my .emacs. I used a shell script to compile and join the whole thing.



I am now rewriting the thing, and something occured to me. When compiling I access several environmental variables telling me things eg the full name of my diff program. Rather then reading environmental variables, i could use some autoconf like tool to tweak the .emacs files and them compile them.



The problem is that autoconf is just plain ugly. I considered cmake, but documentation is very poor especially on constructing your own build system.



Suggestions?



Find the answer here

Can we find out if skype is installed or not on a machine thoough web app?

Programmer Question

Hi,
I am writing some web app, from web app I want to know if skype is installed or not on a machine from which web page is called. Is this possible? if yes how?



It should work at least on Firefox, IE and chrome on windows. If it works on Linux and Mac then it will be great.



Thanks in advance.



Find the answer here

How to learn Python?

Programmer Question

For a beginner's perspective, can you answer the following?




  • Best tool(s) for Python development (for example, Notepad and Vim)

  • Best book to get started

  • Best website for the Python beginner

  • Best problem domain to do a sample project (what are Python-based solutions best suited for?)



Find the answer here

Why are vi and Emacs popular?

Programmer Question

I've never learned to use vi or Emacs yet people do use them still, despite there being other editors out there that are free and useful. What is it about these two and any others like them that means they hold appeal in the face of the newer editors?



Find the answer here

Friday, September 3, 2010

In Java, is this considered an example of a "nested IF statement"?

Programmer Question

Here we have a long-standing assumption that needs to be cleared up in my head. Is the following an example of nesting 'if' statements:



if (...)
...;
else if (...)
...;


I was under the impression that nesting required an 'if' inside another 'if', like so:



if (...)
if (...)
...;


or at least a clear separation of scope when you nest inside an else, like so:



if (...)
...;
else { //if the next statement didn't
//exist, then the curly brace changes nothing?
...;
if (...)
...;
}


This might boil down to how the compiler interprets things, whether the 'if' in else-ifs are considered in the same level as the parent if, or whether they create "new" 'if' statements. Thank you for your time!



edit: I ask because I am a TA in a java lab, and the topic of the day was nested-ifs. In the end, I found out that the teacher considered my first example to be valid for "nested if statements".



Find the answer here

What's the difference between 'git reset' and 'git checkout' in git?

Programmer Question

I think both the 'git reset' and 'git checkout' are the same in the sense that I go back to a specific commit. What's the difference between the two? I'm a little bit confused, as the svn only has 'svn co' to revert the commit.



Find the answer here

Facebook JS SDK FB.Login() how do I get extended permissions?

Programmer Question

Hello.



I am trying to get extended permissions with my FB Connect Application.



I was wondering how one does this with FB.Login() as I am not very knowledgable in JS.



Thanks



Find the answer here

OOP in VB.NET - Child, Parent, Parents

Programmer Question

I'm trying to do something here with VB that I guess I'm not understanding how to do it exactly. Sorry I'm not that good at OOP.



I have a number of things I'm creating and they have two values - parent name and child name (yes, actual people!).



So it would be like this:



Public Class Child
Public Property ParentName As String
Public Property ChildName As String
End Class


And then:



Public Class Parent
Public Property ParentName As String
Public Property ChildName() As String
End Class


Then I need to add these to a Parents class where a Parent can have one or more children.



I start by adding a Child. If that child's Parent name already exists, just add the Child's name to that parent, but if it doesn't exist, create a new parent (with that child). Then add all parents to a collection of parents (with their 1 or more children).



A resulting list would look something like this:



Parents:




  1. Parent: Jonathan Murry

    1. Child: Carl Murry


  2. Parent: Kathleen Anderson

    1. Child: Steven Anderson

    2. Child: Deborah Anderson

    3. Child: Thomas Anderson


  3. Parent: Xu Jing

    1. Child: Liu Ming

    2. Child: Liu Ning




(note on the last one - the parent/child last names don't need to match - in this case, the children take the father's last name instead of the mother's, but we don't list the father).



How would I create these type of classes so that I can add children to a parent, add a parent to parents and then ensure it is querable with something like Linq?



Thx in advance.



Find the answer here

Can you use WCF Data Services (ne OData, ne Astoria, ne ADO.NET Data Service) with NetTcpBinding?

Programmer Question

I'm looking at creating a data query WCF service over a slow satellite connection and I really like WCF Data Services. The problem I see is that HTTP is a very verbose format and since everything I'm doing is internal and .NET, is it possible to use NetTcpBinding instead to reduce some of the overhead?



Is this even possible? Advisable?



Find the answer here

Thursday, September 2, 2010

What is the best OAuth2 C# library?

Programmer Question

It seems like many app providers are using OAuth2 to allow API access, such as Twitter and Facebook. Does anyone use a good library to do OAuth2 processing that is general enough to use across all applications?



Find the answer here

Wednesday, September 1, 2010

"Whack a checkbox" game with ListView

Programmer Question

I have a ListActivity that was originally using an ArrayAdapter. Each item in my ListView contains a checkbox.



I changed Adapters to a CursorAdapter. Everything is working fine except checkboxes are out of control. For example: When I click the checkbox in position 1, the checkbox in position 4 gets checked. If I click the checkbox in position 1 again, it will check (Ie: When I click the checkbox in position 1, if the checkbox in position 4 is not checked, the checkbox in position 4 will get checked; else, the checkbox in position 1 is checked). Unchecking checkboxes doesn't seem to show any weird behavior. Any ideas why?



Update: It's checking the checkbox backwards based on how many items are on screen. What I mean is, if there are 5 items visible, clicking the 1st one will check the 5th, clicking the 2nd one with check the 4th, clicking the 3rd one will check the 3rd one.



Here is a copy of my CursorAdapter



public class InboxAdapter extends CursorAdapter implements CheckBox.OnCheckedChangeListener {
private int mCheckedCount = 0;

public InboxAdapter(Context context, Cursor c) {
super(context, c);
}

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.getId() == R.id.inbox_itemcheck) {
if (isChecked) {
mCheckedCount++;
}
else {
mCheckedCount--;
}
ActivityInbox.this.showMultiPanel((mCheckedCount > 0) ? true : false);
}
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
InboxHolder holder = (InboxHolder)view.getTag();

if (holder.txtDate != null) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date d = new Date(cursor.getInt(cursor.getColumnIndex("created_on")) * 1000L);
holder.txtDate.setText(df.format(d));
}
if (holder.txtSubject != null) {
holder.txtSubject.setText(cursor.getString(cursor.getColumnIndex("subject")));
if (cursor.getInt(cursor.getColumnIndex("read")) == 0) {
holder.txtSubject.setTypeface(null, Typeface.BOLD);
}
else {
holder.txtSubject.setTypeface(null, Typeface.NORMAL);
}
}

if(holder.txtSummary != null) {
holder.txtSummary.setText(cursor.getString(cursor.getColumnIndex("summary")));
}

if (cursor.getInt(cursor.getColumnIndex("read")) == 0) {
view.setBackgroundResource(R.drawable.selector_inbox_unread);
}
else {
view.setBackgroundResource(R.drawable.selector_inbox_read);
}

if (holder.lMessageType != null) {
if (cursor.getInt(cursor.getColumnIndex("read")) == 0) {
holder.lMessageType.setVisibility(View.VISIBLE);
}
else {
holder.lMessageType.setVisibility(View.INVISIBLE);
}
}
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.layout_inbox_item, parent, false);

InboxHolder holder = new InboxHolder();
holder.txtDate = (TextView) v.findViewById(R.id.inbox_item_date);
holder.txtSubject = (TextView) v.findViewById(R.id.inbox_item_subject);
holder.txtSummary = (TextView) v.findViewById(R.id.inbox_item_summary);
holder.chkSelect = (CheckBox) v.findViewById(R.id.inbox_itemcheck);
holder.lMessageType = (LinearLayout) v.findViewById(R.id.inbox_messagetype);

v.setTag(holder);

if (holder.chkSelect != null) {
holder.chkSelect.setOnCheckedChangeListener(this);
}
return v;
}


}



Find the answer here

How do I determine whether an intermittent failure is due to a bug in Firefox or Flash Plug-in?

Programmer Question

We have an old Flash application that has worked fine for years, but intermittently fails on latest versions of Firefox. It runs fine on latest versions of IE and Flash. Recompiling the product is risky, and I'm trying to fully understand the problem before resorting to that. I'd like to be able to point to a known browser or player bug, but I can't really say where the problem is yet.



I've gather the following information using Charles Proxy:



The Flash application gets a list of files it needs to load. It requests a file then waits until the Flash Plug-in dispatches an Event.COMPLETE before requesting the next file. During this process I can see the HTTP requests and server responses. When the application "hangs", Charles Proxy reports that the response actually completed; however, Firefox's status bar shows "Transferring ..."



Sometimes for an extended period, I can't recreate the problem at all. At other times, the hang-up happens over and over again.



Finally, if we switch to using https instead of http, the problem NEVER happens. Because Charles Proxy shows Status Complete while Firefox shows that a Transfer is still occurring, I speculate that the problem is actually in Firefox. I believe that Firefox is failing to recognize when the file actually finished loading, and therefore it fails to tell the Flash Player. The end result is that our code gets no Event.COMPLETE from the player and cannot continue requesting files.



Has anyone seen something similar to this? Is there a known issue in Firefox that would cause such intermittent failure?



Find the answer here

LinkWithin

Related Posts with Thumbnails