Wednesday, May 23, 2012

data source configuration wizard issue Could not get column information for database object named

I'm using Visual Studio 2010 and connecting to MySQL database through MySqlODBC 5.1 driver. The page is a reporting page (I'm using crystal report and devexpresss reporting tool).



I have successfully tested the ODBC connection to my MYSQL database using Data source Configuration wizard, and after creating connectionString I can see my database objects , i.e. Tables , Stored procedures, but when I select any table , it do not expand to show me columns and when i click on finish it gives me data source configuration wizard error message,



<tyrepro..vendor>
Could not get column information for database object named 'tyrepro..vendor'



*vendor is table name here.



I tried connecting to system database and select table , but got same issue.





not-read-only DataGridView, but don't show input in datagridview after leaving, only show programmatical input

In my DataGridView users are able to input data. The DataGridView automatically changes its content when one of the properties of a correspondent list of objects changes with the help of events.



Now I want to give the DataGridView the following behavior: when the user inserts data, and then leaves the cell, the input should be validated. If the validation gives a positive result, the input is saved to an object. The datagridview should then show the input value in the correct format (eg. for a date).



I can make this work: the events between the list of objects and the datagridview can manage this.



The problem is: If the validation gives a negative result, the previous cell value should be restored.



I tried to use DataGridView.CellValidating event, but this doesn't work. What should I do?



SOLVED: I used e.Cancel. This doesn't really do what I thought it promissed. When I use DataGridView1.CancelEdit(), it works like I wanted.





gunicorn + zope error handling

we are trying to setup gunicorn + plone. It works well so far, but fails to handle errors (404, 500 etc) and throws 'Internal Server Error' while it should return plone's error page.



Example case of requesting a page that doesn't exist is pasted below. The question is how should gunicorn be setup so that errors are handled themselves by zope/plone, as other requests?



Cheers and regards



==> var/log/gunicorn-stdout---supervisor-JhaTfg.log <==
2012-05-24 01:41:16 [15137] [ERROR] Error handling request
Traceback (most recent call last):
File "/home/user/testing/eggs/gunicorn-0.14.3-py2.6.egg/gunicorn/workers/sync.py", line 100, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "/home/user/testing/eggs/repoze.retry-1.0-py2.6.egg/repoze/retry/__init__.py", line 90, in __call__
app_iter = self.application(environ, replace_start_response)
File "/home/user/testing/eggs/repoze.tm2-1.0b2-py2.6.egg/repoze/tm/__init__.py", line 24, in __call__
result = self.application(environ, save_status_and_headers)
File "/home/user/testing/eggs/repoze.vhm-0.14-py2.6.egg/repoze/vhm/middleware.py", line 106, in __call__
return self.application(environ, start_response)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/WSGIPublisher.py", line 255, in publish_module
response = _publish(request, 'Zope2')
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/WSGIPublisher.py", line 185, in publish
object = request.traverse(path, validated_hook=validated_hook)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/BaseRequest.py", line 518, in traverse
return response.notFoundError(URL)
File "/home/user/testing/eggs/Zope2-2.13.13-py2.6.egg/ZPublisher/HTTPResponse.py", line 718, in notFoundError
"<p><b>Resource:</b> %s</p>" % escape(entry))
NotFound: <h2>Site Error</h2>
<p>An error was encountered while publishing this resource.
</p>




Using the login Details via Application

I have a CURL(in C++) to send my user and pass to remauth.php file so i think i do something wrong on remuth.php ( because i am basic in php and my program can not run because the auth not passed.)
I use login via Application.



my CURL:



bool Auth_PerformSessionLogin(const char* username, const char* password)
{
curl_global_init(CURL_GLOBAL_ALL);

CURL* curl = curl_easy_init();

if (curl)
{
char url[255];
_snprintf(url, sizeof(url), "http://%s/remauth.php", "SITEADDRESS.com");

char buf[8192] = {0};
char postBuf[8192];
_snprintf(postBuf, sizeof(postBuf), "%s&&%s", username, password);

curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, AuthDataReceived);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&buf);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "IW4M");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBuf);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

CURLcode code = curl_easy_perform(curl);
curl_easy_cleanup(curl);

curl_global_cleanup();

if (code == CURLE_OK)
{
return Auth_ParseResultBuffer(buf);

}
else
{
Auth_Error(va("Could not reach the SITEADDRESS.comt server. Error code from CURL: %x.", code));

}

return false;
}

curl_global_cleanup();
return false;
}


and my remauth.php:



<?php
ob_start();
$host=""; // Host name
$dbusername=""; // Mysql username
$dbpassword=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$dbusername", "$dbpassword") or die(mysql_error());
mysql_select_db("$db_name") or die(mysql_error());

// Define $username and $password
//$username=$username;
//$password=md5($_POST['password']);
//$password=$password;

$username=$_POST['username'];
$password=$_POST['password'];
//$post_item[]='action='.$_POST['submit'];


// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM $tbl_name WHERE username='$username'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
$row = mysql_fetch_assoc($result);
if (md5(md5($row['salt']).md5($password)) == $row['password']){
session_register("username");
session_register("password");
echo "#";
return true;
}
else {
echo "o";
return false;
}
}
else{
echo "o";
return false;
}
ob_end_flush();
?>


///////////////////////////////////





Exception when trying to parse JSON from a MySQL query

I'm having a problem parsing the JSON response from MySQL in Java.



try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://parkfinder.zxq.net/default.php");
httppost.setEntity(new UrlEncodedFormEntity(coordinatesToSend));
HttpResponse response = httpclient.execute(httppost);
Log.d("HTTP Client", "HTTP Request made");

HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,
"iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(bufferedReader.readLine() + "\n");

String line = "0";
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
bufferedReader.close();
result = sb.toString();
Log.d("RESULT", result);
JSONObject json_data = new JSONObject(result);
Log.d("JSON","Finished");
JSONArray nameArray = json_data.names();
JSONArray valArray = json_data.toJSONArray(nameArray);
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}
for (int i = 0; i < nameArray.length(); i++) {
Log.d("NAMES", nameArray.getString(i));
}

} catch (Exception e) {
// TODO: handle exception
}


This is the MySQL Accessing and retreiving info, and parsing it afterwars.
the



Log.d("RESULT", result);


line posts the correct results:



2[{"longtitude":"32.32","latitude":"33.12"}]


however the



Log.d("JSON","Finished");


Never gets called,
so the problem seems to be on this line



JSONObject json_data = new JSONObject(result);


This while thing is taken from a tutorial which I saw many examples of it over the internet and on this site, some stated errors, but not this one.



Any help would be great!
Thanks



EDIT:
The printStackTrace() output:



0`5-14 21:38:18.639: WARN/System.err(665): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of 2[{"longtitude":"32.32","latitude":"33.12"}]`


The php code:



<?php
$host = "localhost";
$user = "**MASKED**";
$password = "**MASKED**";
$database = "parkfinder_zxq_coordinates";
$connection = mysql_connect($host, $user, $password) or die("couldn't connect to server");
$db = mysql_select_db($database, $connection) or die("couldn't select database.");
//$request_parked = $_REQUEST['parked'];
$request_long = $_REQUEST['longtitude'];
$request_lat = $_REQUEST['latitude'];
//if ($request_parked == 'FIND') {
$q = mysql_query("SELECT * FROM Coordinates");
while ($e = mysql_fetch_assoc($q))
$output[] = $e;

print (json_encode($output));
//}

mysql_close();
?>




Read and Write Data to Excel without Installing Office

I am working on a WPF 4.0 application which uses the Microsoft Office Interop to read and write to Excel files. But I am facing a scenario where I need to read/write data from/to Excel files on systems that do not have Office installed.



This is somewhat a repeat of this question. The only reason I reposted this question because the earlier post was 3 years old and I just wanted to know if there is a better way available right now.



The requirement is that I need to write into and save the file as .xls/.xlsx formats and read from the same. I am supporting both the format using the Interop right now.




  • Buying a license is not an option.

  • Installing Excel is not an option.

  • Need to Support Read/Write from .xls/.xlsx formats.

  • Easy to Implement as I am a little behind schedule. Would not be able to give a lot of time on implementation.

  • Need a solution that is trustworthy and robust, meaning it should be something that you have used personally or have a good feedback about.

  • Would prefer a solution that can cater to both read/write and can support both .xls/.xlsx formats. If something like this doesn't exist, can use different solutions, but all the above points would apply to them individually.

  • Don't need suggestions, but more like guidance.



Please do not vote to close this question as duplicate as the other ones do not give a concrete solution. There are too many suggestions. I need a solution that you are confident about as this application goes into final build soon and if I do not get any robust solution to this, we might end up releasing as is.





android - one package replaces another

Android.
Eclipse.
Samsung S2
I have two apps I wrote.
Two different packages.
Both can be built and both run OK on the virtual and real device.
I want to leave both of them on the real device to play around with them for a couple of weeks.
Every time I install one, it replaces the other. Same happens whether I installing by running it from eclipse or by installing the APK straight on the phone.
The files have different names. The app names are different. I tried different package names. No luck.



What am I doing wrong?





Setting up an Outlook email programmatically in Windows

How would I go about this? What language would I need to use (Python preferred, as the rest of my installation script is in Python)? Something with access to the .NET libraries (VB.NET, C#, IronPython, maybe PyWin32) or COM? Or is there just some easy command-line trick?



I'm not against using a .NET library or COM object, but my knowledge of them is limited and I'm using standard Python (and don't know C# or VB, though I'm not against learning).



I'm talking about mostly Outlook 2007 and Outlook 2010. The more generic the better, because it'll be used for users who will be assigned both.





How can I calculate the level of a node in a perfect binary tree from its depth-first order index?

I have a perfect binary tree, i.e. each node in the tree is either a leaf node, or has two children, and all leaf nodes are on the same level. Each node has an index in depth-first order.



(E.g. in a tree with 3 levels the root node has index 0, the first child has 1, the first child of the first child has 2, the second child of the first child has 3, the second child has 4, the first child of the second child has 5, the second child of the second child has index 6.



      0
/ \
1 4
/ \ / \
2 3 5 6


)



I know the size of tree (number of nodes/maximum level), but only the index of a particular node, and I need to calculate its level (i.e. its distance to the rootnode). How do I do this most efficiently?





MVC3 EF app in Azure, why do I have to warm it up every once a while?

I am testing my MVC3 + EF app hosted in Azure. The problem I am having now is that every once a while, say 4-5 hours or a day, when I try to visit the page, it is very slow. It takes about 6-8 seconds to load, then the second load would be a lot faster. I have static content cahced, js at the bottom of the page. So I suspect this is because of warm up, but my question here is why do I have to warm it up once a while.



PS: my app is deployed in production environment, I haven't launched it, so it is only me and my team mate been visiting it so far, it has less then 10-20 page requests from us in day, mostly happen at night time.





Want to do Fruite Ninja like swipe on Sprite?

I am new in cocos2d iphone game development.



And now a days I am stucked at a point i want to do fruit ninja like swipe on a sprite and



want to perform a function after swipe at sprite.I done Googling but did not get solution.i need your kind help.
Thanks



 CCSprite *object=[CCSprite spriteWithFile:@"shield.png"];
[self addRecognizers:object];
[object setPosition:ccp(166,160)];
[self addChild:object];

//now function add recognizers
- (void) addRecognizers:(CCSprite*)node
{
UISwipeGestureRecognizer *swipeMe=[[[UISwipeGestureRecognizer alloc ]init] autorelease];
[swipeMe setDirection:UISwipeGestureRecognizerDirectionRight|UISwipeGestureRecognizerDirectionLeft|UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown];
recognizer = [CCGestureRecognizer CCRecognizerWithRecognizerTargetAction:swipeMe target:self action:@selector(blink:node:)];

[node addGestureRecognizer:recognizer];
}


This is the code i am using





Click Event with fadeToggle() - what is wrong with my code?

I created an interactive map of London using the <map> tag which has 15 <area> tags defined. Upon clicking on any of the 15 areas, the source of the map is replaced by another, according to the area which was clicked on. All the areas have an individual id and the source changes according to that id.



Clicking again on the area reverts the map image back to its original source.



The simplified HTML for this is a bit like so:



<IMG id="londonmap" SRC="images/londonmap.png" USEMAP="#london">
<map name="london">
<area id="dalston" href="#" shape="rect" coords="364,75,500,200"
alt="Dalston Tube Stop" title="Dalston Area">
</map>


The jQuery I used for clicking and unclicking looks as follows:



$(document).ready(function()
{
$('#dalston').click(function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});


Everything up to here works just fine. Now, I thought it would be nice, for just a bit of an extra effect to have the changing images .fadeToggle() when clicked for a smoother transition and as such changed to code to this:



$(document).ready(function()
{
$('#dalston').click(function() {
$('#londonmap').fadeToggle('slow', function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});
});


The problem now is that only half the code reacts as I expected - the original image fades out, but the second one never takes its place. I'm guessing it has something to do with the order in which the events happen, but being a bit of a noob in jQuery I can't really tell what's going wrong.



Any help would be much appreciated as this is the last thing stopping me from finishing the map!





Convert code in MS Access to SQL server

The following two functions, I would like to convert them from Access into SQL server, how can I moddify my code? Thank you so much. I never use SQL server before, and trying to learn it hard. LIS is a drive



Public Function PathDate(Ndate As Date) As Long
PathDate = (Year(Ndate) * 10000) + (Month(Ndate) * 100) + Day(Ndate)
End Function

Public Function NormalDate(LISDate As Long) As Date

If (LISDate = -1) Then
NormalDate = "-1"
Else
NormalDate = MonthName(LISDate \ 100 Mod 100) & " " & LISDate Mod 100 & " ," & LISDate \ 10000
End If
End Function




Renaming Key of Item in Collection with VBA in Excel

I have a collection as follows:



Set NodeColl = New Collection
NodeColl.Add "Node 1", "Node 1"
NodeColl.Add "Node 2", "Node 2"
NodeColl.Add "Node 3", "Node 3"


I am wondering if there is an easy way to rename the keys of selective items without affecting other items or the collection itself. For example, something like NodeColl.Items("Node 1").Key = "Some string"





Saxon in Java: XSLT for CSV to XML

Mostly continued from this question: XSLT: CSV (or Flat File, or Plain Text) to XML



So, I have an XSLT from here: http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html



And it converts a CSV file to an XML document. It does this when used with the following command on the command line:




java -jar saxon9he.jar -xsl:csv-to-xml.csv -it:main -o:output.xml




So now the question becomes: How do I do I do this in my Java code?



Right now I have code that looks like this:



TransformerFactory transformerFactory = TransformerFactory.newInstance();
StreamSource xsltSource = new StreamSource(new File("location/of/csv-to-xml.xsl"));
Transformer transformer = transformerFactory.newTransformer(xsltSource);
StringWriter stringWriter = new StringWriter();
transformer.transform(documentSource, new StreamResult(stringWriter));
String transformedDocument = stringWriter.toString().trim();


(The Transformer is an instance of net.sf.saxon.Controller.)



The trick on the command line is to specify "-it:main" to point right at the named template in the XSLT. This means you don't have to provide the source file with the "-s" flag.



The problem starts again on the Java side. Where/how would I specify this "-it:main"? Wouldn't doing so break other XSLT's that don't need that specified? Would I have to name every template in every XSLT file "main?" Given the method signature of Transformer.transform(), I have to specify the source file, so doesn't that defeat all the progress I've made in figuring this thing out?



Edit: I found the s9api hidden inside the saxon9he.jar, if anyone is looking for it.





jQuery convert data-* attributes to lower cammel case properties

I have the following jQuery script to intialise a jQuery plugin called poshytips. I want configure the plugin using Html5 data attributes. I am repeating myself big time, can anyone come up with a better way to do this?



$('.poshytip-trigger').each(function (index) {
var $this = $(this);
var data = $this.data();

var options = {};

if (data['class-name']) {
options.className = data['class-name'];
}

if (data['align-x']) {
options.alignX = data['align-x'];
}

if (data['align-y']) {
options.alignY = data['align-y'];
}

if (data['offset-y']) {
options.offsetY = data['offset-y'];
}

if (data['offset-x']) {
options.offsetX = data['offset-x'];
}

$this.poshytip(options);
});




jquery autocomplete custom result list

So having this next following code:



var obj = $("#search_input").autocomplete({
minLength: 2,
source: function(req, add) {
$.getJSON("do.php", { OP: "news_search", category: cat_id, get: req }, function(results){
var suggestions = [];
$.each(results, function(i, val){
suggestions.push(val)
});
add(suggestions);
});
},
select: function(event, ui){
console.log(ui);
$("#search_input").val(ui.item.label).attr('data-target', ui.item.value);
return false;
}
}).data("autocomplete");
obj && (obj._renderItem = function(ul, item) {
console.log(item);
return $("<li></li>")
.data("item.autocomplete", item)
.append('<p class="autocomplete-list"><img src="'+item.icon+'" alt="Icono Noticia" /> <a>'+ item.label+'</a></div><div class="clearfix"></div><hr size="1"/>')
.appendTo(ul);
});


As you can see, I am trying to achieve a custom autocomplete result list and by that I mean that on the left of the result list I want to display a photo related with the result, and on the right the text. On click/select it is supposed to set the input field with an extra field data-target where it should contain the article id.



The problem is that I can't get the select to work, I keep getting: d.item is undefined in firebug's console.



Any suggestions?



BTW, I use the var obj = $(...).data("autocomplete"); as it was suggested and accepted on a similar question on stackoverflow, but for me it doesn't work.





Using finally instead of catch

I've seen this pattern a few times now:



        bool success = false;
try
{
DoSomething();
success = true;
}
finally
{
if (!success)
Rollback();
}


And I've been wondering: Why is this better than using catch for rollbacks?



        try
{
DoSomething();
}
catch
{
Rollback();
throw;
}


What are the differences between the two ways of making sure changes are rolled back on failure?





do { } while(0) vs. if (1) { } in macros [closed]


Possible Duplicate:

Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?






When one needs to execute multiple statements within preprocessor macro, it's usually written like



#define X(a) do { f1(a); f2(a); } while(0)


so when this macro is used inside expressions like:



if (...)
X(a);


it would not be messed up.



The question is: wherever I've seen such expression, it's always do { ... } while(0);. Is there any reason to prefer such notion over (in my opinion more clear one) if (1) { ... }? Or am I wrong in my observations and they are equally popular?





How to force UIImagePickerController to record video in landscape mode

I my application is running potrate mode but I want to record video in landscape mode.



    self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.editing=FALSE;
//self.imgPicker.allowsImageEditing = YES;
self.imgPicker.delegate = (id)self;

[self.imgPicker shouldAutorotateToInterfaceOrientation: UIInterfaceOrientationLandscapeRight];
//self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
#if !(TARGET_IPHONE_SIMULATOR)
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;

Can this Recursive Solution be written up into a T-SQL Query using CTE or OVER?

Lets imagine you have the following table called Table1 of Orders in chronological order returned from an In-line UDF. Please note that the OrderID may be out of sync so I have intentionally created an anomaly there (i.e. I have not included the Date field but I have access to the column if easier for you).



   OrderID  BuySell  FilledSize  ExecutionPrice  RunningTotal AverageBookCost  RealisedPnL
339 Buy 2 24.5 NULL NULL NULL
375 Sell 3 23.5 NULL NULL NULL
396 Sell 3 20.5 NULL NULL NULL
416 Sell 1 16.4 NULL NULL NULL
405 Buy 4 18.2 NULL NULL NULL
421 Sell 1 16.7 NULL NULL NULL
432 Buy 3 18.6 NULL NULL NULL


I have a function that I would like to apply recursively from the top to the bottom that will calculate the 3 NULL columns, however the imputs into the function will be the outputs from the previous call. The function I have created is called mfCalc_RunningTotalBookCostPnL and I have attached this below



CREATE FUNCTION [fMath].[mfCalc_RunningTotalBookCostPnL](
@BuySell VARCHAR(4),
@FilledSize DECIMAL(31,15),
@ExecutionPrice DECIMAL(31,15),
@OldRunningTotal DECIMAL(31,15),
@OldBookCost DECIMAL(31,15)
)

RETURNS @ReturnTable TABLE(
NewRunningTotal DECIMAL(31,15),
NewBookCost DECIMAL(31,15),
PreMultRealisedPnL DECIMAL(31,15)
)
AS
BEGIN
DECLARE @SignedFilledSize DECIMAL(31,15),
@NewRunningTotal DECIMAL(31,15),
@NewBookCost DECIMAL(31,15),
@PreMultRealisedPnL DECIMAL(31,15)

SET @SignedFilledSize = fMath.sfSignedSize(@BuySell, @FilledSize)
SET @NewRunningTotal = @OldRunningTotal + @SignedFilledSize
SET @PreMultRealisedPnL = 0
IF SIGN(@SignedFilledSize) = SIGN(@OldRunningTotal)
-- This Trade is adding to the existing position.
SET @NewBookCost = (@SignedFilledSize * @ExecutionPrice +
@OldRunningTotal * @OldBookCost) / (@NewRunningTotal)
ELSE
BEGIN
-- This trade is reversing the existing position.
-- This could be buying when short or selling when long.
DECLARE @AbsClosedSize DECIMAL(31,15)
SET @AbsClosedSize = fMath.sfMin(ABS(@SignedFilledSize), ABS(@OldRunningTotal));

-- There must be Crystalising of PnL.
SET @PreMultRealisedPnL = (@ExecutionPrice - @OldBookCost) * @AbsClosedSize * SIGN(-@SignedFilledSize)

-- Work out the NewBookCost
SET @NewBookCost = CASE
WHEN ABS(@SignedFilledSize) < ABS(@OldRunningTotal) THEN @OldBookCost
WHEN ABS(@SignedFilledSize) = ABS(@OldRunningTotal) THEN 0
WHEN ABS(@SignedFilledSize) > ABS(@OldRunningTotal) THEN @ExecutionPrice
END
END

-- Insert values into Return Table
INSERT INTO @ReturnTable
VALUES (@NewRunningTotal, @NewBookCost, @PreMultRealisedPnL)

-- Return
RETURN
END


So the t-SQL command I am looking for (I dont mind if someone can creates an Outer Apply too) would generate the following Result/Solution set:



OrderID BuySell FilledSize ExecutionPrice RunningTotal AverageBookCost RealisedPnL
339 Buy 2 24.5 2 24.5 0
375 Sell 3 23.5 -1 23.5 -2
396 Sell 3 20.5 -4 21.25 0
416 Sell 1 16.4 -5 20.28 0
405 Buy 4 18.2 -1 20.28 8.32
421 Sell 1 16.7 -2 18.49 0
432 Buy 3 18.6 1 18.6 -0.29


A few notes, the above stored procedure calls a trivial function fMath.sfSignedSize which just makes ('Sell',3) = -3. Also, for the avoidance of doubt, I would see the solution making these calls in this order assuming I am correct in my calculations! (Note that I start off assuming the OldRunningTotal and OldBookCost are both zero):



SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',2,24.5,0,0)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',3,23.5,2,24.5)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',3,20.5,-1,23.5)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',1,16.4,-4,21.25)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',4,18.2,-5,20.28)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Sell',1,16.7,-1,20.28)
SELECT * FROM fMath.mfCalc_RunningTotalBookCostPnL('Buy',3,18.6,-2,18.49)


Obviously, the [fMath].[mfCalc_RunningTotalBookCostPnL] may need to be tweaked so that it can start off with NULL entries as the OldRunningTotal and OldBookCost but this is trivially done. The SQL Set theory of applying the resursive nature is a little harder.



Many thanks,
Bertie.





New Map Scheme of Bing Maps

How can I use New Map Scheme of Bing Maps in my Windows Phone Application



as you can see here:
http://pocketnow.com/phones/bing-maps-on-windows-phone-7-is-using-new-map-scheme





One hour offset in JSON dates

Why does this happen?



 new Date(2013, 5, 30).toJSON()
"2013-06-29T23:00:00.000Z"


It looks like one hour offset.



Thanks.





MySQL query to display periods between dates

In my table, I have two separate date fields, X and Y. In Field x I have the date of 13/08/2008 and in field Y I have the date of 13/08/2015.



I was wondering if there is a sql way working out what the six monthly date periods are between field X and Y, having the results displayed on separate lines? So, I was hoping to have the following results in two fields:



BEGIN     | END
13-Aug-08 | 13-Feb-09
13-Feb-09 | 13-Aug-09
13-Aug-09 | 15-Feb-10
15-Feb-10 | 13-Aug-10
13-Aug-10 | 14-Feb-11
14-Feb-11 | 15-Aug-11
15-Aug-11 | 13-Feb-12
13-Feb-12 | 13-Aug-12
13-Aug-12 | 13-Feb-13
13-Feb-13 | 13-Aug-13
13-Aug-13 | 13-Feb-14
13-Feb-14 | 13-Aug-14
13-Aug-14 | 13-Feb-15
13-Feb-15 | 13-Aug-15


Is this possible?



Thanks





How to call alarm from other application?

I'm creating Android App that will notify user to read book at given times, what I need to create so alarm and application will fire this alarm at given time, there can be more than 1 alarm and when dialog will appear it should show me 2 options like Read(this should go directly to MyApp) and Cancel, so my question is how can I do it in Android. Any ideas would be much more appreciated. Thanks beforehand