Friday, April 29, 2011

How can i create a new instance of a class?

i have a list of class instances of various kinds. i need to be able to create a new instance of a class without knowing for sure what to create. all the objects involved have the same ancestor. the actual copying of the object's member variables is easy...it's the creation of the new object where i have a problem.

admittedly i could do something like this:

case MyObjectTypeInstance.MyTypeEnum of
  obj1:
    Result:=TObjectType1.Create;

  obj2:
    Result:=TObjectType2.Create;

  obj3:
    Result:=TObjectType3.Create;
end;

that wouldn't follow the "open/closed principle".

initially i thought i could do something like "Result:=MyObjectTypeInstance.Create;" but that didn't work as hoped because of destructor difficulties.

here's the latest guess how i should be doing this...

var
  fooA, fooB:TFoo;
begin
  fooA:=TFoo2.Create;    // it could be any of many types

  fooB:=?  // how to create fooB of same class type as fooA????

  // do something

  fooA.Free;
  fooB.Free;
end;

i would've thought this'd be easier!

thank you for your help!

From stackoverflow
  • Option 1 - create a list of name/class mappings: Is there a way to instantiate a class by its name in delphi?

    Option 2 - use a 'of class' variable.

    type
      TBaseObj = class
      end;
    
      TObjA = class(TBaseObj)
      end;
    
      TBaseObjClass = class of TBaseObj;
    
    var
      objCls: TBaseObjClass;
      obj: TBaseObj;
    
    objCls := TObjA;
    obj := objCls.Create;
    //obj is of type TObjA
    
    X-Ray : thank you gabr! in fact, thank you for your massive contribution to StackOverflow.
  • If all classes have a common ancestor, you can do something like this:

    type
      TAncestor = class;
      TAncestorClass = class of TAncestor;
      TAncestor = class 
      public
        constructor Create; virtual;
    
        class function CreateClass(const AId: string): TAncestor;
        class procedure RegisterClass(const AId: string; const AType: TAncestorClass);
      end;
    
    
    class function TAncestor.CreateClass(const AId: string): TAncestor;
    var
      atype : TAncestorClass;
    begin
      atype := GetAncestorClass(AId);
      if atype<>nil then
        Result := atype.Create
      else
        Result := nil;
    end;
    
    class procedure TAncestor.RegisterClass(const AId: string; 
      const AType: TAncestorClass);
    begin
      SetAncestorClass(AId, AType); // Link id to class type
    end;
    

    You can use any kind of identification for the type registration. As long as they are unique.

    X-Ray : thank you Gamecat! in fact, thank you for your massive contribution to StackOverflow.
    Gamecat : Hey, we're in it together ;-). But thanks.
  • You will probably want to create an Abstract Factory or Factory Method class. These are common Design Patterns which are tested, proven development paradigms.

    X-Ray : yes...of course! i should've thought of that! thank you!
  • thank you all for your answers!

    dar7yl's solution suited my needs perfectly.

    type
      TFoo = class
      private
        { private declarations }
      public
        { public declarations }
        class function MakeAnother:TFoo;
      end;
    
      TFoo1 = class(TFoo)
      private
        { private declarations }
      public
        { public declarations }
      end;
    
      TFoo2 = class(TFoo)
      private
        { private declarations }
      public
        { public declarations }
      end;
    
    var
      fooA, fooB:TFoo;
    begin
      fooA:=TFoo2.Create;
      foob:=fooA.MakeAnother;
    
      // do something here
    
      fooA.Free;
      fooB.Free;
    end;
    
    { TFoo }
    
    class function TFoo.MakeAnother: TFoo;
    begin
      Result:=Create;
    end;
    
    Jamo : Thanks for posting this follow-up to your question/example -- greatly helpful to "lurkers and 'laters' with similar questions." : )
    X-Ray : you're welcome. i'm always grateful to see followups like that so i try to do them myself!
    avar : thanks for the code example.
    Oliver Giesen : hmm, if this is what your solution now looks like then it seems I must have misunderstood the question then... Seems to me you're still explicitly specifying which class to create...
    X-Ray : i needed another instance of the same object. perhaps my question wasn't so great.
  • Another, messier version is using "class of type" and TObject.ClassType

    type
     TFoo = class
      private
        { private declarations }
      public
        { public declarations }
        constructor Create(WhatEver : Integer);virtual;// just to show need for params
      end;
    
      TFooClass = class of TFoo;
    
      TFoo1 = class(TFoo)
      private
        { private declarations }
      public
        { public declarations }
        constructor Create(WhatEver : Integer);override;// just to show need for params
      end;
    
      TFoo2 = class(TFoo)
      private
        { private declarations }
      public
        { public declarations }
      end;
    
    
    {$R *.dfm}
    
    procedure TForm10.Button1Click(Sender: TObject);
    var
      fooA, fooB:TFoo;
    
    begin
      fooA:=TFoo2.Create(0);
      fooB:= TFooClass(FooA.ClassType).Create(1);
    
      // do something here
    
      fooA.Free;
      fooB.Free;
    
    end;
    
    { TFoo }
    
    constructor TFoo.Create(WhatEver: Integer);
    begin
      ShowMessageFmt('%s %d', [Self.ClassName, WhatEver]);
    end;
    
    { TFoo1 }
    
    constructor TFoo1.Create(WhatEver: Integer);
    begin
      inherited;
    
    end;
    
    Heinrich Ulbricht : Wouldn't call it messy, but rather flexible :) I used it recently to create clone-functions where the base class is able to create the right child-class instance.

Insert matching parentheses xcode?

How do I insert a matching parentheses in Xcode when I insert the "("? I know how to do this for braces "{", but can't figure out how to do it for parentheses!

Thanks!

From stackoverflow

Using sphinx/miktex to generate pdf files that displays UTF8 Japanese (CJK) text in windows

I have documentation in ReSt (UTF8) and I'm using sphinx to generate HTML and latex files. (No issues with html conversion)

I then want to convert the resulting latex file to PDf. Currently I'm using MiKTeX 2.7's pdflatex.exe command to perfom this conversion. (Converting a source file without Japanese characters produces the expected pdf correctly)

Using the MiKTeX Package Manager I've installed the cjk related packages: cjk-fonts, miktex-cjkutils-bin-2.7, and cjk.

To debug I'm using the following sample:

\documentclass{article}

\usepackage{CJK}

\begin{document}

\begin{CJK}{UTF8}{song}

\noindent Hello World!

\noindent Καλημέρα κόσμε
\noindent こんにちは 世界

\end{CJK}

\end{document}

Running pdflatex.exe on this file produces the following output:

pdflatex jutf8.tex jutf8.pdf
This is pdfTeX, Version 3.1415926-1.40.8-beta-20080627 (MiKTeX 2.7)
entering extended mode
(jutf8.tex
LaTeX2e <2005/12/01>
Babel <v3.8j> and hyphenation patterns for english, dumylang, nohyphenation, ge
rman, ngerman, german-x-2008-06-18, ngerman-x-2008-06-18, french, loaded.

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.2
     サソ\documentclass{article}
?
("C:\Program Files\MiKTeX 2.7\tex\latex\base\article.cls"
Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
("C:\Program Files\MiKTeX 2.7\tex\latex\base\size10.clo")
Overfull \hbox (20.0pt too wide) in paragraph at lines 2--284
[]
[1{D:/Profiles/All Users/Application Data/MiKTeX/2.7/pdftex/config/pdftex.map}]
) ("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.sty"
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\mule\MULEenc.sty")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.enc")) (jutf8.aux)
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.bdg")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.enc")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.chr")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\c70song.fd")Running makemf...
makemf: The cyberb source file could not be found.
Running hbf2gf...

hbf2gf (CJK ver. 4.7.0)

Couldn't find `cyberb.cfg'
maketfm: No creation rule for font cyberb03.

! Font C70/song/m/n/10/03=cyberb03 at 10.0pt not loadable: Metric (TFM) file no
t found.
<to be read again>
                   relax
l.12 \noindent ホ
                 ホアホサホキホシホュマ∃ア ホコマ狐πシホオ

How can I get Japanese to display properly in the resulting pdf using MiKTeX/pdflatex.exe?

From stackoverflow
  • I would use xelatex (available in MikTeX since 2.7) instead of pdflatex and an OpenType Kanji font. The file text.tex consisting of

    \documentclass{article}
    \usepackage{fontspec}
    \setmainfont{Sazanami Gothic}
    
    \begin{document}
    こんにちは 世界
    \end{document}
    

    compiles with "xelatex text" to a PDF with this text in Sazanami Gothic font.

    monkut : Thanks! I'll give it a try.

LDAP Modeling Best Practices

I am very in tune with relational modeling but new to LDAP modeling and am looking for best practices for designing LDAP schemas. Would love to know what are the equivalents of third normal form and other practices in the world of LDAP?

Links to white papers that expand on this subject are greatly appreciated.

From stackoverflow
  • LDAP is inherently NOT compliant with even the first-normal form - some of its attribute can contain multiple values.

    LDAP is a system designed for optimal read-/lookup performance, e.g. it's more appropriate in a scenario where you'll be reading / looking up the data way more than changing it (--> directories; your company phonebook won't be changing dozens times a day).

    LDAP is not geared towards or designed for replacing or competing with standard relational database system which excel at data entry / transformation, where a large number of your operations will be inserting and/or updating data. That's what RDBMS are perfectly suited for.

    So, in closing: LDAP vs. RDBMS is really a non-starter - and the two worlds are quite distinct and quite different in their style of working. I would not recommend trying to blindly apply something from one world to the other - it will be a bad match.

    As for inspiration for LDAP schema design - I would definitely look at Microsoft's Active Directory, Novell's eDirectory (or whatever it's called these days), and possibly other LDAP directories, and learn from their designs.

    Marc

    jm04469 : I used 3NF as an analogy and am simply looking for an enumerated list of best practices for modeling LDAP
    pjp : Also LDAP directories don't implement any kind of referential integrity.
  • Our experience shows the design of the schema and the DIT is very dependent on the purpose of the of the LDAP server.

    For the schema, it is, generally, best to stick with the industry or LDAP server vendor's "standard".

    For the structure of the DIT, unless it is for a file and print service (ie Active Directory) or OES (Netware) then generally a "flat" structure scales better.

    If it is a large implementation (ie>100k) then groups should be avoided, if possible.

    -jim

  • Based on my experience denormalize as much as possible, as the goal, as mentioned earlier, with LDAP is very fast lookup, but that means that the insertion of records may take longer, after a while. It is also important to make certain that you can keep backups of the ldap.

    You may want to look at creating various classes though, such as a user, but also have a class for the authorization user, if needed.

    Look at what is probably going to be needed. For example, at the university I was at we realized that some people that only tangentially have a relationship with the university will have an LDAP account.

    As you scope out what types of users or resources will be in the ldap then it will help you determine how to set people up. For example, if you have one class that is only a username or identifier and a password, and perhaps a certificate, then it would be helpful for flexibility.

    If you are going to allow people to log in from their unix account then there are certain classes that must be in the schema.

  • Pick a standard schema, such as core, cosine, inetOrgPerson, eduPerson, Java Objects, etc. appropriate for your intended purpose. Most LDAP servers come with a collection of defaults.

    Prefer the existing elements, but if you need to extend the schema, prefix with comCompany (your company's domain name, or other unique identifier) to avoid conflicts from future standard elements.

How can I append a new element in place in JavaScript?

I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear.

However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body.

How do I append in place?

From stackoverflow
  • Mm. You could do:

    document.write("<div id='iframecontainer'></div>");
    document.getElementById('iframecontainer').innerHTML = '...';
    

    But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.

    EDIT: Actually, a quick google search revealed this artlcle which discusses why document.write is ugly and a nice alternative for the particular pickle you're in: Give your script tag an ID!

    <script id="iframeinserter" src=".."></script>
    

    And then you can get a reference to the script tag and insert the iframe before it:

    var newcontent = document.createElement('iframe'); 
    var scr = document.getElementById('iframeinserter'); 
    scr.parentNode.insertBefore(newcontent, scr);
    
    James Black : I like your solution. :)
  • If the user can give an id of an element that will be where the iframe should be, then it would be possible to just use css to move the iframe to where it should be on the page.

  • Paulo's answer can also be done without the ID, by simply looking for the last <script> element. This must be the script block we're in, because JavaScript guarantees all content past the closing tag of the current script block has not yet been parsed(*):

     var scripts= document.getElementsByTagName('script');
     var script= scripts[scripts.length-1];
     script.parentNode.insertBefore(d, script);
    

    This can be put in an onload/ready function if you like, but if so the ‘var script’ must be calculated at include-time and not in the ready function (when that executes, more <script>s will have been parsed).

    (*: except in the case of <script defer>.)

MS Sql: Conditional ORDER BY ASC/DESC Question

I want to to make to make the ordering in my query conditional so if it satisfiess the condition it should be ordered by descending

For instance:

SELECT * FROM Data ORDER BY SortOrder CASE WHEN @Direction = 1 THEN DESC END
From stackoverflow
  • I have done something like this

    select productId, InventoryCount, 
        case 
        when @Direction = 1 then InventoryCount 
        else -InventoryCount 
        end as "SortOrder"
    order by 3
    
    Shimmy : I don't understand what you wrote, anyway, I edited my query in the question please review the query.
    MikeW : My answer is essentially the same as the accepted answer, except his is better, having the logic entirely in the ORDER BY clause, where I've included a dummy column and ordered on that.
  • Don't change the ASC or DESC, change the sign of the thing being sorted-by:

    SELECT * FROM table 
    ORDER BY 
    CASE WHEN @Direction = 1 THEN -id else id END asc;
    

    The OP asks:

    Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction?

    id is just whatever column you're sorting by; -id is just the negation of that, id * -1. If you're sorting by more than one column, you'll need to negate each column:

    SELECT * FROM table 
    ORDER BY 
    CASE WHEN @Direction = 1 THEN -id else id END 
    CASE WHEN @Direction = 1 THEN -othercolumn else othercolumn END ;
    

    If you're ordering by a non numeric column, you'll need to find an expression that makes that column "negative"; writing a function to do that may help.

    Shimmy : Guys, I am not the SQL Expert, please explain me what means the id and -id, does it controls the ordering direction?
    Shimmy : Also, I have edited my query, please review it.
    Shimmy : So I actually don't have to write ASC, Right?
    tpdi : Right, asc is the default.
  • SELECT * 
    FROM Data 
    ORDER BY 
    Case WHEN @Direction = 1 THEN SortOrder END DESC, 
    Case WHEN 1=1 THEN SortOrder END
    

Hashing an expression tree

I am working on building some pseudo-intelligent caching into a LINQ query provider. What I'd like to do (ideally) is use the expression tree of a given query as the cache key in some scenarios. However, I don't want to store the entire object graph itself, so what's a quick way to get a hashsum-like value from an expression tree? Or if I'm going in the wrong direction, is there a better option?

From stackoverflow
  • Let's think about this. Presumably you want to store (hash of expression tree, result) in a map.

    Without storing the whole tree, you can't distinguish between an identical tree and a hash collision.

    By definition, hashes map a larger set onto a smaller set (this is why a hash is useful), so by definition, you'll have (at least the possibility of) collisions.

    When you get an expression tree, you'll hash it and then go look up a result in your map, which leads to two possibilities:

    1. it's a hash not in the map, one that you haven't seen before. You have to let this one run, as you don't have a cached result.

    2. it's a hash in the map, but since you didn't store the old expression tree that produced the hash in your map, there's no way to compare the newly passed expression to the old one. You may have a match or you may have a collision, but there's no way to distinguish between those two possibilities. You can't return the cached result, because it might be a collision.

    Furthermore, even if it's not a collision, even if it is the exact same expression tree as the one you last saw, how do we know that the backing object -- a database, a list, whatever* hasn't had elements added or deleted or modified such that the result returned by the expression might be different than the cached result?

    That said, you can hash a tree recursively:

    hashATree:
    if leaf node
      return hash(node)
    else
      return hash(node) *OP* hashATree(left.child) *OP* hashATree(right.child)
    

    where OP is some operation (probably multiplication), or more generally hash(node) *OP* accumulate( children.begin(), children.end(), *OP* );

    Of course, this is the same recursion we use to evaluate an expression tree(expect we call node.eval( children);)

    RossFabricant : To nitpick, hashes don't always go from a big set to a small set, EG perfect hashes.
    Rex M : Your point about collisions is theoretically correct but also practically irrelevant. MD5 and SHA have the potential for collisions as well but we still use them because they are practical. I need a practical hash, not a mathematically collision-proof hash.
    Rex M : To answer your question about synchronization problems with the backing store, I have solved those problems. However, I don't feel comfortable going to production with my current method of keying the cache (storing the expression tree itself)
  • Um, actually I think this might be quite simple.

    The ToString() method of an Expression object will give you a textual representation of the Expression, you could hash that if all you want is to evaluate equivalency of a key.

    JeffN825 : This doesn't incorporate a full hash of the expression tree...and many expression trees many have the same string value, but different underlying nodes. Do you have any suggestions? I need to accomplish this as well. I'm thinking of making a hashing visitor that specifically knows to include and call GetHashCode on the underlying values of ConstantExpressions. What do you think?
    Tim Jarvis : my understanding was that it was the full text of the expression tree, for example this is what I get with a query with a where clause and a projection.....value(Quest.Intersect.Core.DataHubQueryableTable`1[Quest.Intersect.TestHarness.Customer]).Where(cust => (cust.LastName = "jarvis")).Select(cust => new <>f__AnonymousType1`2(CompID = cust.CompanyID, LastName = cust.LastName))
    Tim Jarvis : As you can see this contains the evaluated constants plus the anonymous class etc. Seems to me that a hash of this would be a good enough key in a dictionary....however, having said that the alternative would as you suggest, be creating a visitor that created a composite hash of each node/leaf

Allowed memory size exhausted during non-PHP MySQL import.

When I try to import a large SQL backup using the command:

mysql -u ***** -p***** nxtpp < backup.sql

I get the following error message after the backup is partially executed:

Allowed memory size of 33554432 bytes exhausted

I already know about the memory_limit variable in php.ini, but the problem is that I am not using PHP to import, just the mysql command. How can I fix this? Could the problem have to do with the 128MB of memory the server has?

Edit: It turned out that the phpMyAdmin I was exporting from was producing the error. I could see the error's HTML in the actual dump file. When MySQL executed it, it just printed the error out.

From stackoverflow
  • It looks like there is still php involved somehow. MySQL's error messages are looking different.

    Are you maybe trying to execute this command with the exec() or system() statement in php? Then the memory_limit still applies.

  • Assuming like Peter Smit said that this isn't being run inside of a PHP script, try increasing your MySQL setting for key_buffer to something larger.

    Warning: This is a key performance tuning setting, so change it carefully. Higher values will let MySQL consume much more of your machine's memory.

    As an aside, this should be moved to http://serverfault.com when it goes live.

    jpe

Textbox in custom toolbar.

Is it possible to put textbox control in custom toolbar in Excel. I have created an Add-in that shows this toolbar. What I want to do is when user types in textbox Add-in should call a procedure or function depending what user has typed.

I would like to do it in VBA in MS Excel.

Thanks.

From stackoverflow
  • If you are using Excel 2007 and have implemented IRibbonExtensibility::GetCustomUI then you can use the following XML to define an edit box in your Addin GUI:

    <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
        <ribbon startFromScratch="false">
            <tabs>
                <tab id="MyTab" label="My Tab">
                    <group id="MyGroup" label="My Group">
                        <editBox id="MyEditBox" getText="MyEditBoxCallbackgetText" label="Editbox Label" onChange="MyEditBoxCallbackOnChange"/>
                     </group>
                </tab>
            </tabs>
        </ribbon>
    </customUI>
    
    THEn : That looks good. I should consider to upgrading to 2007. Thank you.
    Cannonade : When I get a chance I can give you the code for 2003, walking out the door right now ;)
    THEn : Thanks that would be great.
  • I found out.

    Sub test()
        Set myControl = CommandBars("test").Controls.Add(Type:=msoControlEdit, Before:=1)
    With myControl
        .Caption = Search
        .OnAction = "tester"
    End With
    End Sub
    
    
    Sub tester()
      MsgBox "I am gonna serach for: " & CommandBars("Test").Controls(1).Text
      CommandBars("Test").Controls(1).Text = ""
    End Sub
    

Application Screen capture and rendering

I'm trying to write a simple app that will do a screen capture of an application and then rendering that capture in the 'main' application (ie, the application that took the screen capture).

I've figured out how to get the window handle and get the application's screen capture, but I'm having trouble rendering the captured screen in the 'main' application.

Using GDI, I have the following code to render:

Bitmap bit(hSrcbmp,hpal);
graphics.DrawImage(&bit,Gdiplus::PointF(0,0));

where hSrcbmp is a bitmap of the captured screen and graphics is a GDI+ 'Graphics' object.

I get the following error after the constructor call to Bitmap: Gdiplus::Image = {nativeImage=0x00000000 lastResult=Win32Error loadStatus=-858993460 }

*Using Visual Studio 2005

*Windows XP

*Visual C++ (non-managed)

Any ideas?

Another question: Any better approach? C# or DirectX or openGL? Thanks

From stackoverflow
  • Screen capture is a Win32 FAQ for 18 years.
    See on win32 group for standard code (MS and other), C and C++

    cbrulak : yes, screen capture, but what about re-rendering that same capture in a different window

Is it possible to use MIPS register names with GAS (GNU assembler)?

If I use register names I get:

Error: illegal operands `add $t0,$zero,$zero'

If I use register number ($8 instead of $t0 and $0 instead of $zero) it works.

(I'm using binutils 2.17).

From stackoverflow
  • The GNU assembler doesn't support symbolic register names directly. A common approach, if using gcc to drive the assembler, is to use the ".S" extension for the assembler source file (which tells gcc to pass the source through the C preprocessor before the assembler) and #include a header file containing definitions like:

    #define zero $0
    #define v0   $2
    #define v1   $3
    

    Then the assembler source can have statements like

    add v0, zero, zero
    
    Matthew Slattery : Minor quibble: `v0` and `v1` are `$2` and `$3` (`$1` is `at`)!
    Lance Richardson : You're right - that's what I get for trusting my memory, will correct.
  • Note: the symbolic names are supported in binutils 2.18 onwards.

Can you help me with Enumeration & Array Indexers?

I'm working on this homework project and having trouble understanding the text explaining how to correctly take the accessed value of the enumeration and then apply the string array value to it. Can you please help me understand this? The text we are using is very difficult and poorly written for a beginner to understand, so I'm kind of on my own here. I've got the first parts written, but need some help on the accessing of the enumeration value and assigning, I think I'm close, but don't understand how to properly get and set the values on this.

Write a class, MyCourses, that contains an enumeration of all the courses that you are currently taking. This enum should be nested inside of your class MyCourses. Your class should also have an array field that provides a short description (as a String) of each of your courses. Write an indexer that takes one of your enumerated courses as an index and returns the String description of the course.

namespace Unit_4_Project
{
    public class MyCourses
    {

        // enumeration that contains an enumeration of all the courses that 
        // student is currently enrolled in
        public enum CourseName
        {
            IT274_01AU,
            CS210_06AU
        }

        // array field that provides short description for each of classes, 
        // returns string description of the course
        private String[] courseDescription = 
         {"Intermediate C#: Teaches intermediate elements of C# programming and software design",
          "Career Development Strategies: Teaches principles for career progression, resume preparation, and overall self anaylsis"};

        // indexer that takes one of the enumerated courses as an index 
        // and returns the String description of the course
        public String this[CourseName index]
        {
            get
            {
                if (index == 1)
                    return courseDescription[0];
                else
                    return courseDescription[1];
            }
            set
            {
                if (index == 1)
                    courseDescription[0] = value;
                else
                    courseDescription[1] = value;
            }
        }

    }


}//end public class MyCourses
From stackoverflow
  • What you're missing is that enums convert to ints. (In fact, under they covers, they basically are ints.)

    And arrays can be indexed by ints.

    Try indexing your array with a parameter of with the type of your enum.

  • Here is my response from CodeGuru:

    Enumerations are strongly typed, so you cannot compare it to an int directly. You can however cast the enumeration to an int. So you would have this instead:

    if ( ( ( int ) index ) == 1)
         return courseDescription[0];
    else
         return courseDescription[1];
    
  • You're close, you just went a little nutty there at the end. The CourseName is nothing but a number. You can index directly into your courseDescription array ...

    courseDescription[(int)index]
    

    and you have it. :)

  • Enums do not implicitly convert to ints. But you can explicitly convert them.

    public String this[CourseName index]
    {
      get { return courseDescription[(int)index]; }
      set { courseDescription[(int)index] = value; }
    

    If you are going to use enums this way, you should define the actual numerical value they represent.

    public enum CourseName
    {
      IT274_01AU = 0,
      CS210_06AU = 1
    }
    

    While the current implementation of enums will work, there is nothing that says it will do so in the future.

  • The trick here is that Enumerations are integral datatypes at their core. This means you can cast back and forth between Enum and Int32 if you want to do so:

    You need to change the "get" section to:

    public String this[CourseName index]
    {
        get {
            return courseDescription[(int)index];
        }        
    }
    

    This works since the enum is basically equivalent to:

    public enum CourseName
    {
        IT274_01AU = 0,
        CS210_06AU = 1
    }
    

suggestions for a daemon that accepts zip files for processing

im looking to write a daemon that:

  • reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file
  • updates a record in the database saying something like "this job is processing"
  • reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file meta data for each file found
  • duplicates each file to s3
  • deletes the zip file
  • marks the job as "complete"
  • read next message in queue, repeat

this should be running as a service, and initiated by a message queued when someone uploads a file via the web frontend. the uploader doesn't need to immediately see the results, but the upload be processed in the background fairly expediently.

im fluent with python, so the very first thing that comes to mind is writing a simple server with twisted to handle each request and carry out the process mentioned above. but, ive never written anything like this that would run in a multi-user context. its not going to service hundreds of uploads per minute or hour, but it'd be nice if it could handle several at a time, reasonable. i also am not terribly familiar with writing multi-threaded applications and dealing with issues like blocking.

how have people solved this in the past? what are some other approaches i could take?

thanks in advance for any help and discussion!

From stackoverflow
  • I've used Beanstalkd as a queueing daemon to very good effect (some near-time processing and image resizing - over 2 million so far in the last few weeks). Throw a message into the queue with the zip filename (maybe from a specific directory) [I serialise a command and parameters in JSON], and when you reserve the message in your worker-client, no one else can get it, unless you allow it to time out (when it goes back to the queue to be picked up).

    The rest is the unzipping and uploading to S3, for which there are other libraries.

    If you want to handle several zip files at once, run as many worker processes as you want.

  • I would avoid doing anything multi-threaded and instead use the queue and the database to synchronize as many worker processes as you care to start up.

    For this application I think twisted or any framework for creating server applications is going to be overkill.

    Keep it simple. Python script starts up, checks the queue, does some work, checks the queue again. If you want a proper background daemon you might want to just make sure you detach from the terminal as described here: http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python

    Add some logging, maybe a try/except block to email out failures to you.

    Carson : this would be running as a service that would be triggered when someone uploads a file. they dont need to immediately see the results, but the upload should trigger this process in the background. im amending the question to reflect this.
  • i opted to use a combination of celery (http://ask.github.com/celery/introduction.html), rabbitmq, and a simple django view to handle uploads. the workflow looks like this:

    1. django view accepts, stores upload
    2. a celery Task is dispatched to process the upload. all work is done inside the Task.

How to flush output in backticks In Perl?

If I have this perl app:

print `someshellscript.sh`;

that prints bunch of stuff and takes a long time to complete, how can I print that output in the middle of execution of the shell script?

Looks like Perl will only print the someshellscript.sh result when it completes, is there a way to make output flush in the middle of execution?

From stackoverflow
  • The problem here is that escaping with backticks stores your script to a string, which you then print. For this reason, there would be no way to "flush" with print.

    Using the system() command should print output continuously, but you won't be able to capture the output:

    system "someshellscript.sh";
    
    j_random_hacker : +1. EDIT: I added a quick demonstration of system(), and deleted my own answer which was otherwise redundant.
  • What you probably want to do is something like this:

    open(F, "someshellscript.sh|");
    while (<F>) {
        print;
    }
    close(F);
    

    This runs someshellscript.sh and opens a pipe that reads its output. The while loop reads each line of output generated by the script and prints it. See the open documentation page for more information.

    friedo : The only thing I would add is that it's usually better to use a lexical filehandle: open my $fh, "someshellscript.sh|" or die $!;
    Nathan Fellman : why is that better?
    j_random_hacker : @Nathan: (1) You can't accidentally clobber an existing filehandle in a containing scope; (2) A lexical filehandle will be automatically closed when all references to the filehandle disappear (usually on scope exit).

XML Parse error while processing the SOAP response

I am using C# .Net 2.0 to write a webservices client. The server's soap implementation is tested and is pretty solid. gSoap/C++ applications had no problem reading the responses. However the .Net implementation complains "There is an error in XML document" while calling one of the methods. Similar responses recieved from the server were happily processed by the xml parser.

Looks like to me the MSXML parser (I hope thats the one .Net is been using) is a very unforgiving parser.

I have no control over the server. Some how I have to work around this problem. So, I was thinking of writing a SoapExtension as describe here

So my question is, can I hook a parser before Deserialize stage and completely bypass the Deserialize stage.

And above all, how do i instruct the SOAP stub to use my extended class ?

From stackoverflow
  • First of all I'd grab a snapshot of the failing XML in the Deserialise stage to try and diagnose the problem.

    You can hook your soap extension into your client app without recompiling. Just add:

    <webServices>
        <soapExtensionTypes>
         <add type="DebugTools.SOAP.SOAPTrace.SoapTraceExtension, DebugTools.SOAP" 
                   priority="0" group="High"/>
        </soapExtensionTypes>
    </webServices>
    

    DebugTools.SOAP.SOAPTrace is the namespace of the SoapTraceExtension
    DebugTools.SOAP is the name of the assembly containing the soap trace code.

    to your app.config or web.config file.

    It would be handy if you could paste in the complete exception with stack trace. There may be something really obvious. Also, if possible the WSDL for the web service, that would be very useful.

    Cheers
    Kev

  • If you would like to step through the serialise/deserialise code, you can use a tool called SGen. This comes with VS in the SDK, and is used as follows:

    1. Compile the app using the normal VS-generated (or wsdl.exe generated) proxy classes (These are usually hidden and are in a file called Reference.cs

    2. Drop to the Visual Studio cmd prompt, and open the Debug/Release folder (i.e. the folder the exe has been compiled to)

    3. Type the following at the cmd prompt (replacing TheApplicationName with yor app's name): SGEN /keep TheApplicationName.exe

    You will now see a number of files have been created. Delete all the generated files except for the .cs file (including the dll it creates)

    Move the .cs file to the source folder, and include it in your project.

    Add the following attribute to your Reference.cs :

    [XmlSerializerAssembly()]
    

    You can now step through the actual serialising and deserialising code to find the actual problem (and if there's no other way to fix the problem, you can alter this generated code as required)

  • BTW, .NET does not use MSXML. It has its own implementation. The performance would be horrible if XmlReader were calling out to MSXML for every Read call.

Producing a Windows Path from an XML URI

What is the proper way to convert an XML URI into a Windows file path?

As a starting point, it's possible to turn:

file:///C:/DirA/DirB/File.txt

into:

C:\DirA\DirB\File.txt

... by first dropping the file:/// substring (having used it to determine we're dealing with a local file) and then placing a backslash wherever a slash appears in the original string. That seems like a good start, but it's not enough. For instance, the URI might look like this:

file:///C:/DirA/DirB/With%20Spaces.txt

... which becomes:

C:\DirA\DirB\With Spaces.txt

... after replacing %20s with spaces. Even that, however, would not be enough, as it may likewise be necessary to deal with other such encodings. Furthermore, some of those characters will not be legal Windows filename charcters, so it's necessary to identify which of those encodings are valid in Windows filenames and flag an error if anything else is encountered.

Is there anything else I'm forgetting? Anybody care to expand on the above?

From stackoverflow
  • You should use PathCreateFromUrl() on Windows.

    See also The Bizarre and Unhappy Story of File: URLs.

    Adrian Lopez : I was hoping for somebody to elaborate on the actual process of turning a URI into a Windows path, but under the circumstances I am marking your answer as accepted.
  • Use the Uri.LocalPath property.

    string path = new Uri("file:///C:/folder/file.txt").LocalPath;
    

    This is platform-senstive, so path is "C:\folder\file.txt" on my Windows machine.

    Note that you can also go the other way (from a local file system path to a file URI) using the constructor:

    var uri = new Uri(@"C:\folder\file.txt");
    
  • WOW, such a simple method !

Does anyone know about an opensource list of most common error messages?

Does anyone know about an opensource list of most common error messages?

My motivation for this question, although I am adept at writing code, English is not my mother tongue.

And, such a list (somewhat, like all those free icons on the net) will shorten the last stages of my development, And good (and fun) error messages are part of a good UI, I think.

One more motivation, I might get some ideas as to things I ought to check and forgot about.

Common scenarios:

  • No authorization
  • More Info
  • Missing details
  • Missmatch user/pass
From stackoverflow
  • In my experience there are only two kinds of error messages: those specific to the application you're developing and those generated by an API your application depends on.

    The first type you will almost always need to write yourself. The second type depends on whether you want to show it to the user. Some are worded simply enough you can just pass it along to the user but in most cases the error messages produced by an API are intended for developers and would only confuse an end user.

    For instance most operating systems have a "File not found" error message or something similar. Assuming the file you attempting to open was chosen by the user it makes sense to pass this error from the OS directly to the user. While a "Divide by zero" error would not help the user unless you application performs calculations directly entered by the user. For most circumstances this error would mean a programming error.

    For application specific errors. The error message is only useful within the context of where it occurred. This is why you won't find a collection of generic error messages. Generic error messages usually don't give the user enough information to know how to respond.

  • Generic error messages are often not very useful, because they do not 1) suggest the user how to fix things, 2) help the developer to fix bugs. So, if you want to write good error messages, decide do you write them for the user, or for the developer, and make them as much specific as you can.

    “Oops, error! [Cancel] [OK]” is useless. “Data integrity test in file.c line 33 failed. Using backup version. Please report this error to developer” is better.

  • I do not know of anything that is exactly like what you ask for; a repository of generic error messages. If you need error messages for system errors, you should look at errno.h; each of those errors has a brief description (check, for instance, the specification for errno.h, or perhaps the Linux version).

    Another option would be to look at translation projects for existing open source software. For instance, check out the Translation Product's .pot files or the Ubuntu translation project; this will give you a lot of error messages and other strings to choose examples from. Another advantage is that you may be able to check out the translations into your native language to use as a sort of Rosetta stone, if you ever need clarification about something (though you appear to speak and write English well enough to post here, so I'm not sure if you need that).

How unit testing a singleton in obj-c?

I have a singleton class, and can't unit test their code.

I have test like:

    Db *db = [[Db alloc] initWithName:@"sample.db"];

[db createDb];

STAssertEquals([db existDb],YES,@"The db is not created!");

But only work the first. When the second is executed, I always get "null" from the initWithName method. When I remove the singleton support code, all work as expected.

I could hack the testing (but I don't know how right now) but wonder if exist a "poper" way to deal with this.

The singleton is located here: http://code.google.com/p/chibiorm/source/browse/trunk/src/Db.m

From stackoverflow
  • Singletons are hard to unit test and are sometimes the result of poor design.

    My recommendation would be to think hard about whether you really need a singleton in the first place.

  • Maybe you could use the Factory pattern and create a factory that hands out only one instance (effectively your singleton). Then the implementation is not a singleton and you can unit test it to your hearts content.

    The only drawback is that you are not protected by the language to create your own instance if you don't retrieve it from the factory. In C++ you may overcome this by making the constructor private and the factory and the unit test friends. I am not sure if Objective-C has a similar feature.

    mamcx : You know a sample implementation? The factory code I know is used for other things...
  • I think you shouldn't return nil on the second alloc but raise an exception. If you want to use a singleton you should not try to create two :).

    However, if I decide to create a singleton my class looks like:

    @implementation MySingleton
    
    static id _instance = nil;
    
    + instance
    {
        if (_instance == nil) {
            // alloc/init
            _instance = [[self alloc] init];
            …
        }
        return _instance;
    }
    …
    @end
    

    As you can see I am not enforcing that there may never be more than one instance. Instead I am using the convention to get the instance only with the instance method.

    Chuck : Surely that should be [[self alloc] init], right?
    Tilo Prütz : It could. As the ellipsis shows there is something missing. I omitted it intentionally since I often use init functions with parameters like `initWithName:`. Now - when thinking over it - it seems to me, that you are right and it should stand there to show that the instance is initialized correctly.

Areas of focus for a Java independent study?

I have an independent study next semester and would like it to be something that applies to future job prospects. I've interned at a company for the passed several years that uses Spring, Hibernate, and ServiceMix. I'd like to learn these technologies during my independent study so I can hit the ground running if I get hired there. Does anyone have advice on a good course of study for these technologies? I'd normally just read blogs, articles, and a book or two. I'd like something more structured though for an independent study.

From stackoverflow
  • Come up with a project of significant size that needs a web interface and a data base. once you've completed that, you'll have learned the technologies and you'll have something in your portfolio to show prospective employers.

  • I was reading last night about software that tries to analyze what is going on by real-time processing of events.

    For example, you have sensors on a long bridge, and the data from the sensors is continuously going to their controllers. Those controllers are tied into an ESB. So, some critical sensors are checked first, based on those results you may use information from other sensors to decide if there is a problem with a bridge.

    You can do this with most anything, predicting which stocks to pick based on how other stocks are doing, as well as what the analysts are saying. So, you could decide which analysts' comments will affect their stocks the most.

    You could also monitor robots and predict the best path for several of them to rescue someone.

    This would require all the tools you listed above, and give you an opportunity to not only work with some others that are doing an independent study, but you may be able to come up with a product that is marketable.

  • Does the company have a mentor policy? If they do - ask them if you can volunteer to work on something.

    Lots of companies have tasks that need doing but they can't afford to get people to do. E.g. convert legacy framework code to new framework, rewrite old utilities in more modern languages.

    If you offer to take the old stuff and rewrite to new you may become indispensible as someone who knows a lot about the system.

    I have a few projects that I know I can't justify putting people on but if I had someone to come in for free - that would be great.

  • Fortyrunnner:

    Vide "I have a few projects that I know I can't justify putting people on but if I had someone to come in for free - that would be great."

    For the above how to get in touch with you?

    Much Thnxs. javahorn shriani.kr@gmail.com

Web front end caching best practices for site?

Summary

As I'm looking on stackoverflow and around the net, I find that there is a general lack of good documentation on best practices for caching a high performance site that uses sessions. It would be helpful if we can share some ideas around some basic building blocks particularly around caching. For the purpose of this discussion, I'm avoiding memcache and focusing on the caching of static and pages that are fully generated.

So to set up the scenario, imagine a web server (say nginx), reverse proxy (say varnish), app server (whatever), db server (say mysql).

Anonymous

  1. Static items (gif/jpg etc.)
  2. Semi dynamic (js/css)
  3. Dynamic

Logged In

  1. Static
  2. Semi dynamic (js/css)
  3. Dynamic

Generally speaking, all of the Anon should be cacheable and most of Logged In (ignore dynamic, no ESI for now).

Anon #1

  • Set far-off Expires
  • Set ETag if possible
  • Cache-Control: max-age=315360000

Anon #2 (have the reverse proxy cache the result if dynamically generated else Anon #1 rules apply)

  • Cache-Control: public, s-maxage=3000

Anon #3

  • Cache-Control: public, s-maxage=300

Logged In #1

  • Set far-off Expires
  • Set ETag if possible
  • Cache-Control: max-age=315360000

Logged In #2 (have the reverse proxy cache the result if dynamically generated else Logged In #1 rules apply)

  • Cache-Control: public, s-maxage=3000

Logged In #3

  • Cache-Control: s-maxage=0, must-revalidate

What are your suggestions? I'll update the post as answers come in.

From stackoverflow
  • I don't know everything about caching, but here are some suggestions:

    Anon #1,2: (static,semi-dynamic items) You could set them to never expire. If you need to change them, change their URL. If-modified-since checks are cheap but not free.

    Anon #3: (dynamic items) Here's where ETags and/or Last-Modified comes in very handy. Depending on what you're serving, you can generate a good Last-Modified header. If your database stores the modified date of all items you were planning to show, you could something to the effect of SELECT MAX(last_updated) FROM items_to_show. Caveat: This takes into account the age of the data, and not the age of your template, so if you've changed your django template, you'd be at a loss as to how to communicate that in the header.

    Or you could do something similar with an ETag. It could be a checksum of the contents that are generated. This will take the changing of the template into account.

    Something to note with both of these approaches to caching dynamic content is that they really save more bandwidth than they do web server/database load. You can always make judicious use of the Expires header though to help in cases where the changes to a page are periodic and predictable.

    My suggestions for the logged in stuff would be similar, except I would look at the Vary header. This can signal to caching proxies that different logged in users will not be served the same content.

    In general, I would use either ETag or Last-modified, but not both.

  • There are some relevant suggestions on the ySlow pages.

    Etags might not be a good idea apparently.

    Jauder Ho : I am well aware of the YSlow stuff. =) I was looking for input from people that worked through the intricacies of Cache-Control for different types of pages/content.
  • I would suggest reading Scalable Internet Architectures There are several chapters devoted to scaling up via caching, CDN etc. It should point you in the right direction to get going. Helped me scale up the site I support immensely.

    --

    Jauder Ho : Rather than suggestions to read books, I'm looking for more concrete input/experiences from people. More along the lines of "This is what I did...."
    MikeJ : I recommended the book becuase its more practical in covering scale/performance and the best practices to achieve that end. It would be up to you then to pick an approach and emprically measure what works well at your site.
  • My best answer to this, is that you have plenty of options for all of the static files, which can produce lots of gains in their own way, each beneficial in a specific scenario, so weigh up the pro's and cons according to your specific need.

    However, what most people neglect to think about is their dynamic content, sure caching db results and the like are great, but still involve actually starting up the parsing engine of PHP/ASP or whatever.

    If you look at the super-cache plugin for wordpress, you will note that it has the ability to actually prepare your html as static files. Not only that, but it also makes a gzip copy, and uses rewrite rules to check for the existence of these files as an appropriate alternative to starting up the parser. This is obviously going to give you the best result, as it is not only saving your processing time, but also bandwidth.

    If you want to see the performance disparity, compare the apachebench results of <?php die('hello world'); with serving a static .html page.

    Obviously you would need to be careful with this sort of caching, but it can be very useful to replace fullpage caching from inside an interpreter like PHP.