Thursday, April 14, 2011

Is there a way to substring a string in Python?

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?

Maybe like myString[2:end]?

EDIT: If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

From stackoverflow
  • >>> x = "Hello World!"
    >>> x[2:]
    'llo World!'
    >>> x[:2]
    'He'
    >>> x[:-2]
    'Hello Worl'
    >>> x[-2:]
    'd!'
    
    Paolo Bergantino : oo, I was about to add more examples, but I see it was done for me. Thank you kind sir.
  • Yes there is. Your example is very close:

    myString[2:]
    
  • myString[2:] .. leave off the second index to go to the end

  • mystring[2:]

  • You've got it right there except for "end". Its called slice notation. Your example should read.

    new_sub_string = myString[2:]
    

    If you leave out the second param it is implicitly the end of the string.

  • Besides the direct answer that others have given, you can find all the other rules for slicing behavior explained in the Strings section of the official tutorial.

    tgray : +1: for having a link to more information :-)
  • One example seems to be missing here: full (shallow) copy.

    >>> x = "Hello World!"
    >>> x
    'Hello World!'
    >>> x[:]
    'Hello World!'
    >>> x==x[:]
    True
    >>>
    

    This is a common idiom for creating a copy of sequence types (not of interned strings). [:] Shallow copies a list, See python-list-slice-used-for-no-obvious-reason.

    Joan Venge : Does this create a new copy?
    gimel : A new copy will be created for lists - see edited answer.

Localized group name

I want to configure a Mutex access rule by assigning privileges to the "Everyone" group. When I create my rule it looks something like the following

new MutexAccessRule("Everyone", MutexRights.Modify | MutexRights.Synchronize | MutexRights.TakeOwnership | MutexRights.ReadPermissions, AccessControlType.Allow)

How do I get the localized "Everyone" group name so this will work on a non english version of the OS.

Thanks

From stackoverflow
  • Rather than using the group name, use the underlying SID, which is not localised.

    var rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                   MutexRights.Modify
                                    | MutexRights.Synchronize 
                                    | MutexRights.TakeOwnership
                                    | MutexRights.ReadPermissions,
                                   AccessControlType.Allow)
    

Can someone explain about Linux library naming?

When I create a library on Linux, I use this method:

  1. Build: libhelloworld.so.1.0.0
  2. Link: libhelloworld.so.1.0.0 libhelloworld.so
  3. Link: libhelloworld.so.1.0.0 libhelloworld.so.1

The versioning is so that if you change the public facing methods, you can build to libhelloworld.so.2.0.0 for example (and leave 1.0.0 where it is), so that applications using the old library won't break.

However, what's the point in naming it 1.0.0 - why not just stick with libhelloworld.so and libhelloworld.so.1?

Also, is it best practice to name your library using 1.0.0 for example, or just 1?

g++ ... -Wl,-soname,libhelloworld.1

Or:

g++ ... -Wl,-soname,libhelloworld.1.0.0
From stackoverflow
  • The primary advantage of this method is easily letting users know which version of the library they have. For example, if I know a bug I'm getting was fixed in 1.0.4 I can easily check what version of the library I am linking against, and know if that's the right way to fix the bug.

    This number is referred to as the "shared object version" or "soversion" and is part of the ELF binary standard. IBM has a good overview of ELF at http://www.ibm.com/developerworks/power/library/pa-spec12/.

  • The way you're supposed to form the x.y.z version is like this:

    1. The first number (x) is the interface version of the library. Whenever you change the public interface, this number goes up.
    2. The second number (y) is the revision number of the current interface. Whenever you make an internal change without changing the public interface, this number goes up.
    3. The third number (z) is not a build number, it is the backwards-compatability count. This tells you how many previous interfaces are supported. So for example if interface version 4 is strictly a superset of interfaces 3 and 2, but totally incompatible with 1, then z=2 (4-2 = 2, the lowest interface number supported)

    So the x and z numbers are very important for the system to determine if a given app can use a given library, given what the app was compiled against. The y number is mainly for tracking bug fixes.

  • From an old email I sent to a colleague about this question:

    Let's look at libxml as an example. First of all, shared objects are stored in /usr/lib with a series of symlinks to represent the version of the library availiable:

    lrwxrwxrwx 1 root root     16 Apr  4  2002 libxml.so -> libxml.so.1.8.14
    lrwxrwxrwx 1 root root     16 Apr  4  2002 libxml.so.1 -> libxml.so.1.8.14
    -rwxr-xr-x 1 root root 498438 Aug 13  2001 libxml.so.1.8.14
    

    If I'm the author of libxml and I come out with a new version, libxml 2.0.0 that breaks interface compatiblity with the previous version, I can install it as libxml.so.2, and libxml.so.2.0.0. Note that it is up to the application programmer to be responsible about what he links to. If I'm really anal, I can link directly to libxml.so.1.8.14 and any other version will result in my program not running. Or I can link against libxml.so.1 and hope that the libxml developer doesn't break symbol compatibility on me in the 1.X version. Or if you don't care and are reckless, just link to libxml.so and get whatever version there is. Sometimes, when enough people do this, the library author has to get creative with later versions. Hence, libxml2:

    lrwxrwxrwx 1 root root     17 Apr  4  2002 libxml2.so.2 -> libxml2.so.2.4.10
    -rwxr-xr-x 1 root root 692727 Nov 13  2001 libxml2.so.2.4.10
    

    Note that there's no libxml2.so in this one. Looks like the developer got fed up with irresponsible application developers.

    ephemient : Umm, false. When you give `-lxml` to the dynamic linker, it will use the *library soname* in `libxml.so`, which would be `libxml.so.1`, so that's what the generated executable links against. ...(continued)
    ephemient : (continued)... Linking directly to `libxml.so` or `libxml.so.1.8.14` *does not* happen when the library is properly versioned. The `lib*.so` symlink is not needed for running executables, only developing them, so you may find that they are often placed in separate binary packages.
    ephemient : To see the library soname, use `readelf -d /usr/lib/libxml.so` (assuming you're on a development system with binutils installed).

What's the advantage of this indirect function call?

I found the following code in a library:

class Bar {
public:
  bool foo(int i) {
   return foo_(i);
  }
private:
  virtual bool foo_(int i) = 0;
};

Now I'm wondering: Why would you use this indirection? Could there be any reasons why the above would be better than the simple alternative:

class Bar {
public:
  virtual bool foo(int i) = 0;
};
From stackoverflow
  • This is often called a Template-Hook pair (a.k.a Hotspot), coined by Wolfgang Pree.

    See this PDF, PowerPoint, HTML

    One reason for doing the indirection as you call it is that things often can/has to be setup prior a method, and some cleaing post a method call. In the subclasses you only need to supply the necessary behaviour without doing the setup and cleaning...

  • If a subclass could change the definition of foo_?, but the consumers needed a static function (for efficiency)? Or for a delegation pattern?

  • This is the template pattern. The foo method contains code that must be executed by all subclasses. It makes more sense when you look at it like this:

    class Bar {
    public:
      bool foo(int i) {
       // Setup / initialization / error checking / input validation etc 
       // that must be done for all subclasses
       return foo_(i);
      }
    private:
      virtual bool foo_(int i) = 0;
    };
    

    It's nicer than the alternative, which is to try to remember to call the common code in each subclass individually. Inevitably, someone makes a subclass but forgets to call the common code, resulting in any number of problems.

  • This is the Non-Virtual Interface Idiom (NVI). That page by Herb Sutter has a good bit of detail about it. However, temper what you read there with what the C++ FAQ Lite says here and here.

    The primary advantage of NVI is separating interface from implementation. A base class can implement a generic algorithm and present it to the world while its subclasses can implement the details of the algorithm through virtual functions. Outside users are shielded from changes in the algorithm details, especially if you later decide you want to do add pre- and post-processing code.

    The obvious disadvantage is that you have to write extra code. Also, private virtual functions are confusing to a lot of people. Many coders mistakenly think you can't override them. Herb Sutter seems to like private virtuals, but IMHO it's more effective in practice to follow the C++ FAQ Lite's recommendation and make them protected.

LastChildFill Not Working When Trying To Dock ItemsControl

I've got the following markup in a WPF UserControl:

<Border Name="_border" BorderThickness="4" BorderBrush="Blue">
    <Canvas Name="_canvas" Background="Black" >
        <DockPanel LastChildFill="True">
            <ItemsControl Name="_itemsControl" Background="Bisque" AllowDrop="True" Height="100" Width="100"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Stretch"
                      ItemTemplate="{StaticResource pictureTemplate}"
                      ItemsPanel="{StaticResource panelTemplate}"
                      Drop="_itemsControl_Drop" 
                      DragOver="_itemsControl_DragOver" 
                      DragLeave="_itemsControl_DragLeave" 
                      PreviewMouseLeftButtonDown="_itemsControl_PreviewMouseLeftButtonDown"
                      PreviewMouseMove="_itemsControl_PreviewMouseMove">

        </ItemsControl>
             </DockPanel>
    </Canvas>
</Border>

I would like the ItemsControl to fill all of the available space, but it is not obeying the DockPanel's LastChildFill property. The Horizontal and Vertical "Stretch" values aren't helping either. What am I missing?

From stackoverflow
  • Whats the size of your DockPanel? Try setting a background on your DockPanel for testing.

    I don't think that you problem is with your ItemsControl not stretching to fill your DockPanel, but actually your DockPanel is not stretching to fit inside the Canvas Control. Canvas control and its children will not resize to fit thier parent.

  • If you remove the Canvas completely, you will not have this problem. Once you introduce a canvas, you need to set size and position of elements in the Canvas (like the DockPanel).

ASP.Net FileUpload Control with Regex Validator postback problem

I'm trying to use a .Net FileUpload control along with a Regex Validator to limit filename to JPG, GIF, or PNG extensions. After postback, the filename is gone from the control (as expected), but this seems to cause the validator to fire and display its error text.

Can anyone suggest a fix, or a better way? Thank you!

From stackoverflow
  • Use a custom validator to do this check and call Page.IsValid in the method that handles the upload which will stop the processing of the upload if the file does not have the valid extension.

  • Just use a custom validator with the following javascript function:

    function UploadFileCheck(source, arguments)
    {
        var sFile = arguments.Value;
        arguments.IsValid = 
           ((sFile.endsWith('.jpg')) ||
            (sFile.endsWith('.jpeg')) ||
            (sFile.endsWith('.gif')) ||
            (sFile.endsWith('.png')));
    }
    

    The custom validator code:

    <asp:CustomValidator ID="cvalAttachment" runat="server" ControlToValidate="upAttachment" SetFocusOnError="true" Text="*" ErrorMessage="Invalid: File Type (allowed types: jpg, jpeg, gif, png)" ClientValidationFunction="UploadFileCheck"></asp:CustomValidator>
    

    That should be all your need to stop it client side before it gets posted back.

  • JavaScript has no "endsWith", so use this code for the custom validator:

    function UploadFileCheck(source, arguments) { var sFile = arguments.Value; arguments.IsValid = ((sFile.match(/\.jpe?g$/i)) || (sFile.match(/\.gif$/i)) || (sFile.match(/\.bmp$/i)) || (sFile.match(/\.tif?f$/i)) || (sFile.match(/\.png$/i))); }

How to create a HTTP request listener Windows Service in .NET

I want to create Windows Service that acts as a HTTP listener and can handle around 500 clients. Are there any special considerations for this kind of service.

I am a little confused between the HTTPListener class and the TCPListener class. Which one to use for a Windows Service that will:

  1. Accept the client connection (around 500)
  2. Process client request
  3. Call another Http based service
  4. Return some value to the calling client


This is what I am doing to start the listener.

    listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:8080/");
    listener.Start();
    listener.BeginGetContext(new AsyncCallback(OnRequestReceive), listener);

private void OnRequestReceive(IAsyncResult result)
{
     HttpListener listener = (HttpListener)result.AsyncState;
     // Call EndGetContext to complete the asynchronous operation.
     HttpListenerContext context = listener.EndGetContext(result);
     HttpListenerRequest request = context.Request;
}

Will I be able to handle N clients simultaneously?

From stackoverflow
  • I'd use HttpListener class. It does many stuff for you and you wouldn't need to reinvent the wheel. Also it integrates with kernel mode http.sys driver in Windows Server 2003 and should offer better performance.

  • If you need to be able to highly responsive HttpListener will not scale very well (you cannot accept more than one connection at a time). But for small scale use, being careful to get context and write the response asynchronously it can work.

    EDIT: Appears I misunderstood HttpListener's ability to accept connections. You can accept multiple connections concurrently (see comment). However IIS's other facilities to host code would avoid reinventing the wheel. So unless there are very specific requirements that preclude IIS, why not take the easy path?

    For serious use, use IIS, creating an Http Handler (a class that implements IHttpHandler or IHttpHandlerFactory, or even an IHttpAsyncHandler) to handle the requests (this is the underlying type that implements .aspx et al).

    The right solution really depends on what you mean by "handle around 500 clients": one at a time or all at once?

    Based on the comment answer: 500 at once, and noting that the processing, in step 3, includes another HTTP call, I doubt using HttpListner will be able to handle the load without ensuring every operation is asynchronous (getting context and request, performing the onward HTTP request and then sending the response)... which will lead to some more difficult coding.

    Unless there is a very good reason to avoid IIS, using IIS will be easier as it is designed to support large scale client request loads with rich functionality, whereas HttpListener "Provides a simple, programmatically controlled HTTP protocol listener.".

    EDIT: Expanded based on more details of load.

    A9S6 : I mean 1-500 clients can be connected to that Service at any given time. Also, the processing time of each client will be small.
    Darrel Miller : Can you provide some source that claims that HttpListener cannot accept more than one connection at a time? I have running code using HttpListener that appears to me to be handling multiple requests concurrently. By calling BeginGetContext multiple times you effectively setup multiple listeners. Also, HttpListener is based on http.sys which is identical to what IIS uses for serving requests, so the performance should be equivalent.
    Richard : Added note to that effect, thank's for the update.
  • I created a TcpListener and started the listener using BeginAcceptTcpClient method. Each incoming request is taken to a separate thread for processing where the client connection is used continuously to get/send data from client. It seems to be working fine for large number of clients.