Tuesday, May 3, 2011

Masterpage Dropdown List not keeping Selected Index

Ok, my masterpage has a dropdown which controls size which affects a lot of things. I need to access the dropdown index from content pages so I do it using this code.

public partial class MasterPage : System.Web.UI.MasterPage
{
public DropDownList MySize { get { return _ddlSize; } }
}

I am using Ajax and when the size changes the menu on the Masterpage changes just fine.

But when I click on the updated menu it uses the zero index of the dropdown list on my contentpage even through visually it shows the size I selected.

  int size = Convert.ToInt32(Master.MySize.SelectedItem.Text); //Uses 0 index :(

I don't want to use Session, I just don't get why this doesn't work 100% of the time. Anyone have any ideas?

From stackoverflow
  • I figured it out!

    I set the dropdown to a public static object

    public static DropDownList MySize;
    

    Then I just set it equal to the page instance each time the masterpage loaded.

    protected void Page_Load(object sender, EventArgs e)
    {
        MySize = _ddlSize;
    }
    

    Calling the DropDownList is a little different since it's a static object.

    MasterPage.MySize.SelectedItem.Text
    

    But it works on all Content Pages that derive from the Masterpage.

    Jimmie R. Houts : Making it static only works if you want it to basically live forever, for all of your users. Static objects live in the iis worker process that your app is running in, which means that it is available globally, even across user sessions, until the worker process is killed or restarted (most of the time an app restart will get rid of it, but not always).
  • did you check this solution in a multi-user scenario, since the value is static it will be reflected across different users

    the view state set in the master page should retain the drop down lists value or try to use hidden controls to hold up the value

Locking a specific command in cmd.exe

Can anyone recommend a way in Windows XP or later to make it possible for users to access cmd.exe while locking out the ability to use type?

From stackoverflow
  • I believe that type is built into the shell's command parser itself, so I'm thinking no.

  • You could always make type.bat (which does nothing), or even compile type.exe and put it in path.

    Greg Hewgill : Making a .bat or .exe does not override the built-in command.
    ldigas : Hmm, yes. It would seem so. I'm mixing up things, this used to work fine in the dos days.
  • Even if you could prevent the use of type, the following command would do the same thing:

    copy file.txt con
    

    There are probably other ways to display the contents of a file without using the type built-in command. Notepad (or any other text editor) jumps to mind.

    ewanm89 : yeah, you could use a web browser even... in fact it's impossible to stop the reading of all files as it's a core operating system function. One however can use ntfs ACLs to restrict just which files can be read(yes it's possible on win XP).

Using vim for html decoration

Do you have any preferred methodology for managing html formatting tags in vim?

The best I've come up with is creating some macros to insert tags at the current cursor position - ctrl-i for <i>, ctrl-j for </i>, etc.

It would be handy to be able to, say 2w{something} to italicize 2 words, for instance, without needing to navigate the cursor to the end point. The best option I can think of would let me use the same keystrokes I use to so flexibly delete a string of text that might be word count, regex match, etc. but would insert both opening and closing tags.

From stackoverflow
  • Give a look to the surround.vim plugin.

    le dorfier : Classic vim - way overkill except when you quickly find out you need it. Lovely.
  • I use Christian Robinson's HTML macros when I have to traffic in raw HTML.

    Generally, I prefer to use reStructuredText and generate HTML.

    le dorfier : I need to work through reStructuredText too; but that's going to take a while and some planning. At first glance it appears to be more comprehensive and conceptually integrated than textile, markdown etc. I'll download and try out the first option first.

Unable to convert Bash script to Zsh script

I need to change the following Bash code to Zsh

TODO_OPTIONS="--timeout --summary"
         cd ()
         {   
             builtin cd "$@"
             RV=$?
             [ $RV = 0 -a -r .todo ] && devtodo ${TODO_OPTIONS}
             return $RV 
         }   

         pushd ()
         {   
             builtin pushd "$@"
             RV=$?
             [ $RV = 0 -a -r .todo ] && devtodo ${TODO_OPTIONS}
             return $RV 
         }   

         popd ()
         {   
             builtin popd "$@"
             RV=$?   
             [ $RV = 0 -a -r .todo ] && devtodo ${TODO_OPTIONS}
             return $RV 
         }   

         # Run todo initially upon login
         devtodo ${TODO_OPTIONS}

I get the following error when I start Zsh with the code

todo: error, unknown argument '--timeout --summary', try --help

I feel that Zsh cannot understand the following line

[ $RV = 0 -a -r .todo ] && devtodo ${TODO_OPTIONS}

Other commands in the first code seems to be right for Zsh.

How can you convert the code to Zsh?

From stackoverflow
  • You're saving the text as one string/object, instead of as a simple "thing to substitute". You can either save the string properly:

    TODO_OPTIONS=(--timeout --summary)
    ....
    devtodo ${TODO_OPTIONS}
    

    Or run word splitting on your variable:

    TODO_OPTIONS="--timeout --summary"
    ....
    devtodo ${=TODO_OPTIONS}
    
    Masi : @viraptor: Thank you for your answer!
    Masi : The first version of your codes works. :)

How to create an Oracle sequence starting with max value from a table?

Trying to create a sequence in Oracle that starts with the max value from a specific table. Why does this not work?

CREATE SEQUENCE transaction_sequence
  MINVALUE 0
  START WITH (SELECT MAX(trans_seq_no)
     FROM TRANSACTION_LOG) 
  INCREMENT BY 1
  CACHE 20;
From stackoverflow
  • You can't use a subselect inside a CREATE SEQUENCE statement. You'll have to select the value beforehand.

  • If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):

    SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
      INTO v_sql
      FROM transaction_log:
    
    EXECUTE IMMEDIATE v_sql;
    

    Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.

    One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.

  • you might want to start with max(trans_seq_no) + 1.

    watch:

    SQL> create table my_numbers(my_number number not null primary key);
    
    Table created.
    
    SQL> insert into my_numbers(select rownum from user_objects);
    
    260 rows created.
    
    SQL> select max(my_number) from my_numbers;
    
    MAX(MY_NUMBER)
    --------------
               260
    
    SQL> create sequence my_number_sn start with 260;
    
    Sequence created.
    
    SQL> insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
    insert into my_numbers(my_number) values (my_number_sn.NEXTVAL)
    *
    ERROR at line 1:
    ORA-00001: unique constraint (NEIL.SYS_C00102439) violated
    

    When you create a sequence with a number, you have to remember that the first time you select against the sequence, Oracle will return the initial value that you assigned it.

    SQL> drop sequence my_number_sn;
    
    Sequence dropped.
    
    SQL> create sequence my_number_sn start with 261;
    
    Sequence created.
    
    SQL>  insert into my_numbers(my_number) values (my_number_sn.NEXTVAL);
    
    1 row created.
    

    If you're trying to do the 'gapless' thing, I strongly advise you to

    1 not do it, and #2 not use a sequence for it.

    DCookie : +1 for the the catch on starting point of sequence. Also, I have to assume if he's setting the CACHE parameter to anything other than 1, he's not concerned about gaps!
    Neil Kodner : i was going to mention the cache being low but thought that was outside the scope of the question. Now if the user is expecting gapless numbers, by way of a sequence, they've got another things coming. Rollback doesn't 'decrement' a sequence ;)
  • Bear in mid, the MAX value will only be the maximum of committed values. It might return 1234, and you may need to consider that someone has already inserted 1235 but not committed.

UILabel text overlapping on update?

Hello,

In my app I change the value of a text label from an initial value of 0 and increment it on a touch event. Sometimes, but not all the time, the new value will be overlayed over the 0, which is not cool..

This is the relevant code:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UILabel *label = (UILabel *)[cell viewWithTag:1000];
label.text = qtyString;

I've tried removing the label from the view, then adding another with the new value, but it didn't affect the problem at all. When I scroll the cell (the labels are part of a table cell) out of the screen and back in, the labels display correctly. Oh, and I've also tried doing

[tableView reloadData];

And it works better, but if I select a cell and then scroll while it is higlighted it poops out on that cell.

Please help :(

From stackoverflow
  • I am experiencing something similar. I have a UILabel where updating text is fine, but the previous text is not removed, so the text is overlapping and messy. I am using [myLabel setText:somemessage] and the UILabel has the options 'opaque' and 'clear context before drawing' enabled. Any ideas?

    JoePasq : Read my answer below.
  • Under your UILabel options UNCHECK 'opaque', that will fix it.

  • Changing opaque doesnt change it altho it would have been logic. What you can do if giving your label an exact height .. This height will match your well height. If you are using

    • (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
      { return 80; //returns floating point which will be used for a cell row height at specified row index
      }

    Like i did then make the height of the label 80 as well that will stop it ..

  • imho, the best way to go around this is to add an else to:

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }else {
        NSArray *cellSubs = cell.contentView.subviews;
        for (int i = 0 ; i < [cellSubs count] ; i++) {
            [[cellSubs objectAtIndex:i] removeFromSuperview];
        }
    }
    

    Hope this helps.

  • I have posted what I think is something simlar but don't think it is the exact same....If anyone wants to have a look to help with the solution, that would be appreciated! Thanks!

    http://stackoverflow.com/questions/1327031/duplicate-rows-in-tableview-on-uitableviewcell

  • I had the same problem with UILabel's text getting all jumbled, I just read the other solutions, went to IB, then checked "Clear context before drawing", and that solved it!

get all of the immediate subdirectories in python

I'm trying to write a simple python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions). But I'm getting bogged down by trying to get the list of subdirectories

From stackoverflow
  • import os
    def get_immediate_subdirectories(dir):
        return [name for name in os.listdir(dir)
                if os.path.isdir(os.path.join(dir, name))]
    
    Shane C. Mason : The question is about getting a list of subdirectories, this will return all files in the current directory.
    RichieHindle : Gah! Sorry, now fixed.
  • os.walk is your friend in this situation.

    Straight from the doc

    walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

  • Using Twisted's FilePath module:

    from twisted.python.filepath import FilePath
    
    def subdirs(pathObj):
        for subpath in pathObj.walk():
            if subpath.isdir():
                yield subpath
    
    if __name__ == '__main__':
        for subdir in subdirs(FilePath(".")):
            print "Subdirectory:", subdir
    

    Since some commenters have asked what the advantages of using Twisted's libraries for this is, I'll go a bit beyond the original question here.


    There's some improved documentation in a branch that explains the advantages of FilePath; you might want to read that.

    More specifically in this example: unlike the standard library version, this function can be implemented with no imports. The "subdirs" function is totally generic, in that it operates on nothing but its argument. In order to copy and move the files using the standard library, you need to depend on the "open" builtin, "listdir", perhaps "isdir" or "os.walk" or "shutil.copy". Maybe "os.path.join" too. Not to mention the fact that you need a string passed an argument to identify the actual file. Let's take a look at the full implementation which will copy each directory's "index.tpl" to "index.html":

    def copyTemplates(topdir):
        for subdir in subdirs(topdir):
            tpl = subdir.child("index.tpl")
            if tpl.exists():
                tpl.copyTo(subdir.child("index.html"))
    

    The "subdirs" function above can work on any FilePath-like object. Which means, among other things, ZipPath objects. Unfortunately ZipPath is read-only right now, but it could be extended to support writing.

    You can also pass your own objects for testing purposes. In order to test the os.path-using APIs suggested here, you have to monkey with imported names and implicit dependencies and generally perform black magic to get your tests to work. With FilePath, you do something like this:

    class MyFakePath:
        def child(self, name):
            "Return an appropriate child object"
    
        def walk(self):
            "Return an iterable of MyFakePath objects"
    
        def exists(self):
            "Return true or false, as appropriate to the test"
    
        def isdir(self):
            "Return true or false, as appropriate to the test"
    ...
    subdirs(MyFakePath(...))
    
    Jarret Hardie : Since I have little exposure to Twisted, I always welcome additional info and examples; this answer is nice to see for that. Having said that, since this approach appears to require substantially more work than using the built-in python modules, and a Twisted install, are there any advantages to using this that you could add to the answer?
    Constantin : Glyph's answer was probably inspired by the fact that TwistedLore also uses .tpl files.
    Jarret Hardie : Well, clearly I don't expect the Spanish inquisition :-) I assumed "*.tpl" was a generic reference to some abstract extension meaning "template", and not a specific Twisted template (I've seen .tpl used in many languages after all). Good to know.
    Jarret Hardie : +1 therefore for twigging to the possible Twisted angle, though I'd still like to understand what Twisted'd 'FilePath' object and 'walk()' function add to the standard API.
    Glyph : Personally I find "FilePath.walk() yields path objects" a lot easier to remember than "os.walk yields 3-tuples of dir, dirs, files". But there are other benefits. FilePath allows for polymorphism, which means you can traverse things other than filesystems. For example, you could pass a twisted.python.zippath.ZipArchive to my 'subdirs' function and get a generator of ZipPaths out instead of FilePaths; your logic doesn't change, but your application now magically handles zip files. If you want to test it, you just have to supply an object, you don't have to write real files.
  • Here's one way:

    import os
    import shutil
    
    def copy_over(path, from_name, to_name):
      for path, dirname, fnames in os.walk(path):
        for fname in fnames:
          if fname == from_name:
            shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
    
    
    copy_over('.', 'index.tpl', 'index.html')
    
    nosklo : -1: won't work, since shutil.copy will copy to the current dir, so you'll end up overwriting 'index.html' in the current dir once for each 'index.tpl' you find in the subdirectory tree.
    Scott Kirkwood : Fixed the code, thanks!
  • I just wrote some code to move vmware virtual machines around, and ended up using os.path and shutil to accomplish file copying between sub-directories.

    def copy_client_files (file_src, file_dst):
        for file in os.listdir(file_src):
                print "Copying file: %s" % file
                shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file))
    

    It's not terribly elegant, but it does work.

How to pass a lambda expression to a C# constructor from an IronPython script?

I'm integrating an IronPython scritping engine into my C# raytracer which, so far, has been a breeze even though I'm completely new to Python. There is one particular thing, though, that I need help with. I have a C# class which defines a constructor like this:

public CameraAnimation(Action<Camera, float> animation)

In C#, I would instantiate this like so:

var camAnimation = new CameraAnimation((camera, time) => camera.Position += new Vector(1, 0, 0));

I can't quite figure out how to make a similar assignment for the Action object in IronPython, so how would the Python syntax look?

From stackoverflow
  • Assuming I interpreted this right, and Action is a generic delegate, the below works (the stubs I used are included).

    Python:

    import clr
    clr.AddReference("IronPythonDelegates")
    
    import IronPythonDelegates
    
    def camActionPy(camera, time):
      print "Camera: " + str(camera) + ", time: " + str(time)
    
    IronPythonDelegates.CameraAnimation(camActionPy);
    

    CSharp:

    namespace IronPythonDelegates
    {
        public class Camera{}
    
        public class CameraAnimation
        {
        private System.Action<Camera, float> animation;
    
        public CameraAnimation(System.Action<Camera, float> animation)
        {
            this.animation = animation;
            this.animation(new Camera(), 1.5f);
        }
        }
     }
    

    I corrected the above to use System.Action, and it no longer requires explicit reflection. It's a bit weird though. For some reason, I could construct a user-created delegate like:

    explicitTestAction = IronPythonDelegates.TestAction[IronPythonDelegates.Camera, System.Single](camActionPy);
    IronPythonDelegates.CameraAnimation(explicitTestAction);
    

    but could not do so with System.Action. E.g. with

    explicitSystemAction = System.Action[IronPythonDelegates.Camera, System.Single](camActionPy)
    IronPythonDelegates.CameraAnimation(explicitSystemAction);
    

    explicitSystemAction is null. TestAction was just defined as:

    public delegate void TestAction(T1 one, T2 two);

    But luckily either way it's fine to just do:

    CameraAnimation(System.Action) or CameraAnimation(TestAction)

    though for some reason I don't remember that working when I first tried...

    Matthew Flaschen : Note, I found System.Action, but unfortunately changing it to use that inexplicably broke the code... Looking at it now.
    srivatsn : Did you add a reference to System.Core.dll? System.Action is defined in mscorlib but System.Action is defined in System.Core.
    Matthew Flaschen : Yes, I have a reference to System.Core. As noted, I have it working now.

Handing exception in BLL and return to client (either winforms or webforms)?

Hi

I am looking for the best way to do exception handling, for example.. when an error occurs in the business logic layer, is the best way to stop the METHOD using a catch and return an EVENT to the presentation layer?

What should this event contain?

Or should i always BUBBLE up exceptions and handle them in the presentation layer?

Anyone have some good links and required reading on this with regards to the best way of handling exceptions and how to handle them in the client ...

For example if i get a NullException in the BLL than i can catch this.. but whats the best way and return to the presentaiton layer and informing it of the issue..

Event? or another try / Catch in the presentation?

From stackoverflow
  • You can do several things;

    1. Focus on improving the user experience when an unexpected error presents itself.

    2. Always log errors either in eventlog or database.

    3. Implement sufficient infrastructure to not let exceptions happen unless they are system exceptions.

    4. Use throw instread of throw exception

    Some links to help you:

    1. http://today.java.net/pub/a/today/2003/12/04/exceptions.html

    2. http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

    3. http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx

  • There are several ways to do it:

    1) Throwing exceptions with describing message inside.

    2) Firing events

    3) Using special interfaces to interact with the user.
    For example you can implement something like IUiCallbacks interface and send the object, implementing this interface, to the BLL class or method. Later, method in BLL can call IUiCallbacks.SendMessage() or IUiCallbacks.SendError() to notify presentation. And you can have different classes, such as WinFormsUiCallbacks, WebFormsUiCallbacks and SilentUiCallbacks, implementing this interface.

    I usually use 1) and 3)

    Example of 3) as requested:

    public interface IUiCallbacks
    {
      void SendMessage(string message);
      void SendException(string message, Exception ex);
    }
    
    public class WinFormsUiCallbacks : IUiCallbacks
    {
      public void SendMessage(string message)
      {
        MessageBox.Show(message);
      }
    
      public void SendException(string message, Exception ex)
      {
        MessageBox.Show(string.Format("Unfortunately, the following errror has occurred:{0}{1}", Environment.NewLine, ex.Message));
      }
    }
    
    public class OrderService
    {
      private IUiCallbacks _iUiCallbacks;
      ...
      public OrderService() { ... }
      public OrderService(IUiCallbacks iUiCallbacks)
      {
        _iUiCallbacks = iUiCallbacks;
      }
      ...
      public void AddOrder(Order order)
      {
        ...
        if(OrderAlreadyExists(order))
        {
          if(_iUiCallbacks != null)
            _iUiCallbacks.SendMessage("The order can not be added, because it is already accepted.");
          return;
        }
        ...
      }
      ...
    }

    So it can be used like this:

    public partial class OrderForm : Form
    {
      ...
      public void btnAddOrderFromExcel_Click(...)
      {
        Order order = LoadOrderFromExcel(...);
        OrderService orderService = new OrderService(new WinFormsUiCallbacks());
        orderService.AddOrder(order);
      }
      ...
    }
    
    nightcoder : I added the example to my answer.

Unable to understand the question by Zsh

I run the following command unsuccessfully

dir

and I get

zsh: correct 'dir' to 'gdir' [nyae]?

What does [nyae] mean in Zsh?

From stackoverflow
  • The n and y stand for no and yes.

    I don't remember the other two offhand, they might be "always" and "exit", but the "a" may stand for abort.

    You just type the corresponding initial.

    zshell has a correction mechanism, so it will sometimes ask you about correcting things before doing so for you.

  • zsh has a powerful correction mechanism. If you type a command in the wrong way it suggests corrections. What happend here is that dir is an unknown command and zsh suggests gdir, while maybe ls was what you wanted.

    1. If you want to execute gdir hit y (yes)
    2. If you want to try to execute dir anyway hit n (no)
    3. If you want to execute completely different spelt command like ls hit a (abort) and type your command
    4. If you want to execute a similar spelt commant like udir hit e (edit) and edit your command.
    Masi : Thank you for explanations!
  • From "An Introduction to the Z Shell"

    If you press y when the shell asks you if you want to correct a word, it will be corrected. If you press n, it will be left alone. Pressing a aborts the command, and pressing e brings the line up for editing again, in case you agree the word is spelled wrong but you don’t like the correction

    Masi : Thank you for the link!

Best jQuery drop-down nav Suckerfish alternative that works with Flash?

I think that my Suckerfish drop-down navigation does not play well with flash. I've done everything I can think of, yet my drop-down navigation keeps displaying underneath my flash movie. If I replace the movie with an image, it displays just fine. Only when I use a flash movie does the navigation display underneath the flash movie. I have already added wmode and it still does not work:

<param name="wmode" value="transparent" />

So I think my only solution left is to try and replace the navigation. So I am looking for a jQuery plugin that will replace my current navigation. My current navigation works like this:

  1. It's a horizontal drop-down menu
  2. When you hover over the menu, the first level drop-down menu appears
  3. When you click on a link in the first level drop-down menu, a second level is revealed below the link that was clicked (not the right like most nav menus). Sort of like a vertical accordion menu.

Is there anything like this currently available? I can't think of anything else to try to make the nav appear on top of the flash movie.

From stackoverflow
  • bah! I was forgetting one thing. You must set the window mode in TWO places! I am using the SWFObject javascript plugin, so my HTML looks like the following.

    In order for your navigation to appear on top of your flash movie, you must not forget to specify wmode="opaque" (or transparent) in the second object tag

    <object id="homepage_slideshow" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="530" height="397">
        <param name="movie" value="flash/homepage_slideshow.swf" />
        <param name="wmode" value="opaque" />
        <!--[if !IE]>-->
        <object type="application/x-shockwave-flash" data="flash/homepage_slideshow.swf" width="530" height="397" wmode="opaque">
        <!--<![endif]-->
        <!-- begin alternative content -->
        <img src="images/photos/homepage-placeholder-photo.jpg" width="530" height="397" alt="Get Moving Again!" />
        <!-- end alternative content -->
        <!--[if !IE]>-->
        </object>
        <!--<![endif]-->
    </object>
    

MySQL database up, but some tables not updating.

I have a mysql db with 10 tables. Each table drives a website where users can look at or submit data to that table.

Now the more popular tables have stopped displaying new data (checking through phpmyadmin). The smaller tables are still working fine.

I don't get any errors when submitting. The data just doesn't show up in the database.

It's all on one shared hosting server. How can it be that only certain tables in a database have problems?

From stackoverflow
  • This kind of question comes up from time to time. Every time I've seen this type of question, it turns out that the app displaying the data is connecting to a different database than the one you're updating through phpMyAdmin.

    So my recommendation is to assume nothing, and double-check every database connection in both your apps and your phpMyAdmin sessions.

  • Try to insert data with phpmyadmin in those tables were you have problems.

  • I have occasionally had trouble with MySQL not updating tables if I have multiple server processes running using the same data files.

    I had these problems with MySQL 4.1 where one server was running standalone and the other was running embedded. MySQL did not generate any error messages on start-up. I have not tried to reproduce my problems with newer versions of MySQL.

Cloud Computing: Who uses it

Who is using Cloud Computing like Windows Azure, Google Apps Engine, Amazone S3 ... and what are you using it for?

Why don't you use dedicated Servers or in-company infrastructure instead?

Do you know a Company that uses CC?

From stackoverflow
  • The company that I used to work for was doing actuarial calculations on a large in-house grid. They embellished this with cloud computing for those peak times when the in-house grid couldn't handle a short term problem. Pay for sufficient virtual machines, spin them up, perform the calculation, destroy the virtual machines. It was a way to handle demand spikes without having to pay for the overhead of that hardware year 'round.

    duffymo : No, Amazon's EC2.
  • I think lot of it for google app engine is speed of putting your work out there . If you are a two person company just starting out without the necessary infrastructure then app engine is a great option . See google's statement here , too.

    Even for medium sized companies it could help with extra loads on peak days. We use ec2 for releasing our product to thousands of sales team . In-house infrastructure just chokes on thousands of parallel downloads and it costs peanuts.

  • We use Amazon EC2 for dev and qa. Saves us a ton of money since the load is relatively low. We are currently evaluating if we should move the prod environments as well.

    crauscher : I'm not sure if moving all my sensitive date to another company? How are your customers thinking about that?
    Tim Jarvis : With EC2 it's kinda like just moving your data to a data centre. You still have full control over your security just not its physical location, It's almost like a huge ESX server...
    CodeToGlory : As long as whichever provider you choose have PCI DSS compliance in place, you should be good as it covers the processes involved in their infrastructure. Also, as Tim mentioned, we will have full control of how we want to implement the security.
  • We use S3 to store our documents online. Cheap and easy. With S3fm you can get your files online wherever you are.

How to make WMV compression using ASF Writer faster ? Any hints ?

I'm compressing raw AVI files to WMV using the ASF Writer. I'm in a big need to make the compression faster. There are any hints & best practicevs on how to achieve this ? Drop/lower the indexer impact ? Any hidden compression parameters ?

The files contains just video in RGB/24bits format and the compression level for the video stream is between 200kbps and 2000kbps.

Any configuration hints (using C++, C#, Delphi, etc)

Here is the the part of the code (using DSPack) that configure the WMV writer.

function CreateWMVWriter(VideoQuality, AudioQuality: Cardinal; videoInfo: PVideoInfoHeader; audioInfo: PWaveFormatEx; hasAudio: Boolean): IBaseFilter;
const
  PROFILE_NAME = 'WMV AutoProfile';
  // BUFFER_WINDOW = $FFFFFFFF;  // auto buffer
  BUFFER_WINDOW = 1000;  // 1 second
  MAX_KEY_FRAME_SPACING = 10000000; // 1 seconds
var
  configWriter : IConfigAsfWriter;
  profileManager : IWMProfileManager;
  profile : IWMProfile;
  stream : IWMStreamConfig;
  mediaProps : IWMMediaProps;
  vmediaProps : IWMVideoMediaProps;
  pmt : PWMMediaType;
  msize : Cardinal;
  vih : PVideoInfoHeader;
  wfe: PWaveFormatEx;
  hr : HRESULT;
  videoBitRate, audioBitRate: Cardinal;
  width, height: Integer;
begin
  videoBitRate := VideoQuality * 1000; // kbits
  // create the profile
  CheckDSError(WMCreateProfileManager(profileManager));
  CheckDSError(profileManager.CreateEmptyProfile(WMT_VER_9_0, profile));
  CheckDSError(profile.SetName(StringToOleStr(PROFILE_NAME)));
  CheckDSError(profile.SetDescription(StringToOleStr(PROFILE_NAME)));
  CheckDSError(profile.CreateNewStream(WMMEDIATYPE_Video, stream));
  CheckDSError(stream.SetStreamName(StringToOleStr('Video')));
  CheckDSError(stream.SetBitrate(videoBitRate));
  CheckDSError(stream.SetBufferWindow(BUFFER_WINDOW));
  // config video media type
  stream.QueryInterface(IID_IWMMediaProps, mediaProps);
  CheckDSError(mediaProps.GetMediaType(nil, msize));
  GetMem(pmt, msize);
  CheckDSError(mediaProps.GetMediaType(pmt, msize));
  with pmt^ do
  begin
    majortype := WMMEDIATYPE_Video;
    subtype := WMMEDIASUBTYPE_WMV3;
    bFixedSizeSamples := True;
    bTemporalCompression := True;
    pUnk := nil;
    vih := PVideoInfoHeader(pbFormat);
    // copy video info header (the same as with the original - copy: rcSource, rcTarget, AvgTimePerFrame, biWidth, biHeight)
    CopyMemory(vih, videoInfo, SizeOf(TVideoInfoHeader));
    // set bit rate at the same value
    vih.dwBitRate := videoBitRate;
    // set new compression ('WMV3')
    vih.bmiHeader.biCompression := MAKEFOURCC('W', 'M', 'V', '3');
  end;
  CheckDSError(mediaProps.SetMediaType(pmt));
  FreeMem(pmt, msize);
  // set media props
  stream.QueryInterface(IID_IWMVideoMediaProps, vmediaProps);
  CheckDSError(vmediaProps.SetQuality(100));
  CheckDSError(vmediaProps.SetMaxKeyFrameSpacing(0));
  // CheckDSError(vmediaProps.SetMaxKeyFrameSpacing(MAX_KEY_FRAME_SPACING));
  // add video stream
  CheckDSError(profile.AddStream(stream));
  // add audio stream (if needed)
  if hasAudio then
  begin
    CheckDSError(profile.CreateNewStream(WMMEDIATYPE_Audio, stream));
    CheckDSError(stream.SetStreamName(StringToOleStr('Audio')));
    audioBitRate := audioInfo.nSamplesPerSec * audioInfo.nChannels * audioInfo.wBitsPerSample;
    CheckDSError(stream.SetBitrate(audioBitRate));
    CheckDSError(stream.SetBufferWindow(BUFFER_WINDOW)); // auto
    // config video media type
    stream.QueryInterface(IID_IWMMediaProps, mediaProps);
    CheckDSError(mediaProps.GetMediaType(nil, msize));
    GetMem(pmt, msize);
    hr := mediaProps.GetMediaType(pmt, msize);
    with pmt^ do
    begin
      // uncompressed audio
      majortype := WMMEDIATYPE_Audio;
      subtype := WMMEDIASUBTYPE_PCM;
      formattype := WMFORMAT_WaveFormatEx;
      cbFormat := sizeof(TWaveFormatEx);
      bFixedSizeSamples := True;
      bTemporalCompression := False;
      lSampleSize := audioInfo.nChannels * audioInfo.wBitsPerSample div 8;
      pUnk := nil;
      wfe := PWaveFormatEx(pbFormat);
      // copy video info header (the same as with the original)
      CopyMemory(wfe, audioInfo, SizeOf(TWaveFormatEx));
    end;
    CheckDSError(mediaProps.SetMediaType(pmt));
    FreeMem(pmt, msize);
    // add video stream
    CheckDSError(profile.AddStream(stream));
  end;

  // create the writer
  Result := AddFilterGUID(CLSID_WMAsfWriter, 'WmvWriter');

  // config the writer
  configWriter := Result as IConfigAsfWriter;
  CheckDSError(configWriter.SetIndexMode(True));
  CheckDSError(configWriter.ConfigureFilterUsingProfile(profile));
end;
From stackoverflow
  • I really don't have a lot of experience with this, but from what has been posted elsewhere, try setting WMMEDIASUBTYPE_WVC1 instead of WMMEDIASUBTYPE_WVC3. Information was gleaned from here.

    Some other links that might be helpful: here and here

Correcting Wrong Marker Folding in VIM

I mistakenly did marker folding to my .vimrc:

{{{8 #CS
something..
}}}8  
{{{9 #Math
...
}}}9  
... many more!

I need to switch the format to "#SOMETHING {{{NUMBER" like:

#CS {{{8 
something..
}}}8  
#Math {{{9 
...
}}}9  
... many more!

What is wrong in the following code:

:%s$/({{{\d/) /(#[:alpha:]/)$\2 \1$g

[Solution]

%s$\({{{\d\) \(#[[:alnum:]]*\)$\2 \1$g
From stackoverflow
  • :%s/{{{\(\d\) \(.*\)/\2 {{{\1/g

    it works, but in your regex I don't understand why do you got a $ after s.

    Masi : The sign after the s does not matter, unless you need the sign. For example, I use normally # but now there was a #-sign in the match so I had to use some other. Choose anything that suits you.
    Masi : A word of advice: Using the .* can cause chaotic backtracking. In my case, I needed to be very precise to avoid backtracking.
    rampion : vim lets you use arbitrary delimiters for `:s`, so `:s$a$b$g` is the same as `:s/a/b/g`. Long story short, it lets you avoid escaping forward slashes when they occur in your pattern or replacement text.
    Raoul Supercopter : thanks for the tips :)
  • You forgot to escape the parentheses, and the POSIX character classes are only valid within a character class [[:alpha:]]:

    :%s$/\({{{\d/\) /\(#[[:alpha:]]/\)$\2 \1$g
    

    Note, however, that your example text doesn't contain any slashes - is this what your sample text is actually like?

    The above regex changes this

    /{{{8/ /#A/
    

    To this

    #A/ {{{8/
    
    Masi : Thank you. I solved the problem. Clearly, I was too uncareful with the intial regex. The errors are fixed in "my solution". Your regex is very similar to mine that I wrote to the post a few minutes ago.
    Masi : Thanks for elaborating the POSIX character classes.

What's the most efficient way of filtering an array based on the contents of another array?

Say I have two arrays, items and removeItems and I wanted any values found in removeItems to be removed from items.

The brute force mechanism would probably be:

var animals = ["cow","dog","frog","cat","whale","salmon","zebra","tuna"];
var nonMammals = ["salmon","frog","tuna","spider"];
var mammals = [];
var isMammal;

for(var i=0;i<animals.length;i++){
   isMammal = true;
   for(var j=0;j<nonMammals;j++){
     if(nonMammals[j] === animals[i]){
       isMammal = false;
       break;
     }
   }
   if(isMammal){
     mammals.push(animals[i]);
   }
}

This is what? O(N^2)? Is there a more efficient way?

From stackoverflow
  • That's actually O(M * N).

    Probably you could do better sorting the animals array first, then doing a binary search. You'll be able to reduce to O(N * log N) - well, that's if log N < M anyway.

    Anyway, if you're working with JS and that runs client-side, then just try to keep amount of data at minimum, or their browsers will yell at you with every request.

    Stuart Branham : I was just writing something about sorting the lists first as well. You end up with n*lg(n) + m*lg(n) to sort the main list and then search main list m times, which is effectively m*lg(n) - much better than n^2
  • With jQuery it's pretty easy:

    function is_mammal(animal)
    {
        return $.inArray(animal, nonMammals) == -1;
    }
    
    mammals = $.grep(animals, is_mammal);
    

    See docs for $.grep and $.inArray.

    Seb : That's easy, but doesn't make it any better than O(N^2). Just because you "hide" the loops doesn't mean $.inArray() and $.grep() don't have them.
  • Basically what you want to do is efficiently compute the set difference S \ T. The (asymptotically) fastest way I know is to put T into a hashmap (that makes |T| steps) and go over each s in S (that makes |S| steps) checking wether s in T (which is O(1)). So you get to O(|T| + |S|) steps.

    Seb : While this _is_ faster than my answer, it requires more memory for the hash table. There're pros and cons everywhere, right? :) Anyway, I believe this is the best solution, so there goes my +1.
    bayer : Yes, that's why I wrote the asymptotically there. ;) Personally I'd guess that for small inputs even the squared solution suffices.

Ruby Time.parse gives me out of range error

I am using Time.parse to create a Time object from a string.

For some reason

Time.parse("05-14-2009 19:00")

causes an argument our of range error, whereas

Time.parse("05-07-2009 19:00")

does not

Any ideas?

From stackoverflow
  • My guess would be that its expecting the second part of the string (the 14) to be the month.

    This link may help you parse it.

  • It is probably expecting Day-Month-Year format, so your first value is trying to specify the 5th day of the 14th month.

  • If you know the format of the string use

    Time.strptime(date, format, now=self.now) {|year| ...}
    

    http://www.ruby-doc.org/core-1.9/classes/Time.html#M000266

    It will solve your problem and will probably be faster than Time.parse.

    EDIT:

    Looks like they took strptime from Time class, but it called Date.strptime anyway, if you are on Rails you can do

    Date.strptime("05-14-2009 19:00","%m-%d-%Y %H:%M").to_time
    

    if you use pure ruby then you need:

    require 'date'
    d=Date._strptime("05-14-2009 19:00","%m-%d-%Y %H:%M")
    
    Time.utc(d[:year], d[:mon], d[:mday], d[:hour], d[:min], 
             d[:sec], d[:sec_fraction], d[:zone])
    

    See also: http://blog.nominet.org.uk/tech/2007/06/14/date-and-time-formating-issues-in-ruby-on-rails/

    Tony : strptime looks cool but I get an undefined method for Time.strptime and I need a time object
    Tony : ...here is the usage Time.strptime(date_time['value'], "%m-%d-%Y %H:%M")
    Miquel : Looks like strptime does not exist in Time anymore, see edit for alternative
    Tony : thanks miguel, that solution looks good. i ended up using this statement: fixed_date_time = "#{$2}-#{$1}-#{$3} #{$4}:#{$5}" if date_time['value'] =~ /(\d{2})-(\d{2})-(\d{4})\s(\d{2}):(\d{2})/ because i saw your post late. i don't plan on changing it because it works and it may even be faster. anyway, voted you up but had to give the answer to the first commenter since his link solved my problem.
    Miquel : I don't think this solution is faster as it has to call _parse anyway, parse implementation use heuristics checking a lot of cases. Additionally, your code will fail when 1.9 is out as they changed to use ISO date formats. My solution will not fail as uses the ruby standard date formating mechanisms.
  • It's beacuse of the heuristics of Time#parse.

    And it's due to anglo-american formats.

    With dashes '-' it expects mm-dd-yyyy, with slashes '/' it expects dd/mm/yyyy

    This behaivour CHANGES intentionally in 1.9. to accomplish eur,iso and jp Date standadrs

  • You probably do not need it to solve this problem but I still recommend checking out the natural language date/time parser Chronic, it has saved me a lot of work a couple of times.

Best way to implement game playback?

I'm creating a grid based game in Java and I want to implement game recording and playback. I'm not sure how to do this, although I've considered 2 ideas:

  1. Several times every second, I'd record the entire game state. To play it back, I write a renderer to read the states and try to create a visual representation. With this, however, I'd likely have a large save file, and any playback attempts would likely have noticeable lag.

  2. I could also write every key press and mouse click into the save file. This would give me a smaller file, and could play back with less lag. However, the slightest error at the start of the game (For example, shooting 1 millisecond later) would result in a vastly different game state several minutes into the game.

What, then, is the best way to implement game playback?

Edit- I'm not sure exactly how deterministic my game is, so I'm not sure the entire game can be pieced together exactly by recording only keystrokes and mouse clicks.

From stackoverflow
  • Why not record several times a second and then compress your output, or perhaps do this:

    recordInitialState();
    ...
    runs 30 times a second:
    recordChangeInState(previousState, currentState);
    ...
    

    If you only record the change in state with a timestamp(and each change is small, and if there is no change, then record nothing), you should end up with reasonable file sizes.

  • Assuming that your game is deterministic, it might be sufficient if you recorded the inputs of the users (option 2). However, you would need to make sure that you are recognizing the correct and consistent times for these events, such as when it was recognized by the server. I'm not sure how you handle events in the grid.

    My worry is that if you don't have a mechanism that can uniformly reference timed events, there might be a problem with the way your code handles distributed users.

    Consider a game like Halo 3 on the XBOX 360 for example - each client records his view of the game, including server-based corrections.

  • A good playback mechanism is not something that can be simply added to a game without major difiiculties. The best would be do design the game infrastructure with it in mind. The command pattern can be used to achieve such a game infrastructure.

    For example:

    public interface Command{
        void execute();
    }
    public class MoveRightCommand implements Command {
       private Grid theGrid;
       private Player thePlayer;
    
       public MoveRightCommand(Player player, Grid grid){
            this.theGrid = grid;
            this.thePlayer = player;
           }
    
       public void execute(){
         player.modifyPosition(0, 1, 0, 0);
       } 
    }
    

    And then the command can be pushed in an execution queue both when the user presses a keyboard button, moves the mouse or without a trigger with the playback mechanism. The command object can have a time-stamp value (relative to the beginning of the playback) for precise playback...

    Steven Richards : This is an elegant way to handle it. If the actual gameplay and the recording are based on the same timing/frame mechanism, you should avoid errors due to timing issues. If you have randomization in your events, you might need to record the starting seed value for your random number generator as well. That's how 'Random Map' functions in RTS games allow you to regenerate a random map you liked.
    Bill the Lizard : This pattern can also give you Undo/Redo capability.
  • There is no need to save everything in the scene for every frame. Save changes incrementally and use some good interpolation techniques. I would not really use a command pattern based approach, but rather make checks at a fixed rate for every game object and see if it has changed any attribute. If there is a change that change is recorded in some good encoding and the replay won't even become that big.

  • How you approach this will depend greatly on the language you are using for your game, but in general terms there are many approaches, depending on if you want to use a lot of storage or want some delay. It would be helpful if you could give some thoughts as to what sacrifices you are willing to make.

    But, it would seem the best approach may be to just save the input from the user, as was mentioned, and either store the positions of all the actors/sprites in the game at the same time, which is as simple as just saving direction, velocity and tile x,y, or, if everything can be deterministic then ignore the actors/sprites as you can get their information.

    How non-deterministic your game is would also be useful to give a better suggestion.

    If there is a great deal of dynamic motion, such as a crash derby, then you may want to save information each frame, as you should be updating the players/actors at a certain framerate.

  • Shawn Hargreaves had a recent post on his blog about how they implemented replay in MotoGP. Goes over several different approaches and their pros and cons.

    http://blogs.msdn.com/shawnhar/archive/2009/03/20/motogp-replays.aspx

  • I would simply say that the best way to record a replay of a game depends entirely on the nature of the game. Being grid based isn't the issue; the issue is how predictable behaviour is following a state change, how often there are new inputs to the system, whether there is random data being injected at any point, etc, You can store an entire chess game just by recording each move in turn, but that wouldn't work for a first person shooter where there are no clear turns. You could store a first person shooter by noting the exact time of each input, but that won't work for an RPG where the result of an input might be modified by the result of a random dice roll. Even the seemingly foolproof idea of taking a snapshot as often as possible isn't good enough if important information appears instantaneously and doesn't persist in any capturable form.

    Interestingly this is very similar to the problem you get with networking. How does one computer ensure that another computer is made aware of the game state, without having to send that entire game state at an impractically high frequency? The typical approach ends up being a bespoke mixture of event notifications and state updates, which is probably what you'll need here.

  • I did this once by borrowing an idea from video compression: keyframes and intermediate frames. Basically, every few seconds you save the complete state of the world. Then, once per game update, you save all the changes to the world state that have happened since the last game update. The details (how often do you save keyframes? What exactly counts as a 'change to the world state'?) will depend on what sort of game information you need to preserve.

    In our case, the world consisted of many, many game objects, most of which were holding still at any given time, so this approach saved us a lot of time and memory in recording the positions of objects that weren't moving. In yours the tradeoffs might be different.

How to do a get and post in php with restful web service server side

Hi can anyone past some code how to do a restful web service get and post method. This would be server side so I would be able to invoke the two services from a client.

Thanks!

From stackoverflow
  • POST:
    <?
    // Helloworld_post.php
    echo "Hello world <pre>"
    print_r($_POST['data'];
    ?>
    
    GET
    <?
    //helloworld_get.php
    echo "Hello world <pre>"
    print_r($_GET['data'];
    ?>
    

    What exactly are you trying to do? You need to use mod_rewrite or its equivalent to make pretty /helloworld/ urls. The beauty of REST is it is just a standard http request. It doesn't specify json encoding or xml encoding or "wtf I am the 1337" encoding.

  • Assume you have a script index.php. You might have two functions inside of it, showForm() and handleForm().

    Assume a request comes in to index.php.

    if (! empty($_SERVER['REQUEST_METHOD'])) {
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
        {
         doSomething();
        }
        else
        {
         showSomething();
        }
    }
    

    There you have it. REST. If you send a GET request to index.php, you'll show some output, and if you send a POST request to index.php, you'll perform some data manipulation. You can take if from there for the other RESTful HTTP request types, such as DELETE, etc.

    Obviously this is a very simple example, and I wouldn't want to create an entire site in this manner. It's best to go about creating a RESTful site in an architecturally sound way. Many frameworks can assist with this.

    REST is a hot topic right now, it seems everyone wants their apps to be RESTful. There's a lot of articles and guides out there on Google, you'd probably do well to spend some time researching various approaches.

    Note about URLs: URIs don't have to be pretty to be RESTful. However, a key point of REST is that all URIs should represent a single resource. As query parameters are not part of a URI, "/index.php?show=2" is not considered RESTful. You'll find that a lot of applications use URL rewriting to convert query parameters into something like "/index/2" instead.

    That being said, there's nothing wrong with having "/index.php" as a URI, just as long as it only represents a single state.