Thursday, April 21, 2011

Autogeneration of tests and stubs with CUnit.

Does anybody know of a free/commercial tool that would automatically generate tests and stubs for C code to work with CUnit framework?

From stackoverflow
  • Try CMock for generating stub implementations of header files.

Postgres csv import duplicate key error?

Hi, I am importing a CSV file to postgres.

copy product from '/tmp/a.csv' DELIMITERS ',' CSV;
ERROR:  duplicate key value violates unique constraint "product_pkey"
CONTEXT:  COPY product, line 13: "1,abcd,100 pack"

What is the best way to avoid this error.. Would I have to write a python script to handle this error..

From stackoverflow
  • Well, the best way would be to filter the data not to contain duplicates. It's usually pretty easy, and doesn't require a lot of programming.

    For example:

    Assuming 1st column of your data is data for primary key and the file is not very large (let's say les than 60% of your ram), you could:

    awk -F, '(!X[$1]) {X[$1]=1; print $0}' /tmp/a.csv > /tmp/b.csv
    

    and load /tmp/b.csv instead.

    If the file is larger, then I would suggest something like this:

    sort /tmp/a.csv | awk -F, 'BEGIN {P="\n"} ($1 != P) {print $0; P=$1}' > /tmp/b.csv
    

Play AVAudioPlayer From A Sleeping iPhone

Hello Friends,

I am creating a alarm application. I am using Audio Session in my main delegate class.

OSStatus result = AudioSessionInitialize(NULL, NULL, interruptionListenerCallback, self);
UInt32 category = kAudioSessionCategory_MediaPlayback;
result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);  

AudioSessionSetActive(YES);

I am using a separate class for audio playing.But i am not able to play audio when iPhone is sleeping.

could any one tell me how to use a audio session so that i can play audio file even when iPhone is sleeping.

Thank You

From stackoverflow
  • If you're actually using an AVAudioPlayer then try adding this where you handle your initialization:

    [[AVaudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    

    The Playback category will allow the sounds to continue if the phone switch is set to vibrate and/or if the phone is locked.

    Good luck,

    Karl

How to remove problematic control from visual studio 2008 toolbox?

I added an asp.net control to my project in visual studio 2008 after that any attempt to open the toolbox or to switch into design mode (aspx file) causes visual studio to freeze.

I've tried to reset visual studio enviroment settings.

update: any other project without this control opens fine!

From stackoverflow

When using Trac and SVN together, how will I know that a file is committed to solve a certain ticket?

For example, a file is modified to do an enhance ticket, what I want to do is associated the committed file to the ticket. When using Trac and SVN together, how will I know that a file is committed to solve a certain ticket? Is this possible?

Thank you.

From stackoverflow
  • you can link to the revision when closing ticket: r253, e.g.
    and you can link to the ticket in commit message: #7525, e.g.

    other than that, I doubt that anything can be done.

    Obviously you could parse log message with on-commit hook and make a notification of sorts re tickets of interest, but you'd need to have access to the server I guess.

  • As stated on the TracWiki, the intended workflow is:

    1. A Trac user begins work on a ticket
    2. They obtain code from the version control system
    3. After the work is completed they perform a commit of their modifications to the version control repository
    4. The user inserts the Trac ticket number into the commit message as a TracLink
    5. Trac can now display the change set for the ticket

    Where the TracLink is something like #1 or ticket:1 or even comment:1:ticket:2 when referring to a ticket.


    If you miss creating the link when the commit is made, you can still create one in the ticket comments themselves using TracLinks such as: r2, r1:3, [1:3], log:@1:3, etc.

    Lasse V. Karlsen : And the basic link could be added via svn:bugtraq properties, at least for clients that support it.
    basszero : Additionaly, you can setup a post-commit script to automatically push tickets to testing (or whatever workflow you use)
    RjOllos : I'm fairly sure the Trac post-commit hook must be enabled (as retractile mentioned), and it is not by default in aTrac installation.
  • You may find the Trac post-commit hook useful. It allows you to close tickets using your commit log messages. See the script here.

To get the row number in gridview

Hi guys,

I have a gridview in which I have set datasource as datatable. Whatever update I make to the gridview, it should reflect only in datatable not to database. When I click update I have to get the row number of particular row which I want to update. How can I get the row number in rowupdating event of gridview inorder to update datatable? Suppose i have datakey and if i get that unique id, how can i update the datatable which is the datasource?. Can anybody help?

From stackoverflow
  • If there is sorting applied then the row numbers in gridview and datatable won't match.

    So if you try to update with the row number in gridview it may end up in incorrect values.

    The updation should be based on a unique ID in the gridview datasource.

    : if soting is not there how can i get rownumber
  • This is the way to get the row id of your updated row :

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
      string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString(); 
    }
    

    Maybe you want only the e.RowIndex. But the above code returns the specified unique data key for the row.

How do I manually install an old cygwin package?

A project I am working on requires an old version of SLAPD (the LDAP server) and must run on Windows, hence I am using cygwin packages:

I've found a binary package of slapd version I need 2.2.x here:

http://www.mirrorservice.org/sites/sourceware.org/pub/cygwin/release/...

How do I manually install it in cygwin? It does not seem to be a package-manager file format (like an RPM or a Deb), but is there a tool to install it for me?

FYI, I'm operating behind a corporate firewall that prevents me from viewing the main cygwin site (including the documentation), so please nobody tell me to RTFM - I wish I could!

Thanks

From stackoverflow
  • If you are using the cygwin package installer to install this package, usually if you select to view the full info and scroll to the package you need you will see some info about the version.

    Now if you click on the version number you will see that it changes from the oldest in the repository to the current. If your repository has the version you need then just finish the wizard.

  • If you need an older version, the Cygwin time machine might help. To use it, I had to invoke setup.exe from the command line, giving it the --no-verify option and it still wouldn't let me downgrade the "cygwin" package itself but at least it is, albeit very slowly, allowing me to install the version I wanted to test as a parallel installation.

Dimming screen around dialog

A popular feature in many applications - dimming a screen around a modal dialog. I need to implement this feature on Windows Mobile, C++. The main wnd is fullscreen, but contains many subwindows. How can everything be dimmed around specific rectangle(bounding required modal window) ?

From stackoverflow
  • On Win32, you can achieve this by placing a semi-transparent full-screen black Window on top of the desktop. Look for examples of rendering semi-transparent splash screens to find an example. Typically GDI+ is used.

    Postscript: I just saw the "Mobile" word in your question - not sure how this will apply in that environment.

  • You should use the BitBlt api (http://msdn.microsoft.com/pt-br/library/aa930997.aspx) with PaintRect so you can paint the hole screen with a copy of current desktop as a transparent.

    Sorry I haven't been more detailed, cause I don't remember how to do it.

    --edit: More links to help you out, both provide the answers to your need: http://www.vbforums.com/showthread.php?t=534771 http://www.developer.com/ws/pc/article.php/2190121

text input in IE7 seems to stop working

DISCLAIMER This is not something that I can replicate in anything other than a full sample, which sadly is not practical as it only happens on a specific PC. I am also aware that the information I have is very flaky.

I have one user (my boss) who runs IE7 and has no addins other than the basic bits like flash etc.

On one page and one page only on our app she sometimes finds that the text inputs will simply stop working. She can't click on them, can't tab to them, can't interact with them in anyway, other control such as dropdowns are fine.

The page is an standard ASP .Net web forms page, with a modal popup (created by SimpleModal 1.2.2).

I have no real information to go on. Has anyone had anything like this, or any suggestions of how I might go about getting better information to diagnose the problem?

From stackoverflow
  • ... Not to fix a bandaid with a tourniquet, but have you tried upgrading to IE8?

    ilivewithian : This is the only way we can replicate the bug at the moment, so we want to keep a hold on it. The chances are as soon as we upgrade, the sooner a user gets the same bug.
  • Use a Developer Toolbar and post an HTML generated for this mysterious control.

    ilivewithian : Funny, I'd known about that for a while, I'm just used to fire bug. Thanks.
  • When a strange error like that happens in IE on a single computer:

    Check the settings for the disk cache (Temporary Internet Files). By default the maximum size is set to a percentage of the available disk space, which with the size of disks today is much more than the program can actually handle. When the cache starts to fill up, various functions in the browser may stop working in different unexpected ways.

    A reasonable value is something like 50 MB. If it's a lot larger than that, clear the cache and set it to a more reasonable value.

    (This is fixed in IE8, where the default value has an upper limit.)

    RichardOD : +1. Good points. One of those mysterious ways is usually View source stops functioning.

VS 2008 how to select current file in editor into solution explorer

It is very time consuming to select file into solution explorer that i am editing. How can i make vs 2008 auto select editor file into solution explorer.

I had it working some point in time back but not sure what needs to change to do that

From stackoverflow
  • There is an option in Visual Studio 2008 called "Track active item" and will automatically select the currently project file being edited.

    Activate the option like so

    Tools->Options->Projects and Solutions->Track active item in Soution Explorer

ASP.NET AJAX Library

Coolite facilitates DialogBox, Window, form, etc. (i.e. most of the controls similar to Desktop GUIs). Is there any other library like 'Coolite Toolkit' for ASP.NET ?

From stackoverflow
  • Free or fee? Telerik and Infragistics both have extensive control libraries for ASP.NET that include both server-side and client-side components. Most, if not all, of these controls would work with ASP.NET AJAX. Microsoft hosts a community control gallery with many more on their ASP.NET site.

  • Free use;

    there is BackBase Ajax Framework built in Java but can be used through script blocks.

    http://bdn.backbase.com/client

    and theres WEB UI of ComponentArt,looks nice :) at componentartdotcom

How do I add files to a windows mobile device when deploying it?

I have a number of images and a CSV data file that I want to deploy to a windows mobile device along with my application. I'm using Visual Studio 2008 and C#.

I've added a "Content" folder to my project which contains the bmp images and the CSV file. When running my program on the emulator (by hitting F5) only the app is deployed, and not the "Content" directory.

I know I can add images to the resource file, but that isn't what I want to do - I want the images to actually be available on the device so that they can be changed without having to deploy a new application.

So my question is how can I set it up so that the "Content" directory is copied to the device?

Thanks in advance!

From stackoverflow
  • Are the files within that folder also marked as content?

  • THe files from a "Content" folder will not be deployed on your device.

    In order to deploy a file, right click it -> Properties -> select "Content" from Build Action

    Ben Dowling : Thanks - that did the trick

Processing FOP with parameters

HI, I want to use FOP to prepare a XML document for printing (ps/pdf). Is it possible to send parameters to FOP to do conditional formating as exist in xsl processors

XSL:

<xsl:param name="isDuplicate">no</xsl:param>
....
<xsl:if test="$isDuplicate='yes'">
    <h2 align="center">Copy</h2>
</xsl:if>
....
From stackoverflow
  • If you're using the fop batch/shell file that comes with the distribution, you can use the --param argument to fop, as documented on the Fop page

      -param name value <value> to use for parameter <name> in xslt stylesheet
                        (repeat '-param name value' for each parameter)
    
    eLAN : You're right; I don't know how I missed that... :)

c# How to sort a sorted list by its value column

Hi, i have a generic sorted list "results" with key = some filename and value = boolean.

I would like to sort the list by the boolean entry or value column. does anyone know how i can do this?

Thanks!

From stackoverflow
  • SortedList is optimized so that inertions occur in an ordered fashion, such that enumeration occurs in a sorted order at minimal cost. Anything else requires a re-sort. Thus:

            SortedList<string,bool> l=new SortedList<string, bool>();
            l.Add("a",true);
            l.Add("a",false);
            l.Add("b",true);
            l.Add("b",false);
            var orderByVal=l.OrderBy(kvp => kvp.Value);
    

    but this enumeration will be significantly slower to calculate, and be performed up-front, requiring extra storage to do so.

    Depending on your situation it might be cheaper to maintain 2 SortedList instances with the key/value reversed.

  • In .NET 2.0, you could add your items to a SortedList:

      public static List<MyObject> SortedObjects(IEnumerable<MyObject> myList) {
         SortedList<string, MyObject> sortedList = new SortedList<string, MyObject>();
         foreach (MyObject object in myList) {
         sortedList.Add(object.ValueIWantToSort, object);
         }
    
         return new List<MyObject>(sortedList.Values);
      }
    

performance of my application using wampserver

I have developed an application using php, mysql and xajax. I always used to test on a setup of which I had installed all applications seperately (apache, php and mysql) and my application was fast (by this I mean that the responsetime of useraction were very low).

I recently removed apache, php and mysql and installed wampserver. From that point on the responsetimes of useractions have increased significantly (tripled). Does anybody have similar experiences? I use the out-of-the-box settings for wampserver and have installed wampserver on both my main computer (Vista) and my laptop (XP).

Any suggestions would be helpfull. I love the idea of a one package deal for php, apache and mysql but if this means that performance goes down I think I would rather revert back to my old setup without wamp.

Thanks, Jasper

From stackoverflow
  • I've never noticed a slowdown with WAMP (compared to my server that has them installed separately). You may be able to fix it by changing something in the Apache, PHP or MySQL configuration. I'd compare what you have now to what it was set up like earlier.

  • I would compare the config files, as there are probably small config changes that could have big affects on Apache, MySQL or PHP.

  • Nope, no slow down on XAMPP/WAMP. it should not be that slow: because it's your own computer.

    do some actual timing and get real figures. it might be your loopback adapter, network, browser and so on.

    to do actual script timing do the following

    add the following to the start of your script

    function microtime_float(){
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
    $time_start = microtime_float();
    

    At the end of your script, add the following:

    $time_end = microtime_float();
    $loadedin = (float)($time_end - $time_start);
    echo $loadedin.' s<br/>';
    

    Then when you load the page, at the end of your age, it will display the time in seconds taken to load the whole script.

    jasperdejong : Thanks Mauris, I added some timings but it turned out that all my xajax and php calls are fast (<200ms). I removed wamp from my system and installed php, mysql and apache seperately. It's all much faster now...
    thephpdeveloper : that's awesome. all the best!

What is faster query ...where Fname = 'mark' or ...where Fname like 'mark'

hi

What is faster query select...where Fname = 'mark' or select...where Fname like 'mark'

thank's

From stackoverflow
  • I believe the equality query, in general, is much faster.

    This SQL Server Performance thread lists the operands in order of performance.

  • In this particular instance, they will most likely be the same because the LIKE has no wildcards. The optimiser detects it's trivial and makes it equality anyway.

    Generally though, "=" will be quicker than "LIKE".

    A simple example

    --Different plans because name has index.
    --uses bookmark lookup but 40% of batch
    SELECT * FROM sys.columns WHERE name = 'offset'
    --uses clustered index scan 60% of batch
    SELECT * FROM sys.columns WHERE name LIKE 'offset'
    GO
    
    
    
    --same plan, 50% each of batch
    SELECT * FROM sys.server_permissions WHERE class_desc = 'ENDPOINT'
    SELECT * FROM sys.server_permissions WHERE class_desc LIKE 'ENDPOINT'
    

Is there any disadvantage to using both MacPorts and RubyGems at the same time?

I'm new to Ruby on Rails, and I'm in the process of setting it up on my OS X system. Most guides seem to recommend using MacPorts to install Ruby and RubyGems, then using RubyGems from there on to install gems. I've noticed that MacPorts also offers many gems (though they're missing some and others seem a few releases behind), and I'm worried that it will somehow conflict with the stuff I'm installing using RubyGems.

Does anyone have any experience working with this kind of setup? Any advice? I want to get this right the first time so I don't end up having things break later on.

Thanks,

Grant

From stackoverflow
  • I recommend using Macports to install Ruby, and then download and installing the latest version of Rubygems by following the instructions on http://rubyonrails.org/down. When you want to install a new gem, use Rubygems, not MacPorts.

  • I use MacPorts to install Ruby and RubyGems, but then I install gems using the gem command (not port). I've found that Ruby gems in MacPorts aren't well-maintained, and the latest MacPorts version is often significantly behind the "real" version (for lack of a better term).

VSFTPD on windows and other issue.

I have to build an vsftpd compatible ftp client. I am not sure about which protocol vsftpd follows, sftp or ftps, I am guessing sftp as i could connect some vsftpd client with port 21(ftp) and 22(sftp) but not 990(ftps).

Now I have to communicate with vsftpd compatible ftp server using C#.NET. Can somebody help me find out some good open source sftp client.

I also need to setup some sftp server on windows. Is there any opensource sftp server.

Thanks.

From stackoverflow
  • vsftpd supports FTP and FTPS, so you need an FTP/FTPS .NET client. It isn't open source but one option is edtFTPnet/PRO. It does FTP, FTPS and SFTP (in case you ever need the latter).

    If you want an SFTP server for Windows, try CompleteFTP. It supports FTP, FTPS, SFTP and SCP on Windows.

Browser feature detection: spell checking?

All the decent browsers (Chrome, FX, etc) now support built-in spell checking.

However the popular but rubbish axis of IE doesn't (not even IE8 - pointless 'accelerators': yes, much needed dictionary support: no). Unless you download an excellent free plugin, but you can't expect corp users to do that.

Our clients want spell checking in the enterprise web app that we supply, so we bought in a 3rd party spell checking component to keep them happy. It works, but isn't terribly good - especially when compared to anything built in to the browser.

It also looks like the spell check dialog in Word 2000 (probably current back when it was developed). Not such a problem for our clients, half of whom are stuck on Office 2000 and IE6.

I want to only enable this component when the user doesn't have built in spell checking.

Does anyone know a way to detect this?

From stackoverflow
  • You already know which browsers have built-in support and which browsers don't so you may use some form of browser sniffing to decide whether you enable the spell-checking component or not.

    You may also try to ask your users if they already have some spell-checking enabled and let them answer Yes/No/Don't know. If they don't know, fall back to automatic detection. This is better than using sniffing only because sniffing is known to be unreliable in some circumstances.

    Detecting things that are part of a browser's UI is hard, if possible. Due to browsers' security policies, a web site can't access most part of the API that could expose something useful for feature detection. And even if security was not a problem, you would probably still face one distinct API for every browser, since internal browser mechanics are not standardized.

    Keith : Thanks (+1) that's kinda what I figured, but I wondered whether anyone had a better way.
  • Not sure if this is possible even with something like browsercap or Microsoft Browser Definition File Schema, as mentioned above it is kind of outside the allowed scope.

    Have you considered just going with a server side spell checker? So they can use the client if they like or click the spell check button like in GMail. This also means that you can control any updates to the dictionary.

    Keith : Our 3rd party component is server side, it's just AJAX driven. It needs to be as our whole interface is too.

Problem using regex to extract text

Hello!

I need to extract from the following lines of code

<label for="<%=foobar.bar %>">Password:</label>

<label for="foobar">Password:</label>

I need to extract foobar, I can use this: (?<=for=")[^"]+(?=(")) to extract:

<%=foobar.bar %>

and

foobar

but I don't want <%= or .bar and if I try to create (?<=for=")[^"]+(?=(")) | (?<=for="<%=)[^"]+(?=(")) it doesn't work becuase the label that included <%= meets both conditions and I don't think you can use XOR? Is this anything anyone can help me with?

Merci :)

From stackoverflow
  • You can try this:

    (?<for="(<%=)?)[^" ]*(?=( %>)?")
    

    Assuming that what you want to capture never includes spaces. Otherwise you can try:

    (?<for="(<%=)?)[^"]*?(?=( %>)?")
    

    To use a non greedy form of [^"]*

  • I believe that it's better to not create uber-regexes. Do your task in several steps:

    1. Extract <%=foobar.bar %> or foobar with your regex (?<=for=")[^"]+(?=("))
    2. Check if result matches regex like <%=([\w]+)\.bar\s*%>.
    3. If it does use $1 group from match, otherwise use result of step 2.
    4. You get foobar
    Sara : thank you, I used (?<=for=\")[^\"]+(?=(\")) and then went on to use: (?<=<%=\s*)[^\s]+(?=\.bar\s*%>)

Display a jpg image on a JPanel

What would be the most appropriate image type to display a jpg image (loaded from a local folder) on a JPanel?

Cheers.

From stackoverflow
  • You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

  • I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

    Here's Sun's docs on the subject matter.

  • ImageIcon image = new ImageIcon("image/pic1.jpg");
    JLabel label = new JLabel("", image, JLabel.CENTER);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add( label, BorderLayout.CENTER );
    
  • I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

Admin, two links to different views ?

Hi guys, in django admin the views that show the register's just have a link to "edit", but what happen if a need an extra(S) links to another views? for example: i have view that show the list of registered People, the nick is linking to the Edit page (the normal way of Django), but i need another links that will show me the "articles" of the people and another the "comments" of the people. how ill make this with django admin? Thanks

From stackoverflow
  • (I'm assuming some field names from your models to answer)

    Make the author field from "comment" searchable:

    class CommentAdmin(admin.ModelAdmin):
       search_fields = ("=author",)
    

    Use list_display and HTML to control what's displayed on the people's list admin page:

    def comments(obj):
        return ('<a href="/admin/pathto/comments/?q=%s">comments</a>' % obj.name)
    comments.short_description = 'comments'
    comments.allow_tags = True
    
    class PeopleAdmin(admin.ModelAdmin):
        list_display = ("name", comments,)
    

    And change /admin/pathto/comments/ to whatever your comment's admin list page is.

    Basically you're going to direct your users to the comments search result page.

    Daniel Roseman : +1, this is absolutely the right way to do it, except I think it's better to keep the function as a method of the ModelAdmin subclass - in which case it will be `def comments(self, obj)`.
    Asinox : Thanks guys, let me try :)

Uninstalling partially installed XCode + iPhone SDK

I tried to install XCode + the iPhone SDK on my mac, but the installer ran out of space during install and I'm left with something to the effect of 30 MB free on my hard disk. How do i remove it?

From stackoverflow
  • Move the folder "Developer" in Macintosh HD to the trash, and then empty the trash.

  • Yup! Just go into your hard drive see the developer folder drag it into trash. Empty that Now Launch the installer for Xcode and it will not see that and just recreate it!

Spring Annotation-based controllers not working if it is inside jar file

Hi,

I've some annotation-based controller inside a sub module. These modules are deployed as jar files.

The annotation-based controllers from the jar file is not getting loaded to the spring configuration.

I'm manually exporting the jar file using the export utility in eclipse.

Did any one faced this problem?

From stackoverflow
  • When you export the jar file using the export utility in eclipse there is a option called Add directory entries. Check this option and export the jar file, this will solve the problem.

    Arun P Johny : Thanks man, you saved my day.

iPhone UITextField within TableCell blanking out

In my iPhone app I have a settings page where a user can enter text into multiple TextFields. The text fields are all cells within a table. The problem I'm noticing is that when a field scrolls off the phone's screen it loses the value currently in the text field.

I notice Apple's apps always have you click on a field to edit it, which brings up a new view with just that field as a text box. Seems like pointless extra clicks, I'm hoping to find a way to allow for a table with UITextFields to preserve their values, even when they scroll of screen.

I do have an event bound to when the user presses the Next/Done button on the keyboard (didFinishEditingField:) to update a value within the table controller, but if they don't press that and the just tap inside another field that isn't triggered.

How can I make sure the values aren't blanked out when I scroll the table and fields leave the current screen?

Edit: For clarification the reason I went with the UITextFields inside of a table and cells, instead of all in one view, is because I wanted it to look like the typical settings page with the stripped background and the groups of inputs.

From stackoverflow
  • Are you reusing cells? Moreover, to create your initial cell do you use dequeueReusableCellWithIdentifier:? I've tried something similar, and it turns out that reusing cells, then adding editable fields to them, produces unexpected results.

  • The problem is that u arent reusing cells properly give all ur textfield cells unique reusable ids Check out my answer herehttp://stackoverflow.com/questions/1180490/iphone-custom-uitableviewcell-with-image-after-scroll/1180817#1180817

    Parrots : Ah ha, thank you sir, that fixed it.
  • I had the same problem, and was not dequeuing cells. Uniquely identifying the cells is confirmed to work.

Is there any BlackBerrry development books or sample apps available?

Hi,

I want to write a BlackBerry mobile application. I've noticed that the information for developing BlackBerry apps is obscure compared to the iPhone.

The samples on the BlackBerry site don't have examples that utilize the most common form objects besides lables and buttons. Does anyone know any other sites with BlackBerry Sample Apps?

Also is there any books on how to develop BlackBerry apps using the BlackBerry API. After some googling I found that everone suggestions a J2ME book. Please don't suggest this, I want a book specifically about the BlackBerry API.

Thanks, Joe

From stackoverflow

linux - running php script from command line when php is installed as apache module

Normally when I want to run a php script from the command line I just create a php page, add a shebang pointing to the php binary, then ./file.php to run it. Since I have php installed as an apache module, I'm not even sure what my shebang should look like. Any ideas?

From stackoverflow
  • If it's just an Apache module, I don't think you can do it… At least, not without using a script like this:

    $ cat run_php_with_apache
    #!/bin/sh
    cp "$1" /var/www/
    curl "http://localhost/`basename "$1"`"
    rm "/var/www/`basename "$1"`"
    
  • The CLI version of PHP had been part of the default installation since 4.3 and has to be explicitly turned off when PHP is being built. If you have access to the command line try

    $ php -v
    

    If you don't get a command not found error then you should be ready to go.

    To actually run a php file from the command line do this:

    $ php -f file.php
    
    David : I get -bash: php: command not found
    Peer Allan : then I think you are out of luck, they must have compiled PHP without the CLI support

How do i know how much space i need for mysql database

Let's say I'm importing multiple csv files into mysql. How can I find out how much space I need for this database (and as far as i noticed it doesn't seem to be the same size like csv files size)?

From stackoverflow
  • Back of the envelope estimation combined with basic knowledge of data type storage requirements.

    For example, CSV file contains:

    • 300k customers;
    • Each customer has first name, last name, address and telephone;
    • Generally you'll need one byte per character (plus one) for a string;
    • Estimate that about 200 characters will be enough to store the above info;
    • 300k * 200 bytes = 60M of data;
    • Add overhead of about 10-20% for indexes, etc;
    • If you anticipate growth, factor that in now. Let's say it'll be 600k within a year;
    • 2 * 60M (doubling) * 1.2 = 144M.

    And there you have an estimate.

  • Just import eg. 100 rows from the CSV. you will get a size for this db including the needed space for indexes. now you can calc up to your estimated rows from the csv. But dont take this numbers to the point, its just an approximation.

  • If you want to get more exact see this MySQL Manual reference.

    Note that if you are using characters sets such as UTF-8 (for Unicode) you may be averaging more than one byte per character in your strings.

How to escape JSON string?

Are there any classes/functions available to be used for easy JSON escaping? Id rather not have to write my own.

From stackoverflow

php variable datatypes

I've just decided to venture off into PHP land for fun and to learn, reading that php is loosely typed and that $var's can be reused is this true that the code below will pose no problem?

$x = 996;
$x = mysql_query("SELECT aString FROM table1");

the variable x will stored as an int datatype with 996, then after the second line it will stored as a string datatype with the string from the query?

There wont be any casting errors?

From stackoverflow
  • You are correct; that's the definition of being "loosely typed". However, that may not be the best practice.

    http://drupaler.co.uk/blog/baby-dont-you-loose-your-type-me/66 is a good read on your subject.

    Rusky : Exactly- using the same variable name just confuses people that have to read the code.
    Jreeter : Thanks I will read this.
  • There will be no errors, except that the second line won't give you a string, mysql_query returns an internal PHP type called a resource (generally some kind of opaque handle/pointer for library functions)

    Jreeter : +1 Thanks Paul!
  • There wont be any casting errors?

    Correct!

    jalf explained it well here

"Cursor is closed" error - when trying to execute an Oracle SP using JDBC

The Oracle version of our database is 10g.

The stored procedure selects all the elements in a table and returns a REF CURSOR type as follows: create or replace

PROCEDURE S_S_TEST( 
  test_OUT OUT OAS_TYPES.REFCURSOR
) 
AS
BEGIN
  OPEN test_OUT FOR      
      SELECT *
      FROM table_p;
   CLOSE test_OUT;
END S_S_TEST;

When this stored procedure is executed in JAVA the following exception is obtained-

java.sql.SQLException: Cursor is closed. at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:323) at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:85) at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1401) at com.ibm.ws.rsadapter.jdbc.WSJdbcCallableStatement.getObject(WSJdbcCallableStatement.java:443)

I am trying to understand what the error is and how it could be fixed. Could someone please help me out?

Thanks!

From stackoverflow
  • The client calling the stored procedure is responsible for closing the cursor. Please remove the code: CLOSE test_OUT;

    The client closes it. In this case the client is the JDBC program that calls the stored procedure.

how to handle php function error

How do i form an if/else statement for a php function failing? I want it to define $results one way if it works, and another if it doesnt. I simply dont want to show an error, or kill the error message if it fails though.

currently, i have;

if(file_get_contents("http://www.address.com")){
    $results = "it worked";}
else {
    $results = "it didnt";}
return $results
From stackoverflow
  • you want PHP's try/catch functions.

    it goes something like:

    try {
        // your functions
    }
    catch (Exception e){
        //fail gracefully
    }
    
    x3ro : I think try/catch only works in PHP5 and with exceptions thrown using throw. Not sure though...
    simonrjones : x3ro is right, I'm afraid try/catch only works with exceptions which are only thrown by PHP's new OO style functionality such as PDO. So not inbuilt functions like file_get_contents() which raises a warning error if the file doesn't exist. You can throw an exception from anywhere, however, and I think it is possible to send normal fatal errors to an exception via the ErrorException class. See http://www.php.net/manual/en/language.exceptions.php and http://www.php.net/manual/en/class.errorexception.php
  • if(@file_get_contents("http://www.address.com");){
        $results = "it worked";}
    else {
        $results = "it didnt";}
    return $results
    

    By prepending an @ to a function, you can surpress its error message.

  • As contagious said, a try/catch function works well if the function throws an exception. But, I think what you are looking for is a good way to handle the result of a function returns your expected result, and not necessarily if it throws an exception. I don't think file_get_contents will throw an exception, but rather just return false.

    Your code would work fine, but I noticed an extra ; in the first line of your if statement.

    if (file_get_contents("http://www.address.com")) {
        $results = "it worked";
    } else {
        $results = "it didnt";
    }
    return $results;
    

    Also, you can store the result of a function call into a variable so you can use it later.

    $result = file_get_contents("http://www.address.com");
    if ($result) {
        // parse your results using $result
    } else {
        // the url content could not be fetched, fail gracefully
    }