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