Thursday, February 10, 2011

iphone application

Hello ,I am new in iphone application and mac. I have to write an application in which i have ta call server webservice and for that I have used soapenvelope. But there is so much data and around 100 images. so, my application is going to slow down. Can anybody help me that how can i use Asynchronus Request or any other way to faster the performance?? Thnaks in advance..

  • Asynchronous requests won't speed up the thing, but it will allow your app to respond while the data is loading. You can find many tutorials on this all over the internet and SO.

    I would suggest you find a way to not have to download 100 images all the time. Perhaps cache them, so you only have to download them once. Or you could bundle images in your app.

    Also, check out ASIHTTPRequest, which is what many people use for large downloads (anyone else love the McSweeney's app? because I do).

How can I append data to a text file with a line break using Python?

I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.

I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is there a way to do this as the current output is almost unreadable?

  • You just need to explicitly append a '\n' each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use os.linesep instead, if you had to output in binary mode for some reason, but that's a pretty unusual use case -- normally, text mode and \n are much better).

    Dynamo : This worked perfectly. Sorry if this seemed easy but as I stated this is my first time trying to do something like this.
    Alex Martelli : @Dynamo, sure, we've all been beginners at some point!-)
    e-satis : Well, I'm not supposed to be a Python beginer, and discover os.linesep with your answer.
  • I am wondering why you don't have a line break when you print. an example.

    >>> import os
    >>> for files in os.listdir("."):
    ...  if os.path.isfile(files):
    ...   print "file: ",files," length: ",len(files)
    ...
    file:  test1  length:  5
    file:  shell.sh  length:  8
    file:  test.txt  length:  8
    
    Dynamo : There is a line break when I use the print command in the console but when I write to the text file it was not showing up. That's part of the reason I was confused as the console did not require me to use \n to create the line break.
    ghostdog74 : yes, if you are using write() method, you need to append "\n"
    From ghostdog74

jquery animation not showing up

$('#main-mission .fade').animate({opacity:1.0;filter:alpha(opacity=100);}, { queue:true, duration:2000 }).animate({opacity:1.0;filter:alpha(opacity=100);}, 1500).animate({opacity:0.0;filter:alpha(opacity=0);}, 800,'linear',function(){
$('#main-mission .fade').html("<font size='3'>... to organize and display the data that people need, to give them the ability to make smarter decisions and purchases that will help the environment, as well as reduce their monthly electricity costs.</font>"); }).animate({opacity:1.0;filter:alpha(opacity=100);}, 2000);

...thats my jquery,

<div id="main-mission">
<table><tr height="28"><td width="11"></td><td width="475" style="height: 75px;" class="boxed"><div class="fade" style="opacity:0.0;filter:alpha(opacity=0)"><font size="4">&nbsp;&nbsp;&nbsp;&nbsp;The Spare Our Green Mission ...</font><br><br></div> </td></tr></table>
</div>

and that is the HTML. I'm not quite sure why it isn't, working... could someone please help?

Thanks.

  • Have you tried removing parts of the chain down to the first element and then adding them back in one at a time to see what is broken? It's a long function call to try and read and parse.

    From Paddy
  • I think that the non numerical values should be in quotes like filter:"alpha(opacity=0)";. What error message are you getting (from firebug, i.e.)?

    -- edit

    Btw. IE8 is using -ms-filter for opacity now.

    Walt W : I think stefita is right - I just had the same problem (jQuery animations) with an object using css style filter:alpha(opacity=0), and putting quotes around the alpha(opacity=0) part worked for me.
    Walt W : Correction - the double quotes actually just disabled the filter: attribute, which is why it started working on my end. Looks like we're out of luck for animations with a filter?
    From stefita
  • You have used semi-colons where you should have used commas to separate the css attributes being animated. Also you don't need to try and add IE support with filter attribute. Try this code, tested in FF3.5 and IE8

    <html>
    <head>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
        <script type='text/javascript'>
            $(document).ready(function()
            {
                $('#main-mission .fade')
                    .animate({opacity:1.0}, {queue:true,duration:2000})
                    .animate({opacity:1.0}, 1500)
                    .animate({opacity:0.0}, 800,'linear',function()
                        {
                            $('#main-mission .fade').html("<font size='3'>... to organize and display the data that people need, to give them the ability to make smarter decisions and purchases that will help the environment, as well as reduce their monthly electricity costs.</font>");
                        })
                    .animate({opacity:1.0}, 2000);
            });
        </script>
    </head>
    <body>
        <div id="main-mission">
            <table>
                <tr height="28">
                    <td width="11"></td>
                    <td width="475" style="height: 75px;" class="boxed">
                        <div class="fade" style="opacity:0.0;filter:alpha(opacity=0)">
                            <font size="4">&nbsp;&nbsp;&nbsp;&nbsp;The Spare Our Green Mission ...</font>
                            <br>
                            <br>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </body>
    </html>
    
    From Ambrosia
  • I agree with Paddy. You should write a simpler version of your code and then try it out. Make only one call to $.animate(). Once you get that working, then add in the callback. Once that works, then add the chaining.

    Also note that you should not use the <font> tag. It is not valid HTML.

    From Alex Kahn

Getting List Item URL in Sharepoint 2007

I'm creating a webpart that aggregates a load of content from different lists throughout our site collection what I can't workout is how to get the exact link to each item. All I seem to get back is {site}/{listtitle}/1.000 how do I get this "1.000" to say "pagename.aspx?id=1", is this something I have to work out myself or is there a function to do this?

  • To get the ID of an item in a list you can use SPListItem.ID. Then you can just append it to the base URL that you want, e.g. "pagename.aspx?id=" + myitem.ID.

    Goyuix : A corollary to this: You can also see the ID for an item in the URL if you look closely... DispForm.aspx?ID=20 etc.
  • How I do it:

    string itemUrl = List.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl + "?id=" + item.ID;
    
    From Chloraphil

JavaScript diagramming tool

Does anyone know any good JavaScript alternatives to mxGraph (http://www.jgraph.com/mxgraph.html) that allows the user to draw Visio style diagrams on a canvas and add/edit/remove properties of elements?

  • gRaphaël, based on SVG (all browsers) and VML (the stuff they call a browser in Redmond) is a generic graph painter with very good performance. I think, it could be extended to meet your needs.

    From Boldewyn
  • Google Docs includes a very good JavaScript diagramming tool. No, it's not open source or free, but is is good.

    From brianegge
  • mxGraph is the one component of this type I've seen, what's wrong with it? gRaphaël is a chart drawing app, the user is looking for diagram drawing.

    From David
  • http://thejit.org/

    elviejo : This is incredibly I didn't know Javascript could look and work at that speed. Highly recommended
    From
  • Joint - http://www.jointjs.com is a free and easy to use JavaScript diagramming library.

    From dave

Creating a CAB file on WinCE

Hello

I want to make a CAB file on a WinCE 5/6 device. The idea is that someone would run a backup script that creates the CAB file, which can then be loaded back onto the device at any point restoring settings to a previously known point.

The settings are xml and custom files in various folders on the device, I am not talking specifically about registry settings.

If this cannot be done is there (commercially) free ZIP file creation software that could be used?

Thankyou in advance Chris

how to load a big picture or swf file by calling Loader.load() in Flex, and make the container adjust the size of the loading content?

Hi All,

I get a ActionScript class for loading the content:

public class LoaderContainer extends Sprite {

    public function LoaderExample() {
        loader = new Loader();      
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
        addChild(loader);
        var request:URLRequest = new URLRequest("File://C:/1.swf");
        loader.load(request);
    }
    private function completeHandler(event:Event):void {
        Alert.show(this.x+"/"+this.y+"/"+this.width +"/"+ this.height);
    }

}

And then add the LoaderContainer to a Panel control in main MXML.

What supprise me is that the LoaderContainer's width/height is changing all the way according to the contents that it loaded.

Is there any way that we can limit the content's size right obeying the container's size?

Thanks Michael

  • Since you're using Flex, is there any reason why you wouldn't just load it directly into an mx:Image or mx:SWFLoader? Since you're loading it and using addChild it's not being wrangled into the Flex framework where you could control it...

    <mx:Image source="File://C:/1.swf" width="100" height="100" />
    
    From onekidney

ruby: how to know if script is on 3rd retry ?

begin
#some routine
rescue
retry
#on third retry, output "no dice!"
end

I want to make it so that on the "third" retry, print a message.

  • Possibly not the best solution, but a simple way is just to make a tries variable.

    tries = 0
    begin
      # some routine
    rescue
      tries += 1
      retry if tries <= 3
      puts "no dice!"
    end
    
    From jtbandes
  • 3.times do
      begin
        ...
      rescue
        ...
      end
      break
    end
    

    or

    k = 0
    begin
    #some routine
    rescue    
      k += 1
      retry if k < 3
      # no dice
    end
    
    DigitalRoss : The best of the early answers...
    From glebm
  • class Integer
      def times_try
        n = self
        begin
          n -= 1
          yield
        rescue
          raise if n < 0
          retry
        end
      end
    end
    
    begin
      3.times_try do
        #some routine
      end
    rescue
      puts 'no dice!'
    end
    
    From Justice
  • The gem attempt is designed for this, and provides the option of waiting between attempts. I haven't used it myself, but it seems to be a great idea.

    Otherwise, it's the kind of thing blocks excel at, as other people have demonstrated.

System.Runtime.InteropServices.COMException: Unknown error (0x80005000)

This is the detailed error info.

Failures: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: Unknown error (0x80005000) at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_NativeObject()

Code that causes the above exception:

 DirectoryEntry de1 = new DirectoryEntry("RNA:");
 IRnaNamespace rnaNamespace = (IRnaNamespace)de1.NativeObject;

After the del object is created, I try to watch the values for variant del, and this is the result: link text alt text

The OS is Windows2008 R2 64bits. And it can run successfully on Windows2008Sp2 32bit.

  • The error is caused by the following statement:

    DirectoryEntry de1 = new DirectoryEntry("RNA:");
    

    Because it will call another project AAA which is built in 32 bits system to create the directory. After rebuilt AAA in 64 bits, everything is OK.

    From Carlos_Liu

Fortran and mysql

Is there a library (opensource), so I can access MySQL in Fortran?

facebook api key problems php

I get an invalid API key which is definitly correct- no whitespaces or nothing- im stuck

Fatal error: Uncaught exception 'FacebookRestClientException' with message 'Invalid API key' in /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebookapi_php5_restlib.php:3112 Stack trace: #0 /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebookapi_php5_restlib.php(309): FacebookRestClient->call_method('facebook.auth.g...', Array) #1 /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebook.php(206): FacebookRestClient->auth_getSession('c6b7baef6d609ba...', false) #2 /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebook.php(167): Facebook->do_get_session('c6b7baef6d609ba...') #3 /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebook.php(68): Facebook->validate_fb_params() #4 /home/maxer/domains/follor.com/public_html/xmasapp/index.php(15): Facebook->__construct('?99a8a43434baf7...', '?02365dce6ae555...') #5 {main} thrown in /home/maxer/domains/follor.com/public_html/xmasapp/facebook/php/facebookapi_php5_restlib.php on line 3112
  • error comes from the code i pulled from the facebook demo app- for the initialisation of the facebook object-

    the quotes should be double quotes and not single quotes for the api key and secret

    $api_key = "bla";
    

    instead of

    $api_key = 'bla';
    
    Mark : I didn't downvote this, but double or single quotes makes absolutely no difference unless you have some `$`s in your key.
    From chris

Upload file suggested by microsoft doest work for me in CGI.

Hi all,

we would like to upload a .zip file in windows mobile to .cgi script running at server. in desktop we have "Webclient.uploadfile" API, it does't support in winmo. do we have any alternative methods to upload file in windows mobile.. we tried a sample

method suggested by Microsoft,but it doesnt work for our CGI script. please let us know any alternatives available for this problem.

Thanks Grabit

  • Hey just follw up this link

    it has detail steps to upload file to server from windows mobile

    From Shadow

display a long string in a table row

i have a tableview which displays the result from the web service the result fron the web sevice is in form of string array, where each string in the array is pretty long. It is like "1|123|JP Morgan|111|2000.0|Pending", similarly there are strings which i diplay in each row of the table. but as you can see the string is very long, to display it in a single table row. in the table view, i can just view first 3 ie "1|123|JP Morgan" the it shows.....

how can i display the entire string in the table

  • You can add a UILabel to your cell's contentView. If you do this, you can set the UILabel.numberOfLines to a number greater than 1. If you set it to 0, it will use as many lines as needed.

    shreedevi : how do i increase the labels at runtime, like i dont know, what would be the result coming from the web service.
    marcc : Set numberOfLines to 0. It will expand as needed then, to fill the frame you've set.
    From marcc
  • Your options are to make it smaller or make a custom table cell. To change the size, set the property cell.textLabel.font to a font of a smaller size (e.g. using [UIFont systemFontOfSize:10]. You may also want to change cell.textLabel.numberOfLines to something greater than 1.

    To see more about making custom cells, read the Table View Programming Guide.

    From jtbandes

emacs C and C++

Hi there,

I have some very specific questions related to emacs for building C applications:

1) How can I compile a file written in C/C++ using emacs.
2) How can I have something similar with MS Intellisense in emacs?
3) How can I add an C/C++ library to the compiler and emacs to know about it.

many thanks

    1. M-x compile (see this SO question)
    2. M-/ (see this SO question, which is exactly the same)
    3. The same way you would w/out using Emacs
  • Emacs is an editor, not an IDE. It has a ton of 'extra' features and is very configurable for an editor - but it's really not meant to be an IDE. If you want an open-source IDE you might want to check out Eclipse.

    Having said that - you can compile from within emacs in a number of ways: 1. Just open a shell in another buffer (M-x shell) and compile from there. 2. Set up a Makefile and use the M-x compile

    I'm sure there are complicated ways to get the other behaviors - but you'd probably be better off using a real IDE.

    cschol : Emacs can be anything you want it to be. Even an IDE. What Emacs is really 'meant to be' is probably another more philosophical discussion.
    Steve Jessop : As the saying goes, "emacs is a great programming environment. All it really needs is a decent text editor" ;-)
    Laurynas Biveinis : @cschol and all the downvoters, look, while you are technically right that "Emacs can be made to be an IDE", you are are overlooking the facts that 1) how easy it is for an Emacs beginner to get IDE features? Are CEDET/JDE installed and preconfigured out of the box? 2) Once you setup CEDET/JDE, well, how is Emacs then comparing against Eclipse/IDEA/VS feature-wise? Refactorings, anyone? I am using Emacs as my main tool, but, folks, let's be honest that declaring "Emacs is an IDE" is a stretch.
    outis : @kastauyra: You can write code, compile and debug from within Emacs. That's enough to make it an IDE in my book, though it perhaps pales in comparison to other IDEs.
    justinhj : @kastuauyra Not all software tools can to be learned in 5 minutes, nor should they be necessarily. Professional programmers will be using tools potentially their whole working lives, so it's worth investing time learning ones that have the flexibility and power to endure.
    Laurynas Biveinis : @justinhj I did not say that Emacs should be so simple that it could be learned in five minutes. I am all for investing time in learning tools, which I am doing with Emacs, BTW. It's just that a lifelong learning of Emacs will give me ability to "refactor" my code with very clever regexps and keyboard macros, and that's it. Missing feature in a tool is a missing feature regardless of a tool user's skill level.
    From Aaron
  • code completion - Semantic (from CEDET package), compilation - depends on what you use to compile, but basically you can use EDE package (from CEDET) to maintain & compile projects

    From Alex Ott
  • Take a look at this blog post I made, which shows you how to write a cpp program in emacs. If you want tab completion you also need to learn to generate and use tags, and the M-/ button.

    When programming using emacs however, you do more than emulate Developer Studio or Eclipse. Learning to use keyboard macros, and program in elisp, will empower you to write little utilities that take a few minutes to write and save many times that in drudge work.

    From justinhj

What free or cheap tools I can use for website creation business?

I need to do a website for a friend who will pay me on delivery. I took a few courses in ASP.NET and think I can do it in ASP, but I am not sure ASP is free, since its a Microsoft product. Is there a way to use some kind of free version of ASP.NET to develop and sell a website or should I buy it? If it's not free, what are the free or cheap alternatives to it?

  • Microsoft offers Visual Web Developer Express for free. It will do pretty much everything you need in terms of developing and testing an asp.net website.

    http://www.microsoft.com/express/vwd/


    Edit-

    The only expense with using ASP.net is the hosting environment. Asp.net typically requires an IIS web server to run. If you are planning on hosting the site yourself this can be a significant investment. If you are using a hosting company windows hosting with Asp.net is typically included at little or no additional charge.

  • Mono has ASP.NET support

  • PHP and Perl are free. I believe you need IIS as your webserver to host ASP applications, meaning you need to run Windows Server.

  • Just about anyone can create a content-only web site using many free tools that available. ASP is an industrial-strength solution for reading/writing to a data base, managing 1,000's of users and/or pages of content or similar.

    For example, You could probably create a site for a family-owned restaurant that had their hours, menu and a map to them, maybe photos of their specialites and a "web coupon" and do it in a few hours.

    But if you wanted to create the corporate site for TGI Fridays or Dennys, let users sign up, keep track of their points, have a loyalty card, etc. you would need additional skills.

    Accepting credit cards? Consider that VISA has very strict standards for storing numbers you accept from customers.

    There's a LOT to creating a web site that is more than some static HTML and a few photos.

  • ASP.NET is free development platform. Try visual web developer express edition which is free. If you need database try sql server 2008 express edition which is free. At microsoft express edition of any product is available for free.

    Yet microsoft is giving away their proven developer tools for free for startups and freelance develoeprs.

    1. If you are a student -> DreamSpark

    2. Small website development company having less than 10 people -> WebsiteSprak

    3. If you are a startup with more employees -> BizSpark

    Microsoft rocks.

XSL for-each: how to detect last node?

I have this simple code:

<xsl:for-each select="GroupsServed">
  <xsl:value-of select="."/>,<br/>
</xsl:for-each></font>

I'm trying to add a comma for each item added.

This has 2 flaws:

  1. Case of when there's only 1 item: the code would unconditionally add a comma.
  2. Case of when there's more than 1 item: the last item would have a comma to it.

What do you think is the most elegant solution to solve this?

I'm using XSLT 2.0

  • If you're using XSLT 2.0, the canonical answer to your problem is

    <xsl:value-of select="GroupsServed" separator=", " />
    

    On XSLT 1.0, the somewhat CPU-expensive approach to finding the last element in a node-set is

    <xsl:if test="position() = last()" />
    
    ShaChris23 : thanks for the XSLT 1.0 approach. It worked fine on my 2.0
    Stobor : I shouldn't try to answer these questions via a phone. I've added the detail on the XSLT2.0 method, in case it wasn't clear earlier.
    From Stobor
  • Final answer:

    <xsl:for-each select="GroupsServed">
      <xsl:value-of select="."/>            
      <xsl:choose>
        <xsl:when test="position() != last()">,<br/></xsl:when>
      </xsl:choose>
    </xsl:for-each>
    
    From ShaChris23

Datagridviewtextboxcolumn lenght and text problem?

Using VB.NET

Am Using a textbox in Datagridview

Code for adding a textbox in DataGridview

Dim ti As New DataGridViewTextBoxColumn
DataGridView1.Columns.Add(ti)

Text box Maximum size should be 5. Text box should display " : "

How to set like this.

Need vb.net code Help

  • I'm not sure what you mean by 'Text box should display ":"' ? Are you wanting to provide a mask or something? Anyway, here's how to the maximum size bit:

        Dim ti = New DataGridViewTextBoxColumn
        ti.DataPropertyName = "TODO"
        ti.Name = "TODO"
        ti.HeaderText = "TODO"
        ti.MaxInputLength = 5
        DataGridViewTextBoxColumnDataGridView1.Columns.Add(ti)
    
    From rip

octave + gnuplot + os x 10.6 : nothing happens

On my first-gen Macbook Pro, with OS X 10.6.1, I can launch gnuplot and get a plot, after I set the terminal to x11, with a command like

plot [-6:6] sin(x).

But when I launch octave, and try a plot command, like

plot([2 3],[4 5]) or plot([-6:0.01:6],cos([-6:0.01:6]))

I get no error messages and no plot. Just another octave prompt. I installed from octave-3.2.3-i386.dmg. What gives?

Any suggestions appreciated.

  • If gnuplot works after setting the terminal to x11 (set term x11), then you could try the same in octave:

    octave-3.2.3:1> setenv GNUTERM 'x11'
    

    I believe that the default terminal of gnuplot on OS X is aquaterm, so it is probably the default terminal when octave is plotting with gnuplot as well.

    Mike Briggs : Jonatan Lindén, thank you! Your suggestion worked.

Compiling program within another program using gcc

From command line i am getting file name which i have to compile using gcc. lets say its like this.

./a.out fileToBeCompiled.c

Then how i can compile this file using gcc within my program? lets say main.c for which a.out is being made.

  • You can always call gcc to compile from an shell execution command within your program.

    Reference to the system function.

    itsaboutcode : Thanks, it work for me.
    ammoQ : Using system is a bad idea, but if it works for itsaboutcode, it shall be fine with me
    From monksy
  • Just exec gcc from within you program.

    int main(int argc, char** argv)
    {
       execv("/usr/bin/gcc", argv);
    }
    
    From stimms
  • Learn how to call fork(), exec(), and wait(). You probably want to use execv() for this purpose.

    From D.Shawley
  • ./a.out fileToBeCompiled.c && gcc fileToBeCompiled.c
    

    If ./a.out fails (it it returns something other than 0) gcc will not be called

    From pmg

HTTP proxy server

I am beginning work on a very basic HTTP proxy server written in C (Edit: something that just forwards my requests). At this point I am having difficulty in understanding how to proceed.

Any help would be beneficial.

  • A proxy server for what protocol? Before you know that, starting coding is not the most beneficial next step.

    After you've decided on what protocol to implement, you (probably) need to read up on the sockets API.

    Once that's done, there's three major routes to go, using a poll/select-based loop, forking off per-session processes or using threads to shuffle data.

    AJ : Its a HTTP proxy and I know sockets API.
    Ferdinand Beyer : Strange. Are Ankit and Alex Xander in fact the same person?
    From Vatine
  • Take a look at micrp_proxy. It implements all the basic features of an HTTP/HTTPS proxy, in only 260 lines of code.

    Another very simple implementation can be found at Proxy

    Alex Xander : Thanx! They are useful links.
    From AJ

Nonblocking webserver on .Net for Comet applications

I am trying to implement a Comet style (e.g. chat) application using IronPython. While I don't need to scale to twitter like dimensions, it is vital that the response time is lightening fast. All the possibilities in Python (Twisted, Tornado, Magnum-Py) do not work with IronPython, often because of epoll support.

Is there a default choice in the .Net world for comet style applications? Or a pure python implementation with long-pulling support? I have tried NTornado, but performance is currently very poor (100-1000x slower than Tornado).

  • There sure is. Check out WebSync, a full comet solution for .NET/IIS. To my knowledge, it's the only full implementation of comet for .NET available today. You can use the on-demand version for free (up to a limit), or pick up the server version to host it yourself. It's pretty inexpensive too, no runtime fees, etc.

    From jvenema

program a Firefox extension to download a page

I want to apply a regex to a page whose URL only my extension is going to know. How do I program a Firefox extension to download the page?

  • Found! "To load from file://, http://, chrome://, resource:// and other URLs directly, use XMLHttpRequest or nsIChannel (example)." - File I/O

Sending mail when a table is updated

Hi, my name is Tayyeb, I have recently finished my course in SQL Server 2005. I am currently working as a Windows System Administrator.

I am a newbie to databases, my question is that we have a database and if a table gets updated then I'd like to receive an email saying what has been updated.

Can anyone help me on this solution?

Thanks in advance

  • You would want to setup insert and update triggers on the table and have them call the msdb.dbo.sp_send_dbmail stored procedure.

    pjp : Just be careful about how you are updating your tables as you could generate a large number of emails.
    stimms : pjp is right, this sets off all sorts of bad idea alarms
    RBarryYoung : +1: readers here should note the importance of using the "dbmail" procedures (new in SQL Server 2005) and not the SQL Mail procedures. Among many other improvements the DBMail procedures send asynchronously, so they are safe to use from triggers. (you should *never* use synchronous communications from triggers, very bad juju).
    RBarryYoung : By "safe" from triggers, I mean that t will never lock-up the user's trying to access the table. Email "flooding" is another thing altogether.
    From CptSkippy
  • Create a table that stores the datetime for the last update in that particular table.

    Set up a trigger for your table that updates the datetime on an update.

    Have an external application poll the datetime at a regular interval, and if it is changed, send an e-mail.

    From Zed
  • Using a trigger is a given. Either solution, DBMail or a polling process, will work. If you go with a polling process, go ahead and make the polling interval something you can change while the polling process is running, if possible. The problem you are going to run into is if you want to test or debug it, you won't want to wait the full polling interval. If the interval is 5 minutes, you either have to restart the poller or have a separate polling interval just for checking if the polling interval changed (can we say recursive?). So write the poller with debugging/testing in mind.

    That might be enough to convince you to use the DBMail solution. I've never used it so others will have to speak to that.

Negative integers to percentage

I have a lot of files with data to convert to percentages using basic math functions:

<param id="1" name="otb" value="0.160"/>
<param id="2" name="blm" value="-0.210"/>
<param id="3" name="mep" value="-0.010"/>
<param id="4" name="plc" value="-0.100"/>

Each id get's it's own equation:

  1. (n-(-.3))/2.3*100
  2. (n-(-.8))/3.3*100
  3. (n-(-.5))/1.5*100
  4. (n-(.1))/1.1*100

So I get:

otb=8 blm=20 mep=24 plc=0

What would be a good way to run all these files through... regex and php? Any quick and dirty code out there? :D

  • As the file seems to be in XML format, I suggest you try the PHP simplexml library. The documentation can be found here.

    You can then access the XML tree simply by accessing the magic properties of the XML object:

    $xml = simplexml_load_file('your/path/to/your/file');
    
    foreach ($xml->param as $param)
    {
        $id = $param['id'];
        $name = $param['name'];
        $value = $param['value'];
    
        // do your calculations...
    }
    
    Workshop Alex : Or a simple transformation with an XML stylesheet. :-)
    Franz : @Bravo Charly: Did this work?
    Bravo Charlie : @Franz: Looks good so far... still reading the documentation. I'm by no means a coder, ha.
    From Franz
  • Stylesheet magic:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
      <xsl:output indent="yes" standalone="yes" omit-xml-declaration="yes" method="xml"/>
      <xsl:template match="*">
        <xsl:copy>
          <xsl:variable name="Values" select="@*[(name(..)='param') and ((name(.)='value'))]"/>
          <xsl:variable name="NonValues" select="@*[. != $Values]"/>
          <xsl:apply-templates select="$NonValues" mode="NonValues"/>
          <xsl:apply-templates select="$Values" mode="Values"/>
          <xsl:choose>
            <xsl:when test="*">
              <xsl:apply-templates select="*"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="."/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:copy>
      </xsl:template>
      <xsl:template match="@*" mode="Values">
        <xsl:attribute name="value"><xsl:variable name="n" select="."/><xsl:choose><xsl:when test="../@id=1"><xsl:value-of select="(($n - (-0.3)) div 2.3) * 100"/></xsl:when><xsl:when test="../@id=2"><xsl:value-of select="(($n - (-0.8)) div 3.3) * 100"/></xsl:when><xsl:when test="../@id=3"><xsl:value-of select="(($n - (-0.5)) div 1.5) * 100"/></xsl:when><xsl:when test="../@id=4"><xsl:value-of select="(($n - (0.1)) div 1.1) * 100"/></xsl:when><xsl:otherwise><xsl:value-of select="."/></xsl:otherwise></xsl:choose></xsl:attribute>
      </xsl:template>
      <xsl:template match="@*" mode="NonValues">
        <xsl:copy>
          <xsl:value-of select="(.)*2"/>pp
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    

    If you can transform the original XML with this stylesheet, you will get a new XML with calculated results. It is a bit complex but basically the code is processing all elements and child elements. For each element, it splits the attributes up in values that need to be converted and other values. It copies every element, every child element and every attribute, except the value attributes. The value attributes are processed and given another value. (But you can also just add the original value, if you want to keep it.)