Thursday, April 7, 2011

PHP Lexical and Syntax analyzer written in C/C++

I'm writing a PHP IDE in Qt4 for my Master's project. I am trying to duplicate a lot of the functionality of Eclipse or Visual Studio without all the bloat and the overhead. I'm trying to do some code completion but I need to do some syntax analyzing to have intelligent code completion. I've looked at the PHP source code and thought about just compiling the Zend engine in my code (and give credit where credit is due), but even after staring at the code for a couple of days I'm not sure where to start with that.

Does anyone know some C++ code that already accomplishes this, or have used the Zend engine for their own purposes, or have some advice about writing my own?

From stackoverflow
  • PHP does not have anything even remotely close to a formal LALR(1) or LL(k) grammar that you could use to implement this in a manner suitable for academia. Zend's parser is not context-aware and is full of ad-hoc disambiguations from what I've seen.

    That is not to say you cannot write something that does simple syntax highlighting. Take for example this javascript implementation. The code for their tokenizer is here and an active thread about the project is here.

What is state of iPhone SDK NDA?

There are lots of iPhone SDK tutorials on the web now. It's a little confusing to come across a tutorial/post where someone is stating they can't do this or that because of the NDA. Yet, the NDA has been lifted. What exactly are the restrictions in regards to posting code and talking about the SDK?

Here's one example: The book 'iPhone SDK Development', http://www.pragprog.com/titles/amiphd/iphone-sdk-development, didn't go to press because of NDA violations. Yet they are going to publish in May 2009. Confusing.

If someone creates an iPhone SDK cheat sheet type app, will it get rejected from the App Store because of NDA violations?

From stackoverflow
  • The NDA has only been lifted for current public releases of the OS. Developer-seeded future releases are still under NDA.

    See also: What are the overall consequences of the iPhone NDA going away?

    4thSpace : So people are free to talk and post code up to SDK 2.2.1? Meaning you can write an iPhone sdk cheat sheet app about 2.2.1 with no fear of NDA violation.
    sjmulder : Correct, 4thSpace

How does peer2peer work through a router?

How does one PC connect to another over the internet to another PC?

An example would be a program listening for connections on PC 1. PC 1 sits behind Router 1. PC 2 has a client program trying to connect to PC 1.

What is the correct technology/technique to use as the listening program in this situation?

From stackoverflow
  • This article by Brian Ford explains how peer to peer communication across NATs work.

    Most routers also expose a Universal Plug and Play interface (uPnP) which can be used for port forwarding and NAT traversal.

    You should also check out the STUNT library which is an easy to use NAT traversal library.

  • You may want to read up on NAT Traversal. NAT traversal is a general term for techniques that establish and maintain TCP/IP network connections traversing network address translation (NAT) gateways.

How can I convert formatted text on a webpage and in the database to RTF or doc.

I have some formatted data that needs to be saved from the web page as a word document or rtf, something ubiquitous so I am thinking RTF. What is the easiest way to save something from .net as rtf? Are there built in tools for this or some plugins?

From stackoverflow
  • A tool like this does the trick for manual one-off conversions.

    And if you want to do the same thing programmaticially

  • Personally, I think the formatting should be left out of the database. I'd much prefer seeing the data stored in a format-agnostic way. It might be useful for other purposes, and you can defer formatting choices until the last moment.

    Chris Ballance : He did not mention a database and you didn't really address his question.
    duffymo : I inferred it from "save", but you're correct - it could just be written to a file system as a document.
    Chris Ballance : However, I like your point about not storing formatting if this is going into a database. If you don't know how the data might come back out, why mark it up before storing.
    Salt Packets : I mean save as a file or feed it as a download to browser. I agree it should be stored in db without formatting.

What's your favorite way to debug your program in Visual Studio?

These day I come up with a large software.

I have to debug in Visual Studio 2008.

The steps I take are:

  1. Using callstack window to find the code blocks that I i thinks it may have bugs.

  2. Using Immediate windows to call some local functions to see whether the data structures in this blocks are correct.

  3. When I got the result in step 2,I have to go to step 1 to find the source of the bug using callstack again.

What is your favorite method to debug large or small program in Visual Studio?

I don't think to run whole the program and watch all the related data structure is good way to debug.

From stackoverflow
  • One of my AHA-moments in VS200x-debugging was realizing that I can use "Attach to process..." in order to start debugging an executable that already is running. For large solutions, it is surprisingly often faster to launch the application in "normal" fashion and then attach Visual Studio to it, compared to starting the debugging session by pressing F5.

  • Putting breakpoints into suspicious methods and using Immediate Window is my way. I'm a huge fan of Immediate Window.

    Also conditional breakpoints are the other way I like. especially when I'm iterating a collection to find an object that is suspicious. I put a condition to breakpoint and press F5 to get it.

    Ctrl + Alt + Q combination is another good shortcut for Quick Watch Window to analyze an object.

  • I prefer unit tests over using the immediate window, mostly because it means I can run the code over and over again extremely simply (and indeed from a build script).

    If you find the problem using the immediate window and fix it without adding any tests, you don't have anything warning you if the same problem comes back again. With a unit test, you have a constant companion to make sure that any future changes don't reintroduce the bug.

    Personally I don't like having to step through code - I find it frustrating compared with unit testing. It's too easy to accidentally step over something you wanted to step into etc. It's sometimes necessary, but it's often a sign that your code is too complicated. I particularly dislike having to debug a whole application rather than just stepping through a unit test in the debugger. It's usually orders of magnitude slower.

  • My favourite way when being introduced to a large application:
    - Always: "Read all the code" end to end (this is the most interesting)
    - Bookmark the central parts of the code.
    - Refactor & write test while debugging

  • To locate the code that corrupts a variable's value I create a data breakpoint for that variable. The program will break its execution every time the variable's data changes, either through correct code, but also through a stray pointer.

  • The important point about debugging in my opinion is to form a theory about where the bug may be. In other words try to look at the code and think about the problem before launching the debugger.

    I asked a similar question, so you may want to check the answers to that as well.

Help using Flotilla and Ruby on Rails

I'm new to Rails (and StackOverflow), so I apologize if this is a "dumb" question. I've put together a really simple Rails application. It receives data from another server (via HTTP POSTs). I would like to graph the data sent - in particular, I am looking to graph temperature versus time.

I am trying to use Flotilla to generate these graphs, but I can't seem to find much documentation on how to use it except for the one line example on the home page:

        = chart("graph", {"Store 1" => {:collection => @store_one, :x => :date, :y => :sales }, "Store 2" => {:collection => @store_two, :x => :date, :y => :sales }})

This is my index.html.erb:

<table>
  <tr>
    <th>Temperature</th>
    <th>Time</th>
  </tr>

<% for post in @posts %>
  <tr>
    <td><%=h post.temperature %></td>
    <td><%=h post.created_at %></td>
  </tr>
<% end %>
</table>
<%= chart("graph", { "Graph1" => { :collection => @posts, :x => :created_at, :y => :temperature }})%>
<br />

The first part simply prints out the list of temperatures and times. This works fine. Unfortunately, the second part - the actual graph - doesn't seem to work. Nothing actually displays.

If I look at the source of the generated HTML, I see:

    <script language="javascript" type="text/javascript" src="/javascripts/jquery.flot.pack.js"></script>
    <script type="text/javascript">
      $.plot($('#graph'), [{"data":[[1234191865.0,12.0],[1234192069.0,15.0],[1234192113.0,16.0],[1234192123.0,18.0],[1234192189.0,21.0],[1234192203.0,25.0],[1234192320.0,27.0],[1234192329.0,29.0],[1234192384.0,30.0],[1234192391.0,31.0],[1234192402.0,35.0],[1234192409.0,29.0],[1234192412.0,31.0],[1234192414.0,27.0],[1234192419.0,25.0],[1234211826.0,27.0]],"label":"Graph1"}], {});
    </script>

but no actual graph is displayed. Thanks in advance for any help.

From stackoverflow
  • Try adding a div element with id graph anywhere in your page; it will be used as a canvas for the chart.

    <div id="graph" style="width:600px;height:300px;"></div>

    The id of the element must match the string you pass as first parameter to chart.

    When in doubt, you can look at the source of the various example pages on the Flot site.

    Cheers, V.

Mimicking the UltraGridColumnChooser's drag & drop ability

(Infragistics 2008 Vol. 3, CLR 2.0)

Infragistics's UltraGrid comes with a column chooser user control, which is simply a vertical arrangement of columns with checkboxes that toggle a column's hidden state. In addition, it allows you to pick a column and drag it directly to the grid so you don't have to manually position it afterwards. (This is particularly handy when you already have a lot of visible columns and have no clue where the new one ended up.)

I'm building my own column chooser based on an UltraTree. Getting the checkboxes to behave the same wasn't an issue, but I haven't found a way to drag a column from the tree to the grid and have it accept it.

In my tree, each UltraTreeNode has a Tag with the following struct:

Private Structure DraggableGridColumn
    Public NodeKey As String
    Public NodeName As String
    Public ParentKey As String

    Public Column As UltraGridColumn
End Structure

I then have an event as follows:

Private Sub columnsTree_SelectionDragStart(ByVal sender As Object, ByVal e As System.EventArgs) Handles columnsTree.SelectionDragStart
    If columnsTree.SelectedNodes.Count <> 1 Then
        Return
    End If

    If Not TypeOf columnsTree.SelectedNodes(0).Tag Is DraggableGridColumn Then
        Return
    End If

    Dim column As UltraGridColumn = CType(columnsTree.SelectedNodes(0).Tag, DraggableGridColumn).Column

    columnsTree.DoDragDrop(column, DragDropEffects.All)
End Sub

In the DoDragDrop call, neither column (of type UltraGridColumn) nor column.Header (of type ColumnHeader) get accepted by the grid. I assume I'm sending the wrong type, and/or that the grid expects a special struct with some additional information. Unfortunately, I've also failed to catch an event (both on the column chooser side as well as on the grid side) where Infragistics's normal column chooser does this properly; the normal drag & drop events never seem to fire.

From stackoverflow
  • It looks like the column would have to be an UltraTreeNode for that to work. Presumably you are putting the column data into a (derived) UltraTreeNode of some sort, so you might want to try decanting it and using that object in the DoDragDrop call.

    -- MarkusQ

    Sören Kuklau : Thanks for your answer — unfortunately, an Infragistics rep has since clarified I would indeed have to re-implement this behavior (that is, reusing the UltraWinGrid's drop portion of the regular Drag & Drop code isn't possible).

Java applet double buffer trouble (and loop trouble)

For some reason when I try to double buffer my Java applet it shows up a white square even though I'm not telling it to. Also if I try to put a loop in start() I get only a white screen even if repaint() is at the end.

/**
* @(#)vo4k.java
*
* vo4k Applet application
*
* @author William Starkovich
* @version 1.00 2009/2/21
*/

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*; 

public class vo4k extends Applet implements KeyListener
{
obj p1, e1;
boolean[] keys;
boolean end = false;
Graphics g2d;
Dimension size;
Image buf; 

public void init() 
{
 keys = new boolean[256];

 for(int i = 0; i < 256; i++)
  keys[i] = false;

 addKeyListener(this);
 p1 = new obj();
 p1.x = 0;

 size = getSize();
 buf = createImage(size.width,size.height); 
 g2d = buf.getGraphics();
}

public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {keys[e.getKeyCode()] = true;}
public void keyReleased(KeyEvent e) {keys[e.getKeyCode()] = false;}
public void controls()
{
    if(keys[KeyEvent.VK_SPACE])
     end = true;

    if(keys[KeyEvent.VK_W])
     p1.x += 10;

}

public void start()
{
// while(!end)
// {


// }
}

public void paint(Graphics g) 
{

 controls();
 //g2d = (Graphics2D) g;
 g2d.setColor(Color.RED);
 g2d.fillRect(0,0,size.width,size.height);
 g2d.setColor(Color.BLUE);
 g2d.drawString("Welcome 2 Java!!", (int) 50, 60 );
 //g2d.drawString("Welcome to Java!!", (int) p1.x, 60 );


 g.drawImage(buf, 0, 0, this);
 repaint();
}
}

class obj
{
    double x,y,l,a,s;
}
From stackoverflow
  • Put a check for size in the paint method. If the size has changed, create a new image and then draw to it, and store the new size information. Also, don't call repaint as you are just have a recursive call to paint.

    If you put an unending loop in the start method then the thread never exits the start method.

    public void paint(Graphics g) 
    {
    
            controls();
            Dimension currentSize  = getSize();
            if ( ! currentSize.equals(size) ) {
              size = currentSize;
              buf = createImage(size.width,size.height); 
              g2d = buf.getGraphics();
            }
            //g2d = (Graphics2D) g;
            g2d.setColor(Color.RED);
            g2d.fillRect(0,0,size.width,size.height);
            g2d.setColor(Color.BLUE);
            g2d.drawString("Welcome 2 Java!!", (int) 50, 60 );
            //g2d.drawString("Welcome to Java!!", (int) p1.x, 60 );
    
    
            g.drawImage(buf, 0, 0, this);
    
    }
    

Excel automation. How to copy more than one cell?

For instance:

 //omitted

vector<_bstr_t> cellData;

Excel::_WorksheetPtr pSheet = application->ActiveSheet;

Excel::RangePtr pRange = application->Cells;

_bstr_t cellValue = pRange->Item[1][1]; //single cell

cellData.push_back(cellValue);

 //omitted

Without:

  • MFC
  • ATL

Question:

  • How to copy, multiple cells, for instance A1:B1, into the vector?
  • Is there a more appropriate method, instead of Item?
From stackoverflow
  • I've never done any Excel automation using C++, but if it works similarly as VBA macros, the WorkSheet class should have a Range property that returns a range of cells in the sheet. You can specify what range you want either by giving two cells id, or a string representing the range.

    Code in pseudo VBA:

    Dim range As Range
    Set range = ActiveSheet.Range("B12:D34")
    Set range = ActiveSheet.Range("B12", "D34")
    Set range = ActiveSheet.Range("B12", ActivSheet.Range("D34"))
    ...
    

    See MSDN for more information about the Range class.

Wampserver problem: Undefined variable: mywampfp

Can't get Wampserver running. Just installed it but get the following in php_error.log:

[28-Jan-2009 10:13:17] PHP Notice: Undefined variable: mywampfp in C:\wamp\scripts\refresh.php on line 252 [28-Jan-2009 10:13:17] PHP Notice: Undefined variable: i in C:\wamp\scripts\refresh.php on line 252

Anyone know what's wrong?

Thanks!

From stackoverflow
  • You should try xampp. Personally I like it better and have had no problems with it.

  • Use the isset function to check if a variable exists before accessing it if you cannot be sure that this variable exists:

    if (isset($mywampfp)) {
        // …
    }
    

    Same applies to elements of arrays, for example:

    if (isset($_GET['mywampfp'])) {
        // …
    }
    

C# :httpwebrequest

I am trying to set value of referer parameter of httpwebrequest header, but it is giving error-

Function that I am using (C#):

webRequest.Headers.Set(HttpRequestHeader.Referer, "http://www.microsoft.com");

Error:

Invalid parameters. A required parameter is not found or contains invalid value.
From stackoverflow
  • Try this method from MSDN If you post your code I can better help you out.

    HttpWebRequest    myHttpWebRequest=(HttpWebRequest)WebRequest.Create(myUri);
    // Set referer property  to http://www.microsoft.com .
    myHttpWebRequest.Referer="http://www.microsoft.com";
    // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
    HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
    // Display the contents of the page to the console.
    Stream streamResponse=myHttpWebResponse.GetResponseStream();
    StreamReader streamRead = new StreamReader( streamResponse );
    Char[] readBuffer = new Char[256];
    int count = streamRead.Read( readBuffer, 0, 256 );
    Console.WriteLine("\nThe contents of HTML page are.......");    
    while (count > 0) 
    {
        String outputData = new String(readBuffer, 0, count);
        Console.Write(outputData);
        count = streamRead.Read(readBuffer, 0, 256);
    }
    Console.WriteLine("\nHTTP Request  Headers :\n\n{0}",myHttpWebRequest.Headers);
    Console.WriteLine("\nHTTP Response Headers :\n\n{0}",myHttpWebResponse.Headers);    
    streamRead.Close();
    streamResponse.Close();
    // Release the response object resources.
    myHttpWebResponse.Close();
    Console.WriteLine("Referer to the site is:{0}",myHttpWebRequest.Referer);
    
  • i have already tried solution i.e. given is msdn. thats not working for me and also tried below code but it is also not working for me.

    webRequest.Headers.Set(HttpRequestHeader.Referer, "http://www.microsoft.com");

  • There are some reserved HTTP Headers which you can't set via webRequest.Headers.Set Referer is one of them.

    For these there is always a special property to set.

    In your case webRequest.Referer = "http://google.com" will do.

  • @kedar kamthe, you can't put HttpRequestHeader.Referer in there, because that is expecting a value, I believe, but not sure... I think you wanted to use this:

    webRequest.Headers.Set("Referer", "http://www.microsoft.com");

    But you should use it as Chris Ballance's example. That should work, but if that doesn't work, just try as I show above ;).

    You should put your code here, so we can see what is wrong.

  • Here is typical use:

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("");
    req.Referer = "http://www.google.com";
    

    Show your code.

problem with viewstate of dynamic controls inside a repeater

I ran into a problem recently when using a repeater that I was adding dynamic controls into and although I've got a workaround that does functionally exactly what I want it to do, I'd like to know if there is a better way to do it for my understanding. I've been working with ASP.NET for about 6 months now, and everytime I think I've got the page lifecycle/viewstate completely sussed something crops up that I can't answer.

I was creating a form where users could register their interest for an event, and register for multiple people.

The aspx went something like:

<asp:Repeater ...>
    <bunch of formatting and always there controls like firstname/lastname/address>
    <asp:PlaceHolder ...>
        <dynamic controls for workshop selection go here>
    </asp:PlaceHolder>
</asp:Repeater>

An event can have workshops that the user can register for, and the availability of the workshops is dependant on the date that they choose to go to the event on. The availability of the workshops is dependent on the date, so they can't choose the workshops until they've selected a date.

Anyway the dynamic controls that I'm adding are basically a bunch of literals and a bunch of radio button groups.

I started off by adding the controls in the ItemDataBound event handler, but when saving my repeater items back to my delegate list the ViewState of the radio buttons was never updated. All the fields that were referenced in the ItemTemplate were handled fine, but not the radio buttons I was adding dynamically.

I tried to use the ItemCreated event instead, adding my buttons there, but that didn't seem to make any difference. In the end I settled on a workaround which was based off of this. Basically I'm just outputing the HTML input fields in a literal and reading them back from the request.

It all works perfectly now, and I'm happy with the functionality, it just seems really dirty to have to output the radio buttons as HTML inputs directly rather than use a server side control. Does anyone have a clue about why the ViewState wasn't being restored properly?

Just to be clear, the controls were recreated in the same order everytime, with the ID properly set. I'm using dynamic controls all over the place and they're working fine, I just can't get them to work in this case when I'm adding them inside a repeater.

//more clarification

I can't create these controls in Page.Init as the user selects the date which causes a postback and I have to wait for the viewstate of that control to load before I create the dynamic controls.

From stackoverflow
  • You're creating (or re-creating) the controls when the repeater is bound to its data source. If this happens after the ViewState has been loaded by the page, the ViewState won't be available to the dynamically-created controls.

    Check you're binding your repeater early enough - Page.Init is OK; Page.Load is too late.

    Andrew Barrett : I can't create these controls in Page.Init as the user selects the date which causes a postback and I have to wait for the viewstate of that control to load before I create the dynamic controls. Besides Page_Load is not too late, ASP.NET is supposed to run through the whole page lifecycle ...
    Andrew Barrett : ... when adding a new control. At least I thought it was supposed to. I can add dynamic controls in page_load and have it work, just not when they are in the repeater.
  • It is worth noting that Radiobuttons controls do not work 'out of the box' in repeater controls. Repeater controls inherit the INamingContainer interface which ensures all rendered html controls have unique name attributes. As radio buttons use the name attribute to group themselves this means you will not be able to create groups of radio buttons i.e. setting the GroupName property will not have the desired effect as the Repeater will override this and create unique names for each RadioButton.

    Andrew Barrett : Yep, I know that, which is why I probably would have to use my workaround regardless. I just really want to know why I can't get the viewstate working.

Recreating/resetting views with Flex ViewStack

I'm writing an Adobe AIR application using a ViewStack for the different application states. Is there a way to make sure that each view component is created/destroyed each time it is shown/hidden?

For instance, if I have a TextInput in a view, I want it to reset to its initial state each time I change to that view, rather than having previously entered text. Or, if I have a Timer, I want it to be destroyed when I leave the view so that it doesn't keep running when I'm in an unrelated part of the application. I know that I can manually initialize/destroy everything on the show() and hide() events, but is there an easier way?

From stackoverflow
  • AFAIK there is no built-in way to do this, so you'll have to do it manually by handling the show and hide events as you mention.

    ViewStack does however have two methods "saveState" and "loadState" which could perhaps help you out with this. The history manager uses these methods to enable back/forward navigation. The docs don't seem to have any examples though.

  • ViewStacks can be the work of the devil when it comes to creation/deletion policies and managing state. We had all sorts of problems when we developed fiat ecoDrive and by about 3/4 of the way though we we're all very anti ViewStacks for the management of view state within our application.

    However... a good bet would be to first set the creationPolicy to ContainerCreationPolicy.NONE. That way it's in your control as to when to create any of the panels in your ViewStack. Then i would think you would need to have some sort of logic so that as the ViewStack changes a panel it deletes or resets the one you were on.

    Another viable alternative would be to use view states instead. Have a base state which acts as the main container and then a simple state for each of your sections. That way when you switch to a new state, the old state gets removed in reverse order to the way it was created. You do have to be disciplined with states though as they can end up getting really complex and messy when they start becoming nested. If you keep it simple it may work as you require.

  • Both answers are correct -- there doesn't seem to be any built-in way to do it. I solved the problem by creating a "wrapper" component for my view component. It creates a new view component each time the view is shown. This isn't ideal, but fits my requirements nicely, and required few changes to my application structure.

    <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" show="init()" hide="cleanup()">
        <mx:Script>
         <![CDATA[
          private var myComponent:MyComponent;
    
          private function init():void
          {
           myComponent = new MyComponent();
           componentContainer.addChild(myComponent); 
          }
    
          private function cleanup():void
          {
           componentContainer.removeAllChildren(); 
          }
         ]]>
        </mx:Script>
    
        <mx:Canvas width="100%" height="100%" id="componentContainer" />
    </mx:Canvas>
    
  • Build your "views" as separate Modules, and then use the ViewStack to switch between them. You could then write a function to destroy the unused module(s) (check each module against the selectedChild property) when the ViewStack's "change" event is fired.

  • I am using different states for my different views. On each state change i add and remove components.

    This causes the add and remove events of UIComponent fire which allows me to initialize and cleanup my components each time they are added.

    This is the idea...

       <mx:states>
          <mx:State name="state1">
             <mx:AddChild>
                <mx:SomeUIComponent id="myComp" add="myComp.initialize()" remove="myComp.cleanup()"/>
             </mx:AddChild>
          </mx:State>
       </mx:states>
    

Is there a book for just Win32 C++ for beginners

I am currently trying to learn C++ win32 with buttons window creation shell procces and im not getting most of this is there a place to learn all of this (place == book) just for beginners

From stackoverflow
  • The following includes answers to the "Win32 for beginners?" question: http://stackoverflow.com/questions/574092/where-can-i-find-good-ebooks-to-learn-win32

    The other part of your question, i.e. "C++ for Win32?", has several possible answers that I know of:

    1. Just use C++ as "a better C", and see references for 'Win32 for beginners using C'.

    2. Microsoft have a library called "MFC", which is a C++ class library that wraps (encapsulates) the Win32 API. MFC was designed long ago and is not good, modern C++ class design (e.g. it uses lots of macros). It is presumably easier to use if you already know the underlying (C-style) Win32 API.

    3. Other C++ class libraries from Microsoft:

      • The "ATL" is newer than MFC, 'lighter' than MFC (i.e. you only link to whatever subset of its functionality you use), and is based on templates.
      • The "WTL" is a windowing template library built on ATL, which has never been officially suported by Microsoft but is available as open source.
      • "ATL Server" (which is a rather confusing name) is a C++-based web framework. It is no longer being developed by MS, but it continues to be supported up through VS2005's support lifetime (see http://blogs.msdn.com/vcblog/archive/2007/07/27/support-policy-for-atl-server-library.aspx)
    4. There may be 3rd-party C++ wrappers for Win32; I'm thinking especially of the cross-platform toolkits like Qt/Windows and wxWidgets.
    Michael Burr : ATL is still fully supported by Microsoft. What you might have been thinking about is one of the following 2 items: 1) WTL - which is a windowing template library built on ATL that has never been officially suported by Microsoft - it's avaliable as open source.
    Michael Burr : OR 2) "ATL Server" (which I think is a rather confusing name) is a C++-based web framework. It is no longer being developed by MS, but it continues to be supported up through VS2005's support lifetime (see http://blogs.msdn.com/vcblog/archive/2007/07/27/support-policy-for-atl-server-library.aspx)
  • Win32 + C++ usually means MFC. Out of print but you may find a used or ebook copy of Jeff Prosise's Programming Windows with MFC. This book is excellent.

  • Get The Petzold. It is the book on Win32 programming. Without all of that MFC muckety muck. Even if you never get this far down, it will help you understand what those MFC classes are trying to do.

  • This is probably the best book to learn MFC:

    http://www.amazon.com/Programming-Microsoft-Visual-C/dp/1572318570/ref=sr_1_1?ie=UTF8&s=books&qid=1235325547&sr=1-1

    If you want to learn how to write a framework for Windows, here's a book on it:

    http://www.amazon.com/Windows-Writing-Reusable-Schulman-Programming/dp/020160891X/ref=sr_1_1?ie=UTF8&s=books&qid=1235325590&sr=1-1

    Michael Burr : While the Dilascia book might be good in a lot of ways, it's from 1992 - it covers Win16 (not Win32) and the C++ is decidedly pre-standard. It's probably not a good choice for a novice tutorial.
    dajames : The Kruglinski book is often recommended, but I find that it goes to great lengths to say what is obvious and doesn't go any further. It may be good for complete newcomers but even they will outgrow it quickly. The Prosise book in much better. There's also http://www.amazon.co.uk/Professional-MFC-Visual-C-6/dp/1861000154 which is quite old but explains very well the things that it does cover. The Dilascia book is a classic for those wanting to write their own frameworks rather than using what's already there; now hard to find.
  • The only book is the Petzold (in C, but easy to convert into C++ classes). Avoid MFC.

    2 380 hits on Professional Win32 api group for more than 20 years

    and you can't find it ?!!!!

How to run a php script through the command line

Hi

I am trying to run a php script on my remote Virtual Private Server through the command line. The process I follow is:

  1. Log into the server using PuTTY
  2. On the command line prompt, type> php myScript.php

The script runs just fine. BUT THE PROBLEM is that the script stops running as soon as I close the PuTTY console window.

I need the script to keep on running endlessly. How can I do that? I am running Debian on the server.

Thanks in advance.

From stackoverflow
  • An easy way is to run it though nohup:

    nohup php myScript.php &
    
    David Schmitt : Be aware though, that the script won't automatically restart after terminating.
  • If you run the php command in a screen, detach the screen, then it won't terminate when you close your console.

    Screen is a terminal multiplexer that allows you to manage many processes through one physical terminal. Each process gets its own virtual window, and you can bounce between virtual windows interacting with each process. The processes managed by screen continue to run when their window is not active.

  • I believe that Ben has the correct answer, namely use the nohup command. nohup stands for nohangup and means that your program should ignore a hangup signal, generated when you're putty session is disconnected either by you logging out or because you have been timed out.

    You need to be aware that the output of your command will be appended to a file in the current directory named nohup.out (or $HOME/nohup.out if permissions prevent you from creating nohup.out in the current directory). If your program generates a lot of output then this file can get very large, alternatively you can use shell redirection to redirect the output of the script to another file.

    nohup php myscript.php >myscript.output 2>&1 &
    

    This command will run your script and send all output (both standard and error) to the file myscript.output which will be created anew each time you run the program.

    The final & causes the script to run in the background so you can do other things whilst it is running or logout.

problems with a jquery selector

Here is my view source:

<input id="ctl00_cp_ctrlNew_lendeeMe" type="radio" name="ctl00$cp$ctrlNew$whoBorrowed" value="lendeeMe" />

And I am trying to use this selector to check one of them, but it is not working:

$("input[@id$='lendeeMe']").attr('checked','checked');

but if I do this, it works fine:

$("#ctl00_cp_ctrlNew_lendeeMe").attr('checked','checked');

That is due tot he crazy way asp.net makes controls, so I figured using the previous selector would be easier. What am I doing wrong?

From stackoverflow
  • The [@attr] style selectors were removed in jQuery 1.3. (Deprecated in 1.2). Try removing the @ sign.

    Or, base it off another attribute, like $("input[value='lendeeMe']").

  • What version of jQuery are you using?

    Because as said here:

    Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the '@' symbol from your selectors in order to make them work again.

    So maybe you want to simply try:

    $("input[id$='lendeeMe']").attr('checked','checked');
    

fcntl, lockf, which is better to use for file locking?

Looking for information regarding the advantages and disadvantages of both fcntl and lockf for file locking. For example which is better to use for portability? I am currently coding a linux daemon and wondering which is better suited to use for enforcing mutual exclusion.

From stackoverflow
  • As you're only coding a daemon which uses it for mutual exclusion, they are equivalent, after all, your application only needs to be compatible with itself.

    The trick with the file locking mechanisms is to be consistent - use one and stick to it. Varying them is a bad idea.

    I am assuming here that the filesystem will be a local one - if it isn't, then all bets are off, NFS / other network filesystems handle locking with varying degrees of effectiveness (in some cases none)

  • What is the difference between lockf and fcntl:

    On many systems, the lockf() library routine is just a wrapper around fcntl(). That is to say lockf offers a subset of the functionality that fcntl does.

    Source

    But on some systems, fcntl and lockf locks are completely independent.

    Source

    Since it is implementation dependent, make sure to always use the same convention. So either always use lockf from both your processes or always use fcntl. There is a good chance that they will be interchangeable, but it's safer to use the same one.

    Which one you chose doesn't matter.


    Some notes on mandatory vs advisory locks:

    Locking in unix/linux is by default advisory, meaning other processes don't need to follow the locking rules that are set. So it doesn't matter which way you lock, as long as your co-operating processes also use the same convention.

    Linux does support mandatory locking, but only if your file system is mounted with the option on. You can use mount-o mand to mount the file system to enable mandatory locks, then use fcntl or flock. For more information on how mandatory locks work see here.

    Note that locks are applied not to the individual file, but to the inode. This means that 2 filenames that point to the same file data will share the same lock status.

    In Windows on the other hand, you can actively exclusively open a file, and that will block other processes from opening it completely. Even if they want to. I.e. The locks are mandatory. The same goes for Windows and file locks. Any process with an open file handle with appropriate access can lock a portion of the file and no other process will be able to access that portion.


    How mandatory locks work in Linux:

    Concerning mandatory locks, if a process locks a region of a file with a read lock, then other processes are permitted to read but not write to that region. If a process locks a region of a file with a write lock, then other processes are not permitted to read nor write to the file. What happens when a process is not permitted to access the part of the file depends on if you specified O_NONBLOCK or not. If blocking is set it will wait to perform the operation. If no blocking is set you will get an error code of EAGAIN.


    NFS warning:

    Be careful if you are using locking commands on an NFS mount. The behavior is undefined and the implementation widely varies whether to use a local lock only or to support remote locking.

    Aman Jain : excellent explanation, kudos!!
    frankc : This is no longer correct. File locking does work on nfs 3.0, but only with fcntl, not flock
  • Both interfaces are part of the POSIX standard, and nowadays both interfaces are available on most systems (I just checked Linux, FreeBSD, Mac OS X, and Solaris). Therefore, choose the one that fits better your requirements and use it.

    One word of caution: it is unspecified what happens when one process locks a file using fcntl and another using lockf. In most systems these are equivalent operations (in fact under Linux lockf is implemented on top of fcntl), but POSIX says their interaction is unspecified. So, if you are interoperating with another process that uses one of the two interfaces, choose the same one.

    Others have written that the locks are only advisory: you are responsible for checking whether a region is locked. Also, don't use stdio functions, if you want the to use the locking functionality.

  • Your main concerns, in this case (i.e. when "coding a Linux daemon and wondering which is better suited to use for enforcing mutual exclusion"), should be:

    1. will the locked file be local or can it be on NFS?
      • e.g. can the user trick you into creating and locking your daemon's pid file on NFS?
    2. how will the lock behave when forking, or when the daemon process is terminated with extreme prejudice e.g. kill -9?

    The flock and fcntl commands behave differently in both cases.

    My recommendation would be to use fctnl. You may refer to the File locking article on Wikipedia for an in-depth discussion of the problems involved with both solutions:

    Both flock and fcntl have quirks which occasionally puzzle programmers from other operating systems. Whether flock locks work on network filesystems, such as NFS, is implementation dependent. On BSD systems flock calls are successful no-ops. On Linux prior to 2.6.12 flock calls on NFS files would only act locally. Kernel 2.6.12 and above implement flock calls on NFS files using POSIX byte range locks. These locks will be visible to other NFS clients that implement fcntl()/POSIX locks.1 Lock upgrades and downgrades release the old lock before applying the new lock. If an application downgrades an exclusive lock to a shared lock while another application is blocked waiting for an exclusive lock, the latter application will get the exclusive lock and the first application will be locked out. All fcntl locks associated with a file for a given process are removed when any file descriptor for that file is closed by that process, even if a lock was never requested for that file descriptor. Also, fcntl locks are not inherited by a child process. The fcntl close semantics are particularly troublesome for applications which call subroutine libraries that may access files.

Exposing Rich Domain Objects as a service

I’ve been trying to wrap my head around how to expose my domain objects to the client. Whether I’m using a rich client or I’m using the web, I want to use the MVP and repository patterns.

What I’m trying to wrap my head around is how I expose my repository and model, which will be on the server. Is it even possible to expose complex business objects that have state via a web service, or will I have to use a proprietary technology that is not language/platform agnostic, like .Net remoting, EJB, COM+, DCOM, etc?

Some other constraints are that I don’t want to have to keep loading the complex domain object from the database or passing it all over the wire every time I want to do an operation. Some complex logic might be that certain areas of the screen might be disabled or invisible based on the users permissions in combination with the state of the object. Validation and error message information will also need to be displayed to the user. I want to be able to logically call a lot of my domain object operations as if it were running on the same machine.

With the web, you have free rein. You don’t have to expose your objects across service boundaries, so you can make them a rich as you would like. I’m trying to create an N-teir architecture that is rich and works when the client calling the model is on a different machine.

From stackoverflow
  • You can expose your domain objects like any other object through REST or web services. I think key is to understand that you will have to expose services that provide business value in a single call, and these do not necessarily map 1:1 to your repositories. So while you on the server may expect a single service call to use multiple repositories and perform various aggregations, the things you expose over any kind of web-service should be more or less complete results. The operations you expose on the service should not expose individual repositories but rather focus on meaningful operations that provide a given business value.

    I hope this helps somewhat.

    Charles Graham : Yeah, that's what I figured.
  • You can use a SOAP formater for .Net remoting, but the resulting service will probably be hard to consume as a service, and it will surly be very chatty.

    If you want your domain model to be consumed as a service,it should be designed as a service.

    As stated in domain driven design, a service is stateless, so it won't expose your objects directly. Your service should expose methods that provides meaningful business operations that will be executed as a single unit.

    Usually consider that the model in your client is in a different bounded context because its concerns will be a bit different from the one on the server.

    Charles Graham : Yeah, maybe I need to finish at book. It's just that things are so easy when you are on the Web. It's hard to think about them when you don't have that conveniance.
    Think Before Coding : Specifically, if your server can manage several users simultaneously and your client allows only one one user at time, you've a concern shift here.
  • What I’m trying to wrap my head around is how I expose my repository and model, which will be on the server. Is it even possible to expose complex business objects that have state via a web service, or will I have to use a proprietary technology that is not language/platform agnostic, like .Net remoting, EJB, COM+, DCOM, etc?

    A good domain model is going to be highly behavioral and designed around the problem domain (and your discussions with domain experts), I'd thus argue against designing it to be exposed to remote consumers (in the same way that designing it from the database or GUI first is a bad idea).

    Instead I'd look at using a style like REST or messaging and decide on the interface you want to expose and then map to/from the domain. So if you went with REST you'd design your resources and API (URL's, representations, etc.) and then you'd need to fulfill it from the domain model.

    If this becomes un-natural then you can always have multiple models, for example mapping a seperate read-only presentation specific model to the same data-source (or which wraps the complex behavioral domain model) is an approach I've used several times.

    Some other constraints are that I don’t want to have to keep loading the complex domain object from the database or passing it all over the wire every time I want to do an operation

    Look at caching in HTTP and supporting multiple representations for a resource, also look at caching within your data-access solution.

    Validation and error message information will also need to be displayed to the user. I want to be able to logically call a lot of my domain object operations as if it were running on the same machine.

    You can either represent this as a resource or more likely look at HTTP status codes and the response bodies you'd want to use in those situations.

Use of @synthesize/@property in Objective-C inheritance

If you have Class A with an instance var "foo" which has a @property/@synthesize directive, and Class B inherits from Class A, does it also need to @property/@synthesize "foo"? The reason I ask is because when I try to use Class B's "foo", the calling class says that "foo" is not something of a structured union or a member, which makes me believe it needs to be explicitly synthesized.

From stackoverflow
  • No, you don't. Synthesized properties are added to class A and it's subclasses automatically.

    e.James : @Georg: The downvote is mine, but I assure you it was not intentional! I clicked the down arrow by accident, and now the vote is "too old to change". If you would be so kind as to make a small edit, I will happily switch it to an upvote (which is what I intended to do in the first place).
    Georg : @e.James: done. :)
    e.James : @Georg: Thanks. That's been weighing on my conscience! :)
  • WHen inheriting you should not need to redeclare any properties or variables.

    Perhaps if you post your ClassB header file or a portion of then people can better pinpoint your problem.

  • If you have Class A with an instance var "foo" which has a @property/@synthesize directive, and Class B inherits from Class A, does it also need to @property/@synthesize "foo"?

    No.

    The reason I ask is because when I try to use Class B's "foo", the calling class says …

    No, the compiler says it.

    … that "foo" is not something of a structured union or a member, which makes me believe it needs to be explicitly synthesized.

    It is. In class A.

    The compiler is giving you that warning because it doesn't know about the @property, which is because you have neither declared it nor imported a header that declares it. You say that class A's header declares the property, so import class A's header into class B's implementation, so that the compiler knows about the property when compiling class B.

How can I target a Flex 3 datagrid in MXML from Actionscript?

I have a datagrid defined in an mxml file (flex 3):

I am using an external class to connect to a sqlite database and generate some results (this is working and I can trace the results).

How can I target the datagrid generated in the mxml from the external class? I have tried:

Application.application.resultsGrid.dataProvider = results.data;

And get 'Error: Access of undefined property Application.' from the amxmlc compiler.

I've also tried:

[Bindable]
public var resultsGrid:DataGrid;

In the class properties.

From stackoverflow
  • Update: The phrasing of your question confused me :(

    If you need to populate the datagrid with from you db, you really should be looking at binding the dataProvider property.

  • Looks like I needed to include import mx.core.*; and it now works.

    I don't really understand your answer. Am I not binding the dataprovider property by doing:

    Application.application.resultsGrid.dataProvider = result.data; ?

    I'm from a PHP background and familiar with OOP in that environment so the idioms in Flex are quite strange to me.

    cliff.meyers : That's not binding, it's assignment. Info on binding: http://www.adobe.com/devnet/flex/quickstart/using_data_binding/
  • as brd664 says, what you are actually doing in

    Application.application.resultsGrid.dataProvider = result.data;
    

    is actually an assignment. It's just like assigning a value to variable as in

    var a : uint = 1;
    

    Binding gives you a little more structure and allows you to populate multiple components based on a single property update. There's a ton of other benefits from binding and probably too much to cover in this post.

    Here is a quick and simple example of how binding works. Note that there is one property that is bindable... when you click the button it sets that property to the value of whatever is in the textInput. This update then causes the bindings to fire and updates anything that has been bound to that property. It's one of flex's biggest features (it's also used extensively in silverlight and wpf and probably a load of other technologies that i'm not aware of). Anyway... have a play with it and see if you can get your component to update from a binding.

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
    
        <mx:Script>
            <![CDATA[
    
                private var _myData : String
    
                [Bindable]
                public function get myData() : String
                {
                 return _myData;
                }
                public function set myData(value : String) : void
                {
                 _myData = value;
                }
    
                private function clickHandler(event : MouseEvent) : void
                {
                 myData = myTextInput.text;
                }
            ]]>
        </mx:Script>
        <mx:VBox>
         <mx:HBox>
          <mx:Label text="{myData}" />
          <mx:Label text="{myData}" />
          <mx:Label text="{myData}" />
         </mx:HBox>
         <mx:TextInput id="myTextInput" text="TYPE HERE" />
         <mx:Button label="CLICK TO BIND" click="clickHandler(event)" />
        </mx:VBox>
    
    </mx:Application>
    

Calling db rows by id but backwards

I am building a Links voting site, the formula works ok after the link is voted the second time, the problem is that when the link just has 1 vote it shows up backwards, from oldest to newest.

What I want is for links with one vote to show from newest to oldest. This is the line that calls the links in the front page:

$articles = Article::getAll("order by ranking desc limit $offset, $num_items");

This is the getAll function code:

static function getAll($conditions = ' ')
    {
        /* Retrieve all the records from the
         * database according subject to
         * conditions
         */

        $db = null;
        $results = null;
        $records = array();
        $query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
        try
        {
            $db = parent::getConnection(); 
            $results = parent::execSql($query);

            while($row = $results->fetch_assoc())
            {
                $r_id = $row['id'];
                $r_created = $row['created'];
                $r_modified = $row['modified'];

                $r_title = $row['title'];
                $r_description = $row['description'];

                if(!get_magic_quotes_gpc())
                {
                    $r_title = stripslashes($r_title);
                    $r_description = stripslashes($r_description);
                }

                $r_url = $row['url'];
                $r_username = $row['username'];
                $r_points = $row['points'];
                $r_ranking = $row['ranking'];

                $article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
                $article->id = $r_id;
                $article->points = $r_points;
                $article->ranking = $r_ranking;
                $records[] = $article;
            }
            parent::closeConnection($db);
        }
        catch(Exception $e)
        {
            throw $e;
        }

        return $records;
    }

If anyone can help I would appreciate it.

From stackoverflow
  • What about adding the created date to the order clause?

    $articles = Article::getAll("order by ranking desc, created desc limit $offset, $num_items");
    
  • I'll do what David says, just that if you want the links ordered by the newest first then you have to add the "created" column in descending order:

    $articles = Article::getAll("order by ranking desc, created DESC limit $offset, $num_items");