Thursday, February 10, 2011

How to call c++ functionality from java

I have a Java program that is mostly GUI and it shows data that is written to an xml file from a c++ command line tool. Now I want to add a button to the java program to refresh the data. This means that my program has to call the c++ functionality.

Is the best way to just call the program from java through a system call? The c++ program will be compiled for mac os and windows and should always be in the same directory as the java program.

I would like to generate an executable can the c program be stored inside the jar and called from my program?

  • If you have access to the code and want an 'interactive' experience with the external program (e.g., make call, get results, make additional calls), investigate JNI, which allows you to call C or C++ code from a Java application by including & linking JNI juice to your C or C++ app with .

    See:

    http://en.wikipedia.org/wiki/Java_Native_Interface

    http://www.acm.org/crossroads/xrds4-2/jni.html

    If you really just need a "launch app and get results" sort of solution, check out Runtime.exec(), which lets you launch an external program & capture its output.

    See: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

    http://www.rgagnon.com/javadetails/java-0014.html

    From DarkSquid
  • Assuming no better communication method is available (SOAP, ICE, Sockets, etc), I'd call the executable using Runtime.exec(). JNI can be used to interface directly, but I wouldn't recommended it. No you can't put an executable in the jar. Well you can, but you can't run it, since the shell doesn't know how to run it.

    Pavel Minaev : What's wrong with JNI? It's there for a reason, and it's definitely much better performance-wise than starting a separate process.
    Stephen C : The problem with JNI is that if you make a mistake your JVM is liable to crash. As in "segfault: code dumped".
    Draemon : @Pavel: Less portable, less stable, tighter coupling
    From Draemon
  • You may also want to look at the Java Native Access API (JNA).

    From McDowell
  • To answer your final question, you can't run an executable from within your jar.

    However, you can store it within your jar and extract it to a temporary directory/file prior to running it (check for its presence the first time and extract if necessary). This will simplify your distribution somewhat, in that you only have the jar to distribute, and ensures that you're running an executable that matches your jarred Java code.

    sixtyfootersdude : I did something similar to this once. Worked well, but I am not sure if it would be difficult if you program needed to work on different platforms.

How to make a modal confirmation dialog before submitting a form?

Hi all, I am a beginner in web/javascript programming and wonder if anyone can give me a kick start simple example of a modal confirm dialog just before a form with multiple submit buttons being submitted using a pre-defined button? I stumbled upon jQuery and SimpleModal and wonder if it would fit my ASP MVC project.

I ended up in the following non-working codes, I think my 1st problem is do not know how to return a value from the dialog?:

<script type="text/javascript">
    $(document).ready(function() {
    $("form").submit(function(ev) {
            return confirm("Confirm?");
        });
    });

    function confirm(message) {
        $("#confirm").modal({
            close: true,
            overlayId: "confirmModalOverlay",
            containerId: "confirmModalContainer",
            onShow: function modalShow(dialog) {
                dialog.overlay.fadeIn("slow", function() {
                    dialog.container.fadeIn("fast", function() {
                        dialog.data.hide().slideDown("slow");
                    });
                });

                dialog.data.find(".confirmMessage").append(message);
                dialog.data.find(".btnYes").click(function() {
                    $.modal.close();                                       
                });
            }
        })
    }        
</script>


<div id="confirm" style="display:none">
    <a href="#" title="Close" class="modalCloseX simplemodal-close">x</a>
    <div class="confirmHeader"><span>Confirm</span></div>
    <p class="confirmMessage"></p>
    <div class="buttons">
     <div class="btnYes">Yes</div><div class="btnNo simplemodal-close">No</div>
    </div>
</div>

It would be nice if anyone direct me to somewhere online for a crash course of web programming :)

  • You don't need to use jquery for a simple modal confirm dialog when submitting a form. The browser provides a few modal system looking dialogs. One being "confirm".

    This simple javascript would do:

    <form method="post" action="myurl.aspx" onsubmit="return confirm('Submit this form?')">
    ...
    </form>
    

    For a crash course you could check out W3Schools or just search google for tutorials.

  • Personally, I didn't bother doing it that way.

    Boxy is a jQuery plugin that has a confirm box control already.

    The example for it is as follows:

    $('#confirm-actuator').click(function() {
        Boxy.confirm("Please confirm:", function() { alert('Confirmed!'); }, {title: 'Message'});
        return false;
    });
    

    If you take a look at the Boxy site itself, it'll also show you how to retrieve the value submitted etc.

    EDIT: Implementation for you would be....

     $(document).ready(function() {
        $("form").submit(function(ev) {
            $('#mySubmitBtn').click(function() {
                Boxy.confirm("Are you sure?", function() { /**DO ACTION FOR CONFIRM**/ }, {title: 'Confirm'});
                return false;
            });
        });
    
    });
    

    And then place an ID on the submit button of mySubmitBtn.

    I've not tested that code off hand but that should hopefully do the trick.

    Hope this helps.

    Though according to the developer this method is not intended to replace the native window.confirm() function provided by browsers as it does not have the capability to block program execution while the dialog is visible.

    However, I don't think that would effect your form submit, so you should be all good to use this method.

    William : Thank you very much for your help. I have tried Boxy and learned a bit more on all those javascript stuff. However I cannot get it working too well and I ended up in using another jQuery plugin (the field plugin for reading/setting hidden fields) and the builtin confirm dialog for my current project.
    Liam : What do you mean by you can't get it to work too well? I had a few problems when I first tried using it, but I'm happy to help if I can. Don't forget to vote up and mark as answer if it's helped by the way. Though I'm new here myself so I'm not sure if everyone does that or not.
    From Liam
  • Here's a breakdown of 3 different ways to accomplish this:

    Modal Confirmation Dialog on Form Submit

    From Jen
  • I'm looking for a good simple solution, too.

    In our case, we're actually trying to replace javascript's "confirm" - apparently the default alert box looks too much like an error so we want to be able to customize it to look more friendly.

    From Sus

Increasing Battery Life on Windows Mobile using GPS and Web updates

I have an app that runs on Windows Mobile and uses the GPS to update its location at various intervals. As expected, enabling the GPS chip uses more battery power. (no duh..)

So currently my technique has been to cycle the the GPS on/off at approx. every 4 minutes to acquire the location, do something if things changed, and update its location to the web only if necessary. Otherwise, shut it off again and wait.

On my one year old HTC Touch Diamond phone, with a fresh charge, leaving the screen ON (but dimmed), + WiFi, and doing nothing else but letting it sit there, I got a maximum of 6 hours from it.

This is "ok", but the usage of the GPS easily cuts an estimate of 2-4 hours of regular 'real-world' usage (YMMV).

The other option I've simply been thinking about is to have the web server instead signal the phone to update its location when needed, instead of the phone just doing it blindly.

That way, the phone only uses power to get a data connection and check the server. If the server tells it to update, only then does it turn on the GPS.

Except that the response time of that is much slower (I'm guesstimating), and if the phone is somewhere it can't readily get a stable update, then you won't even know its last location. At which point, you're stuck waiting.

I was hoping the phone could be more autonomous.

Is there possibly yet a better algorithm I could use to improve this setup?

Thanks.

  • I think your current solution is going to perform the best and provide the best experience to the users.

    If you have your web server trigger the phone to update, you're really relying on too many outside things that could become disconnected (not sure if that affects your users, since you don't mention what the app does).

    If you can and haven't already, you could also make sure that your app doesn't turn on the GPS if the app is running in the background or while the screen is "asleep". That way you just fire it up as soon as the app becomes active and you're not wasting battery while the app isn't in use.

    Personally, I understand that if I'm using a Wifi/GPS/Data heavy application it's going to shorten my battery life considerably anyway. It doesn't seem like the decrease you're experiencing is too far out of line with other apps I've experienced. Keep it the way it is and make the user happy (even if they have to charge a little more often).

  • Does the GPS engine that you are using have any accessible built-in low power operating modes. I have embedded a couple of different GPS chipsets from SiRF and u-blox into products and found that it was cheaper in battery power terms to leave the GPS switched on in its low power mode than to turn it off and then let it re-acquire. In my case it used less energy in a low power mode for all switch off times less than about 15 minutes.

    SiRF (SiRFStar-2 and SiRFStar-3) based GPS engines have a "tricklepower" mode where the GPS is only switched on for a couple of hundred milliseconds on each wakeup. The wakeup interval can be set to maybe 5 seconds, meaning that the power consumed is 5-10% of the continuously on state. There is some small tradeoff in accuracy, but the chipset will return to continuously powered mode if the quality of the fix is degraded.

    Sebastian Dwornik : Very interesting. I looked at the GPS Intermediate Driver API again and there doesn't seem to be any access to such lower level power configuration. :( Good suggestion though.
    Ian : I work on projects where we buy the chips directly from the manufacturer and incorporate them into our products. As a result I have direct access to all of the functionality provided by the chipset that I am using. If the chip is hidden behind an API then the supplier can limit access to functions so that they can use any GPS engine that supports the set of functionality that they have exposed. A possibility is that the low power mode selection is hidden behind an update rate selection option. A faster update rate may be more power efficientfor the reasons in my answer above.
    From Ian

Tomcat : French accents in a solaris directory

One of our client bought a publicity in a newspaper and added to his URL : http://www.website.com/publicité instead of "publicite" (without the accent)...

I'm trying to make the corresponding directory under Solaris and it doesn't seems to work. I grabbed the "get" request and it looks like the "real" request is /publicit%C3%A9 We tried to add a directory with that name but it doesn't work either.

Any idea of how web could fix this problem?

We use Apache and Tomcat as our web container with JAVA (and jsp)

Looks like it's a Solaris server and not a linux..

  • Perhaps you could use Apache's mod_rewrite to change it to publicite (no accent)?

  • Looks like the request has been URL-encoded. The tricky thing is, it's not in standard ASCII, so I don't think it can be reliably decoded to the correct "é" (because you don't know just from the URL that it was originally in Unicode and not ASCII).

    Apparently, there is also no standard for encoding "é" either, so the URL you receive might be different for the same request from two different clients.

    Good luck.

    From Cameron
  • I'm trying to make the corresponding directory under linux and it doesn't seems to work.

    What exactly did you try, and how did it fail?

    You could try this (in bash):

    cd /var/www/html   ## -- Change as needed.
    dname=$(echo -en "publicit\0303\0251")
    mkdir publicite
    ln -s publicite "$dname"
    

    This is a simple version of Paul's idea to use rewrite.

    BTW, I just created a directory "publicité" with no problem by pasting text from this page, and from the commands above. Apache lists the empty directory fine in the browser (Firefox on Linux and WXP), albeit my English-configured Apache messed up the name in the listing:

    Index of /xtra/publicité
    [ICO]   Name Last modified Size Description
    [DIR]   Parent Directory   -
    Apache/2.2.3 (CentOS) Server at localhost Port 80
    

    And I'm seeing the same as you from the Apache access log: "GET /xtra/publicit%c3%a9/ HTTP/1.1"

    From NVRAM

mysql: recover database from frm files

At some point my MAMP installation became corrupt and I decided to move to XAMPP instead. However I now can't get my databases across. Other people have said I simply need to copy the DB files to XAMPP but this only partially work.

I can see the databases however all the tables have message "in use" and if I try to query a table I get the message "#1017 - Can't find file: './data_ms/geo_calendars.frm' (errno: 13)"

Any ideas how I can fix this?

Thanks

  • 1) Check the ownership of the files (geo_calendars.frm along with .myd and .myi should be owned by MySQL)

    2) Check read/ write permissions.

    3) Restart MySQL

    EddyR : beautiful, thank you! downloading batchmod made it easy to change ownership
    From shantanuo

TSQL Constraints on Temp Tables

Very quick and simple question. I am running a script to import data and have declared a temp table and applied check constraints to that table. Obviously if the script is run more than once I check whether the temp table already exists and if so, I drop and recreate the temp table. would that also drop and recreate the check constraints I placed on the temp table?

Logic says yes but I have been known to be wrong about such things.

  • Yes - dropping the temp table will drop any internal dependencies as well, including your constraints.

    From rwmnau
  • Yes, dropping the table will drop constraints, indexes etc that you may have created on it.

    Also, if this is something you're doing repeatedly you may want to truncate it instead of drop/recreate it - that is typically a lot faster. (And sometimes, creating a "permanent" temp table can be a good idea for frequently occuring ops)

    FailBoy : thanks for the tip, but this is generally a once off when migrating clients to our software from other vendors software

How to remove USB drive using C#

I'm trying to write an application to remove USB Drives, but i can't find a way to do it. There's a .NET class to do this or it's possible using the Win32 API? All advises are welcome, thanks for the help.

  • Heres a link to what your looking for:

    http://www.codeproject.com/KB/system/usbeject.aspx

    Explains how to do it, and come with source code, enjoy!

    Matthew Whited : could you make that a link instead of a code block?
    doc : Thanks for the help =)
    David Menard : no problem, sry for code block lol

Refactoring C++ in Eclipse CDT

I've installed the Galileo release (Eclipse 3.5/CDT 5.1) in hopes of utilizing the better refactoring support mentioned in

http://stackoverflow.com/questions/130913/what-is-the-state-of-c-refactor-support-in-eclipse

However I do not see all the mentioned refactoring options listed. I don't see any plug-ins related to refactoring on

http://download.eclipse.org/tools/cdt/releases/galileo

Attempts to add the plugin directly from the refactoring site fails http://ifs.hsr.ch/cdtrefactoring/updatesite/ due to outdated dependencies, so I'm assuming the newest release should have the latest refactoring abilities.

Am I correct in this?

How do others refactor in Eclipse CDT? Do people use other tools/plugins?

  • You should install CDT 6.0. However, my guess is that the options mentioned in the question you linked are not yet ready for mainline.

    My CDT offers Rename, Extract Variable/Constant/Function, Hide Method.

    From those, I only use Rename regularly, the others do not yet seem finished.

    One of the problems with such tools for C++ is that the language is way more complex than other languages (think templates, macros etc.) so implementing such a tool needs tremendously more effort than for, say, Java.

    From Tobias

Where is a good place to look for help starting development with Webkit?

Hello every one,

I have just started to work on WebKit. I am just a beginner with Webkit...

What am trying to do is, i am developing an Application based on Webkit like a basic browser. I am using GUI library other than QT or GTK so where should i start with. I am working on Linux Platform with C/C++ Languages.

I just want to create small program that will display some basic HTML page. like "Hello World" or something from HTML Tags. I want to use WebCore and JavaScriptCore not 'WebKit Objective C APIs'. (Actually i am not sure by which way it will be easy)

I have googled for WebKit application but they are all with either GTK or QT and there are no explanations or documentation on it....am totally confused.

so where should I start with can anyone provide me small examples. that can explain we how to build an application with Webkit.

Thanks. PP :)

ASP.Net Page Sometimes Freezing Before Page Loads

I have a pretty standard ASP.Net page written in C#. Most of the time it loads just fine and works a treat but occasionally the page won't load, I've inserted break points in the Page_PreInit (I don't actually have any code here, I've just created the function so I can see if the codes getting this far) but it's not getting this far. Any ideas where I should start in looking for a solution?

  • A couple of things to help you debug

    • Turn on tracing http://msdn.microsoft.com/en-us/library/y13fw6we%28VS.71%29.aspx
    • It may be throwing an exception you aren't seeing (although I would expect it to give you the YSOD...). Debug the application and turn on "Break when an exception is thrown" for Common Language Runtime Exceptions (hit CTRL+ALT+E to bring up the options)

    When the page doesn't load, what happens? Does it never finish loading, do you get an error message?

    Jack Mills : The page just doesn't load. If you hover the mouse over the page you get the vista loading icon but it never gets any further. This is in the output: "The thread 0x19a4 has exited with code 0 (0x0)."
    Jack Mills : I can't use tracing as I have update panels :(

active record: create record from parent object...

this is what I mean:

job has many docs. I want to create a doc, I can do:

@doc = Doc.new(params[:doc])

but I'd like to enforce the parent-child relationship, since I already know the job.. something like this:

@job.docs.new(params[:doc])

so that the job_id field gets ignored and only the @job object matters...

does it make any sense?

Django : How can I see what custom tags have been defined?

I'm having trouble with a custom tag in Django.

Is there any way I can see a list of what custom tags have been defined and are currently registered?

  • To list all currently active templatetags in django, execute the following in shell:

    from django import template
    for library in template.builtins:
        library.tags
    

    This code basically loops through the django template libraries and print the tags attached to them, thereby showing the names for all template tags currently being used by django and also give you access to their respective functions.

    From tarequeh
  • The admin docs will show them all (I believe, need to double check) Here is a link telling you how to turn on admin docs in 1.0

    Add django.contrib.admindocs to your INSTALLED_APPS list. Then add (r'^admin/doc/', include('django.contrib.admindocs.urls')), to your URL Conf file.

    From Raisins

Link to CSS directory with ~

I have a CSS link that looks like this:

<link href="../../css/WW/parts.css" type="text/css" rel="stylesheet" />

But now I want the CSS directory not to be linked to as "../../", but as "~/", i.e from the top of the project.

So I changed the CSS call to:

<link href="~/project/css/WW/parts.css" type="text/css" rel="stylesheet" />

But what happens is that the path is added to the current paht, instaed of going to the top of the project:

http://localhost:3333/Project/Apps/WW/~/project/css/WW/parts.css

What am I doing wrong? What's the right way to go about this?

  • Normally, "top of project" means the document root. If you're trying to do that, try:

     <link href="/project/css/WW/parts.css" type="text/css" rel="stylesheet" />
    

    If not, start pathing to the CSS from whatever directory / uses.

    From thedz
  • AFAIK ~ is for the server to resolve the URL. If you wan't this, then you need to add runat="server" to the link element. [Edit] Seems that you don't need runat="server", the server will resolve ~ by itself, giving you the "../../path".

    A better solution would be "/css/WW/parts.css" :)

    From cwap

Event Handling For Toolbar Using Haxe Targeting Flash

I am creating a simple UI toolbar component in Haxe for use in a Flash game. The toolbar is your general UI style toolbar, it has a background and several buttons. When the buttons are clicked some game action happens.

I have a question about the best way to implement events for the toolbars buttons. A parent class will create a toolbar and then sign up any functions it wants to the button on click events.

My current solution looks like this:

  • The toolbar extends the sprite class.
  • The toolbar class has a child sprite for each button.
  • Each button has an event listener for MouseEvent.Click event.
  • The MouseEvent.Click is handled by a function on the toolbar that examines a Dynamic typed array and executes each function contained in the array.
  • The Dynamic typed array is public so any classes that want to sign up to the toolbar button on click events can add their callback function to the array.

Code Snippet for a Scene that has a toolbar

this.toolbar = new ToolBar();
this.toolbar.OnAttackButtonClicked.push(OnAttackButtonClicked);

Code Snippet for creating a button in the toolbar

this.attackButton = new Sprite();
this.attackButton.addEventListener(MouseEvent.CLICK, this.OnAttackButtonClickListener);

Code Snippet for the button click handler in the toolbar

private function OnAttackButtonClickListener(event : MouseEvent) : Void
{
    if (this.OnAttackButtonCallbacks != null)
    {
     var index:Int = this.OnAttackButtonCallbacks.length;
     while (index-- > 0) 
     {
      this.OnAttackButtonCallbacks[index](event);
     }
    }
}

I am wondering if this is a good approach or if there is a better way to do it?

  • Solved. Used Custom Events and the Event Dispatcher.

Applying html formating in label control

The html formating is applied great in this case. The Surname is displayed with size 5.

lblWelcome.Text = "Welcome:<font size=''5''>" & txtSurname.Text & "</font>"

Why the html style is not applied in this example?

lblWelcome.Text = "Welcome:<font color=''white''>" & txtSurname.Text & "</font>"
  • You could just set the ForeColor property on the Label.

    lblWelcome.Text = txtSurname.Text;
    lblWelcome.ForeColor = "white";
    

    You'd have to put the 'Welcome' outside the label, but it would probably make more logical sense.

    Welcome:<asp:Label id="lblWelcome" runat="server" />
    
    womp : Even though it doesn't directly answer the question, this is +1 simply because outputting font tags is really 1996...
    g . : @womp - sometimes the answer is there is a better way. :-)
    From g .
  • Hi there.

    As an alternative, you could use the ASP.NET Literal web control and set its Mode property to Encode or Transform.

    Literal1.Mode = LiteralMode.Encode
    
    Literal.Text = "Welcome:<font color='white'>" & txtSurname.Text & "</font>"
    

    In the above code, the HTML elements will be transformed into proper HTML, leaving just the surname text in white.

    Cheers. Jas.

    Chocol8 : I have tried Encode, Transform and PassThrough but it didn't work out. +1 for the literal control :)
  • Please, please, please don't use font tags. Also, if you really want to output HTML from the server side then you should be using a Literal control.

    Here is an example of how I would do it:

    aspx/ascx file:

    Welcome: <asp:Literal id="lit1" runat="server" />
    

    code behind:

    lit1.Text = "<span class='welcome'>" & txtSurname.Text & "</span>"
    

    OR your other example:

    lit1.Text = "<span class='welcomeBig'>" & txtSurname.Text & "</span>"
    

    css:

    span.welcome { color:#fff; }
    span.welcomeBig { font-size:24px; }
    

    Hope this helps

    Chocol8 : I guess CSS overides everything! I got the desired style without even using the literal control
    From Darko Z
  • Also don't forget to HTML encode the surname: Server.HtmlEncode(txtSurname.Text);

    From Dan Diplo

Flash under SSL

I have a difficulty to display Flash contents under SSL only by IE. Is this simply IE's bug? Firefox can display the Flash.

  • Try importing the SSL cert into your keystore. Double-click on the lock icon, then click on "Install Certificate". Flash can be very finicky when it comes to SSL certs. Let me know how this works for you.

    tokyoish : Thanks,though, this didn't work well. I'll try something more.
    From ristonj
  • Check out http://www.sslshopper.com/article-flash-ssl-ie-wtf.html for a possible solution. Flash is unable to load xml if the http header has either Pragma: no-cache or Cache-control: no-cache.

    Kieveli : Hahaha took your point Cherry!

Assign permissions to a user on tables with a certain prefix

I'd like to assign a user all privileges on tables which have a specific prefix, eg. 'abc_'

I'm aware of the use of the wildcard to select all tables thus:

GRANT ALL ON dbname.* TO ...

Essentially, what I'd like to do is:

GRANT ALL ON dbname.abc_* TO ...

This doesn't work so I'm wondering if there is a solution, perhaps using LIKE? (Which I've tried; as yet to no avail).

  • Nope, sorry. Have to do them one at a time (with, of course, the option to do so programatically).

    Greg Annandale : Thanks chaos, looks like I'll have to resort to PHP.
    From chaos
  • $ php -f pcre_grant.php -- localhost root password database user1 abc_ ALL
    
    
    pcre_grant.php will look like:
    
    <?php
    
    list($script, $db_host, $db_username, $db_password, $db_name, $regexp, $username, $perms) = $argv;
    
    $link = mysql_connect($db_host, $db_username, $db_password);
    mysql_select_db($db_name);
    
    
    $result = mysql_query("SHOW TABLES");
    while($row = mysql_fetch_row($result)){
        if(preg_match('/'.$regexp.'/',$row[0]))
         mysql_query("GRANT ".$perms." ON `".$db_name."`.`".$row[0]."` TO ".$username);
    }
    
    mysql_close($link);
    ?>
    

HTML Diff Component for .NET

Is anyone aware of a good managed code .NET component which can do HTML Diffs? I'd like to compare two HTML files and show the differences.

  • Microsoft has a managed-code tool called XmlDiffPatch, which should work for HTML files as well. You can run it as a stand-alone executable, or import the diff assemblies into your project.

    Noldorin : It would only work well for valid XHTML, I'd bet.
    Andy Mikula : XML != XHTML...

Linq join several arrays

 I have List<Product[]> and I need to join them in Product[] from it.
  • You can use SelectMany and then ToArray to do this.

    var result = source.SelectMany(i => i).ToArray();
    
  • You can use .Concat() extension method as well, and then .ToArray(): x.Concat(y).Concat(z).ToArray();

    From Ravadre

Geneva Server STS

My requirement is the claims assigned to a user are company aware so say for example User 1: is publisher for Product Manager for Company 1 but the same user is only editor for Company B. Can this be achieved through Geneva Server, or additional code needs to be written to override classes.

  • In my opinion it's the relying party itself should be making decisions on what roles to attach to a token based upon the identity itself.

    However you can set rules based on individual relying parties and choose to serve information as a claim based on whatever the backing store says. Now how you represent that information in whatever backing store you are using (AD, LDAP, SQL, whatever) is a design decision at your end. You may also want to look at harnessing the claims transformation language in beta 2.

    It's really hard to give any specific advice without knowing details about where your claim backing store is going to be and why you think you need to go this route.

    chugh97 : I am planning to use SQL Server as backing store
    blowdart : You realise that Geneva Server must authenticate against an Active Directory. At the minimum your users must be in an AD to use Geneva Server
    Miau : Are you sure about that? I didnt think it had a dependency on ADFS
    blowdart : Server does yes - or rather ADFS as it's been branded.
    From blowdart

How to Set a Value to NULL when using Zend_Db

When performing UPDATE and INSERT queries using Zend_Db, I frequently need to set values equal to NULL (not ''). However, the default behavior of Zend_Db::insert() and Zend_Db::update() seems to be that values that are empty are translated into empty strings ('') and put into the database as such.

Does anyone know of way to actually force a NULL value to go into fields if the value is empty in php?

  • Try setting the affected fields to: new Zend_Db_Expr('NULL')

    Gabriel Sosa : I like this method for the _abstraction_ that this method give to you
    From William
  • I've always just been able to do this using PHP's null:

    $toUpdate = array('nullValue' => null, 'otherValue' => 'something');
    Zend_Db::update($table, $toUpdate, $where);
    
    From Johrn

Flash CS4 Textfield weirdness!

I've been working on a flash project where a designer has included a typewriter effect.

The effect was working for the best part of a day, and now with some minor changes to other parts of the fla, it's not working!!

Does anyone have any ideas why this doesn't work....

import flash.text.TextField;

var phrase_string:String="SALE IS ENDING";
var n:Number= phrase_string.length;
var i:Number = 0;

addEventListener(Event.ENTER_FRAME, textCheck);

function textCheck(e:Event):void
{
    if (i < n)
    {
     display_txt.text = phrase_string.substr(0,i+1);
     i++;
     trace(phrase_string.substr(0,i+1));
    }
}

This just runs on the first frame of a movieclip containing the dynamic textfield (with fonts embedded) called display_txt

I'm completely flummoxed!

  • This is a classic font embedding problem. Some fonts treat bold and italic weights differently, and to display these bold or italic versions, you might need to add a new 'Font' (the same font name but different font weight) to export in your library.

    From danjp

(Setup & Deployment) Create a folder & rename destination folder

Hi all,

I've been using Visual Studio's Setup & Deployment Project to create an installer for a windows service and what i need is to create a folder within the application folder when the installer is run. How would i go about doing this? I tried adding a folder to the Application Folder in the File System on Target Machine bar, but that's not working.

Also is there a way to specify what the name of the application folder will be? Right now i have a solution named Tracker.Import.Service and the output folder the install creates is Tracker.Import.Service.

Thanks

  • Did you put anything in the sub-folder you created in the Application Folder? Try adding a target text file to the sub-folder.

    If the sub-folder is empty it will not be created. The installer project will not detect any dependencies on it and will not add it the installer package.

    You can set a default for the Application Directory by

    • Viewing "Target System on Local Machine"
    • right clicking on "Application Folder" and selecting properties.
    • Set the value of DefaultLocation to the directory where you want the application installed.
  • Further to Jeff's response above, an empty sub-folder will be created if you set the AlwaysCreate flag for the directory to true via the properties panel (it is false by default).

Sort ruby array by updated_at

Hello,

all I want to do, is to fetch the lastest item from my models and have them in an array sorted (freshest items first) by the attribute "updated_at".

Somewhere is an error, but I can't find it:

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end


  @results = @results.sort_by{ |result| result.updated_at}
  • You need to do the comparison in the sort. `

      @results = Array.new
      Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
          @results << item
      end
    
      Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
        @results << item
      end
      @results.sort!{|a,b|a.updated_at <=> b.updated_at}
    

    This will sort the @results array in place.

    Stefan : Thanks for your answer!
  • notes    = Note.find    :all, :limit => 3, :order => "created_at DESC"
    pictures = Picture.find :all, :limit => 3, :order => "created_at DESC"
    @results = (notes + pictures).sort_by(&:updated_at)
    
    Stefan : Thanks for your answer!
  • Maybe not as terse, or readable, but it is a little DRYer. I can't convince myself this is better than weppos's answer. I do like replacing "Class.find :all" with just "Class.all".

    results = [Note, Picture].inject([]) do |memo, clazz|
      memo + clazz.all(:limit => 3, :order => "created_at DESC")
    end
    results = results.sorted_by(&:updated_at)
    

read a int from a file wrote by java's writeInt method in C++?

How would one go about doing this? Also, is there an easy way to do it? Using a lib like Boost or something?

  • Ideas:

    1. Read it in as straight binary, then convert/interpret bytes as necessary. So if Java wrote out 4 bytes for the int, then you read in 4 bytes. If there is any endian-ness to change then do that, then cast (or copy) the byte array to a c++ int
    2. If you can change the Java code, you could write it out as something common that C++ can read like UTF-8 text or ascii, or Google Protocol Buffers format or something else.
    From Alex Black
  • The DataOutputStream which writes out the int writes out a 4 byte int, with the high bytes first. Read into char*, reinterpret and if you need to convert the byte order use ntohl.

    ifstream is;
    is.open ("test.txt", ios::binary );
    char* pBuffer = new char[4];
    
    is.read (pBuffer, 4);
    is.close();
    
    int* pInt = reinterpret_cast<int*>(pBuffer);
    int myInt = ntohl(*pInt); // This is only required if you are on a little endian box
    delete [] pBuffer;
    
    Pavel Minaev : All well and good until you hit a platform where `sizeof(int) != 4`. Or a one where integers are ones' complement or sign-bit, and not two's complement (all allowed by ISO C99).
    Pavel Minaev : ... as well as ISO C++
    anio : On what platform are integers ones' complement or sign-bit? I would like to know.
    Steve Jessop : @mamin: The PDP-1 used one's complement, and there are still three of them in existence (plus emulators).
    From anio
  • The only cross-platform way to do it is to read it byte by byte (that is, char by char), and build an integer out of them. You'd want to use long, because int is not guaranteed to be wide enough to hold a 32-bit value. I'll assume you've read the bytes into a char[4] array here (other answers have already demonstrated how to do that):

    char bytes[4];
    ...
    long n = (long(bytes[0]) << 24) | (long(bytes[1]) << 16) |
             (long(bytes[2]) << 8)  |  long(bytes[3])