Tuesday, December 28, 2010

How to split and join array in C++?

Programmer Question

I have a byte array like this:



lzo_bytep out; // my byte array
size_t uncompressedImageSize = 921600;

out = (lzo_bytep) malloc((uncompressedImageSize + uncompressedImageSize / 16 + 64 + 3));
wrkmem = (lzo_voidp) malloc(LZO1X_1_MEM_COMPRESS);

// Now the byte array has 802270 bytes
r = lzo1x_1_compress(imageData, uncompressedImageSize, out, &out_len, wrkmem);


How can I split it into smaller parts under 65,535 bytes (the byte array is one large packet which I want to sent over UDP which has upper limit 65,535 bytes) and then join those small chunks back into a continuous array?



Find the answer here

Splitting a string using the empty string as the delimiter yields leading empty string but no trailing empty string

Programmer Question

Suppose you have this expression in Java:



"adam".split("")


This is telling Java to split "adam" using the empty string ("") as the delimiter. This yields:



["", "a", "d", "a", "m"]


Why does Java include an empty string at the start, but not at the end? Using this logic, shouldn't the result have been:



["", "a", "d", "a", "m", ""]


Find the answer here

Monday, December 27, 2010

Removing a text block from a file : sed ?

Programmer Question

Hi,
Following an attack, I need to remove 4 lines of text added to .htaccess files in my site, and was thinking SED would be the way to go, but cannot see how in spire of many attempts.



The added lines are



RewriteEngine On
RewriteCond %{HTTP_REFERER} ^http://
RewriteCond %{HTTP_REFERER} !%{HTTP_HOST}
RewriteRule . http://targeturlhere.net/%{REMOTE_ADDR}


I managed to create the script to remove added htaccess files containing those lines only, but for existing htaccess files in which that was appended I have to edit the file and cannot delete it. I cannot just remove line by line nor use "RewriteEngine On" as the start marker, as this instruction "RewriteEngine On" is sometimes legitimate elsewhere in the file.



In most cases those lines are the last, but I guess in other files they could be in the middle, so I was trying to remove exactly that block - and have a script I could reuse in a similar case.



(Edit: my 4 lines are below one another, no blank line in between but the editor here seems to either show no breakline, or one adding a blank line)



Any hint or tip ? Thanks.



Find the answer here

Objective C: Can't find .js file in my mainBundle?!

Programmer Question

This is driving me crazy as I cannot figure out what in the world is going on. I load up files form you main bundle all the time, xml files, html files, etc. But, now I am trying to get the contents of a javascript file but it can never find it. I am using:



NSData *jsData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"global" ofType:@"js"]];
if (jsData) {
NSLog(@"%@", jsData);
} else {
NSLog(@"Can't find file");
return;
}


Even checking the [[NSBundle mainBundle] pathForResource:@"global" ofType:@"js"] string returns null.



My activity.js file is in my Resources folder, the exact location where my other files are location that work totally fine using the above method.



Why can't it find my js file?



Find the answer here

Pushing an array into a vector.

Programmer Question

I've a 2d array, say A[2][3]={{1,2,3},{4,5,6}}; and I want to push it into a 2D vector(vector of vectors). I know you can use two for loops to push the elements one by on on to the first vector and then push that into the another vector which makes it 2d vector but I was wondering if there is any way in C++ to do this in a single loop. For example I want to do something like this:



myvector.pushback(A[1]+3); // where 3 is the size or number of columns in the array.


I understand this is not a correct code but I put this just for understanding purpose. Thanks



Find the answer here

OpenTK based/compatible text rendering library

Programmer Question

I noticed an example for text rendering in the OpenTK documentation, but is there a library that has already been developed for this purpose? I am looking to use this for a video game, so it does need to be as performant as possible.



Find the answer here

draw a square matrix

Programmer Question

I want to make a game where I need a square shaped matrix with 6 row and six columns.
How to do that?
Pls help me.



Find the answer here

Saturday, December 25, 2010

Can you write files in Chrome 8?

Programmer Question

I'm wondering if, with the new File API exposed in Chrome (I'm not concerned with cross-browser support at this time), it would be possible to write back to files opened via a file input.



You can see an example of what I'm trying to accomplish here: http://www.grehz.com/ide.



I know I can use server side scripts to dynamically create the files and allow the user to download them normally. I'm hoping that there's a way to accomplish this purely client side. I had read somewhere that you can write to files opened via a file input. I haven't been able to find any examples of this, though I have seen passing references to a FileWriter class.



I would be completely not surprised if this wasn't possible though (it seems likely that there are security issues with this). Just looking for some guidance or resources.



UPDATE:



I was reading here: http://dev.w3.org/2009/dap/file-system/file-writer.html



As I was playing around in Chrome, it looks like FileSaver and FileWriter are not implemented, but BlobBuilder is. I can call getBlob() on the BB object, is there any way I can then save that without FileSave or FileWriter?



Find the answer here

Friday, December 24, 2010

MVC Entity Framework: Cannot open user default database. Login failed.

Programmer Question

This type of stuff drives me nuts. I'm having trouble finding the exact issue that I'm having, maybe I just don't know the terminology. Anyway, I had a working website using MVC and Entity Framework, but then I coded an error in a partial view page (ascx). Then all of a sudden I started to get this message.




Cannot open user default database. Login failed.
Login failed for user 'NT AUTHORITY\SYSTEM'




I've found plenty of suggestions about opening SQL Server Management Studio, Double Click on Security, Double Click on Logins, Double click on NT AUTHORITY\SYSTEM and then double click on User Mapping. In this view I'm suppose to check the box for my database so that this user is mapped to this login. However, since I created my database in Visio Studio 2008 as part of my solution, it doesn't show up to allow me to click on it. So what do I do now?



What drives me nuts is that everything was working fine. I was using my computer name to access the website and everything was working fine until the coding error. I've fix the error but still getting the error. I should also mention that this error started yesterday too around the same time but later cleared itself up. If I use localhost to access the site, it works just fine.



IIS7 configuration for my website:



Application Pool = DefaultAppPool
Physical Path Credentials Logon = ClearText


With in connection strings. I do see the one for my database in this solution. Entry Type is local



metadata=res://*/Models.DataModel.csdl|res://*/Models.DataModel.ssdl|res://*/Models.DataModel.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\FFBall.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"


And somewhere I remember changing the identity from Network Service to LocalSystem. Because when I first stared I was getting this same message, but I changed this value and it started working. I saw that suggested somewhere too but I do not recall. Wait I remember now, I believe in IIS7, under Application Pools, DefaultAppPool identity is set to LocalSystem.



Additional things I've tried.




  • Restart the computer

  • Recycle the application pool.

  • Antivirus isn't running.



Any help would be appreciated.



Thank you in advance.



Find the answer here

Thursday, December 23, 2010

The C++ Standard: Book Recommendation.

Programmer Question

I'm planning to buy this book:



The C++ Standard: Incorporating Technical Corrigendum No. 1

http://www.flipkart.com/standard-british-standards-institution-incorporating-book-0470846747



Since it's cost is too much for me (being an Indian we've the habit of buying only low-price edition books :D), I want to make sure if this is the correct edition/version of the Standard. So I need some good advice if I should go for it, or there is better option for me which I'm unaware of.



PS: I want to buy hard copy, not PDF.



Find the answer here

Red Hat - Accept Self-Signed Certificates

Programmer Question

Hi:



Is there a way I can get a Red Hat Linux box to trust a self-signed certificate?



e.g. wget https://example.com - gives an error that certificate is untrusted as 'https://example.com' has a self-signed certificate; with wget '--no-check-certificate' can over-ride checking of the certificate. But I would like to get the Red Hat to implicitly trust the self-signed certificate - is there a way to do this?



Thanks.



Find the answer here

sql trigger inserting row into two tables

Programmer Question

I was looking for a way to create a trigger that would insert the same row into two tables with the same values.



For example, a new row is inserted into pushNotificationQueue as soon as that is inserted, I would like that same exact row to be inserted into messages.



I tried this



CREATE TRIGGER add_to_messages
after insert on mbb_pushNotificationQueue
FOR EACH ROW
insert into mbb_messages select * from mbb_pushNotificationQueue


the only problem with that is that it goes through and adds entries that have already been previously added.



Find the answer here

File Downloader Componenet (Delphi) !

Programmer Question

Hi , i need a file downloader component for Delphi . may you help me ?



Find the answer here

How to manage different form contexts of same form element in single DOM tree

Programmer Question

Hi,



As my question title could be bit unclear to you (I tried best), following is what I'm exactly trying to do.



I'm having a form element (say a user_info form), where such form elements will be generated for different users by java script and displayed in different js tabs (example: dojo tabs).



once form elements are generated, later I need to react on user actions performed on different html elements defined inside user_info form. In this case I need to identify what is the context (in which user_info form element) in which user is working on. The simplest example would be how to retrieve form id of the form in which user actions are being performed.



According to my understanding, I can not simply retrieve from by form id, because now DOM tree contains duplicate form instances of the same from element. So, IS there anyway, I could identify form context based on the user actions on its input elements.



Thank You.



Find the answer here

Wednesday, December 22, 2010

php array code with regular expressions

Programmer Question

there are few mistakes which it is showing as



Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in array 4,9,10,11,12... can anyone resolve them






Find the answer here

how to determine if forum has new posts

Programmer Question

Hey, i am coding a small php forum from scratch and would like to show readers what posts he hasnt read yet and what forum categories have unread posts since this visit, pretty much how phpbb or invision boards work.



How do i approach this, cookies? phpbb doesnt seem to use cookies for this, not very a good idea do have a cookie for each post... maybe use css visited attribute? but i dont see how would that work if a new post pops up.



Thanks.



Find the answer here

How to properly pass address to google geocoding service

Programmer Question

I'm getting some problems trying Google Geocoding service when using special characters like "�" or letters with accents.



Whenever I try something like:
"barcelona, n� 10"



I get 0 results. But trying:
"barcelona n 10"



I get results...



I suspect is something related with encoding.
I tried this:



geocoder.geocode({'address': encodeURI( $('#direction').val() )}, function(){} );


But didn't help.



Any Idea?



Find the answer here

Clojure Protocols vs Scala Structural Types

Programmer Question

After watching the interview with Rich Hickey on Protocols in Clojure 1.2, and knowing very little about Clojure, I have some questions on Clojure Protocols:




  • Are they intended to do the same thing as Structural Types in Scala? What benefits do Protocols have over Structural Types (performance, flexibility, code clarity, etc.)? Are they implemented through reflections?

  • Questions on interoperability with Scala: Can Protocols be used instead of Structural Types in Scala? Can they be extended (if 'extension' term can be applied to Protocols) in Scala?



Find the answer here

Update View at runtime in Android

Programmer Question

The example is pretty straightforward: i want to let the user know about what the app is doing by just showing a text (canvas.drawText()). Then, my first message appears, but not the other ones. I mean, i have a "setText" method but it doesn't updates.



onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(splash); // splash is the view class
loadResources();
splash.setText("this");
boundWebService();
splash.setText("that"):
etc();
splash.setText("so on");
}


The view's text drawing works by doing just a drawText in onDraw();, so setText changes the text but doesn't show it.



Someone recommended me replacing the view with a SurfaceView, but it would be alot of trouble for just a couple of updates, SO... how the heck can i update the view dinamically at runtime?



It should be quite simple, just showing a text for say 2 seconds and then the main thread doing his stuff and then updating the text...



Thanks!



Update:



I tried implementing handler.onPost(), but is the same story all over again. Let me put you the code:



package coda.tvt;



import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;



public class ThreadViewTestActivity extends Activity {

Thread t;
Splash splash;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

splash = new Splash(this);
t = new Thread(splash);
t.start();

splash.setTextow("OA");
try { Thread.sleep(4000); } catch (InterruptedException e) { }
splash.setTextow("LALA");
}
}


And:



public class Splash implements Runnable {

Activity activity;
final Handler myHandler = new Handler();

public Splash(Activity activity) {
this.activity=activity;
}

@Override
public void run() {
// TODO Auto-generated method stub

}

public synchronized void setTextow(final String textow) {
// Wrap DownloadTask into another Runnable to track the statistics
myHandler.post(new Runnable() {
@Override
public void run() {
TextView t = (TextView)activity.findViewById(R.id.testo);
t.setText(textow);
t.invalidate();
}
});
}
}


Although splash is in other thread, i put a sleep on the main thread, i use the handler to manage UI and everything, it doesn't changes a thing, it only shows the last update.



Find the answer here

Thursday, December 16, 2010

Is it possible to unit test a static library project using XCode's SenTestingKit?

Programmer Question

I've created an iOS unit test target for doing logic tests following the steps provided in Apple's documentation.



However my build fails and i get the following error:




Undefined symbols:

"_OBJC_CLASS_$_MyClass",
referenced from:
objc-class-ref-to-MyClass in LogicTests.o ld: symbol(s) not
found collect2: ld returned 1 exit
status




Ordinarily, if I wanted to use my static library within an application I would include the library.a file, and the headers(including the MyClass.h file...). Is something additional required to run logic tests on a static library WITHIN that same project if my test cases are utilizing MyClass.h ?



Tjhanks



Find the answer here

Wednesday, December 15, 2010

Alternatives to Lua as an embedded language?

Programmer Question

I am working on an embedded system running Linux on a DSP. Now we want to make some parts of it scriptable and we are looking for a nice embeddable scripting language. These scripts should integrate nicely with our existing C++ code base, be small and fast.



I understand that Lua is the industry choice for problems like this. We will probably go with Lua because it is tried-and-true and proven to be stable and so on. However, as a programming language it has some rather quirky corners.



So, what alternatives are out there for embeddable languages?



Find the answer here

HTTPS github access

Programmer Question

I'm stuck behind a firewall so have to use https to access my github repository. It's a new one I'm creating & am using cygwin 1.7.7 on XP.
I've tried setting the remote to https://oharab@github.com/oharab/ExcelANT.git, but pushing prompts for a password, but doesn't do anything once I've entered it.
https://oharab:github.com/oharab/ExcelANT.git and cloning the empty repo from scratch but each time it gives me the same error
error: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed while accessing https://github.com/oharab/ExcelANT.git/info/refs



Turning on GIT_CURL_VERBOSE=1 gives me



* About to connect() to github.com port 443 (#0)
* Trying 207.97.227.239... * successfully set certificate verify locations:
* CAfile: none
CApath: /usr/ssl/certs
* SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
* Expire cleared
* Closing connection #0
* About to connect() to github.com port 443 (#0)
* Trying 207.97.227.239... * successfully set certificate verify locations:
* CAfile: none
CApath: /usr/ssl/certs
* SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
* Expire cleared
* Closing connection #0
error: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed while accessing https://github.com/oharab/ExcelANT.git/info/refs

fatal: HTTP request failed


Is this a problem with my firewall, cygwin or what?



Ben



Posted too soon!



I hadn't set the http proxy in the git config, however it's an ISA server that needs NTLM authentication, not basic, so unless anyone knows how to force git to use NTLM, I'm scuppered!
B.



Find the answer here

Problem minimizing function in Matlab (fmincon)

Programmer Question

Hi everyone,



I have a function which calculates the acoustic strength of a fish depending on the incident angle of the wavefront on the fish. I also have some in situ measurements of acoustic strength. What I'm trying to do is figure out which normal distribution of angles results in the model data matching up most closely with the in situ data.



To do this, I'm trying to use the Matlab function fmincon to minimize the following function:



function f = myfun(x)

TS_krm = KRM(normrnd(x(1),x(2),100,1), L);
f = sum((TS_insitu - TS_krm).^2);


So what this function does is calculates the sum of squared residuals, which I want to minimize. To do this, I try using fmincon:



x = fmincon(@myfun, [65;8], [], [], [], [], [0;0], [90;20], [], options);


Thus, I'm using a starting orientation with a mean of 65 degrees and a standard deviation of 8. I'm also setting the mean angle bounds to be from 0 to 90 degrees and the standard deviation bounds to be from 0 to 20 degrees.



Yet it doesn't seem to be properly finding the mean and standard deviation angles which minimize the function. Usually it outputs something right around N(65,8), almost like it isn't really trying many other values far from the starting points.



Any ideas on what I can do to make this work? I know I can set the TolX and TolFun settings, but I'm not really sure what those do and what effect they'd have. If it helps, the typical values that I'm dealing with are usually around -45 dB.



Thanks!



Find the answer here

How to add category prefix to log4net message?

Programmer Question

I like to add category prefix to all the messages on the existing logging messages. However it is tedious to add this prefix to all the existing logging messages one by one. Is there a way in I can just add an attribute to the class level then all the messages in this class will be logged for certain category?



Instead of the way right now as below,



Log.Info("[Ref] Level 1 Starts ...");


I really want to something like this or a different way to define the log4net.ILog.



[LoggingCategory("Ref")]
public class MyClass
{
public void MyMethod()
{
Log.Info("Level 1 Starts ...");
}
}


Find the answer here

How Sum Groups and provide totals in separate columns?

Programmer Question

I have beek looking at this problem for a while and while i know i could do this programiticly in LINQ. I started thinking about solutions that would scale if this were a vary large data set. I'm building my experieance with SQL and believe there is a way to get the result with out performing an insert.



What I have is data that looks like this:



ids type    total
A01 x 1
A01 x 2
A01 x 3
A01 y 4
B01 y 2
B01 x 3
B01 y 1
C01 x 1
C01 y 2
C01 x 5
C01 y 6


What I want is data that looks like this:



id  x total y total
A01 6 4
B01 3 3
C01 6 8


I's my belief incorrect?



Find the answer here

Tuesday, December 14, 2010

Measure distance from an iPhone to an Object using proximity sensor

Programmer Question

I have read many Forums on this topic but I still haven't found an exact answer. Is the iPhone's proximity sensor only a trigger that turns the display on or off or can one get a distance from the sensor to an object?



Thank you!



Find the answer here

Looking at Sorts - Quicksort Iterative?

Programmer Question

I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up.
I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?



Find the answer here

Method overload resolution unexpected behavior

Programmer Question

I'm wrestling with a weird, at least for me, method overloading resolution of .net. I've written a small sample to reproduce the issue:



class Program
{
static void Main(string[] args)
{
var test = new OverloadTest();
test.Execute(0);
test.Execute(1);

Console.ReadLine();
}
}

public class OverloadTest
{
public void Execute(object value)
{
Console.WriteLine("object overload: {0}", value);
}

public void Execute(MyEnum value)
{
Console.WriteLine("enum overload: {0}", value);
}
}

public enum MyEnum
{
First = 1, Second = 2, Third = 3
}


Will print:



enum overload: 0
object overload: 1


Basically the overload called is different depending on the value (0, 1) instead of the given data type.



Could someone explain?



Update



I should have pointed out that there's a different behaviour between C# 2 and C# 3



Do((long)0) => object overload //C# 2
Do((long)0) => enum overload //C# 3


Find the answer here

Android Developing - Slow Intenet Connectionvia 3G

Programmer Question

Hello,



i'm developing a Client/Server Application with Android/Rails and Communication via REST Json



When i'm testing my App via Emulator, all works fine.
Also when i deploy the app on my phone with WIFI on it works and the speed is ok.



But when i disconnect from WIFI and use the 3G connection, the phone becomes incredible Slow and it takes Minutes du get one JSON Response from the Server.



I'ved debug a little bit and the Problem seems to be the HTTPClient, which execute Method takes ulta long.



Any Suggestions what to do?



HTC Magic 
Android 1.6


Regards



Find the answer here

ASP.NET MVC: Use action to generate dynamic sitemap.xml bad?

Programmer Question

I want to add/remove urls to sitemaps whenever a user deletes or submits information.



I have a few questions:




  1. Should I put slugs on the URL in the sitemap? Products/Details/1/my-slug -> URL works without slug.

  2. Should I Use an action to generate a sitemap? In robots.txt I'll link to this action.

  3. If not action, are there libraries that allow me to easily edit sitemap.xml files?

  4. Sitemaps has a limit to the # of URLs and size, is there a way to automatically create more sitemaps when this limit is met? I'd have to also update the robots.txt and add more links to sitemaps.



Find the answer here

Monday, December 13, 2010

iPhone- Draw on map and and search by or get coordinates from graphic

Programmer Question

I have an app that uses mapkit and I have the annotations and everything going.

I would like some functionality that allows the users to draw, either freehand or draw out a box, on the map. After the user creates this graphic (for lack of a better term) i would like to query my annotations for those that intersect with this graphic. If this is inherent or easy to do great, otherwise if i can get the geometry of the graphic and can do searching with the min/max x/y through coordinates i have stored in a db.
I have looked into openGL/ GLPaint but cannot quite connect the dots (so to speak).
Thanks.



Find the answer here

TinyMCE clearing changes on form submit

Programmer Question

I've added a toggle button to TinyMCE (using the jQuery plugin version) that looks like:



        $('a.mce_show').click(function(){
// toggle all textareas
$('.wysiwyg').tinymce().show();
});

$('a.mce_hide').click(function(){
// toggle all textareas
$('.wysiwyg').tinymce().hide();
});


The problem is if you hide the editor, make a change and click 'submit' it'll discard the change. If you hide the editor, make a change, show the editor then click submit it'll be fine.



How do I get it to submit properly without having to re-show the editor?



Find the answer here

dtd and mixed content

Programmer Question

Hi all,



Does someone know way a mixet content element (in dtd) there is a need to add the "*" at the end?



For example:



I know that if I drop the "*" in the end of the decleration I will get a bad DTD decleration...
But - I have no idea what is the reason of that...



Anyone know why?



Find the answer here

EF4: LINQ 2 Entities query works in C# but not in VB

Programmer Question

[EDITED: I left the original question below, with some more context and code to reproduce the problem. The short version below contains the essence of the question]



Short version: the query below throws a System.NotSupportedException: "Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types." The exception is only raised in the VB.Net version. When translated to C#, no exception is raised.



   Dim doesThisCrash = From outerOrder In orders
Where outerOrder.ProductId =
(From p In products Join o In orders On p.Id Equals o.ProductId
Order By p.Id
Select p.Id).FirstOrDefault()
Select outerOrder
doesThisCrash.ToList()


So, to make it crash, it seems that we need a subquery where the original ObjectSet (orders) is joined with another ObjectSet (products), and ordered. When using just the orders or the products set, no crash occurs. When leaving out the Order By, also no crash.



I'm inclined to think this is a (VB.Net) compiler bug, unless there is something obvious that I'm overlooking here...



For now my question still stands:




  • why does a seemingly exact same query work in C# but not in VB?

  • can this query be made to work in VB.Net?



[/EDIT]



Optional, longer version (original question):



My domain looks very different, but I translated the problem to a simpler version, with the following entities (note: I actually defined these using the .edmx designer, so this is a simplified version):



    public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
}

public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int ProductId { get; set; }
public DateTime OrderDate { get; set; }
}

public class Customer
{
public int Id { get; set; }
}


I'm trying to work out a linq-to-entities query that should strucurally look like this, in VB.Net:



    Dim db = New SampleEntities()
Dim orders As IQueryable(Of Order) = db.Orders
Dim products As IQueryable(Of Product) = db.Products
Dim currentDate = DateTime.Now

Dim qLinq = From outerOrder In orders
Where outerOrder.OrderDate = currentDate AndAlso
outerOrder.ProductId =
(From p In products Join o In orders On p.Id Equals o.ProductId
Where o.OrderDate = outerOrder.OrderDate AndAlso
outerOrder.CustomerId = o.CustomerId
Order By p.DateCreated
Select p.Id).FirstOrDefault()
Select outerOrder


This raises a System.NotSupportedException:



"Unable to cast the type 'System.Linq.IOrderedQueryable1' to type 'System.Linq.IQueryable1'. LINQ to Entities only supports casting Entity Data Model primitive types."



When leaving out the 'Order By' part, no exception is raised.



I don't really see a reason why this query would not be supported... So I decided to try the same thing in C#:



var qLinq = from oOut in orders
where oOut.OrderDate == currentDate
&& oOut.ProductId ==
(from p in products join o in orders on p.Id equals o.ProductId
where oOut.OrderDate == o.OrderDate
&& oOut.CustomerId == o.CustomerId
orderby p.DateCreated
select p.Id).FirstOrDefault()
select oOut;


To my surprise, this works! Then I translated the C# query to extension method syntax, and then back to VB, but got the same results (the C# version works, the VB.Net version raises the same exception).



So I guess my question is twofold:




  • why does a seemingly exact same query work in C# but not in VB?

  • can this query be made to work in VB.Net?



For reference, here are the queries in extension method syntax:



C# version:



        var q = orders.Where(outerOrder => 
outerOrder.OrderDate == currentDate &&
outerOrder.ProductId ==
(products
.Join(orders,
f => f.Id,
o => o.ProductId,
(f, o) => new { f, o })
.Where(t => t.o.OrderDate == outerOrder.OrderDate
&& outerOrder.CustomerId == t.o.CustomerId)
.OrderByDescending(t => t.f.DateCreated)
.Select(t => t.f.Id))
.FirstOrDefault());


VB.Net version:



    Dim q = orders.Where(Function(outerOrder) outerOrder.OrderDate = currentDate AndAlso
outerOrder.ProductId = (products.Join(orders,
Function(p) p.Id,
Function(o) o.ProductId,
Function(p, o) New With {.p = p, .o = o}).
Where(Function(x) x.o.OrderDate = outerOrder.OrderDate AndAlso
outerOrder.CustomerId = x.o.CustomerId).
OrderByDescending(Function(x) x.p.DateCreated).
Select(Function(x) x.p.Id).
FirstOrDefault()))


Find the answer here

Options for MySQL entity-relationship diagrams for data models?

Programmer Question

On Windows, and reviewing options for viewing (and possibly printing) MySQL entity-relationship diagrams. So far I've reviewed the following





Toad for MySQL is my choice currently because it lines up the relationship to the columns, and the auto-align semi-works.



Have any other suggestions, the tool does not have to be "free" but it doesn't hurt either.



Find the answer here

Sunday, December 12, 2010

parse mysql error code - is it the right way?

Programmer Question

In my php/MySQL code I insert new record into a table (InnoDB) which has many UNIQUE column keys. If insertion fails (with ER_DUP_ENTRY) I need to know which column's value wasn't unique.



I was told that to achieve this, you must extract value of %d from error message you get:
"Duplicate entry '%s' for key %d".



This should work but I don't like the solution. Parsing/regex matching some string gives unnecessary complexity to simple task I always try to avoid. Now the question: is this the right way to go? Isn't there any better solution?



Find the answer here

bash: run a command for n minutes, then SIGHUP it

Programmer Question

Is there any bash/linux command to launch a long-running command, then kill it after n minutes? I guess I could hack something up with perl using fork and kill, but does anyone know of something already out there?



Find the answer here

Saturday, December 11, 2010

Positioning problems on image hover?

Programmer Question

I've created a gallery so that various images are ordered into columns. The images are links to iframes so when they are clicked, a web page is loaded describing the image. One feature of the gallery that I'd like to integrate is when the user hovers over the image, the name of the image appears. I have this almost working except there is one flaw. The name of the image appears at the bottom right of the containing div, not the bottom right of the image. How can I fix this? Here is the web page: http://www.givetoagiver.co.cc/gallery.php
and here is the style sheet:
http://www.givetoagiver.co.cc/style.css
Thank you



Find the answer here

Really simple question about creating non-standard sized byte groups

Programmer Question

So for a project that space really matters in, I'd like to be able to write to a file a number which takes up THREE bytes. So essentially, an unsigned type where 16,777,215 is the highest possible number.



The number is given as an unsigned int, and I've already checked to ensure it's between 0 and 16,777,215. How do I go beyond that?



Code in Java is preferred, but ANSI C works too. Thanks!



Find the answer here

Sometimes my jQuery accordian jumps a line

Programmer Question

I found this tutorial



http://designreviver.com/tutorials/jquery-examples-horizontal-accordion/



and made this lovely menu



http://cfdp.dk/frontend/



but sometimes it jumps a line anyone know why?



Find the answer here

using NSPredicate with a set of answers

Programmer Question

I have a set of strings containing personIDs and I have a NSFetchedResults of people managedObjects with unique strPersonIDs. I tried to create an NSPredicate but it fails. Any help with this would be greatly appreciated. I'm a bit new to NSPredicate so be kind.



NSSet *zipSet = [NSSet setWithSet:[self getziplist:searchText]];
searchString = [NSString stringWithFormat:@"(strPersonID IN %@)",zipSet];
NSPredicate *searchPersonPredicate = [NSPredicate predicateWithFormat:searchString];


The runtime error message is: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(strPersonID IN {(
300040,
300082,
412218
)})"'



Find the answer here

Multimedia Qustion Answering algorithms and methods?

Programmer Question

Hi



I am doing some research on Multimedia Question Answering Systems and the latest methods and ways in which such a system can be made in the hope making a simple MQA system my self?



Thanks



Find the answer here

Tuesday, December 7, 2010

find path of a key in a multi-dimensional tree-like array

Programmer Question

hey, I have this array (the actual array can be several level deeps and spans a tree-structure)



array
3 =>
array
4 =>
array
7 => null
8 => null
5 => null
6 => null


Now, e.g. I want the path to key 7, it can be shown like this:



array
0 => int 7
1 => int 4
2 => int 3


Can someone help me with such a recursion function?
I am able to get:



array
0 => int 7
1 => int 4


using:



function tree_path($key,$tree,&$path=null) {
if(!is_array($path)) $path = array();
if(is_array($tree)) {
if (!array_key_exists($key,$tree)) {
foreach ($tree as $id=>$child) {
$found = tree_path($key,$child,$path);
if($found) $path[] = $id;
}
} else {$path[] = $key; return true; }
}
}


Oh. I recently saw the use of passing-by-reference in foreach loop. Can something like that be added here?



Find the answer here

Monday, December 6, 2010

Why aren't there that many modern day design pattern books?

Programmer Question

And does it matter? I saw very few on Amazon that were new. Most of the design pattern books were about three years old, tops. Maybe that's not too terribly old but many others were from around 2002, 04, etc. It just doesn't seem to be too hot a topic. Have we discovered all we can about design patterns?



Find the answer here

Word Automation - File is in use by another application or user.

Programmer Question

I have a WinForms application where I am using Word Automation to build documents via a template, and then save them to the database. After the document is created, I retrieve the document from the database, write it to the file system in a temp directory, and then open the document using the Word Interop services.



There is a list of documents loaded and the user can open only 1 instance of each document, but can open multiple different documents simultaneously. I don't have any problems with opening, saving, and closing when they open 1 document, however, when they open multiple documents simultaneously, I get the following error when closing any of my instances of Word:



The file is in use by another application or user. (C:\...\Templates\Normal.dotm) 
This error is commonly encountered when a read lock is set on the file that you are attempting to open.


I am using the following code to open the document and handle the BeforeDocumentClosed event:



public void OpenDocument(string filePath, Protocol protocol, string docTitle, byte[] document)
{
_protocol = protocol;
documentTitle = docTitle;
_path = filePath;

if (!_wordDocuments.ContainsKey(_path))
{
FileUtility.WriteToFileSystem(filePath, document);

Word.Application wordApplication = new Word.Application();
wordApplication.DocumentBeforeClose += WordApplicationDocumentBeforeClose;

wordApplication.Documents.Open(_path);

_wordDocuments.Add(_path, wordApplication);
}
_wordApplication = _wordDocuments[_path];
_currentWordDocument = _wordApplication.ActiveDocument;

ShowWordApplication();
}

public void ShowWordApplication()
{
if (_wordApplication != null)
{
_wordApplication.Visible = true;
_wordApplication.Activate();
_wordApplication.ActiveWindow.SetFocus();
}
}

private void WordApplicationDocumentBeforeClose(Document doc, ref bool cancel)
{
if (!_currentWordDocument.Saved)
{
DialogResult dr = MessageHandler.ShowConfirmationYnc(String.Format(Strings.DocumentNotSavedMsg, _documentTitle), Strings.DocumentNotSavedCaption);

switch (dr)
{
case DialogResult.Yes:
SaveDocument(_path);
break;
case DialogResult.Cancel:
cancel = true;
return;
}
}

try
{
if (_currentWordDocument != null)
_currentWordDocument.Close();
}
finally
{
Cleanup();
}
}

public void Cleanup()
{
if (_currentWordDocument != null)
while(Marshal.ReleaseComObject(_currentWordDocument) > 0);

if (_wordApplication != null)
{
_wordApplication.Quit();
while (Marshal.ReleaseComObject(_wordApplication) > 0);
_wordDocuments.Remove(_path);
}
}


Does anyone see anything wrong that I am doing to allow opening of multiple documents at the same time? I am fairly new to Word Automation and the Word Interop services, so any advice is appreciated. Thanks.



Find the answer here

Sunday, December 5, 2010

How to draw an arc between two images in WinForms?

Programmer Question

Hey.



I have to do this: to draw an arc between two images from my canvas, so when I click the button with the arc on it and I put click on one image to paste the arc on it and then to draw the arc as long as i need and to paste it to the second image.



Good Day.



Find the answer here

Domain driven programming and events

Programmer Question

I'm doing some asp.net mvc coding using DDD. I have objects representing the business entities and service repositories that handle fetching and adding them. I'm new to this and as my application grows I begin to see a lot of secondary code that must run as a result of adding, deleting or changing my domain objects/data.



I'd like to make an event driven system where one action triggers other parts of code to run. For instance when I delete a user I want to be able to subscribe a number of other things to this action so they all are run when a delete takes place.



How have you coded your applications to handle these situations? How can I establish a reliable and coherent OO system for my problem? I already know about events and delegates but I'm more interested in coding techniques and nice practices.



Find the answer here

How do you make layouts for several Android screen sizes?

Programmer Question

I've done some research on building layouts that work for multiple screen sizes and I'm looking for some clarification.



Is it common practice to just make a separate layout file for each of the three screen sizes (small, medium, large) or can you accomplish this with an easier method?



I've been testing my projects on a large screen device, and even though I use DIPs (density independent pixels) for padding, margins, etc, it still scrunches stuff up when I view it on smaller screens. Should I be designing my projects for medium-sized screens and then just allow Android to scale it appropriately?



I'm not sure if this is a good question or not, but I am looking for what the common practice is for designing for multiple screen sizes. What do you do?



Edit: In addition to this, for example, let's say I have a button that is 40dip above the bottom of the screen, should I literally write 40dip, or should I be using some sort of pixel math like 40 * screenWidth / blahblah or something so that it scales depending on the screen size the user has? I have limited experience with UIs...



Find the answer here

PKG_CHECK_MODULES for somelib++

Programmer Question

I am trying to make my autotools project in C++ link against library, that originates as C library (libsomelib.so), but also has bindings to c++ (libsomelib++.so). I ma trying to use PKG_CHECK_MODULES to check if this package is installed, and use autotools to link against it. However both libs come in one package (c++ version requires configure flag), and have only one .pc file, in which independently of configuration settings there is only line



Libs: -L${libdir} -lsomelib


without any mentioning of ++ version. There is also no separate ++.pc file that i noticed at other programs. Therefore automatic linking against ++ version is impossible. I thought about manually adding -lsomelib++ to linking flags, but that's rather ugly (and it will not work if somebody compiled it without --with-cxx flag). I could also test for it's existence by AC_SEARCH_LIBS, but since it's C++ library it's not so straightforward.



Is missing ++.pc file mistake of package distributor or is it some deeper idea, and i don't know how to use it?



If somebody is really qurious i will say that package in question is ossp-uuid.



Find the answer here

MS SQL to produce XMl data rows from JOINed select statement

Programmer Question

I have a three tables in SQL server 2008 which are setup as follows:



EMPLOYEE TABLE



empid(PK)
1
2



joined to EMPLOYEEATTRIBUTES



dataId(PK) | empId(FK) | attributeid | attributeVal
10 | 1 | A1 | somevalue1
20 | 1 | A2 | somevalue2
30 | 2 | A1 | somevalue3
40 | 2 | A3 | somevalue4



joined to ATTRIBUTES



attributeid | attributeName
A1 | attribute1
A2 | attribute2
A3 | attribute3



I need to get the xml data out into the following format





somevalue1
somevalue2


somevalue3
somevalue4



Anyone know how this can be done??



Find the answer here

Friday, December 3, 2010

Is it safe to assume a server would have PHP 5?

Programmer Question

I've been learning up on PHP, and a lot of the time in the books and tutorials I read, features come up as having been introduced in PHP 5. I don't know anything about PHP history, so I don't know if I can safely use these features on most servers. I know in Python, adoption of new versions is very slow (few apps use 3.x, most desktops have 2.6, many server distros like Red Hat have versions as early as 2.4).



Is there a similar situation in the PHP ecosystem? My server has version 5.2, but are some servers still running PHP 4? What version of PHP can I safely assume a server would run?



Find the answer here

Word Wrap in Net Beans

Programmer Question

I'm just learning to code in java. Netbeans is great but I just found there's no way to wrap text in it (or hopefully I haven't found it yet). Is there any way to do this, and if not, is there any similarly good IDE for Java with this functionality (hopefully free as well).



Thanks.



Find the answer here

Notification messages in GWT

Programmer Question

Do you know a JavaScript library or a GWT module which presents styled notification messages (e.g. info, warning and error messages) as does in Vaadin framework or similar to the Growl component in primefaces?



Find the answer here

Can I make use of MySQL's completion hash in Vim?

Programmer Question

In the mysql client, \# rebuilds the completion hash for autocompleting your command, while \e opens editor $EDITOR to edit your command.



Is there any way of making use of the completion hash in the invoked editor (Vim in my case)?



Thanks.



Find the answer here

PHP input sanitizer function?

Programmer Question

What's a method to sanitize PHP POST data for passing to a mail function? (I prefer a method that's not part of the mysql_function() family of functions.)



I take the data, sanitize it, print it back to the user and send it in an email to a preset address.



Find the answer here

Thursday, December 2, 2010

Entity Data Model with Oracle

Programmer Question

Hi, I'm using VS 2008 SP1. I want to create an edmx file using my existing database in Oracle 10g. I tried to add ADO.Net Entity Data Model item, but in the Entity Data Model Wizard, .NET Provider for Oracle does not show up. Can someone suggest a way to connect to existing Oracle database to generate the edmx file? Thanks.



Find the answer here

MVC Advantages of Unit Testing Controllers

Programmer Question

hi guys



My application already has unit test for domain layer I would like to know what are the pros/cons of unit testing controller



and what test cases should one write when testing controllers.



Thanks



Find the answer here

Wednesday, December 1, 2010

What is this in rails?

Programmer Question

    create! do |success, failure|      
success.html { redirect_to admin_blogs_path }
end


Seems to be doing alot but where is it....is it part of rails



Find the answer here

Small Javascript question involving null and delete() in regards to garbage collection...

Programmer Question

Quite the title.



Anyhow, If I were to write something like:



var h = 5;  
delete h;


...I'd be eliminating the reference, but not the memory.

Now, if I set the variable to null, would that replace the memory with the null object?



var h = 5;  
h = null;


If so, wouldn't it be better to not only delete() the reference, but also replace the memory with a null object, for better memory optimization?



var h = 5;  
h = null;
delete h;


If I want to create a buckload of dynamic objects in a long and complex script, what's the best way to get rid of, or otherwise induce the garbage collector to eliminate, objects? Because in addition to just eliminating references, I had read that you could hint the collector to free memory if it was occupied by null...



Find the answer here

iPhone's mail "To" field.. is that a UITextField or a UITextView?

Programmer Question

Hey folks,



I am trying to replicate the iPhone mail box in my app. I was wondering if the "To" field they are using in the app is a TextField or a TextView. If yes, they are adding multiple lines for the recipient names.. guidance from any one who has worked on it before would be helpful..



Find the answer here

LinkWithin

Related Posts with Thumbnails