Friday, April 29, 2011

What is a multibyte character set?

Does the term multibyte refer to a charset whose characters can - but don't have to be - wider than 1 byte, (e.g. UTF-8) or does it refer to character sets which are in any case wider than 1 byte (e.g. UTF-16) ? In other words: What is meant if anybody talks about multibyte character sets?

From stackoverflow
  • Typically the former, i.e. UTF-8-like. For more info, see Variable-width encoding.

  • The former - although the term "variable-length encoding" would be more appropriate.

  • I generally use it to refer to any character that can have more than one byte per character.

  • Did you check this out: http://en.wikipedia.org/wiki/Multi-byte_character_set Or this: http://msdn.microsoft.com/en-us/library/5z097dxa(VS.71).aspx

  • All character sets where you dont have a 1 byte = 1 character mapping. All Unicode variants, but also asian character sets are multibyte.

    For more information, I suggest reading this Wikipedia article.

  • A multibyte character will mean a character whose encoding requires more than 1 byte. This does not imply however that all characters using that particular encoding will have the same width (in terms of bytes). E.g: UTF-8 and UTF-16 encoded character may use multiple bytes sometimes whereas all UTF-32 encoded characters always use 32-bits.

    References:

  • The term is ambiguous, but in my internationalization work, we typically avoided the term "multibyte character sets" to refer to Unicode-based encodings. Generally, we used the term only for legacy encoding schemes that had one or more bytes to define each character (excluding encodings that require only one byte per character).

    Shift-jis, jis, euc-jp, euc-kr, along with Chinese encodings are typically included.

    Most of the legacy encodings, with some exceptions, require a sort of state machine model (or, more simply, a page swapping model) to process, and moving backwards in a text stream is complicated and error-prone. UTF-8 and UTF-16 do not suffer from this problem, as UTF-8 can be tested with a bitmask and UTF-16 can be tested against a range of surrogate pairs, so moving backward and forward in a non-pathological document can be done safely without major complexity.

    A few legacy encodings, for languages like Thai and Vietnamese, have some of the complexity of multibyte character sets but are really just built on combining characters, and aren't generally lumped in with the broad term "multibyte."

  • Here is joel's article about unicode http://www.joelonsoftware.com/articles/Unicode.html

  • What is meant if anybody talks about multibyte character sets?

    That, as usual, depends on who is doing the talking!

    Logically, it should include UTF-8, Shift-JIS, GB etc.: the variable-length encodings. UTF-16 would often not be considered in this group (even though it kind of is, what with the surrogates; and certainly it's multiple bytes when encoded into bytes via UTF-16LE/UTF-16BE).

    But in Microsoftland the term would more typically be used to mean a variable-length default system codepage (for legacy non-Unicode applications, of which there are sadly still plenty). In this usage, UTF-8 and UTF-16LE/UTF-16BE cannot be included because the system codepage on Windows cannot be set to either of these encodings.

    Indeed, in some cases “mbcs” is no more than a synonym for the system codepage, otherwise known (even more misleadingly) as “ANSI”. In this case a “multibyte” character set could actually be something as trivial as cp1252 Western European, which only uses one byte per character!

    My advice: use “variable-length” when you mean that, and avoid the ambiguous term “multibyte”; when someone else uses it you'll need to ask for clarification, but typically someone with a Windows background will be talking about a legacy East Asian codepage like cp932 (Shift-JIS) and not a UTF.

generic inheritance in C#?

I can do

public class MyGenericClass : DL
//but i cannot do
public class MyGenericClass <T> : T

How would i do the second? if i cannot do that, how can i do something like

public class MyGenericClass <T> 
{
    T obj;
    //have all MyGenericClass.XYZ call obj.XYZ
}
From stackoverflow
  • This is not possible, because depending on what type T is, the public interface of MyGenericClass would change.

    If you have lots of different classes that all expose the same interface, you could declare MyGenericClass to expose that interface, and in the implementation of all of the functions delegate the calls to obj

    Daniel Earwicker : But in the second case, where T is used to declare a member, that member could be public, and then the public interface of MyGenericClass would change depending on the type of T.
    Jason Coyne : Just the datatype of the property, which is inherently handled by .net and generics. My point was more that entire functions and properties would be added and removed if it worked the way he wanted, not jsut a datatype change
    Daniel Earwicker : That's circular: "inherently handled by generics" - why doesn't it inherently handle the case that doesn't work? :)
    Jason Coyne : Its not up to me what they support and what they don't. Although I will note that several of the other answers indicate some of the problems that would cause.
    Daniel Earwicker : No problem - just thought you might want to improve your answer. At the moment, it gives the wrong reason ("the public interface").
  • You could do something like

    public interface IXyzable { void xyz(); }
    
    public class MyGenericClass<T> : IXyzable where T : IXyzable {
        T obj;
        public void xyz() {
            obj.xyz();
        }
    }
    

    Edit: Now I understand the question

  • You'll need all your possible T's to implement some interface so that you know that obj.XYZ() makes sense, then you can do

    public interface Ixyz
    {
        void XYZ();
    }
    
    public class MyGenericClass<T> : Ixyz where T:Ixyz, new()
    {
        T obj;
    
        public MyGenericClass()
        {
            obj = new T();
        }
    
        public void XYZ()
        {
            obj.XYZ();
        }
    }
    

    I've made MyGenericClass implement Ixyz too since it obviously does expose the right method, but maybe that's best left out since it allows

    var x = new MyGenericClass<MyGenericClass<SomeClass>>();
    

    which is unlikely to ever be a good idea.

  • This is pretty much duck-typing, but you could use reflection. When you create the generic class with a reference to the obj, use reflection to try and find a method with the right signature. As long as you store a reference to the method, performance won't be too bad.

    class BaseGeneric<T>
    {
        private T obj;
        private MethodInfo mi;
        private const string MethodNameOfInterest = "Xyz";
    
        public BaseGeneric(T theObject)
        {
            this.obj = theObject;
            Type t = obj.GetType();
             mi = t.GetMethod(MethodNameOfInterest);
        }
    
        public void Xyz()
        {
            mi.Invoke(obj, null);
        }
    }
    

    Of course, you would need to add a lot more for error checking and such, but that is the gist of what you could do. Also, don't forget to add the System.Reflection namespace to your using clause.

    Erich Mirabal : why the down vote? I answered the question, didn't I? I would not recommend doing it, but it does solve his problem: BaseGeneric.Xyz() calls the underlying object's Xyz() method no matter what that type is.
    Jason Coyne : Your solution has all the downsides of reflection, and no benefits of duck typing. The external object (BaseGeneric) must have all of the functions declared on it. If you know those functions, just call the same function?
    Erich Mirabal : It caches the MethodInfo, so the performance penalty is reduced. It looks like the underlying object - so it quacks. It does make him implement each method all over again, so that is the biggest downside. However, T could be anything that implements Xyz, which comes in handy in certain scenarios.
    Jason Coyne : If you make him implement the method manually, then why not just call the implementing method directly? Why use reflection at all? That was the source of the down vote
    Erich Mirabal : Yeah, you are right. I appreciate the explanation. The only upside to my method is that T could be any class that has the method Xyz. This is handy iff there is no access to the code and can't make it use interfaces. Very limited use, but similar to the upcoming dynamic type in C# 4.0.
  • The .NET type system won't allow type declarations of the form you're attempting. One reason why this is disallowed should be intuitive: how would MyGenericClass<T> act when T is a sealed class (e.g. System.String)?

    If you absolutely need this functionality (and you know that the type T you'll be using isn't sealed), you can generate proxies at runtime using the classes in the Reflection.Emit namespace. It may also be possible to achieve this effect using AOP tools like PostSharp.

    Daniel Earwicker : MyGenericClass would produce a compiler error. If this language feature was available, inheriting from T would automatically constrain T to be unsealed. Although this is only part of the problem (see my answer).
  • The specific question, why can't you do this:

    public class MyGenericClass<T> : T
    

    And you can do this:

    public class MyGenericClass<T> 
    {
       T obj;
    }
    

    The reason is that the CLR likes to be able to compile a single version of the code for MyGenericClass that will work for any reference type specified for T.

    It can do this for the second case, because it can quietly replace T with object and insert appropriate casts, roughly equivalent to:

    public class MyGenericClass 
    {
       object obj;
    }
    

    But for the inheritance version, that trick doesn't work.

    Also, many useful facilities would be impossible to describe through interface constraints. When you inherit from a type, you can do a lot more than just call methods on it - you can override them as well. Consider this hypothetical example:

    class MyBase 
    {
        public virtual void MyVirtual() { }
    }
    
    class MyGenericDerived<T> : T
    {
        public override void MyVirtual() 
        {
            Console.WriteLine("Overridden!"); 
        }
    } 
    
    MyBase obj = new MyGenericDerived<MyBase>();
    obj.MyVirtual();
    

    What I want to do there is something like a "mix-in", where MyGenericDerived supplies definitions for virtual functions in whatever base it is applied to. But how does the compiler know that T will have a method called MyVirtual that can be overridden? I'd need to put a constraint on T. How would I express that through interfaces? It's impossible. Using interfaces to describe constraints isn't an adequate solution once you allow inheritance from type parameters. So that's another reason why it doesn't exist in the language today.

  • What about this:

       class BaseClass<T>
        {
           public T property { get; set; }
        }
    
        class GenericClass<T> : BaseClass<T>
        { 
    
        }
    
    class Program
    {
        static void Main(string[] args)
        {
    
            GenericClass<int> l = new GenericClass<int>();
            l.property = 10;
        }
    }
    

    This achieves what you want to do?

    Erich Mirabal : I don't think so. He wants GenericClass to expose all the methods of T without re-implementing anything. At least, that's my best guess as to what he is asking.

Keep a http connection alive in C#?

How do i keep a connection alive in C#? I'm not doing it right. Am i suppose to create an HttpWebRequest obj and use it to go to any URLs i need? i dont see a way to visit a url other then the HttpWebRequest.Create static method.

How do i create a connection, keep it alive, browse multiple pages/media on the page and support proxys? (i hear proxy are easy and support is almost standard?) -edit- good answers. How do i request a 2nd url?

{
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
WebRequestObject.KeepAlive = true;
//do stuff
WebRequestObject.Something("http://www.google.com/intl/en_ALL/images/logo.gif");
}
From stackoverflow
  • You can set the HttpWebRequest.KeepAlive property to true.

    For the Proxies, there is a property also: HttpWebRequest.Proxy

  • Have you tried the HttpWebRequest.KeepAlive property? It sets the appropriate Keep-Alive HTTP header and does persist the connections. (Of course this must also be supported and enabled by the remote web server).

    The HttpWebRequest.KeepAlive documentation on MSDN states that it is set to true by default for HTTP1.1 connections, so I suspect the server you're trying to contact does not allow connection persistence.

    Proxy is used automatically and its settings are taken from your system (read Internet Explorer) settings. It is also possible to override the proxy settings via HttpWebRequest.Proxy property or by tweaking the application configuration file (see http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx).

  • Set HttpWebRequest.KeepAlive property True .NET will take care of the rest. It's just database connection pool. Works transparently.

    You can create new connection freely .NET will figure it out that you are connecting an already connected server and will use it. Also depends on your Net.ServicePointManager.DefaultConnectionLimit number it will establish new connections (if you do multhithreading).

How do I get a list of custom fields in JIRA with Perl SOAP?

I was curious if anyone else had an idea how to get a list of all of the custom fields you have created in JIRA? If so, how did you do it?

I've been trying to use a Perl SOAP routine I found on JIRA SOAP service documentation, but I have no idea how to implement it.

From stackoverflow

Where to go to browse for open source projects to work on?

I've decided to have a look around for open source projects that need a hand and lend a bit of time to one or two. One question though, is there a site(s) that lists current open source projects that are looking for developers and is there anywhere I could for example filter open source projects by language/technology/etc.

What I'm after is a way of getting an overview of many open source projects so I can make a decision whether they interest me or not.

Ideas where to find such information?

From stackoverflow
  • Source Forge is a great place to start.

  • Check out Freshmeat for an open source directory of sorts. Other than that, I'd recommend just browsing around the web on topics you are interested in to see what's out there.

  • Check out CodePlex as well.

  • Well, I would just head over to Sourceforge, find a project that interests you and start going through their bug list to help fix stuff. Sourceforge can filter out the languages or topics you're not interested in.

  • I like scanning through interesting projects on GitHub, forking them if I think they're interesting and if I feel I can contribute, go right ahead! I haven't contributed to anything yet, but it all seems very easy and inviting.

  • The best: http://code.google.com/ and Sourceforge

  • The three major ones:

    SourceForge

    CodePlex

    Google Code

    Gary Willoughby : SourceForge is ok but i find it a major pain to navigate and not very user friendly while browsing projects.
  • While you're probably not interested in participating in it yourself, the Google Summer of Code has a list of projects that are participating. A project participating generally means that it wants more contributors, it has mentors who are willing to help new contributors, and it has an ideas list with tasks that are good for someone just getting started on the code base (though they are generally designed to be a full time, summer long project, they do range in scope).

    Looking through this list can definitely help you find things to do more easily than trawling through every open source project available on SourceForge, Google Code, or GitHub (though GitHub is nice because you can so easily fork, hack away with as many patches and throwaway branches as you need, and then request that your code be merged in once its done).

  • Ohloh is a great repository of repositories, indexing many projects.

  • I would recommend choosing a piece of software that you like and use, and finding a way to contribute to that. Specifically, fix an annoyance or bug that you have noticed. If you don't see any annoyances or bugs, look for the project's bug tracker. This way it's a project you're invested in, and you are already at least partially up to speed on how the code works from an end-user perspective.

  • Craigslist.com is a good place to contribute your skills too... I know that you wont find your open source projects at craigslist, but hey, someone could use your technical skills for free.... if you have time to spare why not let that someone benefit from it...

Idea for a project

Hi,

me and my schoolmate were tasked to come up with an idea for a project that would have something to do with simulating things that concern the operation system (e.g. animation of disk algorithms such as FCFS; implementing your own virtual file system- with FUSE for example etc.). The problem is that all of the mentioned ideas are already taken and we can't come up with one.

So we would be grateful if anyone could lend us a hand at coming up with an idea for a project. The requirements are that it's not too complicated (max. 2 weeks of work) and it's possible to implement it with Java.

Thanks.

From stackoverflow
  • How about process scheduling? Preemptive or cooperative, either one.

  • A project that I had a lot of fun with was simulating the system memory for Operating Systems. This involves creating a cache, main memory, and optionally depending on your scope, a swap file. Then, use these virtual memory objects to do cache/main memory lookup, check for hits/misses that defer to the next layer, etc.

    Arnold Spence : +1, I was typing that when your post appeared :)
    JoshJordan : :) Its a very interesting project. I actually remember getting confused between objects in my program's memory and the memory I was trying to simulate.
    Daniel : Good suggestion, but unfortunately already taken :P
  • Perhaps you could simulate a really basic desktop system that allows multiple logins and switching between users?.. too involved?

  • You could try to implement a buddy allocator. It's a memory allocation method that is used in operating systems such as the Linux kernel. You could also try a standard malloc-like allocator. Also, as somebody already said, process or thread scheduling is another great thing.

  • From Operating Systems (Deitel), some project ideas:

    1. Create a simulation program to compare various deadlock prevention schemes, e.g. denying the “wait-for” condition, or denying the “no-preemption”. You can generate a sample user population, user arrival times, user resource needs (assume the system has n identical resources) in terms both of maximum needs and of when the resources are actually required, and so on. Each simulation should accumulate statistics on job turnaround times, resource utilization, number of jobs progressing at once, and the like. Observe the results of your simulations and draw conclusions about the relative effectiveness of these deadlock prevention schemes.

    2. Develop several aging algorithms and write simulation programs to examine their relative performance. For example, a process’s priority may be made to increase linearly with time. For each of the aging algorithms you choose, determine how well waiting processes are treated relative to high-priority arriving processes.

    3. Develop a simulation program to investigate the relative effectiveness of the first-fit, best-fit, and worst-fit memory placement strategies. Your program should measure memory utilization and average turnaround time for the various memory placement strategies. Assume a real memory system with 1GB capacity, of which 300MB is reserved for the operating system. New processes arrive at random intervals between 1 and 10 minutes (in multiples of 1 minute), the sizes of the processes are random between 50MB and 300MB in multiples of 10MB, and the durations range from 5 to 60 minutes in multiples of 5 minutes in units of one minute.Your program should simulate each strategy over a long enough interval to achieve steady-state operation.

    4. Develop a simulation program to investigate how changing the number of pages allocated to a process affects the number of page faults it experiences.Use reference strings that simulate spatial locality over both large and small regions of memory and temporal locality over both large and small periods. Also test the simulation using reference strings that are essentially random. Describe the optimal page-replacement algorithm for each reference string.You might also wish to simulate the effect of multiprogramming by interleaving different reference patterns.

    5. Create an application to encode and decode secret messages within bitmap pictures. When encoding, modify the least significant bit in each byte to store information about the message.To decode, just reassemble the message using the least significant bit of each byte.

    Techboy : > Operating Systems (Deitel) Good book, I used that at University

Finding best position for element in list

Hello,

I have List collection that is populated in specific order (the requirement is that, this order can not be changed). This list contains entity type objects.

After initial population of the list, I need to insert few more object, that are coming from another data source. These objects need to be inserted at specific position, so that sorting is correct.

For example if initial list has following elements

  1. AAA
  2. AAB
  3. AAC
  4. ACC
  5. ADA

After initial population I want to insert "ABB" element, it need to be inserted between 3 and 4.

At moment I have following method of finding correct position for new elements.

    private static int FindPositionForArticle(string word)        
    {
        string key = word.ToLower();
        for (int i = word.Length; i >= 0; i--)
        {
            if(i < word.Length)
                key = key.Remove(i, 1);

            int pos = 0;
            int insertPos = 0;
            foreach(ArticleEntity article in list)
            {
                if(article.Text.ToLower().StartsWith(key))
                    insertPos = pos;
                else if (!article.Text.ToLower().StartsWith(key) && insertPos > 0)
                    return insertPos++;
                pos++;
            }
        }
        return 0;
    }

The purpose idea behind this method:

  1. Take "word" that need to be inserted and try to find position of element with same name as "word"

  2. If nothing has been found, remove last character from "word" and search again.

  3. Repeat removal of last characters until best position has been found.

Unfortunately my methods has bugs(implemented incorrectly). Currently my methods suggests that best position would be 0, which is totally incorrect.

If You want to play with my example code You may download it at:

http://dl.getdropbox.com/u/204110/FindPosition.cs.txt

Thank You in advance.

From stackoverflow
  • int index = list.BinarySearch(word);
    

    If index is positive or zero, the item has been found in the list. If negative, it contains the bitwise complement of the index of the next highest item in the list.

    So, for this:

    List<string> list = new List<string>{"AAA","AAB","AAC","ACC","ADA"};
    int index = list.BinarySearch("ABB"); // => -4
    int insertIndex = ~index; // => 3
    list.Insert(insertIndex, "ABB");
    
    Daniil Harik : The problem is my list is actually public class ArticleEntityCollection : ObservableCollection May be I should refactor my code to simple List
    Chris Doggett : Yeah, unfortunately, ObservableCollection doesn't implement BinarySearch. If you really need the observable functionality, you could always derive from List and override the add/remove functions to fire events notifying that the list had changed.
    Daniil Harik : I've refactored to List. As I was not using ObservableCollection functionality. Your solution worked fine.
  • Have you considered using a SortedList data structure? If it will hold complex data types that need to be sorted in a certain specific way, you can create it specifying an IComparer object.

    The only thing the IComparer has to do is be able to determine if one item belongs before, or after another. Given that, the SortedList will keep the order correctly.

    Using this structure would guarantee that the ordering remains as you specify internally and that way you won't have to maintain code that essentially implements sorting.

    Daniil Harik : Could you please give an example of how such IComparer may look. Thank You very much.
    Ben S : It you're using strings and want them alphabetically sorted then you don't even need to bother with an IComparer. Otherwise, have a look at the MSDN page about it, it has a VB and a C# example: http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx
  • Wouldn't a SortedList of type string work better?

  • This code:

        private static System.Collections.SortedList list = new System.Collections.SortedList();
    
        static void Main(string[] args)
        {
            list.Add("AAA" , "AAA");
            list.Add("AAB", "AAB");
            list.Add("AAC", "AAC");
            list.Add("ACC", "ACC");
            list.Add("ADA", "ADA");
            Console.WriteLine("List before");
            for (int j = 0; j < list.Count ; j++)
            {
                Console.WriteLine(list.GetByIndex(j));
            }
            list.Add("ABB","ABB");
    
    
            Console.WriteLine(list.IndexOfKey("ABB"));
    
            for (int j = 0; j < list.Count; j++)
            {
                Console.WriteLine(list.GetByIndex(j));
            }
    
    
            Console.ReadLine();
    
        }
    

    is Inserting the item where you need it..

    Or do you need something else?? there is no need for Icompare, you are sorting common strings.

    Daniil Harik : Thank You. Will try it out :)
  • Since that list you are using accessible via its index, you may want to implement a binary search similar to Chris Doggett's anwser. This will give you a better runtime than going through the list as you currently implemented it sequentially:

    Your runtime is currently linear to the number of items in the list, and if you insert n items like this you will get a runtime of about n2 operations.

    Using a binary search (as SortedList does internally by the way) you will end up with the much better runtime of log2(n) per insert, e.g. *n**log2(n) total runtime when inserting n items.

    The basic idea of a binary search is simple:

    1. List item

    2. First, you take the complete range as possible position (left = 0, right = current count in the list)

    3. If left equals right, you have found a suitable position

    4. Otherwise, pick the middle element (left+right)/2 and compare it to the key to be inserted.

      • If the result of the comparison is < 0, you set right to the middle index-1, therefore resetting the search range for the next iteration to the left half of the list
      • If the result is greater than 0, you set left to the middle index+1, so that the next search will be in the right part
      • Otherwise the comparison is 0 and you've got a duplicate, handle as you wish (ignore or insert at the same index), and break the loop (see 5.)
    5. Loop at 3.; the search range is now smaller...
  • I've done what you're trying to do like this. You have a list of your ArticleEntity objects. You need to sort this list. So first of all you need to add the ability to sort to your class. My examples are in VB, shouldn't be too hard to convert to C#.

    Add sorting to your class like so:

     Public Class ArticleEntity
        Implements IComparable(Of ArticleEntity)
    
        Public Overloads Function CompareTo(ByVal Other As ArticleEntity) As Integer _
            Implements IComparable(Of ArticleEntity).CompareTo
            Return Me._PropertyToSort.CompareTo(Other._PropertyToSort)
        End Function
    

    Then after you add everything you need to add to your List Of(ArticleEntity) you can:

    MyListOfArticleEntities.Sort()
    

    I think this is what you're looking for. Let me know if it's not.

  • Does your collection need to be a List?

    If you don't need to access elements from the list before inserting the new elements, a heap sounds like it would do the job better. Basically you would:

    1. Insert all your initial elements into the heap
    2. Later, insert the extra items in the exact same way
    3. Read out each item, in sorted order, from the heap into a List.

    Each of those steps is only O(log n) time per object. I'm certain that C# has an implementation of heaps.

    Note: I mean "heap" in the sense of the data structure, not in the sense of the global memory pool.

Java Netscape LDAP Delete

I have been using the Java Netscape LDAP library to modify LDAP entries (http://www.mozilla.org/directory/javasdk.html). I now need a way to delete an entry. I looked through the library but could not find anything that I think would work.

Found “LDAPDelete” but that looks like it’s used from the command line.

If someone could post some sample code of how do this with an object ID it would very helpful.

ADDED: After searching and finding the object I used the return value from getDN() method as the DN string.

From stackoverflow
  • Take a look at LDAPConnection.delete(java.lang.string dn) Thats what you should be using to delete an entry.

    In pseudo code:

    LDAPConnection myCon = new LDAPConnection("192.168.1.1",389);
    myCon.delete("cn=Alan,ou=engineers,dc=fool,dc=com");
    

    You'll have to javify that example, but that should work.

    Netscape Directory API Documentation

    Ben : I hadn't noticed that and was haivng trouble with the DN but got it working. Thanks!

Get top href and innerHTML from within an iframe

Is there any way to grab any information from the top from within an iframe on a separate domain? Somebody has tasked me with validating that their advertising is not next to things like pornography, etc... but their ads are always inside an iframe on publisher sites.

Interestingly, when I put twitter.com in an iframe, they have iframe busting technology turned on - like so:

<script type="text/javascript">
//<![CDATA[
    if (window.top !== window.self) { setTimeout(function(){document.body.innerHTML='';},1);window.self.onload=function(evt){document.body.innerHTML='';};}
//]]>
</script>

What strikes me is that, as a different domain, they still have the ability to get window.top. However, when I try to extend this functionality to window.top.location or window.top.href to get the URL of the top window, I get

uncaught exception: [Exception... "Component returned failure code: 0x8007000e (NS_ERROR_OUT_OF_MEMORY) [nsIDOMNSHTMLDocument.write]"  nsresult: "0x8007000e (NS_ERROR_OUT_OF_MEMORY)"  location: "JS frame :: http://tester.tester.com/iframe3.html :: <TOP_LEVEL> :: line 9"  data: no]
http://tester.tester.com/iframe3.html
Line 9

which is really just a permission error that is being misreported by Gecko (I think).

Any thoughts on this? Is an equality statement available because the iframe doesn't actually get the data while getting the data itself is not available?

Any information I can get would be better than nothing, so please feel free to put in partial answers. Thanks.

From stackoverflow
  • No there's not. It's due to Cross-site scripting attacks.

  • Is an equality statement available because the iframe doesn't actually get the data while getting the data itself is not available?

    It's an ancient quirk of JavaScript that you can always get the ‘window’ object of a cross-domain frame/iframe/parent/opener. But — for obvious security reasons — you can't access most members of the object. There have occasionally been ways to circumvent these restrictions in the past due to browser bugs, but nothing you can rely on.

    Pretty much the only thing you can usefully do with an unknown window object is check to see if it's the same object as some other known window object, such as the current one.

    If you want to test whether an unknown window is at least inside your own domain, you can try to access otherwindow.location inside a try...catch block.

    Is there any way to grab any information from the top from within an iframe on a separate domain?

    No, but you can record the ‘Referer’ header at the HTTP server end to see what page included the <iframe>. But surely your advertising network should be doing this for you already anyway?

    if (window.top !== window.self)

    Curious; window.self is the same thing as window; I don't know why you'd ever use the longer version. The shortest idiom for this test is:

    if (top!==self)
    

    which works as long as you aren't defining any other variables called ‘top’ or ‘self’.

    Adam Nelson : Unfortunately, the ads we would serve would already be in an iframe, so we're 2 layers down on the iframe. Everything else is very helpful. Thanks!
    bobince : Shame... is there really no reporting from the ad network that runs the in-between frame? I'd certainly want to know where my impressions were going...
    Adam Nelson : There's no real time reporting that I've found yet. Keep in mind that we need the data at the moment of interaction, otherwise a nefarious site will simply show us pages that don't raise flags - although it is a start to do this in a batch method.

How do I get all the entities of a type with a required property in Google App Engine?

I have a model which has a required string property like the following:

class Jean(db.Model):
    sex = db.StringProperty(required=True, choices=set(["male", "female"]))

When I try calling Jean.all(), python complains about not having a required property.

Surely there must be a way to get all of them.

If Steve is correct (his answer does make sense). How can I determine if that's actually causing the problem. How do I find out what exactly is in my datastore?

From stackoverflow
  • Maybe you have old data in the datastore with no sex property (added before you specified the required property), then the system complain that there is an entry without sex property.

    Try adding a default value:

    class Jean(db.Model):
        sex = db.StringProperty(required=True, choices=set(["male", "female"]), default="male")
    

    I hope it helps.

    /edit: Go to the local datastore viewer (default is at http://localhost:8080/_ah/admin/) and list your entities. You can try fixing the issue manually (if possible) by filling the missing property.

How can I deploy an ASP.NET web application using Team Build?

I have managed to install Team Foundation Server 2008 and I created a separate build server (which works because my builds are currently failing).

I have created a simple "Hello World" Web application (all is the standard Default.aspx page) and have it in TFS's source control system.

Previously, prior to TFS, I'd simply precompile my web application and xcopy the results on to a pre-created IIS Virtual directory.

Scouring Google for a while, I have yet to find a step by step guide on correctly deploying an application from TFS Source via TeamBuild to a designated test web server. I know MS Build falls into this equation, so any guidance would be helpful.

I have seen bits and pieces about deployments, with folders such as _PublishedWebSites mentioned, but have yet to find anything step by step.

From stackoverflow
  • This can be done via the build scripts directly, the Vertigo Software guys usually are the best source of info for a lot of TFS questions like this...unfortunately their blog posts don't usually rank that high on google. This one's by Jeff Atwood, one of the creators of this site:

    Copying Web Files After a Team Build

  • I've had success using a exec task in the AfterDropBuild target in the TFSBuild.proj file.

    <Target Name="AfterDropBuild>
        <Exec Command="xcopy /Y /E &quot;$(DropLocation)\\$(BuildNumber)\%(ConfigurationToBuild.FlavorToBuild)\_PublishedWebsites\MyWebsite1\*.*&quot; &quot;\\server\MyWebsite1\&quot;" />
        <Exec Command="xcopy /Y /E &quot;$(DropLocation)\\$(BuildNumber)\%(ConfigurationToBuild.FlavorToBuild)\_PublishedWebsites\MyWebsite2\*.*&quot; &quot;\\server\MyWebsite2\&quot;" />
    </Target>
    

    Note that the permissions need to be setup correctly for the TFS service user to access the folder on the server your are copying to.

    RandomNoob : I found some other resources that outlined what you described here, I was able to successfully migrate a web application from my old source control system, create a build and deploy it as shown with the copy command
  • Firstly you should be using WebDeployment projects as this will do a lot more compilation and checking of your code and markup. See here for more info.

    I have 4 environments setup DV [Development], PY [Prototype], PP [Pre-Production], PD [Production] all matching branches in TFS. Each of these has also has an entry in the sln configuration manager where you can setup what projects are required to be build and the build flags.

    Once that is setup correctly you can then start setting up deployment scripts. I prefer use MSbuild to deploy as it will give you a lot more fine-grained approach to deployment. MSbuild is a bit strange to start with however once you get the hang of it it's quite powerful.

    My deployment script which is added to the TeamBuild config is below. Basically as you can see I do a bit of post-build cleanup before I copy to the live servers. I also use 2 MSbuild frameworks (imported at the top).

    <Import Project="$(MSBuildExtensionsPath)\Microsoft\SDC Tasks - Release 2.1.3155.0\Microsoft.Sdc.Common.tasks"/>
    <Import Project="$(MSBuildExtensionsPath)\FreeToDev\MSBuild Tasks Suite 3.5\FreeToDev.MSBuild.tasks"/>
    
    <PropertyGroup>
     <InetpubFolder>\\PathToInetPub</InetpubFolder>
     <AppFolder>AppFolder</AppFolder>
     <AppFolderPath>$(InetpubFolder)$(AppFolder)</AppFolderPath>
     <WebDeployName>WebDeployProjectName</WebDeployName>
     <Debug>0</Debug>
     <AppConfiguration>DV</AppConfiguration>
    </PropertyGroup>
    
    <Target Name="AfterDropBuild">
     <Message Text="Begin Release to $(AppConfiguration) Webserver" />
     <Message Text="DropLocation = $(DropLocation)" />
     <CallTarget Targets="PostBuildCleanUp"  />
     <CallTarget Targets="DeployApp"  />
    </Target>
    
    <Target Name="DeployApp">
    
     <GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)">
      <Output TaskParameter="DropLocation" PropertyName="DropLocation"></Output>
     </GetBuildProperties>
    
     <PropertyGroup>
      <CodeDropLocation>$(DropLocation)\$(AppConfiguration) Release</CodeDropLocation>
     </PropertyGroup>
    
     <ItemGroup>
      <AppFilesToDelete Include="$(AppFolderPath)\**\*.*" Exclude="$(AppFolderPath)\Library\*.*;$(AppFolderPath)\App_Offline.htm;$(AppFolderPath)\jobs\**\*.*" />
     </ItemGroup>
    
     <ItemGroup>
      <FilesToDeploy Include="$(CodeDropLocation)\$(AppFolder)\**\*.*" Exclude="" />
     </ItemGroup>
    
     <Copy SourceFiles="$(CodeDropLocation)\$(AppFolder)\App_Offline[RemoveToActivate].htm" DestinationFiles="$(AppFolderPath)\App_Offline.htm" OverwriteReadOnlyFiles="true"/>
    
     <Message Text="Deleting files in $(AppFolderPath)" />
     <Microsoft.Sdc.Tasks.File.DeleteFiles Files="@(AppFilesToDelete)" Force="true" Condition="$(Debug)==0" />
    
     <Message Text="Copy $(CodeDropLocation)\$(AppFolder) to $(AppFolderPath)" />
     <Copy Condition="$(Debug)==0" SourceFiles="@(FilesToDeploy)" DestinationFiles="@(FilesToDeploy->'$(AppFolderPath)\%(RecursiveDir)%(Filename)%(Extension)')" SkipUnchangedFiles="true"/>
    
     <Message Text="Deploy to $(AppConfiguration) Completed" />
     <Microsoft.Sdc.Tasks.File.DeleteFiles Files="$(AppFolderPath)\App_Offline.htm" Force="true" />
    
     <OnError ExecuteTargets="ErrorHandler" />
    </Target>
    
    <Target Name="ErrorHandler">
     <Message Text="Error encountered!!" />
    </Target>
    
    <Target Name="PostBuildCleanUp">
    
     <GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)">
      <Output TaskParameter="DropLocation" PropertyName="DropLocation"></Output>
     </GetBuildProperties>
    
     <PropertyGroup>
      <CodeDropLocation>$(DropLocation)\$(AppConfiguration) Release</CodeDropLocation>
     </PropertyGroup>
    
     <ItemGroup>
      <PostBuildCleanUpFilesToDelete Include="$(CodeDropLocation)\*.*;$(CodeDropLocation)\bin\*.xml;$(CodeDropLocation)\bin\*.pdb"/>
     </ItemGroup>
    
     <RemoveDir Directories="$(CodeDropLocation)\_PublishedWebsites\Web" />
     <Microsoft.Sdc.Tasks.File.DeleteFiles Files="@(PostBuildCleanUpFilesToDelete)" Force="true">
      <Output TaskParameter="DeletedFiles" ItemName="FilesThatWereDeleted" />
     </Microsoft.Sdc.Tasks.File.DeleteFiles>
     <Message Text="The files that were removed were @(FilesThatWereDeleted)" />
    
     <FTDFolder TaskAction="Move" Path="$(CodeDropLocation)\_PublishedWebsites\$(WebDeployName)" TargetPath="$(CodeDropLocation)\$(AppFolder)"/>
    
     <RemoveDir Directories="$(CodeDropLocation)\_PublishedWebsites" />
    
     <RemoveDir Directories="$(CodeDropLocation)\$(AppFolder)\WebDeploy" />
    
     <OnError ExecuteTargets="ErrorHandler" />
    </Target>
    

    Obviously you will need to modify to your system setup. Also it clears down the target folder before it starts to copy the new build accross. This is to make sure they system is clean but obviously you will need to add anything that you need to keep to the ExcludedFiles list.

    I also have a folder for each environment in the main application project. This holds the web.config replacements (another feature of WebDeployment projects) and any other environement specifc files.

    It will be a long process to get it working correctly but hopefully this will get you started!! (Obviously if you choose this apporach!)

Ajax.net but no script

I want use ajax.net to do some js. like below:

ScriptManager.RegisterStartupScript(Submit, typeof(Button), "alert", "location.href='test.aspx';", true);

If user turn off the javascript, it will not redirect to another page.

I want to know how to set <noscript></noscript>.

Thanks a lot!!

From stackoverflow
  • Here:

    <noscript>
      <meta http-equiv="refresh" content="0; URL='no-script.aspx'">
    </noscript>
    
  • I would use Response.Redirect("test.aspx") which does not require JavaScript and should be supported by most of the modern browsers.

IE6 ignoring active link CSS style

The CSS active link style is being correctly applied in IE7, FF, and Safari but is not applied IE6.

.side_nav a.active 
{
    color:#FFFFFF;
    background-color:#9F1F63;
}

Interestingly the background color (background-color:#9F1F63;) is being applied in IE6 but not the font color (color:#FFFFFF;)

Any ideas on why this is happening and how I can fix it appreciated.

The complete styling for the nav below:

.side_nav 
{
    text-align : left;
    margin-left: -10px;
}

.side_nav ul 
{
    list-style-type: none;
    list-style-position:inside;
    margin-left:0px;
}
.side_nav li 
{
    margin-top: 10px;
    display: list-item;
    list-style-type:none; 
}
.side_nav a, .side_nav a:visited
{
    text-decoration: none;
    color : #9F1F63;
    font-weight : bold;
    padding: 5px 10px 5px 10px;  
}
.side_nav a:hover 
{
    color:#B26D7F;
}
.side_nav a.active 
{
    color:#FFFFFF;
    background-color:#9F1F63;
}

EDIT: Thanks but the suggestions haven't helped. When I change to a:active the active effect does not work in any browser. I think this might be due to how I have applied the style in the HTML.

    <div class="side_nav">
        <a class="active" href="Page1.aspx">Page1</a><br />
        <a href="Page2.aspx">Page2</a><br />
        <a href="Page3.aspx">Page3</a><br />
    </div>
From stackoverflow
  • Try adding a more specific selector to .side_nav a.active such as div .side_nav a.active where div is the parent element.

    The color is probably being overwritten from the .side_nav a rule.

    Also, you may have a typo - are trying to use the :active selector?

    strager : See his HTML example. It's a class name.
  • In IE6, it matters which order you specify the anchor links. You should specify them in this order to achieve the intended result: first a:link, then a:visited, a:hover and a:active.

    Leah : Thanks for the tip about the order. This did not help though. See edit above.
  • Your CSS has a period where there should be a colon, in .side_nav a.active (should be .side_nav a:active

    With this fixed, it works for me in IE6.

    Leah : When I use a:active none of the active effects apply in any browser. With a.active both the effects apply in all browsers I have tested except IE6.
    Leah : Thanks for testing it in IE6. I wonder whether we have an older version here in our locked down environment.
  • I tried copying your code, and the format did work.
    Your problem is you see the link as visited - you have both formatting of the visited and active (so you have the purple background and the purple text).
    You should override the color for visited links with the active class:

    .side_nav a.active, .side_nav a.active:visited
    {
        color: #FFFFFF;
        background-color: #9F1F63;
    }
    
    Leah : Thanx Kobi! It was the visited link. Working consistently in IE6 now.
  • Try to use "!important". Like this: .side_nav a.active { color: #FFFFFF !important; background-color: #9F1F63; }

    David Dorward : If `!important` solves the problem then, 19 times in 20 (if not more) you should be writing more specific selectors instead. `!important` is a clumsy weapon.
  • Thanks Andrei Bacean It is working fine now.

    Ajeet

    David Dorward : Please provide your thanks by commenting on answers and accepting them (click the tick by the side). Don't "answer" the question with something that isn't an answer.

IIS Application pool PID

is anyone familiar with a way to get the Application pool that is associated with a process ID ? I am using Win32_Process to query the W3WP services and return the PID now I am trying to get the app pool associated with it.

From stackoverflow
  • ServerManager serverManager = new ServerManager();
    ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;
    

    Try working with this and it should get you what you need.

  • If you are just using command line to figure it out ad-hoc you can do this too:

    The script is already placed in systemroot\system32 on Windows Server 2003 so simply go to your Command Prompt and type in iisapp.vbs (the .vbs is optional) and you'll have an instant list of all the App Pool information you've always wanted to know. You may need to type cscript iisapp.vbs if CScript isn't your default WSH script host.

    Let's see an example of the output:

    W3WP.exe PID: 1468 AppPoolId: AppPoolForSite1.com
    W3WP.exe PID: 3056 AppPoolId: AppPoolForSite2.com
    W3WP.exe PID: 1316 AppPoolId: AppPoolForSite3.com

    Direct from the horse's mouth, Microsoft documents this:

    http://www.microsoft.com/resources/documentation/WindowsServ/2003

    Adonis L : Thanks I can review this script for code example
  • On Windows Server 2008 this has changed.

    in systemroot\system32\inetsrv you find the appcmd.exe

    using

    appcmd list wp

    you get a list of all the worker processes and which apppool they are serving.

    Doug : This doesn't seem to list app pools that run as a machine user (SYSTEM/NETWORK SERVICE)... any thoughts?
  • If you're running on Windows Server 2008 and you ONLY want the PID, to feed to another script or command, you can use this:

    c:\windows\system32\inetsrv\appcmd list wps /apppool.name:"My Application Pool" /text:WP.NAME
    

    For example, to create a batch script that creates a memory dump of a particular app pool, use this:

    c:\windows\system32\inetsrv\appcmd list wps /apppool.name:"My Application Pool" /text:WP.NAME > "%temp%\pid.txt"
    for /F %%a in (%temp%\pid.txt) do c:\debugger\adplus.exe -hang -o d:\dumps -p %%a
    pause
    

Excel VBA copy XL-2007 Macro-Enabled Workbook as excel-2003 file with no macros

I''m looking for a vba macro that will make a copy of the current Excel 2007 macro-enabled workbook with the name I specify as an Excel 2003 macro-free document. It should also keep the current workbook open and in the Excel 2007 format (so save-as wouldn't work).

I can't figure out how to do the copy operation...

From stackoverflow

Html / php page being cached (client side) when it should not be

URL is here: http://www.thexsoft.com/DownloadFolder/download.php?file=P2PTransfer

This page is basically a way for me to have set url to download a certain problem i published. This page should never ever be cached, but it seems to be caching still.

I have set the following items:

<meta http-equiv="expires" content="0" >
<meta http-equiv="cache-control" content="no-cache" >
<meta http-equiv="pragma" content="no-cache" >
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" >

The html code on the page validates 100% when i don't have the fastclick.net ad code in, but i keept it in now because it normally is in.

From stackoverflow
  • Pragma: no-cache prevents caching only when used over a secure connection (https). A Pragma: no-cache META tag is treated identically to Expires: -1 if used in a non-secure page. The page will be cached but marked as immediately expired.

    http://support.microsoft.com/kb/234067

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">
    
    DaNieL : Does this trick works even for the CSS on the page?
    Eddie : I believe that you're incorrect about "pragma: no-cache" only preventing caching for HTTPS connections, unless you are talking about how some very specific version of some browser acts.
    apphacker : @DaNiel CSS doesn't belong in the same place as the markup, especially when you're worried about caching issues.
    Emre : @Eddie this is how IE works. You can check it out here http://support.microsoft.com/kb/234067
  • Yes, in some circumstances browsers cache aggressively, especially IE6. You need to check the http headers your server is sending, and if that isn't the issue try a cachebusting URL (insert a random/timebased get variable) to make the browser think it's a new URL.

  • I checked your headers using Firebug:

    Cache-Control: max-age=1209600
    Expires: Tue, 28 Apr 2009 18:49:15 GMT
    

    In PHP you can send HTTP headers with header().

    header('Pragma: no-cache');
    header('Expires: -1');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    
    Emre : I think you should use header('Cache-Control: no-cache'); see this page http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html