Wednesday, April 13, 2011

PHP: Creating a psuedo-join method inside an object

I am trying to create an object that is capable of handling query-like conditional statements. This is so I can 'join' two conditions together to create a dependency between them based on the type of 'join' being used. I currently have a simple object that contains the following methods:

public function addCondition ( Condition $condition, $join = null )
{
    $this->conditions[] = $condition;
}

public function validate ( )
{
    foreach ( $this->conditions as $condition )
    {
        $result = $condition->validate( );
        [...]
    }
}

The problem is, I need to be able to perform a conditional join between two statements, that will affect the return value of the the validate method. The idea is that you could supply a condition as follows:

$this->addCondition($condition_1);
$this->addCondition($condition_2, 'AND');
$this->addCondition($condition_3, 'NOT');

This would then generate the logic required to specify that the results of the third condition would backwards-chain to affect the results of the first condition.

In the example, lets say:

condition_1 = Apple is Red
condition_2 = Apple is Ripe
condition_3 = Apple is Golden Delicious

Using this I should assume that if I was to pass a ripe, red and golden delicious apple, the result of validate() would be false. The method should fail because the 'join' for condition_3 is NOT.

However, at present there is no way of telling the code that the result of the entire method depends on the result of the previous condition and the way it is joined to it.

Any help is greatly appreciated! Thanks.

From stackoverflow
  • Put the logic in your Condition subclasses.

    Create a Condition_And class that takes two (or more) Condition objects and returns true only if they are both true.

    Create a Condition_Or class that takes two (or more) Condition objects and returns false if any is true.

    Create a Condition_Not class if you feel it is necessary (Apple is NOT Golden Delicious).

    Stringing these together should get you any query you're looking for. Since they're all subclasses of the same type, you can build them up putting NOTs inside of ORs inside of ANDs inside of ORs and so on.

  • Conditionals that involve both AND and OR are inherently nested. Your class does not seem to have a way to express this.

    No nesting means that your conditions must either all be joined with AND, or all be joined with OR. In any case - you can't use both at the same time.

    For your example, AND seems the natural choice, so all you need is a NOT flag for each condition:

    $this->addCondition($condition_1, true);   // e.g.: must be true to succeed
    $this->addCondition($condition_2, true);
    $this->addCondition($condition_3, false);  // e.g.: must be false to succeed
    

    You would then do:

    $valid = true;
    
    foreach ( $this->conditions as $condition )
    {
      $valid = $valid && $condition->validate();
      if (!$valid) 
      {
        // react to "validation failed at $condition"
      }
    }
    
    return $valid;
    

Client-Side validation with groups

I have several tabs that are loaded via ajax, and each one has a set of validators. I want to allow the user to change tabs only if the tab is valid

I thought setting a validationgroup to the validators and then check for the specific group like this, would work:

function validatePage(group) {
    return Page_ClientValidate(group);
}

However, when I call the function, it always returns true. Can anyone see what I'm doing wrong?

I check it like this

alert(validatePage("presentaciones"));

And I have some validators:

// (...)
<asp:TextBox ValidationGroup="presentaciones" id="txtDescription" runat="server" Text='<%# Eval("Description") %>' MaxLength="50" />
<asp:RequiredFieldValidator ID="DescriptionRequiredFieldValidator" runat="server" ControlToValidate="txtDescription" SetFocusOnError="true" ValidationGroup="presentaciones" ErrorMessage="Debe ingresar una descripción" Display="Dynamic" />
// (...)
From stackoverflow
  • I have made groups work server-side with Page.Validate(group) but I wasn't aware this could be done client-side. Perhaps you need to implement a custom validation control that checks the status of each tab.

  • My guess is that the validation scripts are not being wired up. In your function do an alert((typeof(Page_Validators) == "undefined")) and see if it displays true. You said you are loading the tabs via ajax. You may want to see if placing a validator on the page somewhere will help wire up the validation scripts.

    The other thing to watch for is Firefox and legacy rendering mode....client side just plain does not work in that scenario.

Does the Google Ad javascript really need to be in the HEAD tag?

The google ad manager help site is pretty prescriptive about how the calls to their Javascript API need to be made and how combining blocks of javascript calls could cause code to break.

(http://www.google.com/admanager/help/en_US/tips/tagging.html)

I don't really like the idea of inserting so much JS in the head of my pages. I would prefer it to be inserted at the bottom of the page and wrapped in a document.ready() call.

Have others had any success moving away from the very specific way that Google prescribes?

TIA

Pat

From stackoverflow
  • Have done the move with the Google Ad section outside of HEAD and just in the BODY part itself. Really doesn't make a difference since when it was moved, it was just right after the parameters used for the ads to display.

    Probably has more to do with trying to have the script loaded before the necessary hooks on the page want to try and call or use any of the functions included in the script file.

    From the tagging guide you mention:

    JavaScript tags occur out of sequence

    This error indicates that calls to Ad Manager JavaScript functions do not occur in the proper sequence. This error may prevent ads from appearing. It may also cause Ad Manager to fetch the wrong ads; for example, if you fetch ads for the page before specifying page-level attributes for the page, you may fetch ads that do not factor in the targeting criteria.

    This may be why they're trying to be prescriptive about where to place the code.

dedicated server backup solutions?

Duplicate: http://stackoverflow.com/questions/15208/whats-the-best-linux-backup-solution

I am about to purchase a dedicated linux server that has 160GB hard disk and will be used primarily for website hosting.

The server doesn't come with backup/restore facilities and wondered if anyone knows how / what is the best (and cheapest) method for backing up the server on a daily basis.

The server is rented so I cannot physically backup onto tape / dvd etc.

I have little linux experience so wondered if there is a open source web based interface that can perform the backups / restores etc.

From stackoverflow
  • At work, we use BackupPC over a remote SSH login. BackupPC is an open source, disk-based backup system.

    We also evaluated Amanda and a variety of other open source backup packages. None of these actually require the use of tape drives, but most of them still use a heavily tape-based model. And we didn't particularly enjoy worrying about virtual tape volumes.

    BackupPC, on other other hand, requires a single large disk partition to use as storage pool, and it stores content using a chained hash of file contents. This allows it to consolidate files that are duplicated across multiple servers and multiple backup runs. So if you have multiple servers with duplicated content, BackupPC will use considerably less disk space.

    If you're only trying to back up a single server, then rsync may also be an excellent choice. But BackupPC has a web-based administration interface, and it supports incremental and full backups. It can be configured to avoid backups during business hours. (However, if one of your servers hasn't been backed up for a long time, BackupPC will go ahead and grab a backup whenever it can.)

    Overall, it's a very simple system to maintain. It runs without any human intervention, and it e-mails you if something goes wrong or if a server's most recent backups are getting too stale.

    Subtwo : I am sysadmin for a small company (in my spare time) and I've used BackupPC successfully. It is really easy to maintain and install.
  • On a linux machine you can use RSYNC!

    Or write a simple shellscript which does a SSH login, crate a .rar/.zip/.bz2... and moves it over (maybe via scp) to the backup server.

    If you need a commercial product with a good support, you should have a look at the IBM Tivoli backup solutions.

    Chris : tar + scp works well for me. If only it were that easy on Windows.
    Martin K. : Have a look at the mingw windows tutorials! There you can use scp, tar and shellscripts well on windows.
  • If it were me, I would consider two things: either Tarsnap (http://www.tarsnap.com/) or using rsync to your home machine.

    The advantage of Tarsnap is that it will be easy and fast. The disadvantage, of course, is that it's not free... But it's still worth mentioning, just because it rocks.

    The other option -- using rsync to copy the data back to your home machine -- is the cheaper of the two, although the first run will take a while (after that, though, it will only copy over the parts of files which have changed, so it will be much faster).

    If you want more information on using rsync... It can be found easily on the web, or post here and I'll include the backup script which I use.

  • Do you need to make an exact image of the server, or you just want to backup some data?

    If the latter (If you just want to backup some data), you may use a utility like rsync available on most linux distributions (like Debian).

    The good thing with rsync is that you're getting incremental backups, and it's algorithm doesn't need to know all the source and destination's content to run: that means small transfer bandwidth after you've done the first initial backup. All the traffic is also encrypted, if you use rsync over the internet. If you're on Debian, simply use aptitude to install the maintained version:

    apt-get install rsync
    

    If I had access to the hardware, I'd buy a raid controller and do a RAID 1 (mirror) with the existing hard drive. In this case, if one of the disk drive dies, the second one will fail over and all what you'll have to do is replace the dead drive.

    Hope it helps!

  • Use Jungle Disk, and backup to a cloud, amazon s3 or mosso

    Belliez : I use Jungle Disk for my windows backup. Can this also be done using command line in linux?
    Elijah Glover : It says it's linux supported, install and give it a demo, or look at support docs
    Martijn Heemels : The new Jungle Disk Server Edition is in beta. I've been testing it on several servers and love it. It's a great solution for servers. The pricing will be low, as always from Jungle Disk. http://blog.jungledisk.com/2009/10/06/jungle-disk-server-edition-free-public-beta/
  • I'm using Duplicity. It's basically rsync, except that it's encrypted, which doesn't hurt in any case. Just remember to separately back up the keys :-)

  • I use backup-manager

    Backup Manager is an easy-to-use tool for generating archives.

       It  is  designed  with  simplicity  in mind for those who don’t want an
       obfuscated tool for making tarballs.
    
       There are different methods for building archives: tarballs,  incremen‐
       tal tarballs, mysql dumps, svn dump. You can also write your own method
       with a generic method that will execute a command and will archive  its
       output.
    
       Every times you run Backup Manager, you can upload archives thanks to a
       couple of upload methods: trhough FTP, SSH or even with RSYNC.
    
       It’s also possible to export your archives to removable media like  CDR
       or DVD.
    

Anything wrong with this kind/type of coding style?

Is there anything wrong with the below code? It is java codes, but somehow it looked like a C program to me. If there is something incorrect with the OO implementation, can you tell me the name of the violation? looking at S.O.L.I.D or CodeSmell but I still have no idea why the below codes looked weird to me.

public void root() {
    BufferedWriter bw=new BufferedWriter ()
    writeHTMLHeader(bw);
    writeBody(bw);
}
public void writeHTMLHeader(BufferedWriter bw) {
    bw.write("<html><head>");
    ...
    bw.write("</head>");
}
public void writeBody(BufferedWriter bw) {
    bw.write("<body>");
    ...
    //pull some information 
    writeMenu(br);
    ...
    bw.write("</body></html>");
}
public void writeMenu(BufferedWriter bw) {
    Integer count=0;
    writeSubMenu(bw, count);

    bw.write("Some other menu items");
}
public void writeSubMenu(BufferedWriter bw, Integer count) {
    bw.write("Some submenu items");
        count=count+1;
}

so it is OK to pass bw and other variables (and changing them) while passing down the chain of methods call?

From stackoverflow
  • Writing on a buffered reader seems a trifle malodorous.


    The question has now been corrected to use a buffered writer throughout.


    The triple-letter names are not very meaningful.

    The inconsistency without obvious reason of having ddd() called from one of the others, instead of having them all called by root() is a little odd.

    The blank lines in (some but not all) of the triple-letter functions are not needed.

    As illustrated, frankly, none of the triple-letter methods buy anything. However, we should probably assume the 'real' code would have more activity per method.

  • I think your method are suppose to take a BufferedWriter, not a BufferedReader

    You should write the methods so that they take the least specific type necessary to do their job. In this case you'd want to define the methods to take a Writer as this will allow you to pass any type of Writer to the methods.

  • Too little code to make a proper statement. However you might like the Visitor Design Pattern

    You could think of making bufferedWriter an instance variable and use it directly instead of passing it as an argument.

  • Apart from the fact that it's br (implying "buffered reader") instead of bw, it's hard to say given the information you've provided (assuming, of course, that "Some stuff" is actually something useful, and the methods have more helpful names than aaa, bbb, ccc and ddd.

    I can imagine situations where this sort of code is exactly the right way to do it, and situations where this sort of code could not be more wrong.

  • I would use a "try{} finally{}" to close the reader / writer object in the finally block.

    -> always ensure anything that can be closed is closed

    also your aaa ... ddd methods may need to be set as private, but that depends of the other part of the code.

    -> Less exposure implies less problems

  • It's a lot of code bloat!

    Try to generalize aaa,bbb ... and replace the inner writes etc. with if{}else{} paths depending on your (generalisation-)controlling parameter list.

    The visitor design pattern is also a way, but it offers complexity.

    BufferedWriter br=new BufferedWriter ()
    

    Isn't globaly defined! You should do it in the class!

  • Meaningful method names?

  • Having ddd() appear before ccc() seems counter-intuitive at least to me.

    I guess the method names are not real, but shortened for the example. This, however, makes the question impossible to answer for me.

    If the methods names in the real code are descriptive, this code might be the result of some well-executed refactoring, at some stage. Perhaps ddd() is a long step, refactored out of bbb() for some valid reason?

  • I don't see anything wrong based on what you have given us. While there are other design patterns that could solve this problem let's look at a better example. Assume we are rendering some Html. (This is example will be loosley based on C#)

    public void Render(StreamWriter stream)
    {
       WriteTableBegin(stream);
    
       DataSource.ForEach(row=>WriteRow(stream,row));
    }
    
    private void WriteTableBegin(StreamWriter stream)
    {
    
       //Cut this logic to keep it simple but we are building attributes etc...;
       string tableBeginTag=
       stream.Write(tableBeginTag);
    }
    
    private void WriteRow(StreamWriter, object row)
    {
      //etc...
    }
    

    In my opinion this code is easy to write and easy to read and understand. The point of Render is to write it's Html to the stream. This is using a Composite Method refactoring to provide well named scoped methods which do one thing and do it well.

  • IMO, using raw Java code to make HTML markup doesn't properly exercise a separation of concerns. JSF, Wicket, etc. were all designed to allow the markup to be markup and the logic to be logic. Sure, there may be times where it is better to use code to generate markup but those are few and far between.

    Keeping your Markup separate allows you to quickly design/redesign the interface when the functionality doesn't change and allows you to change the functionality when the interface doesn't change.

    As far as the code itself, from a code smell point of view, I'd want to see the html/root tag being emitted in root rather than subfunctions. Each function would emit the tags appropriate to its use and nothing else.

How do I reference configuration information from within multiple class libraries?

I've got a bunch of DLL projects that I'm pulling into my application, each contains their own Settings.settings/app.config. When I compile the app and run for debugging, everything works just fine, but come deployment time I can't get my DLLs to read their own settings files.

I've been doing some reading and it has become apparent that there's a couple of methods to getting each dll to read its own configuration - one is to dedicate a .dll.config to the library and the other is to embed the dll's configuration in the process.exe.config.

I'm having significant issues trying to implement either and I wondered if anyone has any good docs on this - there appears to be a shortage on the Net.

I'd like a separate .dll.config for each of the libraries if possible, but in a pinch, getting each of my libraries to read their own section of the process.exe.config will do.

Can anyone point me in the right direction because I'm so close to rolling this application out but this stumbling block is causing me a significant headache.

Edit: When I merge the configuration files, I start getting TypeInitializer exceptions when I initialize objects withing my libraries. This is likely just me being retarded, but does someone have a working example of a merged config file and some basic demonstrative code for reading it from multiple assemblies?

From stackoverflow
  • Have each class library define configuration settings in a custom ConfigurationSection.

    Then add custom section handlers to your process.exe.config file.

    This MSDN article is pretty comprehensive in its explanation, with examples in both VB and C#.

    BenAlabaster : I've had to do this in the past - that's a LOT of work considering the libraries and main assembly are this close to completion.
    Ian Nelson : Yeah, it does involve writing some pretty repetitive code! Dmitryr has created a tool to generate the config sections from a fragment of a XML configuration, which might help: http://blogs.msdn.com/dmitryr/archive/2005/10/02/476245.aspx
  • What are the "significant issues" you encountered? I started with embedding the dll's config in the exe's config, which worked, but was cumbersome. I now have all the config stuff in one dll project. The only thing I needed to do to make that work (besides copying the settings over) was to change the Settings class to be public.

    Here's an example of a merged app.config that works:

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="SharedConfig.Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
            <!-- Begin copy from library app.config -->
            <section name="SharedConfig.Library.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
            <!-- End copy from library app.config -->
          </sectionGroup>
        </configSections>
        <applicationSettings>
          <SharedConfig.Client.Properties.Settings>
            <setting name="Bar" serializeAs="String">
              <value>BarFromClient</value>
            </setting>
          </SharedConfig.Client.Properties.Settings>
          <!-- Begin copy from library app.config -->
          <SharedConfig.Library.Properties.Settings>
            <setting name="Bar" serializeAs="String">
              <value>BarFromLibrary</value>
            </setting>
          </SharedConfig.Library.Properties.Settings>
          <!-- End copy from library app.config -->
        </applicationSettings>
      </configuration>
    
    BenAlabaster : I attempted this in the first instance because I thought it would be a quick (if a little dirty) fix to the issue and I could get this rolled out. But the minute I merged the all the config files, I started getting TypeInitializer exceptions trying to initialize my objects within my libraries.
    BenAlabaster : Then I went to attempting to have dedicated .dll.configs and I can't get the libraries to reference their own files, I know it's likely something simple I'm doing wrong - but even OpenExeConfiguration doesn't seem to want to do the because the Settings.settings files don't seem to update
    Daniel Pratt : Based on my experience, I'm not surprised you didn't get very far with each .dll loading its own config. One the other hand, your issue with the first scenario has me puzzled. Maybe something about the way you merged them?
    BenAlabaster : Which leads me to wonder what I did wrong - I literally merged the two - a la diff.
    Daniel Pratt : I can imagine that diff may not have "done the right thing". I set up a simple solution to verify this and it does indeed work. I'm going to edit my post to include the merged app.config.
    BenAlabaster : Thanks - I appear to have got it working :) Much appreciated
  • See http://stackoverflow.com/questions/634439/if-app-config-for-a-dll-should-be-in-the-main-config-what-do-we-do-with-wcf-refe. The real answer is "copy and paste". That's unfortunately the general solution Microsoft had in mind. In some cases, the .NET 2.0 Settings mechanism can be used, as it bakes the default values into the DLL itself. At runtime, the DLL can then save updated settings - into the .exe.config.

    BenAlabaster : I don't need to have the DLL save settings - they're read-only. The issue is that I can't get the DLLs to load their settings from the merged process.exe.config file. The minute I merge the config files I start getting TypeInitializer exceptions.
    John Saunders : You should edit your post and add an example of the exception you receive (full stack trace, please, and all inner exceptions). Also provide the config snippet that's involved. Does your main application have the assemblies loaded that contain the config section types?

creating expiring ASP.NET session value

I like to create a session value that expires in 5 minutes.

How to do that, do I need to manually compare creation time when I read it?

Session("sessionval") = myvariable
Session("sessioncreated") = now
From stackoverflow
  • you can not define custom timeout to a session variable.

    Maybe you can use cache for this, with a unique key dependent to session.

    You can set timeout to a cached item.

    Cache.Insert("key_dependent_to_session", value, Nothing, 
      DateTime.Now.AddMinutes(5), TimeSpan.Zero)
    
    AnthonyWJones : Take it a little further create a couple of static (Shared in VB parlance?) accessor methods of a static (Shared) class. Have those methods discover the current session ID and do some suffixing of the key name.
  • That is correct. Session state doesn't have an Expiration concept.

    If your data are not per-user, you can use Cache instead. You could even use Cache, but include the user name as part of the key, which would sort of give you an expiring session state.

    AnthonyWJones : Even it is is session specfic you could use the session ID as part of the key.
    Cerebrus : @John: "Session state doesn't have an Expiration concept." How do you explain that statement given the timeout attribute of the sessionState object?
    John Saunders : .Timeout is for the entire session state, it's not a per-item expiration.
  • If you are asking how to do it on a single variable I do not think it is possible, but you can define the session timeout period using the web.config

    <system.web>  
        <sessionState timeout="5" />
    <system.web>
    

    this would affect all of your session objects, not just a single one.

    My suggestion for giving a custom expiration date to a single item is to create a cookie, that way you can actually set it's expiration value.

    Response.Cookies.Add(New Web.HttpCookie("AdminID", admin.AdminID))
    Response.Cookies("AdminID").Expires = Now.AddMinutes(5)
    
    TheTXI : @Anthony: that's why I specifically said in the answer that if you are asking how to do it in a single item I do not think it can be done.
    cgreeno : @TheTXI it is an option and the warning is on the box. I would not personally choose this option(web.config) but it is perfectly valid answer +1
    TheTXI : BTHB: I would not personally choose it either, but given the lack of fine detail as to what the OP is wanting to do, it was a possibility however remote.
    AnthonyWJones : @TheTXI: Your additional suggestion now has the flaw that the burden of holding the value placed on the client and bandwidth needed to include it in all requests whether required or not, in addition to reducing its type to a string. Not mention that clients could block or worse spoof them.
    Cerebrus : @Anthony, notwithstanding the above obvious flaws, cookies are still used commonly. It remains upto the OP to choose the best possible solution for his/her context. I must admit that the cookie solution didn't even occur to me. Definitely, +1.
  • 1) Put this in web.config

    <configuration>
       <system.web>
         <sessionState mode="InProc" timeout="5">
         </sessionState>
       </system.web> 
    </configuration>
    

    2) Set System.Web.SessionState.HttpSessionState.Timeout = 5 mins.

  • I tend to agree with TheTXI.

    Although a single Session item cannot be assigned a custom timeout, you should note that in InProc session mode, Sessionstate is itself added as an item to the ASP.NET cache. This enables it to have a "timeout".

    In your particular scenario, a Cache object is the best suited solution.

    AnthonyWJones : -1. To be consistent. The question is not about expiration of the whole session state.
    TheTXI : @Anthony: You sure are liberal with the downvotes and assumptions as to what the original author is looking for, especially for someone who never even bothered to post his own answer.
  • If you want to use the SessionState you could create your own wrapper so instead of caching the actual item, you can cache the wrapper. Here is a quick dirty untested example of a wrapper that checks if the item is null, or if it has expired it will call a Func that you can provide a refreshed item.

    The Func takes the last set value so if you can determine if the value is still valid you could avoid reloading it.

    public class TimeExpirationItem<T>
    {
        private T _item=default(T);
        private TimeSpan _expirationDuration;
        private Func<T> _getItemFunc;
        private DateTime _expiresTime;
        public TimeExpirationItem(TimeSpan expirationDuration, Func<T, T> getItemFunc)
        {
            this._getItemFunc = getItemFunc;
            this._expirationDuration = expirationDuration;
        }
        public T Item
        {
            get
            {
                if (_item == null || ItemIsExpired())
                {
                    _item = _getItemFunc(_item);
                    _expiresTime = DateTime.Now.Add(_expirationDuration);
                }
                return _item;
            }
        }
        public bool ItemIsExpired()
        {
            return DateTime.Now > _expiresTime;
        }
    }
    

    Again this code is provided as is with no warranty and it is untested but is an example of the things you can do.

    Using it would be something like the following:

    Session.Add("ObjectKey",new TimeExpirationItem<MyObject>(new TimeSpan(0,0,5),mo=>MyObjectRepository.GetItemByLogin(Request.User.Identity.Name));

    Sam Schutte : Great solution man!
    JoshBerke : Thanks much:-)..

WPF - PageFunctions. Why are they needed?

I've been dabbling in WPF for a couple of months now and I've managed to grasp most of what's about and why/when it's used but I'm still struggling to see the value of the PageFunction class.

Can someone give me a simple, but concrete example of when a PageFunction might be the correct tool for the job?

From stackoverflow
  • PageFunction in a page = Dialog box in desktop application (without Page).

    You can use a PageFunction every time you use a dialog box in a desktop application and that you want to develop a webnavigation-like behavior to your program.

  • Mainly, it seems to be a pattern to formalize branching in task based UI.

    Let's say you have a form with a checkmark for an optional feature, but this feature requires additional information which is too complicated to fit on the same page. Using this pattern allows delegating information collection to another component.

    Moreover, there is kind of a strategy pattern applied, since you could have various subsystems able to collect the same information, all of them inheriting the PageFunction(of T), so that the code actually calling those does not need to know any detail about it.

    Those are just some ideas, I have not exactly looked into it.

  • The main thing page functions enable is implementing workflows with sub-tasks and managing the return stack.

    If you just rely on page-to-page navigation, it's hard to pause the current navigation path, do something else, and then come back and continue. PageFunctions enable that through the concept of Returning and unwinding the navigation stack.

    I provided some real world examples of this here: http://www.paulstovell.com/wpf-navigation

WPF Grid Question, can I determinate the absolute position of something, which is positioned automatically in a WPF Grid?

I like to use a grid to position some objects in WPF, because it cares about the position and stuff. In addition, however I also like to be able to draw accross the cells with a Canvas.

I figured out that this can be done by embedding the grid in a canvas. However in order to connect two elements, I need then the absolute position in pixels.. any ideas?

From stackoverflow

What Mercurial DVCS hosting would you recommend for a small open source project?

I'm looking around for free Mercurial hosting for a small-scale open-source project.
If you've ever used such a service, who is doing the hosting, and would you recommend them?

I know SF.net can be set up to host HG repos, but it looks like a lot of trouble (for the benefit of having a big, known, service that's unlikely to go down anytime soon).

There's also the list of free HG hosts right in Mercurial's official documentation, but I'd like to hear from those that actually got down and dirty with it :-)

From stackoverflow
  • BitBucket is certainly the most popular. I've experimented it for while, then I jumped into git.

    Aaron Maenpaa : +1 I've been very happy with both bitbucket and Mercurial.
    Steve Losh : +1 as well - BitBucket is great. You get repository hosting, a version-controlled wiki and a great issue tracker for free!
    quark : +1 BitBucket has a *very* nice interface.
    kitsune : +1 Bitbucket rules
    idursun : Bitbucket also lets you to create a private repository in the free plan
  • I use Bitbucket for a bunch of Open Source projects and am very happy with it, too.

  • Have you considered using Project Kenai? I have an account but have not hosted any projects there so I can't comment on the quality of service.

    Chris Upchurch : Oracle has just announced that Project Kenai is going to be discontinued: http://www.oracle.com/technology/community/sun-oracle-community-continuity.html
  • For small code examples and if you don't need a wiki and stuff, you could try http://freehg.org else you should give http://www.sharesource.org a chance. Or just use Mercurial as intended by publishing your source decentralized to other developers using the integrated webserver for example :).

  • sourceforge.net just added Mercurial, Bazaar and Git support.

  • Bitbucket is the best hoster i have encountered so far.

    The service is fast and rock-solid and the staff is very fast at addressing any itch you might have.

What are the most common virus file types currently circulating?

I am working on a project that will involve file upload to a server. I am interested in understanding what kinds of files virus writers currently tend to target. I am aware of the following threads:

How would you programmatically test a file for viruses ? ensuring uploaded files are safe How can I determine a file’s true extension/type programatically? Server side virus scanning

But am interested in general in finding out about common attack vectors.

Thanks,

  • Ian
From stackoverflow
  • exe is probably the most common

  • .exe and .scr are most common filetypes. Also, there are "tricks" with double extensions like readme.txt.scr or readme.doc.exe

  • All of them. There aren't any "safe" file types when a JPG image can infect you with a virus and you can even trick the browser to execute JavaScript in any file no matter its declared type.

    But the biggest and most widespread danger doesn't even involve uploaded files - ANY text that is entered by users and displayed on your page is a potential vector of Cross-Site-Scripting attacks.

  • I ran an "upload file" form for a little while and a few things I found:

    • All sorts of PHP scripts (shells, redirects, various "owned by $LAMER", you name it)
    • I think I had a few browser exploits (.html, .jpgs)
    • A bunch of files with the wrong extensions (ie, PHP scripts with the extension .rar, hoping that the server's mime-type guesser did the wrong thing)
    • Zip files full of all of the above

    Anyway, those are just a few things I found. Hope they are helpful.

How to add files to project on google code?

I normally organize my project in multiple files. Now, for the first time I have created a project at code.google.com/hosting.

How to add files to the project?

The project has got directory structure and many files. I want them to be visible under trunk (like it is in other projects).

NOTE: I am novice in this area (I have no clue about what to do). I am searching for an UPLOAD button.

From stackoverflow

Authorization Asp.net web.config

I have an application that has a backoffice. This backoffice was isolated with the use of roles like this:

<location path="backoffice">
    <system.web>
     <authorization>
      <allow roles="admin"/>
      <deny users="*"/>
     </authorization>
    </system.web>
</location>

But now we have another type of role that needs access. The companyadmin role.

Can I just say?:

 <location path="backoffice">
        <system.web>
         <authorization>
          <allow roles="admin,companyadmin"/>
          <deny users="*"/>
         </authorization>
        </system.web>
    </location>
From stackoverflow
  • yes, you can add n roles like that.

    If you prefer, you can also:

    <allow roles="admin"/>
    <allow roles="admin1"/>
    <deny users="*"/>
    
    GoodEnough : what the hell is going on with that grammar?
  • Yes, exactly so (assuming you properly authenticated your users, and set their roles accordingly). Check the MSDN article: http://msdn.microsoft.com/en-us/library/8d82143t(VS.71).aspx

  • Yes, roles, users and verbs takes comma separated values.

    MSDN Reference

Mysql query with wildcard on number strings

I am trying to query a mysql table which contains strings of numbers (i.e. '1,2,3,4,5').

How do I search to see if it has '1' but not '11' bearing in mind if it is '9,10' '9%' doesnt work??

Fixed!

(field like '10' OR field like '%,10,%' OR field like '%,10' OR field like '10,%')
From stackoverflow
  • You need the function FIND_IN_SET. Btw, '9%' should work, if the column contains the values you specified, are you sure you're querying

    SELECT * FROM table WHERE field LIKE '9%'?
    
    sydlawrence : '9%' definitely doesnt work have tried it direct into CLI, on the sun site is says that numbers dont work correctly with wildcards 9% would pick up 9 or 900 but not 9,10
    sydlawrence : ah ha, I didnt use LIKE I used =
    soulmerge : I'm running mysql version 5.0.70 and just tried it - it works. What type is the column?
  • You could try the function find_in_set

    select find_in_set('1','1,2,3,11,12')
    
    David Grayson : That's cool, I didn't know about that function.
  • Standard SQL can do it as well:

    ...
    WHERE 
      ',' + SetValue + ',' LIKE '%,1,%' 
      AND ',' + SetValue + ',' NOT LIKE '%,11,%'
    

    This expression cannot make use of an index, therefore performance will degrade quickly as the table size rises.

    For better performance your table should be properly normalized, e.g.

    SetId  SetValue
        1  1
        1  2
        1  3
        1  4
        1  5
    

    instead of

    SetId  SetValue
        1  '1,2,3,4,5'
    

Data Type of a field

Hey guys and gals, I have a field in a table that I will be storing different kinds of data in it, Like: X-Large, Medium, Small....or I might store: 22-March-2009, 1 Year, 2 Years, 3 Years...or 06Months, 12 Months, 1 Year, or I might store: "33-36", "37-40"...and that data is not fixed, i might need in the future to add new categories...

The obvious choice of a data type would be an nvarchar(length), but any other suggestions? is there a way to go around this??? thanks in a advance...

From stackoverflow
  • nvarchar(max) would work. Otherwise, you might have multiple columns, one of each possible type. That would keep you from converting things like double-precision numbers into strings and back.

    • nvarchar(max) if the data is restricted to strings of less than 2Gb.
    • ntext if you need to allow for strings of more than 2Gb.
    • binary or image if you need to store binary data.
  • No matter what you do, such database design does not look good.

    Still, you can use BLOB data type to just store any data in a column, or a Text type if it’s text (this way search will work better, understanding upper and lower case and such).

  • Sounds like you're trying to store a "size". Maybe you need a "Size" table with those values in it (X-Large, Medium, Small, 1 Year, etc.) and an ID field that goes in the other table.

    Why you would also want to store a date in the same field is a bit confusing to me. Are you sure you shouldn't have two different fields there?

    ETA: Based on your comment, I would suggest creating a couple additional tables:

    SizeType - Would define the type of "size" you were working with (e.g. childrens clothing, childrens shoes, mens shoes, womens shoes, mens shirts, mens pants, womens shirts, womens pants, etc.). Would have two columns - an ID and a Description.

    Size - Would define the individual sizes (e.g. "Size 5", XL, 33-34, 0-6 Months, etc.). Would have three columns - and ID, a Description, and the corresponding SizeType id from SizeType.

    Now on your product table, you would put the ID from the size table. This gives you some flexibility in terms of adding new sizes, figuring out which sizes go with which type of products, etc. You could break it down further as well to make the design even better, but I don't want to overcomplicate things here.

    Maen : It is size, but size for baby wear is based on age, months or years..and size for shoes have different system than clothes, what do you think i should do?

What's the difference between data and code?

To take an example, consider a set of discounts available to a supermarket shopper.

We could define these rules as data in some standard fashion (lists of qualifying items, applicable dates, coupon codes) and write generic code to handle these. Or, we could write each as a chunk of code, which checks for the appropriate things given the customer's shopping list and returns any applicable discounts.

You could reasonably store the rules as objects, serialised into Blobs or stored in code files, so that each rule could choose its own division between data and code, to allow for future rules that wouldn't fit the type of generic processor considered above.

It's often easy to criticise code that mixes data in, via if statements that check for 6 different things that should be in a file or a database, but is there a rule that helps in the edge cases?

Or is this the point of Object Oriented design, to stop us worrying about the line between data and code?

To clarify, the underlying question is this: How would you code the above example? Is there a rule of thumb that made you decide what is data and what is code?

(Note: I know, code can be compiled, but in a world of dynamic languages and JIT compilation, even that is a blurry concept.)

From stackoverflow
  • It all depends on the requirement. If the data is like lookup data and changes frequently you dont really want to do it in code, but things like Day of the Week, should not chnage for the next 200 years or so, so code that.

    You might consider changing your topic, as the first thing I thought of when I saw it, was the age old LISP discussion of code vs data. Lucky in Scheme code and data looks the same, but thats about it, you can never accidentally mix code with data as is very possible in LISP with unhygienic macros.

  • Code is any data which can be executed. Now since all data is used as input to some program at some point of time, it can be said that this data is executed by a program! Thus your program acts as a virtual machine for your data. Hence in theory there is no difference between data and code!

    In the end what matters is software engineering/development considerations like performance, efficiency etc. For example data driven programs may not be as efficient as programs which have hard coded (and hence fragile) conditional statements. Hence I choose to define code as any data which can be efficiently executed and all else being plain data.

    It's a tradeoff between flexibility and efficiency. Executable data (like XML rules) offers more flexibility (sometimes) while the same data/rules when coded as part of the application will run more efficiently but changing it frequently becomes cumbersome. In other words executable data is easy to deploy but is inefficient and vice-versa. So ultimately the decision rests with you - the software designer.

    Please correct me if I wrong.

    Robert Gould : well it all boils down to 1's and 0's anyways
    Lazarus : Surely if your data is 'executed' then the actual data forms a programming language of some kind and becomes stored code rather than data?
    SDX2000 : Yes one more way of looking at it. Compare this with the equivalence between energy and mass.
    Rik : "Hence I choose to define code as any data which can be efficiently executed and all else being plain data" - What determines whether it can be "efficiently executed"?
    SDX2000 : Ans: What form it (the data) has and often where its executed. Eg. XML config data is executed by program (a VM) while C++ code describing the same directly on the microprocessor.
  • In Lisp, your code is data, and your data is code

    In Prolog clauses are terms, and terms are clauses.

  • The line between data and code (program) is blurry. It's ultimately just a question of terminology - for example, you could say that data is everything that is not code. But, as you wrote, they can be happily mixed together (although usually it's better to keep them separate).

  • Data are information that are processed by instructions called Code. I'm not sure I feel there's a blurring in OOD, there are still properties (Data) and methods (Code). The OO theory encapsulates both into a gestalt entity called a Class but they are still discrete within the Class.

    How flexible you want to make your code in a matter of choice. Including constant values (what you are doing by using if statements as described above) is inflexible without re-processing your source, whereas using dynamically sourced data is more flexible. Is either approach wrong? I would say it really depends on the circumstances. As Leppie said, there are certain 'data' points that are invariate, like the days of the week that can be hard coded but even there it may be advantageous to do it dynamically in certain circumstances.

    Phil H : But in using an object, you can't tell what is stored as data and what is generated by code. Hence parameters in .Net: obj.Length could be generated (code) or just stored (data). The blurring lies in the fact that you do not care when you use it.
  • This is a rather philosophical question (which I like) so I'll answer it in a philosophical way: with nothing much to back it up. ;)

    Data is the part of a system that can change. Code defines behavior; the way in which data can change into new data.

    To put it more accurately: Data can be described by two components: a description of what the datum is supposed to represent (for instance, a variable with a name and a type) and a value. The value of the variable can change according to rules defined in code. The description does not change, of course, because if it does, we have a whole new piece of information. The code itself does not change, unless requirements (what we expect of the system) change.

    To a compiler (or a VM), code is actually the data on which it performs its operations. However, the code to-be-compiled code does not specify behavior for the compiler, the compilers own code does that.

    eglasius : +1 for data is information and code is behavior (actually had answered the same at pretty much the same time) - don't agree that much on calling data static though / real time data is highly "dynamic", although usually handled as measurements it makes it harder to describe the difference
    SDX2000 : What do you mean by code is "behaviour"? Whose behaviour? The computers? If yes then its data for the microprocessor. Think about this.
    Rik : Of course, data can change. A better term might be that data _values_ can be considered "immutable". So, the values are static, and the data can change -or more accurately, change it's value- according to the rules defined by the code.
    troelskn : I don't think that distinction holds. Consider a declarative programming language: Is it code or data?
    eglasius : @troelskn check my answer, I actually didn't go much into the definition but into the "it's not about" arguments ... I don't think it is that hard to reason what is information vs. behavior, but getting into where they go is what adds confusion
    Phil H : Part of my question is that you can change even the code by acquiring code dynamically - you could write code that accepted a new class and added an instance of it to an array of rule objects. Then your code has changed, but it's still code, isn't it?
    eglasius : @Phil Agreed, the fact that you loaded it up dynamically doesn't make it be something else. Notice that you could perfectly be loading behavior+data when getting that instance of rule into the system, or you could have one that is just behavior and will receive all data from the system at runtime.
    eglasius : Notice that we are talking about defining what is code vs. data, not where/how you are supposed to have it/integrate it/etc.
  • The important note is that you want to separate out the part of your code that will execute the same every time, (i.e. applying a discount) from the part of your code which could change (i.e. the products to be discounted, or the % of the discount, etc.)

    This is simply for safety. If a discount changes, you won't have to re-write your discount code, you'll only need to go into your discounts repository (DB, or app file, or xml file, or however you choose to implement it) and make a small change to a number.

    Also, if the discount code is separated into an XML file, then you can give the entire application to a manager, and with sufficient instructions, they won't need to pester you whenever they want to change the discount rates.

    When you mix in data and code, you are exponentially increasing the odds of breaking when anything changes. So, as leppie said, you need to extract the constantly changing parts, and put them in a separate place.

  • Data is information. It's not about where you decide to put it, be it a db, config file, config through code or inside the classes.

    The same happens for behaviors / code. It's not about where you decide to put it or how you choose to represent it.

    Phil H : Then how would you define data's code subclass?
    eglasius : not sure I got your question right, but you can have hierarchical data just like you can have hierarchical code, that's organizing them, doesn't change which they are
  • I would say that the distinction between data, code and configuration is something to be made within the context of a particular component. Sometimes it's obvious, sometimes less so.

    For example, to a compiler, the source code it consumes and the object code it creates are both data - and should be separated from the compiler's own code.

    In your case you seem to be describing the option of a particularly powerful configuration file, which can contain code. Much as, for example, the GIMP lets you 'configure' plugins using Scheme. As the developer of the component that reads this configuration, you would think of it as data. When working at a different level -- writing the configuration -- you would think of it as code.

    This is a very powerful way of designing.

    Applying this to the underlying question ("How would you code the above example?"), one option might be to adopt or design a high level Domain Specific Language (DSL) for specifying rules. At startup, or when first required, the server reads the rule and executes it.

    Provide an admin interface allowing the administrator to

    • test a new rule file
    • replace the current configuration with that from a new rule file

    ... all of which would happen at runtime.

    A DSL might be something as simple as a table parser or an XML parser, or it could be something as sophisticated as a scripting language. From C, it's easy to embed Python or Lua. From Java it's easy to embed Groovy or Clojure.

    You could switch in compiled code at runtime, with clever linking or classloader tricks. This seems more difficult and less valuable than the embedded DSL option, in my opinion.

    Phil H : But aren't most configuration files read on start-up? Surely a dynamic system that acquired these discount rules on-the-fly would be necessary for a 24/7 supermarket chain. In which case, do you pick the flexibility of adding a new object (code), or the limits of data?
    slim : It's up to the designer when a configuration file gets read - at startup; once lazily; always; when triggered by an admin command. I was thinking in terms of an embedded scripting language, but you could also (re)link object code at runtime.
    slim : Clarified the answer.
  • Fundamentally, there is of course no difference between data and code, but for real software infrastructures, there can be a big difference. Apart from obvious things like, as you mentioned, compilation, the biggest issue is this:

    Most sufficiently large projects are designed to produce "releases" that are one big bundle, produced in 3-month (or longer) cycles, tested extensively and cannot be changed afterwards except in tightly controlled ways. "Code" most definitely cannot be changed, so anything that does need to be changed has to be factored out and made "configuration data" so that changing it becomes palatable those whose job it is to ensure that a release works.

    Of course, in most cases bad configuration data can break a release just as thoroughly as bad code, so the whole thing is largely an illusion - in reality it doesn't matter whether it's code or "configuration data" that changes, what matters is that the interface between the main system and the parts that change is narrow and well-defined enough to give you a good chance that the person who does the change understands all consequences of what he's doing.

    This is already harder than most people think when it's really just a few strings and numbers that are configured (I've personally witnessed a production mainframe system crash because it had one boolean value set differently than another system it was talking to). When your "configuration data" contains complex logic, it's almost impossible to achieve. But the situation isn't going to be any better ust because you use a badly-designed ad hoc "rules configuration" language instead of "real" code.

  • Relationship between code and data is as follows:

    code after compiled to a program processes the data while execution

    program can extract data, transform data, load data, generate data ...

    Also program can extract code, transform code, load code, generate code tooooooo...

    Hence code without compiled or interperator is useless, data is always worth..., but code after compiled can do all the above activities....

    For eg)

    Sourcecontrolsystem process Sourcecodes

    here source code itself is a code

    Backupscripts process files

    here files is a data and so on...