Tuesday, August 31, 2010

Code hook before EntityManager is initialized in JBoss AS 6

Programmer Question

Hi *,



I'm looking for a callback facility that allows me to execute some code before an EntityManager is started in JBoss 6.



More specifically, I would like to process a Liquibase changelog, before the EntityManager is initialized.



Any hints greatly appreciated!
J.



Find the answer here

ASP.NET MVC HTML helper methods for new HTML5 input types

Programmer Question

HTML5 appears to support a new range of input fields for things such as:




  • Numbers

  • Email addresses

  • Colors

  • URLs

  • Numeric range (via a slider)

  • Dates

  • Search boxes



Has anyone implemented HtmlHelper extension methods for ASP.NET MVC that generates these yet? It's possible to do this using an overload that accepts htmlAttributes, such as:



Html.TextBoxFor(model => model.Foo, new { type="number", min="0", max="100" })


But that's not as nice (or typesafe) as:



Html.NumericInputFor(model => model.Foo, min:0, max:100)


Find the answer here

CSS Main Body does not stretch to page?

Programmer Question

I am beating my head against a wall trying to figure out why the code I have written for a particular site doesn't quite work.



The main body of my pages (the white area in link below) should be stretching from navigation to the footer but only does so on certain pages.



The footer is automatically placed at the bottom of every page regardless of height (i.e. will be at page bottom on a 400px height page).



Is it possible I am just missing something very basic?



I have posted a link to the dev version of the site at:



www.contendertest.com



The pages I am having trouble with are index and the 'enroll' link.



Find the answer here

What is the preferred method for generating locally unique identifiers in VB.NET?

Programmer Question

I'm looking for a method of generating unique identifiers for a record class being created locally and then persisted in various formats (XML, SQL, etc.)



I've seen people using DateTime and GetHashCode, but that seems to lend itself to duplicate identifiers depending upon the sample size.



GUID is a bit overkill, as I don't need anything that unique (large) at the global level. I'm also aware of using GUIDs and GetHashCode to get the size down a bit, but duplicates tend to crop up here as well.



Can anyone suggest a best practice or method for generating simple unique identifiers?



Find the answer here

If i use captcha will i be able to stop the spam completely in my blog?

Programmer Question

Hi,



i have a blog and the only user input is the commenting system, now i want to avoid the spam totally, which method will be wise to adopt? akismet way or captcha method..



my client doesnt mind his user entering few verification string to post comment, if i adopt it will i be able to completely control the spam if yes then could you please suggest few good and easy plugin like 4 digit , not the complex one.



thank you



Find the answer here

Monday, August 30, 2010

Ajax call to a method that prints javascript

Programmer Question

Ok,



I have a some javascript code in the database






will that code work if a server side method was called via Ajax call, for example:



$.ajax({
type: 'GET',
url: path + '/doTheJSStuff/',
)};


where the doTheJSStuff is a method that echo/prints the JS code



Find the answer here

Saturday, August 28, 2010

I need to Play .M4V foramt audio from url, Problem with playing .M4V format

Programmer Question

Hi,



i have a url for the video file. the format of that file is itunes M4V.



I applied the URL in Api demos example, which is playing for some time, after sometime song is breaking.



Is there any problem with this format or any way to play .M4V format.



Please let me know...



Thanks



Find the answer here

Prototypes in JavaScript

Programmer Question

In the JavaScript the same thing you can do in many different ways.



Consider the examples:



1:



function Circle(radius) {
return {
"r" : radius,
"area" : function(){
return Circle.pi * this.r * this.r;
}
}
}
Circle.pi = 3.14159;

var a = Circle(10);
alert(a.area());


2:



function Circle(radius) {
this.r = radius;
}

Circle.pi = 3.14159;
Circle.prototype.area = function(){
return Circle.pi * this.r * this.r;
}

var a = new Circle(10);
alert(a.area());


The second is better than first because we dont define the same function area for any instance of the Circle.



But lets consider
3:



function Circle(radius) {
return {
"r" : radius,
"area" : Circle.area
}
}
Circle.pi = 3.14159;
Circle.area = function(){
return Circle.pi * this.r * this.r;
}

var a = Circle(10);
alert(a.area());


Is there any reason to prefer second style instead of third? Or I misunderstood something at all?



Find the answer here

Friday, August 27, 2010

iPhone SDK Remote file exists, without cache

Programmer Question

I need to check if a file exists on my server without using cache. The methods I have used are all returning a 200, even if the file does not exist, so I can only assume there is a cache problem, or theres a problem with my code.



Heres my code: for arguments sake..the URL is changed in this example, but the url is correct in my code.



NSString *auth = [NSString stringWithFormat:@"http://www.mywebsite.com/%@.txt",[self aString]];
NSURL *authURL = [NSURL URLWithString:auth];

NSURLRequest* request = [NSURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:5.0];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request
delegate:self];

NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"statusCode = %d", [response statusCode]);

if ([response statusCode] == 404)
NSLog(@"MISSING");
else
NSLog(@"EXISTS");


the response is always 200, even if I rename the file on the server.



Find the answer here

Thursday, August 26, 2010

What's the proper way to safely run this error-prone system call in perl?

Programmer Question

So as part of a startup script for OS X computer lab systems, I am running a built-in shell command called systemsetup to sync the system with a network time server. It's running inside a perl script as follows.



#!/usr/bin/perl

system("systemsetup -setusingnetworktime off");
system("systemsetup -setusingnetworktime on");


Flipping it to off first ensures that it updates when it is flipped on.



The problem is that every so often, that command throws the following error writeconfig[1841:903] *** -[NSMachPort handlePortMessage:]: dropping incoming DO message because the connection or ports are invalid and then stalls either the shell or the script's execution depending on where I'm running it.



This actually happens shockingly little in practice—on 500 lab systems running the script daily at boot, I only notice a problem on a single system every few weeks. Strangely, it's actually very easy to replicate in testing.



So what I understand is that this is fairly obviously a bug in systemsetup that that error is being thrown, but I'm sure there's a way to make my perl script handle it gracefully, right?



The best thing I've come up with at the moment is systemsetup -setusingnetworktime off&>/dev/null which pipes both STDOUT and STDERR to /dev/null.



Find the answer here

Access Database Security Question

Programmer Question

Hi,



I have a database in Access 2003 that I only want certain people to be able to access.
In my database I have a table which lists the people that should be able to access the database. (Tbl_BIRT_Users). The table contains their name, ntlogin and email address. It also has an 'adminstrator' field.



My question has two parts:



1 - On opening the database how can I get it to lookup the ntlogin (environ username) of the person and ensure that that person is authorised to use the database?



2 - I need the database to look at the 'administrator' Yes/No field and grant read only access to non admins and full access to admins.



Thanks!



Find the answer here

How to repaint a push button in Win32?

Programmer Question

I have a window with a button that paints the entire window red when clicked, but my code paints the whole window, even the button. When I resize the window or cause the part of the window where the button is to repaint, the button will return. I've only been able to paint the button a solid color after painting the window, but that only makes it look like a square with nothing in it.



So how do I paint the button its default color?



//WinMain 
hmain = CreateWindowEx (0, L"Window", L"Window", WS_OVERLAPPEDWINDOW, 0, 0, 200, 200,
NULL, NULL, hinstance, NULL);

HWND hwnd2 = CreateWindowEx (0, L"Button", L"Red", WS_CHILD | BS_PUSHBUTTON, 0, 0, 50, 50,
hmain, (HMENU) redbtt, hinstance, NULL);
//Winmain

//WndProc
COLORREF red = RGB (255, 0, 0);
HBRUSH redbrush = CreateSolidBrush (red);

switch (msg) {
case WM_COMMAND: {
if (LOWORD (wparam) == redbtt) {
color = 'r';
RECT rect;
GetClientRect (hmain, &rect);
HDC hdc = GetDC (hmain);
FillRect (hdc, &rect, redbrush);
ReleaseDC (hmain, hdc);

/*GetClientRect ((HWND) lparam, &rect);
hdc = GetDC ((HWND) lparam);
COLORREF color = GetBkColor (hdc);
HBRUSH brush = CreateSolidBrush (color);
FillRect (hdc, &rect, brush);
ReleaseDC ((HWND) lparam, hdc);*/
}

break;
}
case WM_PAINT: {
HBRUSH brush;

if (color == ' ') {
brush = (HBRUSH) (COLOR_WINDOW + 1);
} else if (color == 'r') {
brush = redbrush;
}

PAINTSTRUCT ps;
HDC hdc = BeginPaint (hmain, &ps);
FillRect (hdc, &ps.rcPaint, brush);
EndPaint (hmain, &ps);
break;
}
//WndProc


Find the answer here

How to use distinct with group by in Linq to SQL

Programmer Question

I'm trying to convert the following sql to Linq 2 SQL:



select groupId, count(distinct(userId)) from processroundissueinstance 
group by groupId


Here is my code:



var q = from i in ProcessRoundIssueInstance
group i by i.GroupID into g
select new
{
Key = g.Key,
Count = g.Select(x => x.UserID).Distinct().Count()
};


When I run the code, I keep getting Invalid GroupID.
Any ideas? Seems the distinct is screwing things up..



Here is the generated sql:



SELECT [t1].[GroupID] AS [Key], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t2].[UserID]
FROM [ProcessRoundIssueInstance] AS [t2]
WHERE (([t1].[GroupID] IS NULL) AND ([t2].[GroupID] IS NULL))
OR (([t1].[GroupID] IS NOT NULL)
AND ([t2].[GroupID] IS NOT NULL)
AND ([t1].[GroupID] = [t2].[GroupID]))
) AS [t3]
) AS [Count]
FROM (
SELECT [t0].[GroupID]
FROM [ProcessRoundIssueInstance] AS [t0]
GROUP BY [t0].[GroupID]
) AS [t1]


Find the answer here

HTACCESS Redirects

Programmer Question

In my htaccess file, I have the following two rules. I would like to make the second one occur on the condition that the first one doesn't match. Currently, they both get run. Is there any way around the collision?



redirect 301 /lorem/ipsum-keyword.html /lorem/dolorem-keyword.html
RewriteRule (.*)-keyword.html$ /dir/file.php?param=$1


Thanks in advance.



Find the answer here

Tuesday, August 24, 2010

Convert a system to multilanguage

Programmer Question

I have to translate a web application written in asp.net / javascript with a lot of html/javascript code created in the codebehind, which approach could be the best to translate it, or make it multilanguage support?



Find the answer here

Mathematics and programming

Programmer Question

I read a lot of blogs and forum posts about mathematics in programming and made a conclusion for myself that basic mathematics is needed in programming. I'm not a good mathematician. But is it somehow possible to improve my logical and algorithmical thinking without going deep into math science? Are there any excercises or some books that could help me to improve these skills so that I could become an good architect?
Thank you in advance.



Find the answer here

Is it better to use the [using] directive in C# or the [dispose] method? Does this apply to external (COM) objects?

Programmer Question

I've seen this be a lively debate between the Microsoft C# folks and Microsoft Exchange CDO support groups.



What is better, the using directive, or the dispose directive when finished with an object?



 using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}


On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.



Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?



Find the answer here

Tools for mapping time series data

Programmer Question

Hello, I'm looking for suggestions/examples of tools or APIs that enable the mapping of large amounts of time series data into an intensity map.



The data includes dimensions for country, series, and year. Here's an example http://spreadsheets.google.com/ccc?key=t9ZwziZAgy768ZTXDEg8Maw&authkey=CPn0pdoH&hl=en_GB&ui=1



Find the answer here

Monday, August 23, 2010

Trouble creating csv for download

Programmer Question

Using this lovely example I am getting some funky results. What I have is:



Protected Sub btnCSV_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCSV.Click

Response.Clear()
Response.Buffer = True
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition", "inline; filename=" + FileName + ".csv")

CsvHelper.ProduceCSV(dt, Response.Output, True)

End Sub


But what is happening is that the csv file contains the html output from the page as well as the csv data from the CsvHelper. What gives?



Find the answer here

basic regex help

Programmer Question

$string = 'word1 word2 "phrase 1" "phrase 2" -word3 -word4 -"phrase \"hello\" 3" -"phrase 4"';


i want to search strings that contains (word1 OR word2 OR 'phrase 1' OR 'phrase 2') AND doesn't contain (word3 OR word4 OR 'phrase "hello" 3' OR 'phrase 4')



what would be the regex that would parse $string for me?



Find the answer here

Prism 4.0 compatible with WP7 (windows phone 7)?

Programmer Question

Hi there,



Does anyone know if the latest drop (i beleive its 6) of prism v4.0 is compatible with WP7?



Actually really all i am interested in currently is the MVVM implementation / support that comes with prism 4.0 ...



So would this be compatible with WP7?



Any help really appreciated



Find the answer here

Sunday, August 22, 2010

Team Password/Login Manager

Programmer Question

I have been doing some searching around trying to find some software, preferably for ubuntu, that can provide a secure store for the various logins and passwords that our team has for our servers and services. I have found a lot of personal password managers, but I am looking more for something that members of our team can log into, using separate usernames and passwords rather than using one shared master password, for login retrieval. Furthermore, something that could restrict access to certain entries based on group policy would be amazing. Does anyone know of any such software?



Find the answer here

Couple of questions about Cocos2d and iPhone ??

Programmer Question

1- is it possible to use interface builder to design the game background and then use code to add cocos2d objects?



2- Is it possible to use iphone UI objects as well as cocos2d objects, for example uibutton, uiScrollView, etc.



3- is it possible to useiphone default template, and cocos2d templates togather? for example my home screen is a simple viewcontroller which is loading from a xib file, but the actual game page is a cocos2d template, which has no xib file, and the navigate between them?



Find the answer here

Benchmarks of scripting languages doing the same task?

Programmer Question

This is not a X vs Y question - do not reply as same.



Does anyone know where I could find reviews or reports on tasks that people did in two or more high-level scripting languages to see which one was more suited for a certain job? (note that this is different from looking for a language suited for all jobs!) I really want to know which types of operations are better suited to which languages so that I can make the most of them.



For example: sockets, the file system, logic evaluation, regex, or drawing.



Given my options I'm mostly interested in Python, PHP, Perl, and Ruby.



Find the answer here

How to display different size images in CListCtrl

Programmer Question

In my MFC program,I want to display different size images in a list!
I use CListCtrl and CImageList!
But the CImageList only can load fixed images!



Find the answer here

iphone os audio export question

Programmer Question

Im kind of newb to audio processing but have ExtAudioFile converting pcm to kAudioFormatMPEG4AAC and if i save the file as .caf it plays fine. but not as .m4a (on desktop)



looking at the audio file it seems the header doesnt match another .m4a header and seems very short and has 'caaf' in it. my guess is it might be mpeg4aac data but the header isnt right for a proper .m4a file



so my question is, what do i need to do on iphone to further process this in a proper .m4a file?



Find the answer here

Saturday, August 21, 2010

C++ (or maybe Java/C#) books for understanding 'under the hood' ?

Programmer Question

Hi, what are the best c++ books for learning the very advanced concepts? I know about OO programming, i dont need to know about classes but i'd like to know about how casting works, how the various memory data structures differ in their actual implementation (big O notation etc), deep and shallow copying, garbage collection etc?



Any very good books people could recommend? If not to C++ then perhaps Java and C# as they're similar?



Find the answer here

PHP syntax and structure for radio button and its values

Programmer Question

Radio box code:



Apples />

Oranges


$choice=array("A"=>1.00, "B"=>0.80);
echo $choice["A"]; // will give me the value of 1.00
echo $choice["B"]; // will give me the value of 0.80


Given the code snippet above, is there anything wrong in terms of either the HTML radio box, the array or the choices?



Find the answer here

Table too big in MySQL database

Programmer Question

Hi. I am making an online game and one table in my database. The most important one maybe. It's starting to become very large. I am creating a function where you can go together with multiple users and for that I have a table that look like this so far:



CREATE TABLE `oc` (
`id` int(11) NOT NULL auto_increment,
`leader` varchar(40) NOT NULL default '',

`car` int(11) NOT NULL default '0',
`car_type` char(2) NOT NULL default '',

`seats` varchar(3) NOT NULL default '0',
`share` enum('1','2') NOT NULL default '1',
`location` varchar(100) NOT NULL default '',

`user1` varchar(40) NOT NULL default '',
`user2` varchar(40) NOT NULL default '',
`user3` varchar(40) NOT NULL default '',
`user4` varchar(40) NOT NULL default '',
`user5` varchar(40) NOT NULL default '',
`user6` varchar(40) NOT NULL default '',
`user7` varchar(40) NOT NULL default '',
`user8` varchar(40) NOT NULL default '',
`user9` varchar(40) NOT NULL default '',

`leader_gun` char(2) NOT NULL default '',
`user1_gun` char(2) NOT NULL default '',
`user2_gun` char(2) NOT NULL default '',
`user3_gun` char(2) NOT NULL default '',
`user4_gun` char(2) NOT NULL default '',
`user5_gun` char(2) NOT NULL default '',
`user6_gun` char(2) NOT NULL default '',
`user7_gun` char(2) NOT NULL default '',
`user8_gun` char(2) NOT NULL default '',
`user9_gun` char(2) NOT NULL default '',

`user1_inv` varchar(40) NOT NULL default '',
`user2_inv` varchar(40) NOT NULL default '',
`user3_inv` varchar(40) NOT NULL default '',
`user4_inv` varchar(40) NOT NULL default '',
`user5_inv` varchar(40) NOT NULL default '',
`user6_inv` varchar(40) NOT NULL default '',
`user7_inv` varchar(40) NOT NULL default '',
`user8_inv` varchar(40) NOT NULL default '',
`user9_inv` varchar(40) NOT NULL default '',

`user1_ready` enum('0','1') NOT NULL default '1',
`user2_ready` enum('0','1') NOT NULL default '1',
`user3_ready` enum('0','1') NOT NULL default '1',
`user4_ready` enum('0','1') NOT NULL default '1',
`user5_ready` enum('0','1') NOT NULL default '1',
`user6_ready` enum('0','1') NOT NULL default '1',
`user7_ready` enum('0','1') NOT NULL default '1',
`user8_ready` enum('0','1') NOT NULL default '1',
`user9_ready` enum('0','1') NOT NULL default '1',

PRIMARY KEY (`id`)
) TYPE=MyISAM ;


Now I wonder what my limitations are. It would be cool to have up to 30 users that could play together, but then my table will need 3 times as many fields. 30 x user1_gun 30 x user1_inv and 30 x user1_ready.



This db will be used heavily since all users will need all the information in the db when they access the page to list all the others username and such. All users can also change at least 3 values in the table.



Should I limit my table to 9 users or can I make a table for 100 users?? I have no idea. I can some coding, but have never managed large mysql databases and servers before now.



EDIT: OK. Just to be clear. I have a user table with all kinds of info on my users, a table for cars connected to the user table, a table for weapons connected to my user table. This is not my only table with where a maximum of 9 players can play the game! The oc table need to have fields for usernames and guns each user has selected and user that have signaled that they are ready.. I don't think I need Database normalization...



Find the answer here

Blank char counter in C

Programmer Question

I am trying to create a small function that returns the number of spaces in a Char*
variable using the C language.



Let's say I have this string :"hello hello hello". I want the function to return 2.
This is the code I have so far:



int blankcounter(char* pline)
{
int i=0;
int counter = 0;
while (pline[i] != '\0')
{
if (pline[i++] ==' ')
counter++;
}
return counter;
}


the source that i am reading from is a txt file and 1 correction that i have to add is that the code that i posted indeed works but got 1 downside: if for example i want to read : "hello whats up "i want my function to be able to return 2 but it returns 3 because of the space that appears just after the wordup do u have any suggestion for me so it will return 2 ?



Find the answer here

Binding the IsEnabled property to whether a text block has data

Programmer Question

I'm using silverlight for windows phone and I want to bind the IsEnabled property of a button to whether a textblock has text in it or not. In other words, I want my button to be enabled when the textblock's Text is not empty and disabled otherwise.



Is it possible to do this purely in XAML using Styles/Setters/Triggers or any other mechanism or do I have to write a converter?



PS: I'm still learning silverlight, .NET etc ..



Find the answer here

Friday, August 20, 2010

Where should a Visual Studio Add-in store its settings?

Programmer Question

Currently I'm storing the settings for my custom addins in the registry but this seems like a kludge. I was wondering if there was an official place to store add-in settings. My preference would be to store them where Visual studio stores settings so they can be exported and imported easily.



Is it possible to store add-in settings with Visual Studio settings or is there a better way?



Find the answer here

Why does Ruby have both private and protected methods?

Programmer Question

Before I read this article, I thought access control in Ruby worked like this:




  • public - can be accessed by any object (e.g. Obj.new.public_method)

  • protected - can only be accessed from within the object itself, as well as any subclasses

  • private - same as protected, but the method doesn't exist in subclasses



However, it appears that protected and private act the same, except for the fact that you can't call private methods with an explicit receiver (i.e. self.protected_method works, but self.private_method doesn't).



What's the point of this? When is there a scenario when you wouldn't want your method called with an explicit receiver?



Find the answer here

Is it better to create proxies for table with multi-faceted domains or use inheritance?

Programmer Question

I'm using NHibernate and Dynamic Proxy. I have one table (Customer) with generic fields: charField1, charField2, etc. One record in this table may represent company A while another record may represent company B. However, a different domain model will exist for company A's data than company B's data because they require different information. Likewise, Company A will make use of a different business logic layer than Company B.



Because of this, CompanyA's record would have different associations with different tables than Company B.



I have been reading about the use of proxies and their capabilities in NHibernate and it seems like this could be useful for my scenario; however, would it be better to simply inherit from BaseCompanyTable?



If I use a proxy, I'm imagining creating interfaces that simply have the appropriate mappings to other tables/domains based on the company's mapping type and that is what the interceptor would handle. My ViewModel would then query only that company information and have the interfaces to deal with. When it saves, the business logic would validate it, post it, the interceptor would only save the BaseCompanyTable.



Find the answer here

Using Test::MockDBI multiple times with different results

Programmer Question

Hi, I'm trying to test some code in different situations (for different result sets). I've got the first test running well, but the next one is trying to reuse the first "table".



My result sets:



my $usernames_many = [
{ username => '1234567' },
{ username => '2345678' },
];
my $usernames_empty = [
];


but now when I try these calls:



$mock_dbi->set_retval_scalar(MOCKDBI_WILDCARD, "SELECT username FROM location", $usernames_many);
is_deeply(find_multiple_registrations($mock_db, 15), [ '1234567', '2345678' ], "many entries");

$mock_dbi->set_retval_scalar(MOCKDBI_WILDCARD, "SELECT username FROM location", $usernames_empty);
is_deeply(find_multiple_registrations($mock_db, 15), [ ], "no entries");


The first test passes, but the second one results in:



not ok 3 - no entries
# Failed test 'no entries'
# at ./report_many_registrations_test.pl line 28.
# Structures begin differing at:
# $got->[0] = '1234567'
# $expected->[0] = Does not exist


Which seems to indicate the first resultset was used again instead. How can I clean a resultset? Or reset the state in some other way?



Find the answer here

How to hide the button title in iphone application?

Programmer Question

I want to hide the title of the button. How can i do in iphone application?
eg



UIButton *b =.....
[b setTitle:buttonTitle forState:UIControlStateNormal];

now i want to hide the title. How can i?


Find the answer here

Thursday, August 19, 2010

Help with Objective-C variable declaration syntax

Programmer Question

Is there a difference between these two declarations? Is one better practice?




  • NSString* hello = @"HelloWorld";

  • NSString *hello = @"HelloWorld";



Thanks--



Find the answer here

Wednesday, August 18, 2010

Java: writing to a file, where is the output file ?

Programmer Question

        FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");


Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.



Find the answer here

How can I set a button background color on iPhone?

Programmer Question

How can I set a custom background color of a button?



Interface Builder doesn't seem to have an interface to do this.



Is it only available programmatically?
If so, can you provide an example, please?



Find the answer here

VisualStudio Default Code Discovery Method

Programmer Question

A little while back (after recently installing VStudio 2010) I used the Go to Definition... feature and a little box opened up asking me if i wanted to:




  • Use the object explorer

  • Open Meta-Data View

  • Something I can't remember



Well I wasn't really paying much attention and selected meta-data view, I'd now like to set it to Object Explorer but I can't for the life of me find it in the myriad of VStudio options.



Could someone direct me there before I go insane?



Find the answer here

How do you load a dictionary into a console application from an app.config?

Programmer Question

Hello,



I want to load a dictionary at startup in my console app from my app.config.



I know that I could use an xml library or linq to XML to load it to parse and traverse it. My question is there a BUILT IN way of doing it.



Isn't there some way to add an application configuration section into the app.config and then have it loaded automagically using ConfigurationManager class in the System.Configuration namespace?



Any example? BTW, I am in NET20.



EDIT

Sorry, I should have clarified. I want to load the dictionary WITHOUT using AppSettings. I know how to do that already. Of course, the downside of using AppSettings is that I have to change my code to add new values to my dictionary. That is why I am looking for a way to do it automatically.



Seth



Find the answer here

Rails, get column name of value

Programmer Question

This might be a little odd, but how can I get the column name from object in my model?



For example, I have a table which happens to have all 50 states in it as separate columns (I know, I know that could be way more efficient), so they look like:



al_allowed, ak_allowed, etc...


These columns are booleans, but I wanted to know in my model how to get the column names?, for example if for a particular record (in this case Campaigns), I want to see which states are checked off, and if they are True, I want to push the states abbreviation(the column name) into an array.



Find the answer here

Tuesday, August 17, 2010

How can I store a reference to object property in another object?

Programmer Question

This is a C# winforms app.



Preface:



I am creating a form that will allow users to import data from an existing MySql or SQL Server database into my SQL Server database. This allows users to quickly import IP addresses and other data without having to re-enter it via a control.



Example:



Simplified, I have two objects, FieldObject and SensorObject. FieldObject exists to store the source and destination database field names and types. SensorObject is the object I later populate from the records in the database. For simplicity's sake, I am omitting the type handling and other functionality that is not relevant to the question. (The data for DestinationField is limited to a list that I provide the user, and comes from an array or list within the program.) Here is an example of both:



public class FieldObject
{
public string DestinationField {get; set;}
public string SourceField {get; set;}
}

public class SensorObject
{
public string Name {get; set;}
public string IPAddress {get; set;}
}


Problem:



When the user populates the various fields of FieldObject, I use the information to populate the destination database, though I have a large switch statement that checks the destination field name to know what property of SensorObject it belongs.



For example:



// Reader is a SqlDataReader with the prerequisite database connection
FieldObject myField = new FieldObject
{
DestinationField = "name",
SourceField = "proprietary"
};
SensorObject mySensor = new SensorObject();
switch (myField.DestinationField)
{
case "name":
mySensor.Name = Convert.ToString(Reader[myField.DestinationField]);
break;
case "ip_address":
mySensor.IPAddress = Convert.ToString(Reader[myField.DestinationField]);
break;
}


As you can see it would require more redundant code to handle more properties for the object.



Question:



I'd like some way of storing the property of SensorObject that the data belongs to, so that when iterating FieldObjects in a list, I can effectively eliminate the switch statement.



Something like:



foreach(FieldObject f in myFieldList)
{
mySensor(f.mySensorField) = Convert.ToString(Reader[f.DestinationField]);
}


I am not certain what technique in C# lends itself to this sort of application. I've looked into reference values and reflection, and neither seem appropriate.



I appreciate any insight and advice or even ways to rethink this approach.



Find the answer here

Monday, August 16, 2010

how join list tuple and dict into a dict?

Programmer Question

how join list tuple and dict into a dict?



['a','b','c','d'] (1,2,3) and {'a':'10'}
d excluded for list be compatible with the tuple

output {'a':'1','b':'2','c':'3','a':'10'}


Find the answer here

Sunday, August 15, 2010

New to PHP, can I just insert PHP in code?

Programmer Question

Let's say I just want to use php include to grab html from another file. can I just put in that little php script and name my .html file (index.html) to index.php and it'll work? I thought id have to add my server password an other info in PHP to use it.. What do I do?



Find the answer here

Add links to datagridview

Programmer Question

hello,



i hava a datagridwview with a datagridviewlinkcolumn and a split array with the links. How can I add this links from the array to the datagridviewlinkcolumn?



thanks



Find the answer here

reason why there is no "if Empty" in python

Programmer Question

the zen of python says "Explicit is better than implicit."



i find that an is Empty to check whether some sequence is empty is so much more explicit than implicit booleanness



if some_sequence is Empty:
fill_sequence(some_sequence)


compare with



if not some_sequence:
fill_sequence(some_sequence)


this gets even more confusing with some unfavorably choosen variable names



if saved:
mess_up()


compare with



if saved is not Empty:
mess_up()


see also: http://stackoverflow.com/questions/53513/python-what-is-the-best-way-to-check-if-a-list-is-empty i find it ironic that the most voted answer claims that implicit is pythonic.



so is there a higher reason why there is no is Empty in python?



Find the answer here

Saturday, August 14, 2010

What API function do I need to use to know if a windows is beeing shown in the taskbar?

Programmer Question

I am making a taskbar in C# and I know how to get a list of open windows, but I must know what windows I must show in the taskbar. How can I do this?



Find the answer here

Adding and hiding JLayeredPane dynamically

Programmer Question

I want to add/hide/remove jlayeredpanes dynamically on runtime and also should hide the contents on each pane when another pane is selected. I have tried the following code and i am not sure how to do this. The following code hides the content of each pane when alternate pane is selected but it does not hide its content constantly. When we mousemove over the hidden content area they are made visible again. Plz help me out in this!!



import java.awt.Color;



import java.awt.Component;



import java.awt.Dimension;



import java.awt.event.ActionEvent;



import javax.swing.Box;



import javax.swing.JButton;



import javax.swing.JLayeredPane;



import javax.swing.JOptionPane;



public class floorsetup {



public static void createfloor(String name)
{
String name1=name+"_pane";
JButton b = new JButton(name);
final JLayeredPane jp = new JLayeredPane();
jp.setName(name1);
floor_plan.dynamicPane_floors.put(name1, jp);

//jp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jp.setAutoscrolls(true);
jp.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jp.setMinimumSize(new java.awt.Dimension(1000, 700));
jp.setOpaque(true);
jp.setBounds(floor_plan.ground.getBounds());
floor_plan.jLayeredPane2.add(jp);
jp.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
//floor_plan.jLayeredPane2.setVisible(false);

int x = 0,y = 0;
//ComponentOrientation componentOrientation = jLayeredPane2.getComponentOrientation();
// Rectangle bounds = jLayeredPane2..getBounds();
// x=bounds.x;
//y=bounds.y;

//System.out.println(bounds);

x=evt.getX();
y=evt.getY();
System.out.println(x);
System.out.println(y);
// String name=floor_plan.table_name.getText();
String name="some name";
if(floor_plan.delete!=1)
tablesetup.addButton(name,x,y, (JLayeredPane) evt.getSource());
System.out.println((evt.getSource()));
}
});

b.setActionCommand(name);
b.setAlignmentX(Component.CENTER_ALIGNMENT);
b.setPreferredSize(new Dimension(125, 25));
b.setBackground(Color.green);

floor_plan.floors.add(b);
floor_plan.floors.add(Box.createRigidArea(new Dimension(10, 15)));
// b.setSize(125, 25);
floor_plan.dynamicButtons_floors.put(name, b);
MouseListenerClass M1 = new MouseListenerClass();
MouseClass M2 = new MouseClass();
b.addMouseMotionListener(M1);
b.addMouseListener(M2);
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {

if(floor_plan.delete==1)
{
removeButton(evt.getActionCommand());
}
else if(floor_plan.edit==1)
{
String edit_name = JOptionPane.showInputDialog("Name of the button:");
JButton source = (JButton) evt.getSource();
source.setActionCommand(edit_name);
source.setText(edit_name);
floor_plan.dynamicButtons_floors.put(edit_name, source);
}
else
{
String switcher=evt.getActionCommand();
switcher+="_pane";
switch_pane(switcher,evt);
}
}
});

floor_plan.floors.validate();

floor_plan.floors.repaint();
}
public static void removeButton(String name) {


JButton b = floor_plan.dynamicButtons_floors.remove(name);
floor_plan.jLayeredPane2.remove(b);
floor_plan.jLayeredPane2.invalidate();
floor_plan.jLayeredPane2.repaint();


}
public static void switch_pane(String name,ActionEvent evt)
{
JLayeredPane jp = floor_plan.dynamicPane_floors.get(name);
System.out.println(floor_plan.jLayeredPane2);
System.out.println(jp);
floor_plan.ground.setVisible(false);
floor_plan.ground.setEnabled(false);
jp.setVisible(true);
jp.moveToFront(floor_plan.ground);



}


}



Find the answer here

Where can I save a variable to be used between calls to a Django view?

Programmer Question

I am looking to return a random number between 0 and 4 in a Django view, which is repeatedly called. The number is limited in that it can't be the same as the number that was called previously. It would be fine if the number loops rather than being random, it just can't be the same as what was returned before.



I tried using a variable outside of the view, and incrementing it within the function, but that wouldn't save between each call to the view.



I hope that explanation works, I am brand new to Django.



Find the answer here

Running rake db:migrate without some initializers

Programmer Question

I am trying to run jruby -S rake db:migrate, but I do not want to start up a daemon in config/initializers whenever I do a migrate. Is there a way to do this? Up until now, I have just been moving the daemon file to a file with a .bak extension so that rails doesn't load it when I do the migrate.



I suspect that this is a stupid way of doing things. Is there a better way?



Oh and I am running jruby ( if it matters ).



Find the answer here

Given a latitude / longitude to a certain number of decimal places, how to tell the area covered (in metres)?

Programmer Question

If i have a position specified in latitude and longitude, then it can cover a box, depending on how many digits of accuracy are in the position.



For example, given a position of 55.0� N, 3.0� W (i.e. to 1 decimal place), and assuming a truncation (as opposed to rounding), this could cover anything that's 55.01� to 55.09�. This would cover the area in this box: http://www.openstreetmap.org/?minlat=55.0&maxlat=55.1&maxlon=-3.0&minlon=-3.1&box=yes



Is there anyway to calculate the area of that box? I only want to do this once, so a simple website that provides this calculation would suffice.



The main reason I want to do this is because I have a position to a very high number of decimal places, and I want to see how precise it is.



Find the answer here

Friday, August 13, 2010

Extension methods to extend class members?

Programmer Question

Hi all. I'd like to write an extension method that extends some member of my class. Specifically, I'd like to extend an enum. However, this is not working:



namespace mynamespace
{
public class myclass
{
public enum ErrorCodes
{
Error1, Error2, Error3
}

public static double GetDouble(this ErrorCodes ErrorCode)
{
return (double)((int)ErrorCode);
}

public void myfunc()
{
ErrorCodes mycode;
MessageBox.Show(mycode.GetDouble().ToString());
}
}
}


Specifically, it doesn't recognize GetDouble() as an extension. This is not just for enums either, I tried creating an extension method for doubles and had the same problem, too.



Find the answer here

How to export data from Excel spreadsheet to Sql Server 2008 table

Programmer Question

I want to import data from an Excel file - assume Excel 2003 / .xls - to Sql Server 2008.



Have tried adding a linked server to the JET OLE DB Access driver, and of course it fails on the 64-bit machine.
But when I try to drop the linked server while experimenting, there's another error saying that the linked server already/still exists!



I have also tried changing the Excel driver to 32-bit (regedit tool) but am not sure if it's doing anything, same error is coming up!



Some more details:
Say Table1 in Excel file has 5 columns.
I want to map to Database.dbo.Table1 with 5 columns again, but with different names in table.
Is there a way to do even do such an import?



Find the answer here

INFORMIX-SE for Windows with 4Js Genero Client

Programmer Question

OK, so I recently downloaded 4J's Genero Studio 90-day trial version. I would like to use INFORMIX-SE for the backend with Genero's client. Is INFORMIX-SE for Windows available on a trial version?.. I see that IDS is available as a free download, but IDS would be an overkill for my app.



Find the answer here

How to implement where clause on Android Query method?

Programmer Question

I'm trying to query a word, for this Im using the db.query method. But I want use a where clause, I've done like this on my code, but, the emulator returns an error.



public String select(String wrd) {
String list = new String();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like " + wrd + "", null, null, null, "id desc");
if (cursor.moveToNext()) {
do {
list = cursor.getString(0);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;


}



Im calling this method in other class, parsing a String argument.



Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);                                    
String body;
if(cursor.moveToFirst()){
body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
if(body == ""){
Toast.makeText(getBaseContext(), "There is no words to save!", Toast.LENGTH_LONG).show();
}
else{
String words = this.dh.select("Testando");
StringTokenizer st = new StringTokenizer(body);
while(st.hasMoreTokens()){
if(words == st.nextToken())
Toast.makeText(getBaseContext(), "found! "+words+"", Toast.LENGTH_LONG).show();
this.dh.insert(st.nextToken());
Toast.makeText(getBaseContext(), "The set of words has been updated!", Toast.LENGTH_LONG).show();
}
StringBuilder sb = new StringBuilder();
sb.append("Set of words:\n\n");
sb.append(words + " ");
txtView.setText(sb.toString());
}
}


Find the answer here

Sending UDP packets via Java

Programmer Question

Hi all,



I'm trying to send UDP packets from my PC to an FPGA via my laptop's ethernet cable. I've been using Java's DatagramPacket and DatagramSocket to send the UDP packets. However, these packets will only send over my laptop's wireless interface. How can I specify that the packets should go through my ethernet interface?



Thank you.



Find the answer here

Monday, August 9, 2010

Ruby on Rails: is there a way to retrieve a javascript var from render :udate do |page| ?

Programmer Question

I can set javascript variables.. but can I retrieve them? if so. how?



Find the answer here

Multiple events doesn't show, can anyone help, urgent?

Programmer Question

Hi all,



I'm having a little issue where both the events doesnt display. The first event will display but in order to see the second events, I would have to delete the first event. Does anyone know how to go about this issue? This is what the json returned is:



[{"id":"4319aef0-9c28-9429","title":" Hello","start":1281096000,"end":1281268800,"allDay":false,"notify":false,"repeat":"","duration":""},{"id":"4319aef0-9c28-9429","title":" Hello 1","start":1281355200,"end":1288558800,"allDay":false,"notify":false,"repeat":"Every 1 Week","duration":"5 days"}]



Find the answer here

Disable warning that solution is not under source control?

Programmer Question

Shamefully, we use TFS at work for a C# project. I wish we could move to svn or git, but we can't change that. All of us working on the project hate the automatic check-out "feature" of TFS, so we checked in our solution and project files as unbound from TFS.



Now, whenever we open the project, we get the following message:




The solution you have opened is under source control but not currently configured for integrated source control in Visual Studio. Would you like to bind this solution to source control now?




Is there a way to disable this message while keeping the solution unbound from the buggy and annoying integrated source control?



Find the answer here

Why is it bad to use goto?

Programmer Question

I just came across some C# code that had a goto statement in it (which I didn't even know C# supported). I only vaguely remember hearing about goto statements in one of my college classes. I seem to remember my professor saying it should never be used but I don't remember why.



Should I consider rewriting this piece of code or is this unlikely to cause problems?



Find the answer here

Why do the authors of the C/C99 standard, don't specify a ..standard for the sizeof floating point types?

Programmer Question

This is considerably puzzling since planes had gone down due to overflows.



I noticed on windows and linux x86, float is 4bytes, double is 8, but long double is 12 and 16 on x86 and x86_64 respectively. Why aren't they same? Why do they try to achieve? It can't be merely tradition since C99 is supposed to be breaking such barriers with the specific integral sizes. Or at least I hope it's not merely tradition or incompetence.



Find the answer here

Sunday, August 8, 2010

Characters not showing up correctly when using textInput in flash

Programmer Question

I have a textInput field form that's not displaying the characters it should when typed into. E.g. when the letter "�" on my keybard is pressed "�" shows up. This only happens once the flash movie is being displayed in a browser (that is embedded in html), preview through flash does not have this problem. The font is properly embedded as "nameInp.text = "����" shows the correct text in the textInput. It is only when I try to type when it doesn't work as it should.



I have Window mode set to window and I've tried setting "System.useCodePage = true;"



Anyone know of a solution to this problem?



Find the answer here

How to read individual '-webkit-transform' values in JavaScript?

Programmer Question

Webkit's blog post from last year on 3D transforms explains the various transform 'functions' that can be used in the -webkit-transform property. For example:



#myDiv {
-webkit-transform: scale(1.1) rotateY(7deg) translateZ(-1px);
}


My question: how do you access individual values in JavaScript? When you read the webkitTransform property of the element, you just get a matrix3d() function with 16 values in it, like this...



matrix3d(0.958684, 0.000000, .....)


Is there a way to just read the value of an individual transform thing, like rotateY()? Or do I have to read it from the matrix3d() string, and how?



Find the answer here

c++ Start process with argument

Programmer Question

i know how to Start process with argument but im trying to create a program that uses this arguments. for example IE8 uses Process::Start( "IExplore.exe","google.com"); as a argument to open new window with url google.com. i want my program to use the argument are send it but i don't know how to get the the argument. like Process::Start( "myprogram.exe","TURE"); i want my program to get the ture
thanks in advance
Rami



Find the answer here

Flash Builder 4 Welcome/Start Panel?

Programmer Question

i have closed the welcome panel in FB4 and now i can not find it. ridiculous. how can i open the panel again?



Find the answer here

What font and size is used in Windows 7 File Explorer Tree

Programmer Question

I am having a hard time to find out which font is used by the Win 7 File Explorer in the tree view on the left hand side. Better, of course, would be if I can programmatically find out which the right font is (C#).



I searched the Windows 7 design guidelines but this particular scenario is not listed (at least I couldn't find it).



So anyone good with fonts?



Find the answer here

Thursday, August 5, 2010

MS SQL Query - Loop question

Programmer Question

I'm trying to create a query that would generate a cross-check table with about 40 custom columns that show Y or N. Right now I have



SELECT DISTINCT [Company],
[Option1],
[Option2],
[Option3],
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 1 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 2 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 3 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
.............
-- REPEAT ANOTHER 40 times
FROM [Table1]
WHERE [Table1].[OtherCondition] = 'True'
ORDER BY [Company]


So my question is, how do I create a loop (while? for?) that will loop on Variable and assign Y or N to the row based on the condition, rather than creating 40+ Case statements?



Find the answer here

How to turn a html form into a complex JavaScript object

Programmer Question

Is there a way to turn a form into a complex JavaScript object based some structured form?



Now, I have no idea if this should be done in a better way, but basically I want something like this:










and I want this in JavaScript:



var form = GetForm();
var obj = ConvertFormToComplexObject(form);

//
// Followings should be true
//
// obj.Foo == 1;
// obj.Parent != null
// obj.Parent.Child1 == 1;
// obj.Parent.Child2 == 2;
//


Any suggestions?



Thanks,



Find the answer here

Plugins installed on Eclipse not visible

Programmer Question

When I install a plugin in Eclipse everything goes well. But after restarting the new plugin is not visible. I have tried it with different plugins, but they have all the same problem. The only place where I can see them is when I look at "What is already installed?".



What could be the problem?



Find the answer here

Wednesday, August 4, 2010

Trouble with JSON parsing in iPhone App

Programmer Question

I've been trying to make this work for some time now, but I think I need someone on the outside to see what I'm doing wrong. In my app, I'm getting a JSON value from a web server, and parsing it into my table view.



responseData = [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://myserver/json"]];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dict = [responseString JSONValue];
theData = [dict objectForKey:@"data"];


My only problem now, is that 'theData' is apparently a NSString, as far as I am able to see. The following error is what I get from GDB when I call '[theData count]' from my view controller.



-[NSCFString count]: unrecognized selector sent to instance 0x6eb5380


And what my JSON looks like



{
"code": 100,
"data": [
{
/** Some object */
}]
}


Find the answer here

Xpath Node to String

Programmer Question

How can I select the string contents of the following nodes:




word
test



word
test2
more words



I have tried a few things



//span/text()


Doesn't get the bold tag



//span/string(.)


is invalid



string(//span)


only selects 1 node



I am using simple_xml in php and the only other option I think is to use //span which returns:



Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => url
)

[b] => test
)

[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => url
)

[b] => test2
)

)


*note that it is also dropping the "more words" text from the second span.



So I guess I could then flatten the item in the array using php some how? Xpath is preferred, but any other ideas would help too.



Find the answer here

Building a GUI for a Sudoku Solver (Complete with ASCII Example)

Programmer Question

.



OVERVIEW, SAMPLE



Hello everyone,



I have created a basic Sudoku solver that can solve most problems fairly quickly. I still have a lot of work ahead of me to make it solve even the hardest problems, but I'd like to try to implement a basic JFrame GUI first.



I have worked with internet applets in the past, but never before with JFrames.



I want to create something similar to the image below (for starters):



-------------------------------------------------------------------------------------------------
! Sudoku Solver 1.0 - [] X !
-------------------------------------------------------------------------------------------------
! _____________ _____________ _____________ _____________ _____________ _____________ !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !5! !_! !_! | !_! !_! !_! | !6! !_! !1! | | !5! !7! !2! | !4! !9! !3! | !6! !8! !1! | !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !6! !_! !_! | !_! !_! !2! | !4! !_! !_! | | !6! !1! !3! | !8! !5! !2! | !4! !7! !9! | !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !_! !_! | !7! !_! !1! | !_! !_! !2! | | !8! !4! !9! | !7! !6! !1! | !3! !5! !2! | !
! -_____________-_____________-_____________- -_____________-_____________-_____________- !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !_! !4! | !_! !2! !_! | !_! !3! !_! | | !1! !6! !4! | !9! !2! !7! | !5! !3! !8! | !
! | _ _ _ | _ _ _ | _ _ _ | .---. | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !3! !_! | !_! !_! !_! | !_! !9! !_! | | > | | !2! !3! !8! | !5! !1! !6! | !7! !9! !4! | !
! | _ _ _ | _ _ _ | _ _ _ | '---' | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !_! !_! | !_! !4! !_! | !_! !_! !_! | | !7! !9! !5! | !3! !4! !8! | !1! !2! !6! | !
! -_____________-_____________-_____________- -_____________-_____________-_____________- !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !2! !_! | !1! !_! !5! | !9! !_! !_! | | !4! !2! !7! | !1! !8! !5! | !9! !6! !3! | !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !_! !_! | !6! !_! !_! | !_! !_! !5! | | !3! !8! !1! | !6! !7! !9! | !2! !4! !5! | !
! | _ _ _ | _ _ _ | _ _ _ | | _ _ _ | _ _ _ | _ _ _ | !
! | !_! !_! !6! | !_! !3! !_! | !_! !_! !7! | | !9! !5! !6! | !2! !3! !4! | !8! !1! !7! | !
! -_____________-_____________-_____________- -_____________-_____________-_____________- !
! !
! .-------------------------------------------------------------------------------------------. !
! | | !
! | Solved Puzzle in 9.096ms | Completely Solved: True | !
! | | !
! '-------------------------------------------------------------------------------------------' !
! !
-------------------------------------------------------------------------------------------------


.



SPECIFICS



: Left Puzzle




  • 9x9 Sections should be clearly defined (lines in between; seperate boxes)

  • Text boxes should only accept numbers/only allow for one number to be entered (if possible)



: Right Puzzle




  • 9x9 Sections should be clearly defined (lines in between; seperate boxes)

  • Doesn't matter if boxes can/cannot be edited so long as they can display the result



: Button In Center




  • Should run [SudokuPuzzle].solve();



: Bottom Text Box




  • Should not be editable



.



WHAT I'M LOOKING FOR



I know from past experiences that this can all be done in a JFrame, but because I have never built one myself, I'm not quite sure which components (content items, panels, settings, etc) I need to use to meet my specifications. I have yet to find a way to limit my text boxes to numbers and prevent the user from inserting more than one value at a time. Are text boxes really the best option, or am I missing something that can more specifically suit my needs?



I not only need to know which classes I need, but also how to organize these so that the button stays comfortably between the two puzzles and the text box sits underneath. From what I've read, MigLayout seems like an option to simplify this process.



.



END NOTES



Many, many thanks to anyone who helps. If any part of this question appears a little rude or abrupt, I apologize. I tend to post most of my questions at night, so the community has a few hours to mull it over before I try all the responses (that and the fact that I'm out doing stuff most days).



I will be awake for 1-2 more hours to answer any questions.



Again thanks,



Justian



Find the answer here

MSMQ: Remote access in transactional context

Programmer Question

Considering MSMQ version 3.0



Hello.



I want to send and read messages from a remote MSMQ queue.



In version 3.0 remote reads with transactions are not supported.
In version 4.0 transactional reads can be made not with receive method but with peek.



I saw a problem using transactional remote reads with MessageQueueTransaction and the answer suggest to use DTC transations. (TransactionScope)



http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.msmq.programming&tid=7dd22d35-1750-443d-a9b4-c771fde76e7b&cat=&lang=&cr=&sloc=&p=1



My question is if i can make transactional remote sends with MessageQueueTransaction object or, because it is a remote send, i need to use TransactionScope.



Thanks



Find the answer here

What code would you put before/after your R session?

Programmer Question

R allows us to put code to run in the beginning/end of a session.



What codes would you suggest putting there?



I know of three interesting examples (although I don't have "how to do them" under my fingers here):




  1. Saving the session history when closing R.

  2. Running a fortune() at the beginning of an R session.

  3. I was thinking of having an automated saving of the workspace. But I didn't set on solving the issue of managing space (so there would always be X amount of space used for that backup)



Any more ideas? (or how you implement the above ideas)



p.s: this is continuing a thread started on "stat.overflow"



Find the answer here

Sunday, August 1, 2010

Standalone .jar runs great, but when embedded in HTML, framerate drops to 1 fps.

Programmer Question

I have a single .jar file that I create by using the runnable .jar file export function in Eclipse. This file runs flawlessly when you just download it and run it. Now I'm trying to embed it in an HTML file, but having trouble.



Here is the standalone jar



Here is the page where I attempt to embed the .jar file. I could not make it run on it's own, but If I took the Main.class file from the bin/ directory of my Project and included that too, it almost works.




Voronoi Cells







Here is that page online



With this arrangement, in Chrome, the applet shows, but the framerate is only around 1 fps.



It crashes Firefox.



It works fine it Safari!



Who cares what it does in IE.



What is the correct applet tag I should use? I would prefer to reference only the single standalone .jar file if possible. Why is the framerate so bad in Chrome?



Find the answer here

How do you fill in a resource string at run-time?

Programmer Question

I have an application I'd like to localise. However, the strings to be localised occasionally contain parts I'd like to provide at runtime, such as action links.



For example, I have a string like this: Please click here for help. I can't just split it into two resources since in different languages it'll be in a different location.



Is there any way to do this or should I stick to hard-coding the link to the controller/action in the resource itself?



Find the answer here

Instruments say this code from Erica Sadun is leaking

Programmer Question

I have this snippet of code from Erica Sadun (the only woman I ever heard that kicks butts in programming) from a class she created, that Instruments say is leaking.



- (void)cacheBeginPointForTouches:(NSSet *)touches
{
if ([touches count] > 0) {
for (UITouch *touch in touches) {
CGPoint *point = (CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch);
if (point == NULL) {
point = (CGPoint *)malloc(sizeof(CGPoint));
CFDictionarySetValue(touchBeginPoints, touch, point);
}
*point = [touch locationInView:self.superview];
}
}
}


Instruments is pointing to



 point = (CGPoint *)malloc(sizeof(CGPoint));


as the leaking line.



As this malloc stuff is not familiar to me. I know that it allocates memory, but as I never worked with C, C++ and other flavors of C, malloc and I are not acquaintances.



Another question I don't understand is why she put an asterisk before "point" on



*point = [touch locationInView:self.superview];



So, do you see something wrong with the code and why instruments are saying it is leaking there? An explanation about the asterisk is a bonus! :)



thanks.



Find the answer here

UIView willMoveToSuperview error

Programmer Question

I get this random error when I run my app and tap on a button that Plays sound,




UIView willMoveToSuperview:]: message
sent to deallocated instance 0x1b1a20




Then the app freezes?? Any ideas?



Find the answer here

Android custom view onTouchEvent

Programmer Question

Hello,



I'm implementing an OpenGL ES based application for Android. The device I'm testing on is an HTC Desire. It auto updated to Android 2.2 today.



I've got a custom GLSurfaceView that implements onTouchEvent however it seems that the default behaviour of Android has changed. For example, when keeping focus on a single touch area the function used to be a called 20-30x per seconds and now it seems it only gets called once every 2 seconds. Does anyone know how to fix this or get the default behaviour back?



Thanks in advance.



Find the answer here

LinkWithin

Related Posts with Thumbnails