Saturday, April 30, 2011

WCF Web Service, cross-domain example.

Can anyone point me to a good/simple example of creating a WCF web-service sitting on one website, followed with a simple example consuming that WCF web-service on another website?

From stackoverflow
  • http://msdn.microsoft.com/en-us/library/ms751514.aspx has some good examples for using WCF.

    Consuming WCF from another site should be failrly straight forward, just don't forget to use a clientaccesspolicy.xml file.

    madcolor : I've created a WCF service and now it wants me to use Svcutil.exe to generate (I guess) the class for my client.. does one always have to use Svcutil.exe?
    John Saunders : No. You can use "Add Service Reference", which is pretty much the same thing.
    sweeney : how does one *use* a clientaccesspolicy.xml file? I see them mentioned here and there but have no idea where to get one or how to create my own.
  • If you are looking for WCF techniques and examples in general, I would highly recommend you visit IDesign's web site. The company was founded by Juval Lowy, one of the preeminent experts on WCF. The downloads are free to access and use; you just have to provide your email address.

What does python3 do with the methods passed to the "key" argument of sorted()?

I have a question about how python treats the methods passed to sorted(). Consider the following small script:

#!/usr/bin/env python3

import random

class SortClass:
    def __init__(self):
        self.x = random.choice(range(10))
        self.y = random.choice(range(10))
    def getX(self):
        return self.x
    def getY(self):
        return self.y

if __name__ == "__main__":
    sortList = [SortClass() for i in range(10)]
    sortedList = sorted(sortList, key = SortClass.getX)
    for object in sortedList:
        print("X:", object.getX(),"Y:",object.getY())

Which gives output similar to the following:

X: 1 Y: 5
X: 1 Y: 6
X: 1 Y: 5
X: 2 Y: 8
X: 2 Y: 1
X: 3 Y: 6
X: 4 Y: 2
X: 5 Y: 4
X: 6 Y: 2
X: 8 Y: 0

This script sorts the SortClass objects according to the value of each instance's x field. Notice, however, that the "key" argument of sorted points to SortClass.getX, not to any particular instance of SortClass. I'm a bit confused as to how python actually uses the method passed as "key". Does calling getX() like this work because the objects passed to it are of the same type as the "self" argument? Is this a safe use of the "key" argument?

From stackoverflow
  • Methods on classes are just functions.

    class MyClass(object):
    ...     def my_method(self): pass
    ...
    >>> MyClass.my_method
    <function my_method at 0x661c38>
    

    When you fetch a method from an instance of a class, Python uses some magic (called descriptors) to return a bound method. Bound methods automatically insert the instance as the first argument when they are called.

    >>> MyClass().my_method
    <bound method MyClass.my_method of <__main__.myClass object at 0x6e2498>>
    

    However, as you have noticed, you can also directory call the function with an instance as the first argument: MyClass.my_method(MyClass())

    That's what happening with sorted(). Python calls the function SortedClass.getx with the item in the list which happens to be an instance of SortedClass.

    (By the way, there are better ways to do what you are doing. First of all, don't use methods to expose attributes like getX. Use properties or plain attributes. Also, look at operator.itemgetter and operator.methodcaller.)

iPhone development books

I've looked on SO and it seems that most people have been recomending books as the best iphone development resource due to the lack of resources on the web. I've seen the book the The Pragmatic Programmer: iPhone SDK development been recomended a few times.

I'm planning to go buy a couple of books. Which should I go for? Please give reason :)

A bit of background : I have a strong background in C and I've played around with Cocoa so something iphone specific would be best ( but I'm open for suggestions ;))

Update I'm not looking for simple listings of iphone SDK related books, I can google that ;) I want books that people are reading/have read and would recomend :)

Final Update I just ordered my copy of Beginning iPhone Development: Exploring the iPhone SDK. My main reasons on chosing it are that it's already in print (unlike the pragmatic one) and I looked at the preview on their website and I liked it.

From stackoverflow
  • I've been reading Beginning iPhone Development and really enjoying it (currently at Ch. 6). Some things I like about it:

    • Very clear step by step walk-through of what to do and why.
    • The authors take time to explain related topics as you go.
    • Support forums to ask additional questions and report errors.
    hhafez : Could you explain what you found good about this book?
    schooner : I like htis book as wel, very good for iPhone biggers, steps you through all the issues and processes invovled from start to end.
    Kb : @Nogwater: +1 I agree. This is one of the better new-platform-introductions I have read. Half way through.
  • I've been working with Erica Sadun's "The iPhone Developer's Cookbook" of late, and have found it quite useful in getting up to speed, but also moderately frustrating. My frustration stems from the author's resistance to structuring projects using the file layout and program structure favored by Apple.

    Basically, all of the examples pile the whole of the program structure into a single file, rather than the generally accepted practice of separating out header and class files. Additionally, the author has a propensity for recommending the use of unpublished or private frameworks, which while it works, can be dangerous. John Gruber gives a much more elaborate explanation of this issue.

    All in all, the style of the book can make apples-to-apples comparisons between example projects in the book and code one encounters in the wild a little tricky. I'm not necessarily advising you to steer clear of it -- a lot of it is quite useful, particularly if you're coming to this with some established understanding of program and project structure in Xcode) -- I just wouldn't use it as your only resource.

  • I love the Pragmatic book. The book is still in beta, and they add content/make corrections to it as readers comment about what they would like to see in the forum.

    They also have a couple of great screencasts at $5 per episode (one on iPhone, one on Obj-C). They also are very generous in answering questions on their forum.

    I also have handy Programming in Objective-C, by Stephan Kochan. I came to iPhone development from Flash and ActionScript, so the Obj-C book is required!

  • You should buy them ALL. Seriously, there are only three or four of them. You should also read all of the Apple docs on iPhone development (which are like books, but free) and delve deep into the sample projects. Additionally, you should consider springing for the WWDC 2008 video set if you can afford it. It's 500 bucks but there are a LOT of videos and it's info straight from the horses mouth so to speak.

    After that you should set your target on a simple project of your own devising, and learn what you need to know to get it built.

    There are a lot of moving parts to iPhone development, but once you get rolling, you will find them all fall into place. Good luck!

    Steve : +1 on the Apple content. It's such a reflex to initially look to books, that we forget about the original documentation.
  • For general cocoa programing check out Cocoa Programming for Mac. This is a bit more general purpose but helps with iPhone Development.

    foljs : Does not answer the question.
  • Seconding Dave Mark and Jeff LaMarche's Beginning iPhone Development: Exploring iPhone SDK from Apress. I've been enjoying it. I'd recommend pairing it with Learn Objective–C on the Mac, unlike older Objective C books covers Objective C 2.0 and the syntactic sugar you'll likely see in iPhone examples.

    Although Apress sells a PDF eBook only version for $28, sadly that's more than what Amazon charges .

    A little trick though, if you want to be cheap (and perhaps a bit dishonest), bring an iPhone with you to Barnes and Noble and follow the discount ebook URL from the back page. They just ask a question like 'What's the first word on Page 35', use the book in front of you to provide the answer and voila: you can buy it at the discounted $10 PDF ebook add-on price. You can do the same with ObjectiveC book too. Note, Apress ebooks are locked with your email address as a password so they may not work with all PDF readers.

    Once you get to the later chapters, they just touch the surface on OpenGL ES stuff, so you may want to check out Jeff LaMarche's blog's or this blog for more opengl tutorials.

  • I've read "iPhone Open Application Development", "iPhone SDK Application Development" and "iPhone SDK Development (Pragmatic Bookshelf)"

    Out of all of these I prefer the Pragmatic book the most. The Open Application Development book, is useful if you don't want to use xcode (ie: developing on non mac platform) but otherwise it is too much trouble. Many of the examples do not work (this is even with the "update 2.0 edition"!) I haven't checked there website if they have updated code samples though

    Also by Jonathan Zdziarski (iPhone SDK App Dev), I found this book rushed and doesn't give the reader enough information to go from A to B. And the lack of the use of IB is very limmiting as IB is one of the most useful tool in iPhone Development.

    The last book I got (iPhone SDK Dev from the Pragmatic Bookshelf) has been the best of all three. It is full of information, it is being updated as we speak to include some 3.0 goodies and most of all it fills in all the gaps so the reader is not left wondering how on earth he can do simple tasks.

    The last book will be my main reference out of the three :)

AS3 (or any language) trig library for triangles?

Does anyone know of a library for easily dropping in parameters of angles and lengths of sides, and letting it automagically extrapolate the non-given angles and lengths using trig? Even if it had lame performance, it would be very useful for prototyping, and performance could be optimized (even supplying table lookup and the sort). If nothing like that is out there, I will probably write it.

Thanks,
umop

From stackoverflow
  • It'll be tough to find a library because trig is so simple, you just need to do a quick formula.

       a^2 + b^2 = c^2
    
       s=o/h c=a/h t=o/a
    

    I'm thinking writing your own function to do these chores would be very very quick :)

Styling UITableViewCells with gradient backgrounds

Hi folks,

I've been looking for ways to improve the overall attractiveness of my iPhone applications. A majority of the functionality happens in UITableView. I think I can start by adding subtle gradients to UITableViewCells, as that seems to improve the feel of the app by an order of magnitude. Selecting the appropriate fonts/sizes helps a great deal also. My question for this forum is, what's the best strategy of adding gradients to UITableViewCells? Are you using Core Graphics/Quartz? Are you using a 1x1 pixel image and stretching it? I'm interesting in something along the lines of the following screenshot of the Tumblr iPhone app: http://dl-client.getdropbox.com/u/57676/screenshots/tumblr.jpg

Does anyone have any good examples of how to make your UITableViewCell's stick out?

And for performance reasons is it better to use an image or draw with Quartz? If Quartz, I'd love to see some sample codes of how folks are drawing the gradients into the cells.

Thanks.

From stackoverflow
  • I'd use Quartz 2D for this, but setting up images in Photoshop is perfectly valid too.

    As for performance, if you're re-using cells by type I don't think it would be an issue - but if you do find it a bottleneck you could draw to a bitmap context once, obtain an image from that and use that everywhere - a sort of hybrid solution.

    Daniel Dickison : Marco's answer seems to suggest that UIImageView does in fact stretch its image, perhaps because its frame/bounds get set explicitly by the cell layout?
    Phil Nash : yeah, as I said that's perfectly valid. It's just that if you know Quartz 2D it's so easy to do this that that would be my first course, personally
    Daniel Dickison : I just noticed that my comment above doesn't make any sense -- I think I had meant to comment on HitScan's answer instead of yours. Sorry for the confusion!
    Phil Nash : no problem :-)
  • UITableViewCell supports separate views for their background and selected background, so it makes sense to make use of these properties. To do that, you're going to need to come up with an image that's the full size of your cell anyway (UIImageView doesn't stretch it's image), so you may as well make it on a desktop machine once, and save the cycles on the phone that would have to be spent to stretch an image or make it dynamically. Though if you intend to allow the user to change the gradient colors, you'll have to create it once dynamically anyway.

  • I think the easiest way, by far, of handling UITableView with custom cell is using Interface Builder. It makes UI design work much easier than doing it by pure core. Here is a great tutorial (with a video!) on how to do that. Highly recommended. I am not using any other method of UITableView coding since I followed that.

    Having said so, adding a gradient to your cell will be extremely easy. Just use InterfaceBuilder to add an image containing your gradient to the cell view and you are done. You won't have to worry about Quartz, and performance wise you'll get similar results since CocoaTouch's components are very well optimized to do plain task such as displaying an image.

  • I work for Tumblr, and while I didn't write the iPhone app (he did), I have the source and can tell you how it's done.

    In -tableView:cellForRowAtIndexPath:

    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"postCellBackground.png"]];
    cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"postCellBackgroundSelected.png"]];
    

    Pretty simple, really: PNG images in a UIImageView as the cell's background views.

    The two images are 1x61 vertical gradients that UIKit automatically stretches horizontally to fit the width of the cell.

  • As of iPhone SDK 3.0, there's a much simpler solution that relies on the new CAGradientLayer and doesn't require subclassing or images.

Curl function to select options from a select box and auto submit

Hi all

i am a newbie and try different things everyday and always come here when i am stuck with something.

I want to write a script using curl and php that goes to this link :http://tools.cisco.com/WWChannels/LOCATR/openBasicSearch.do and then goes through each page for each country capturing a list of every partner in every country and saving it to database.

i have no ideas how script will select countries one by one from select box and redirect page to country page...which is the very first thing to do, once we are on the page pattern matching comes in play for storing name and address in database which i can manage.

Problem is before we select any country url is::http://tools.cisco.com/WWChannels/LOCATR/BasicSearch.do and after we select country say 'india' url is:http://tools.cisco.com/WWChannels/LOCATR/performBasicSearch.do , there is no reference to any country selected.

The Idea that i had was to traverse the HTML page, and enter all countries in an array and then make a recursive function to call a page with specific country but for that we need something different in URL for each country in recursive function right?

Please help

From stackoverflow
  • Your url is messed up, so I can't see the exact page you are talking about, however what is most likely happening is that when you change the country the website is making a POST request to the same page with a variable like country (although it may be something else) with the value of the country name/country id that you selected. If you View Source on the page you will be able to see the input field's name that is being passed on. Once you do that, while making your cURL request you can set the cuRL option of CURLOPT_POSTFIELDS, which reads like so:

    The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

    So, keeping that in mind you would do something like this:

    $ch = curl_init('http://tools.cisco.com/WWChannels/LO...BasicSearch.do');
    $ch = curl_setopt($ch, CURLOPT_POSTFIELDS, array('country' => 'India'));
    $ch = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $contents = curl_exec($ch);
    curl_close($ch);
    

    As I said, though, the country => India part of it is an educated guess as to what the field might be passing. You have to inspect the HTML to find out for yourself.

  • For automation/scraping, I would recommend that you use a virtual browser, such as SimpleBrowser. It's part of SimpleTest, but you can use it on its own.

  • thanks for help

How to compare Oracle XML Gateway Message Designer maps? (.xgm)

They are XML, but it seems that they seem to be recreated each time the map is being saved and the ids of the elements inside are changing each time. The tool (Message Designer) is quite old and not very convinient to use.

Have you any hints how to version, track changes in such map? Or is there an alternative for Message Designer?

From stackoverflow
  • When developing and loading Oracle XML Gateway message maps, there are several methods you can employ to track versions. However, they are all manual and require setting a standard within a development team.

    Aside from version tracking tools like SVN etc. each time you change a message map, you can change the Map name in the Properties tab. Then each time you load the map, you will be able to choose which version you want to use/test from the Trading Partner Setup in the XML Gateway. If your question is how to compare two existing map files to find the differences between them... unfortunately, the most effective way is to start two sessions of Message Designer, tile them and move through them side by side. Identifying which elements are mapped to which is relatively straightforward (assuming you are comparing slight variations of the same source and target definitions and mapping). You can focus particularly on elements or levels that have a blue circle icon in the Element Mapping tab - that's where the logic used becomes important. True that the map files themselves are in XML, but it is of little use to compare the XML one to the other using a comparison tool... there's really no substitute in this instance for human analysis. Using the Message Designer tool to compare exposes the logic and the pre, in, and post process procedures as well as the elements themselves.

    Hope this helps, if I have misunderstood the question please feel free to elaborate and I'll be happy to answer again.

    Best,

    Meg Hanson

    Oracle XML Gateway Consultant

Hook LoadLibrary call from managed code

We would like to hook calls to LoadLibrary in order to download assemblies that are not found. We have a handler for ResolveAssembly that handles the managed assemblies, but we also need to handle unmanaged assemblies.

We have attempted to hook LoadLibrary calls by re-writing the imports table via techniques specified in "Programming Applications for Microsoft Windows", but when we call WriteProcessMemory() we get a permission denied error (998). (Yes, we're running with elevated privs)

Has anyone succeeded in re-writing the imports table while the CLR is loaded? Can anyone point me in the right direction?

Update: We resolved the permission denied issue, but now when we iterate the Imports Table of a mixed assembly (managed + unmanaged), the only entry we find is mscoree.dll. Does anyone know how to find the native imports? (we're working in C++/CLI).

From stackoverflow
  • Should work, but try using detours (or the free N-CodeHook) instead.
    Detours is almost the de-facto way of instrumenting Win32 binaries.

    jn_ : ... or you could use an open source lib like N-CodeHook (http://newgre.net/ncodehook) which also has 64bit support (you have to pay for X64 when using detours)
    Shay Erlichmen : @jn: self promoting :) I will give ncodehook a try next time I need to deal with code injection although I must admit that detours has been working for me quite well. Have you thought about mirroring the API? so that existing detours apps can easily migrate?
    jn_ : Got me ;-) Actually no, I haven't thought of that. Will put it on my todo list. thx
  • Why don't you do the heavy-lifting for unmanaged stuff in (unmanaged) C++/CLI, exposing to .NET just the results (say a string containing a DLL name).

  • The best way would be to hook LoadLibrary/LoadLibraryEx, do the download if needed, and pass the downloaded file down the chain. However, I'd be worried about blocking the GUI during that download.

  • We resolved the specified issue via a call to VirtualProtect() prior to calling WriteProcessMemory() and then call it again afterwards to restore the protection levels. This temporarily removes the read-only protection for the memory where the IAT resides. This works well for us and resolves the issue for when LoadLibrary() is called.

    Now if I can just figure out why LoadLibrary() is not called when an unmanaged assembly links against a lib (not a static lib)...

    By the way, Detour and N-Code Hook both look like nice products and are most likely the way I should go, but I would like to avoid adding a 3rd party assembly if possible.

    Joshua : That's easy. You didn't hook all four variants (LoadLibraryA, LoadLibraryW, LoadLibraryExA, LoadLibraryExW).
  • I have successfully hooked from Managed code. However, I did it by injecting an unmanaged DLL into the remote process and have it rewrite the import table in DllMain. You may want to consider this method.

    Here is my hooking function:

    //structure of a function to hook
    struct HookedFunction {
    public:
        LPTSTR moduleName;
        LPTSTR functionName;
        LPVOID newfunc;
        LPVOID* oldfunc;
    };
    
    BOOL Hook(HMODULE Module, struct HookedFunction Function) {
        //parse dos header
        IMAGE_DOS_HEADER* dos_header = (IMAGE_DOS_HEADER*)Module;
        if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) return 0; //not a dos program
    
        //parse nt header
        IMAGE_NT_HEADERS* nt_header = (IMAGE_NT_HEADERS*)(dos_header->e_lfanew + (SIZE_T)Module);
        if (nt_header->Signature != IMAGE_NT_SIGNATURE) return 0; //not a windows program
    
        //optional header (pretty much not optional)
        IMAGE_OPTIONAL_HEADER optional_header = nt_header->OptionalHeader;
        if (optional_header.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0; //no optional header
    
        IMAGE_IMPORT_DESCRIPTOR* idt_address = (IMAGE_IMPORT_DESCRIPTOR*)(optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress + (SIZE_T)Module);
        if (!optional_header.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size) return 0; //no import table
    
        //enumerate the import dlls
        BOOL hooked = false;
        for(IMAGE_IMPORT_DESCRIPTOR* i = idt_address; i->Name != NULL; i++)
            //check the import filename
            if (!_stricmp(Function.moduleName, (char*)(i->Name + (SIZE_T)Module)))
                //enumerate imported functions for this dll
                for (int j = 0; *(j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module)) != NULL; j++)
                    //check if the function matches the function we are looking for
                    if (!_stricmp(Function.functionName, (char*)(*(j + (SIZE_T*)(i->OriginalFirstThunk + (SIZE_T)Module)) + (SIZE_T)Module + 2) )) {
                        //replace the function
                        LPVOID* memloc = j + (LPVOID*)(i->FirstThunk + (SIZE_T)Module);
                        if (*memloc != Function.newfunc) { //not already hooked
                            DWORD oldrights;
                            DWORD newrights = PAGE_READWRITE;
                            VirtualProtect(memloc, sizeof(LPVOID), newrights, &oldrights);
                            if (Function.oldfunc && !*Function.oldfunc)
                                *Function.oldfunc = *memloc;
                            *memloc = Function.newfunc;
                            VirtualProtect(memloc, sizeof(LPVOID), oldrights, &newrights);
                        }
                        hooked = true;
                    }
    
        return hooked;
    }
    

How can I safely write to a given file path in Cocoa, adding a numeric suffix if necessary?

We want to write to "foo.txt" in a given directory. If "foo.txt" already exists, we want to write to "foo-1.txt", and so on.

There are a few code snippets around that try and answer this question, but none are quite satisfactory. E.g. this solution at CocoaDev uses NSFileManager to test if a path exists to create a safe path. However, this leads to obvious race conditions between obtaining a path and writing to it. It would be safer to attempt atomic writes, and loop the numeric suffix on failure.

Go at it!

From stackoverflow
  • Use the open system call with the O_EXCL and O_CREAT options. If the file doesn't already exist, open will create it, open it, and return the file descriptor to you; if it does exist, open will fail and set errno to EEXIST.

    From there, it should be obvious how to construct the loop that tries incrementing filenames until it returns a file descriptor or constructs a filename too long. On the latter point, make sure you check errno when open fails—EEXIST and ENAMETOOLONG are just two of the errors you could encounter.

  • int fd;
    uint32_t counter;
    char filename[1024]; // obviously unsafe
    
    sprintf(filename, "foo.txt");
    if( (fd = open(filename, O_CREAT | O_EXCL | O_EXLOCK, 0644)) == -1 && errno == EEXIST ) 
    {
        for( counter = 1; counter < UINT32_MAX; counter++ ) {
          sprintf(filename, "foo-%u.txt", counter);
          if( (fd = open(filename, O_CREAT | O_EXCL | O_EXLOCK, 0644)) == -1 && errno == EEXIST )
            continue;
          else
            break;
        }
    }
    
    if( fd == -1 && counter == UINT32_MAX ) {
     fprintf(stderr, "too many foo-files\n");
    } else if( fd == -1 ) {
     fprintf(stderr, "could not open file: %s\n", strerror(errno));
    }
    
    // otherwise fd is an open file with an atomically unique name and an
    // exclusive lock.
    
  • How about:

    1. Write the file to a temporary directory where you know there's no risk of collision
    2. Use NSFileManager to move the file to the preferred destination
    3. If step 3 fails due to a file already existing, add/increment a numeric suffix and repeat step 2

    You'd be basically re-creating Cocoa's atomic file write handling, but adding in the feature of ensuring a unique filename. A big advantage of this approach is that if the power goes out or your app crashes mid-write, the half-finished file will be tucked away in a tmp folder and deleted by the system; not left for the user to try and work with.

iPhone SDK mem management issues - EXC_BAD_ACCESS

I've been staring at this same issue for a long time now, and would really appreciate any help or suggestions. I'm sure its something simple, but I can't seem to find it. In my app delegate I'm loading up a bunch of accessory objects (an object I created, which supports NSCopying) with the following code:

NSString  *path   = [[NSBundle mainBundle] pathForResource:@"Accessories" ofType:@"plist"];
NSDictionary *accDict = [[NSDictionary alloc] initWithContentsOfFile:path];

self.colors = (NSArray *) [accDict objectForKey:@"Colors"]; 
self.exteriorAccessories = [self loadAccessoriesForMode:EXTERIOR_MODE withDictionary:accDict];
self.interiorAccessories = [self loadAccessoriesForMode:INTERIOR_MODE withDictionary:accDict];
[accDict release];

And this is the definition for the method its calling:

-(NSArray *)loadAccessoriesForMode:(NSString *)mode withDictionary:(NSDictionary *) dictionary
{
    NSMutableArray *tempValues = [[NSMutableArray alloc] init]; 
    for (NSDictionary *value in [dictionary objectForKey:mode])  
    {
        Accessory *accessory = [[Accessory alloc] initWithDictionary:value];
        [tempValues addObject:accessory];
        [accessory release];
    }

    NSArray *returnArray = [[NSArray alloc] initWithArray:tempValues copyItems:YES];
    [tempValues release];
    [returnArray autorelease];

    return returnArray; 
}

When I get to the release for accDict I'm getting an EXC_BAD_ACCESS exception. If I take out the release of accessory inside the loop, everything is fine - but I'm leaking Accessory objects (which seems obv. to me - if I init it and I alloc it, its my job to release it).

When I step through this in the debugger, I'm seeing the init, copy and dealloc methods all fire on my Accessory object as expected. I can also post code for the Accessory object if you think it will help, but I think the problem is somewhere in this code.

From stackoverflow
  • Please prefix this with an "I know nothing about objective C but":

    It looks to me like you need to release the accessory items after you have copied them into the "returnArray", or maybe not specify "copyItems".

  • Run Clang on your code. It's a godsend. Clang rules! It will do Static Analysis of your code and tell you what you might be leaking. Great stuff.

  • I think I've found the cause, but I'll post it here so others can possibly benefit. It didn't really have anything to do with the code I posted. Rather the problem was inside of the Accessory object. I was setting things directly instead of calling the getters through self.

    So this:

    value = [dict objectForKey:@"myKey"];
    

    Instead of this:

    self.value = [dict objectForKey:@"myKey"];
    

    Somehow this was causing me to have bad side effects on the NSDictionary itself (I thought that was not mutable, but it seems I was somehow messing things up). The only way I found this was to use the very helpful advice that I found on Cocoa With Love.

    When I used the Print Description option in XCode, I was able to see that the NSDictionary somehow contained AccessoryValue objects - one of my custom objects that should NOT have been there since this was just loaded from a simple plist. Print Description can be found in XCode by hovering over the object to see its details (while the process is paused in the debugger) and clicking on the little up/down arrows right next to the triangle that expands into object details. For dictionaries, this will dump their entire contents to the console.

    Jason Coco : It's important to know how the property "value" is defined and what's happening in its accessor methods. Are there retains and releases going on in there?
    Bdebeez : Yes, value is a property with (nonatomic, retain). So my hunch was that calling "value =" just set the pointer to that w/o calling retain, whereas "self.value =" calls the appropriate setter method, thus invoking the retain.
  • I was battling with the Exc_Bad_Access issue for a day and finally found the answer. The issue was when I try to access one of the objects stored in an NSDictionary, the first time was OK but the second access the object turned to be nil even though the object counts in the dictionary remains the same. This strange behavior was due to releasing the object twice. Here is an example:

    NSString* nstring=[[[NSString alloc]init]autorelease] [AnNSDictonaryInstance setObject:nstring forKey:0];

    ... [nstring release];

    Notice that nstring was set autorelease then release again? It won't show problem right away unit you try to read the dictionary object the second times. I hope one day Apple's development team will be able to flag this as an violation while compiling.

    I hope this post will help someone out.

    Wayne of Campbell

C# File Browsing w/ Checkboxes

Ok, so this question kind of builds on my last one. I am trying to build a "file browser" but it will do other things.

What I am trying to accomplish:

1)Have a tab dedicated to listing files just like "Browse Files" except I want to be able check certain files and directories. I also want the functionality of "Browse Files" as
change location.

2) Get value's from checkboxes to apply elsewhere.

From stackoverflow

How to Cross Compile for Cell Linux on the PS3 from Windows?

How can a cross compilation setup be achieved to allow compiling Cell Linux programs on a Windows PC using the cygwin toolchain? The cygwin tools provide a GNU compiler to use in building the cross compiler, and associated tools for the build process e.g. rpm, cpio, make, flex, bison and so on.

I am moderately confident this is possible, but unaware of anyone who has actually done this. It has already been done for x86 Linux, but I wish to use Windows, without requiring the use and overhead of a virtual machine running an entire 2nd operating system.

The Cell Linux toolchain is a patched GNU toolchain, with C and C++ compilers for the PPU and SPU processors, and associated binutils. The sources for the Cell Linux SDK for Cell Linux can be found here. The source RPMS here have build scripts for use with the rpmbuild tool on Linux.

The specific question is: how can a set of Cell Linux GNU compilers for the PPU and SPU processors be built, on Windows, using Cygwin.

From stackoverflow
  • I've never done it, so I can't give you step by step instructions, but I can give you a general idea.

    The instructions you linked will serve as a pretty good outline, but there will be definite changes.

    For the host PC, you can install gcc and other build tools from MinGW or cygwin. That will give you the windows native parts of your toolchain.

    Then you'll need to download the sources for the cell portions of the toolchain and compile them (with the appropriate options, --target, etc.) using the build environment you just installed.

    Then you download and compile the sources for libspe2, and you're done.

    But I'll warn you - it sounds easier than it is. Be prepared to spend a lot of time on it.

  • Since you can already do this on Linux x86, why don't you just install Linux a virtual machine? Also, what might be even easier, is to install Portable Ubuntu for Windows. It runs Linux alongside Windows using coLinux. Although this may not be optimal, it is probably much easier than trying to compile everything on Windows.

    grrussel : It may well be easier, but its less convenient for an end user developer to get a program compiled if it takes switching between two operating systems before deploying to a 3rd.
    Zifre : With Portable Ubuntu, you don't really have to "switch" OSs, it runs on the Windows desktop.
    none : This is correct, coLinux runs in parallel and you can interactively use it from Windows, i.e. by opening a shell connection via SSH or mapping virtual drives. coLinux really IS an excellent option to run Linux on Windows.
    none : Also, the performance of coLinux is much better than Cygwin, I have been using coLinux on Windows for quite a while now and it seems to be ideally suited to do what you want to do, if you are already contemplating to use cygwin, than coLinux is the next logical step which is also likely to be less frustrating.
    none : In addition, compiling all the other linux packages will be much more straightforward under colinux, simply because it really is a full featured linux system that doesn't have too many limitations.
  • You should be able to build a canadian cross compiler on Linux that runs on windows and creates code for PS3. Have a look at the excellent crosstools from Dan Kegel.

    Did you check if the Cell/PS3 devtools for windows/cygwin work for you?

  • the ps2dev toolchain can easily be set up under cygwin

    http://ps2dev.org/ps3/Tools/Toolchain

    grrussel : Sadly, the linked toolchain looks to be very dated
    Stowelly : if you check the forums they are constantly updated, and the scripts provided will get from svn all the updates required
  • A set of tools compiled to run on Windows via Cygwin can now be found on Sourceforge.

Subsonic Deeploads: Is This Supported?

It could very well be that I'm just missing the correct vernacular in this space, but I'm looking for a particular piece of functionality in SubSonic. In NetTiers it was called a "DeepLoad". A deep load runs to the database and fetches many objects (ie. fetch this OrderDetail and all of it's LineItems) in one database call.

Again, I want to run to the data store once an build up a potentially dense object graph or related items populated by the data store.

How do I do this in SubSonic and what is it called in SubSonic?

From stackoverflow
  • There is no eager loading, and DeepSave in ActiveRecord only calls Save. Here is an example with Northwind Order class foreign key method.

    [Test]
    public void SelectOrderDetails()
    {
        Order order = new Order(10250);
        OrderDetailCollection details = order.OrderDetails();
        Assert.IsTrue(details.Count == 3);
    }
    
  • You can do this in SubSonic 3.0 (not yet released, but almost there...) using IQueryable with lazy loading:

    var db=new NorthwindDB();
    var order=db.Orders.Where(x=>.xID==20).SingleOrDefault();
    Assert.Equal(3,order.OrderDetails.Count());
    

    if you're not on 3 (which requires .net 3.5) you can do this with Active record as Paul mentions - but it will make two calls.

image swap technique - to fade instead

Hey, I am using this code below to swap on image on hover:

$(function() {
 $("#compost").hover(function() {
  origImage=$(this).attr("src");
  $(this).attr("src", "images/order-compost-over.gif")
 },function() {
  $(this).attr("src", origImage)
 });
});

Ia m trying to use fadeIn instead of a swap. I tried working it in but no luck.I tried having the img tag fadeIn but it didnt work.

Thanks,

Ryan

From stackoverflow
  • Check out ImageSwitch. Does everything you want and a fair bit more.

  • If you're trying to "merge" the two images, you won't be able with standard techniques.

    Instead, you should:

    • Create a new IMG object
    • Position that absolutely over the previous image
    • Set the new image's src to the old one and set its opacity to 1.
    • Set the old image's src to the new URL and set its opacity to 0.
    • Now animate both simultaneously to oposite values
    • Finally, get rid of the new image.

    This is a tricky one, but should work fine :)

asp.net mvc: How to pass anonymous type to UserController?

I tried the following but doesnt work:

<%Html.RenderPartial("userControl",new {personID=Model.ID, name="SomeName"});%>

In the usercontrol I have a hidden field in an ajax form to which I assign personID. It wont compile, the hidden id is not recognized.

From stackoverflow
  • You'd either have to use reflection or a helper class like RouteValueDictionary if you wanted to get the correct property from the anonymous type.

    RouteValueDictionary is probably the easiest. Create an instance of it, passing the Model, and then use its index operator to query the values.

    Eg:

    <%
        var modelDictionary = new RouteValueDictionary(Model);
    %>
    <input type="hidden" name="personID" value="<%= modelDictionary["personID"] %>" />
    
  • I am not sure why would you want to do that, but here is how (strongly type Model is much better):

    <%
        ViewData["PersonID"] = Model.ID;
        ViewData["Name"] = "SomeName";
        Response.Write(
            Html.RenderPartial("userControl"));
    %>
    

    OR

    If you just do this:

    <%=Html.RenderPartial("userControl")%>
    

    and if your "userControl" is also strongly typed, it should be able to read "Model.ID"

Car return value? Or scheme being werid.

Okay i noticed this semi weridish behavior in one of my projects using scheme, and lists. I managed to isolate the behavior, into a single section. The code is:

(define x (list 1 2 3))
(define y (list 4 5))
(define z (cons (car x) (cdr y)))
(define w (append y z))
(define v (cons (cdr x) (cdr y)))
(set-car! x 6)
(set-car! y 7)
(set-cdr! (cdr x) (list 8))

x
y
z
w
v

Gives us the output of:

(6 2 8)
(7 5)
(1 5)
(4 5 1 5)
((2 8) 5)

Can anyone explain to me:

  1. Why does (set-car! x 6) not update Z? Since according to my understanding car/cdr return pointers or references to the corresponding values. This is really werid and im kinda confused.
  2. If car/cdr does not return references/pointers then how is the final set-cdr! manipulating the list v?

Any ideas? Its a simple fix, but im more curious as to why the weridness with the variables is going on.

From stackoverflow
  • (define z (cons (car x) (cdr y))) has allocated a new cons cell for the head of z. The head of x is a different cons cell to the head of z, so changing the contents of this cons cell for x does not change z.

    UberJumper : If you assume that, then why does set-cdr! manipulate v?
    Matthias Benkard : uberjumper: It doesn't. It manipulates the cons cell that the cdr of x points to, which is the same as the one that the car of v points to. v itself remains unchanged, as does x (by the set-cdr! call, I mean).
  • Okay, let's step through your program line by line. I'm also assigning unique numbers (think of them as object addresses, if you're used to C-like languages) for each newly-created object so you can see what's what. :-)

    (define x (list 1 2 3))             ; => #1 = (1 . #2), #2 = (2 . #3), #3 = (3 . ())
    (define y (list 4 5))               ; => #4 = (4 . #5), #5 = (5 . ())
    (define z (cons (car x) (cdr y)))   ; => #6 = (1 . #5)
    (define w (append y z))             ; => #7 = (4 . #8), #8 = (5 . #6)
    (define v (cons (cdr x) (cdr y)))   ; => #9 = (#2 . #5)
    (set-car! x 6)                      ; => #1 = (6 . #2)
    (set-car! y 7)                      ; => #4 = (7 . #5)
    (set-cdr! (cdr x) (list 8))         ; => #2 = (2 . #10), #10 = (8 . ())
    

    Now, let's look at your values (for each reference, use the last assigned value):

    x   ; #1 => (6 . #2) => (6 . (2 . #10)) => (6 2 8)
    y   ; #4 => (7 . #5) => (7 5)
    z   ; #6 => (1 . #5) => (1 5)
    w   ; #7 => (4 . #8) => (4 . (5 . #6)) => (4 . (5 . (1 . #5))) => (4 5 1 5)
    v   ; #9 => (#2 . #5) => ((2 . #10) 5) => ((2 8) 5)
    


    Edit: I'm adding a diagram to explain my answer, since you can't have diagrams in a comment. I don't have time to make a diagram showing the values above, but this hopefully explains a few things.

    Expression tree

    Each pair has two "slots", car and cdr, represented as the left and right boxes in the diagram above. Each of these slots, as you see, has three possible things:

    1. An atom (a number in your examples, or symbols in the diagram, such as let, s5, and sqrt)
    2. A reference (represented as an arrow in the diagram)
    3. Null (represented as a black box in the diagram)

    You can put any of these in any of the slots. So, in my explanation above, each of the # items is an arrow, each of the non-# numbers is an atom, and each of the () is a black box. So, in the line

    (define v (cons (cdr x) (cdr y)))
    

    you are creating a pair, where the left-hand slot has the same contents as the right-hand slot of x (i.e., an arrow going to pair 2), and the right-hand slot has the same contents as the right-hand slot of y (an arrow going to pair 5). In other words, both boxes in v contain arrows, each going off a different pair.

    Hope this makes more sense. :-)

    UberJumper : Can you explain more related to V? Why does cons part for Z return values(#6), but cons of (cdr x)(cdr y) (#9) still be bound to two references?
    Javier : both z and v are defined as the cons of two existing values; but the car of z is a number (immutable value), while the car of v is a cons cell (mutable value, shared). set-car! and set-cdr! modify cons cells, not the values they hold.
    Kyle Cronin : +1 for the diagram. What did you use to make that?
    Chris Jester-Young : Xfig (http://www.xfig.org/). :-)
  • remember that each variable doesn't hold a list, they hold just a cons cell. a list (or a tree) is a composite structure of several cons cells, some of which may be shared between several structures.

    also, you're thinking about pointers and references, instead of thinking about values, which can be either immutable values (like numbers, or symbols) or mutable values (like conses or strings) mutable values are allocated, garbage collected and passed by reference.

    one last point to remember: the cons procedure always allocates a new cons cell.

    after (define z (cons (car x) (cdr y))), z holds a brand new cons with the same as x and the same car as x, and the same cdr as y. when you (set-car! x), you just change the x cons cell, not z.

    after (define v (cons (cdr x) (cdr y))), v holds a brand new cons whose car is the same value as the cdr of x; that is a cons cell. the very same cons cell as (cdr x). it's shared by the two lists. when that shared cons cell is modified by (set-cdr! (cdr x) ...), both lists are affected.

How do I Copy the Values of an IDictionary into an IList Object in .Net 2.0?

If I have a:

Dictionary<string, int>

How do I copy all the values into a:

List<int>

Object?

The solution needs to be something compatible with the 2.0 CLR version, and C# 2.0 - and I really dont have a better idea, other than to loop through the dictionary and add the values into the List object one-by-one. But this feels very inefficient.

Is there a better way?

From stackoverflow
  • Try the following

    public static class Util {
      public List<TValue> CopyValues<TKey,TValue>(Dictionary<TKey,TValue> map) {
        return new List<TValue>(map.Values);
      }
    }
    

    You can then use the method like the following

    Dictionary<string,int> map = GetTheDictionary();
    List<int> values = Util.CopyValues(map);
    
    Guffa : IIRC C# 2.0 can't infer the genric types, so you have to specify them in the call: Util.CopyValues(map)
    JaredPar : @Guffa, my code will work in C# 2.0 and up. C# cannot do local type inference in 2.0 but it can still do method type inference.
  • This should work even on 2.0 (forgive the C# 3.0 use of "var"):

    var dict = new Dictionary<string, int>();
    var list = new List<int>(dict.Values);
    
  • If you can use an IEnumerable<int> or ICollection<int> instead of a List<int> you can just use the Value collection from the dictionary without copying anything.

    If you need a List<int> then you have to copy all the items. The constructor of the list can do the work for you, but each item still has to be copied, there is no way around that.

  • It's probably worth noting that you should step back and ask yourself if you really need the items stored in a list with random indexed access, or if you just need to enumerate each of the keys or values from time to time.

    You can easily iterate over the ICollection of MyDictionary.Values.

    foreach (int item in dict.Values) { dosomething(item); }
    

    Otherwise, if you actually need to store it as an IList, there's nothing particularly inefficient about copying all the items over; that's just an O(n) operation. If you don't need to do it that often, why worry? If you're annoyed by writing the code to do that, use:

    IList<int> x=new List<int>(dict.Values);
    

    which wraps the code that you'd write into a copy constructor that already implements the code you were planning to write. That's lines-of-code-efficient, which is probably what you actually care about; it's no more space-or-time efficient than what you'd write.

How do I structure Python code into modules/packages?

Assume I have this barebones structure:

project/
  main.py
  providers/
    __init.py__
    acme1.py
    acme2.py
    acme3.py
    acme4.py
    acme5.py
    acme6.py

Assume that main.py contains (partial):

if complexcondition():
  print providers.acme5.get()

Where __init__.py is empty and acme*.py contain (partial):

def get():
  value=complexcalculation()
  return value

How do I change these files to work?

Note: If the answer is "import acme1", "import acme2", and so on in __init__.py, is there a way to accomplish that without listing them all by hand?

From stackoverflow
  • This question asked today, Dynamic Loading of Python Modules, should have your answer.

    arantius : Not quite what I was hoping for, but it led me to a workable solution, thanks.
  • If I'm reading your question correctly, it looks like you're not trying to do any dynamic importing (like in the question that Van Gale mentioned) but are actually trying to just import all of the modules in the providers package. If that's the case, in __init__.py you would want to have this statement:

    __all__ = ["acme1", "acme2", "acme3", "acme4", "acme5", "acme6"]
    

    Then to import everything you would use from ... import *

    from providers import *
    

    And then instead of using the package name explicitly in the code, you would just call the imported classes

    acme1.get()
    acme2.get()
    

    If you have enough modules in the providers package that it becomes a problem populating the __all__ list, you may want to look into breaking them up into smaller packages or storing the data some other way. I personally wouldn't want to have to deal with dynamic importing schennagins every time I wanted to re-use the package.

Why is my toolbar not visible when in landscape mode?

My aim was to get the application functioning in both landscape and portrait mode, and all I could figure out to do it was this code below. The app was working fine in portrait, but when switched to landscape, the text wouldn't expand (to the right) to fill up the additional space. I made sure my springs/struts where set, and that the parents had "allowResizing" selected in IB.

Here's what I've done instead:

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation duration: 
(NSTimeInterval)duration {
  UIInterfaceOrientation toInterfaceOrientation = self.interfaceOrientation;

  if (toInterfaceOrientation == UIInterfaceOrientationPortrait) {
    self.myView.frame = CGRectMake(0.0, 0.0, 320.0, 480.0);
  }
  else {
    self.myView.frame = CGRectMake(0.0, 0.0, 480.0, 256.0);
  }
}

Note that it looks just fine in portrait mode (toolbar appears):

Portrait

But the toolbar is gone in landscape mode:

Landscape

Any ideas?

From stackoverflow
  • There are a few reasons why it could be messing up... maybe your UIToolbar has the wrong parent. Maybe a layoutSubviews is being run and moving it somewhere strange. Or something else.

    I recommend you implement a didRotateFromInterfaceOrientation: on your view controller and read the frame of the UIToolbar after the rotation to see where it has gone. This will be the best way to discover the exact problem.

  • If you use Interface Builder - you get this same result if you don't specify constraints in the object inspector to pin the toolbar to both edges and the bottom (click on the little red lines to specify constraints).

    You can also do the same in code - you need to lookup how to do this (but its easier in IB)

How to start Java from within a C process?

I want to add some Java (actually Clojure) based event handlers to a HUGE legacy C application. What is the most straight forward and easily maintained way to do this? I would like the Java classes to be running in the same process as the C code. Is this even possible?

From stackoverflow
  • The Java Native Interface would seem to be designed for this. In particular, this section of the spec seems relevant.

  • The source code for the java command is available. It provides a good example of how to create a Sun JVM within a C program.

    The Java 6 (and upcoming JDK 7) version is available at OpenJDK.You can download source code for Java 5 under two different licenses.

  • By the way, this is easy to make it "seem" correct, but much more difficult to actually do correctly. Why do you want them running in the same process? Why not the same thread?

    You might consider making a bridge through TCP/IP between your C code and a Java process. This would be much better because it would avoid the maintenance surprises.

    You're thinking "maintenance surprises, what maintenance surprises?" Ah! Today you want to call from C to Java, but tomorrow someone is going to want to go back the other way. That's where your trouble becomes REAL painful.

    I've been here before. Take my advice: do the TCP/IP bridge. This will keep your Java from crashing. -Stosh

    RBerteig : I'd upvote a large number of times if it were allowed. Nothing is ever as simple as it should be when getting Java to interoperate with anything else. I have a horror story, but there isn't room in this margin ;-)
    Arthur Ulfeldt : johnstosh, could you be more specific about 'the TCP/IP bridge'.
  • You could do it this way, but given that you really want to script a large C app, have you considered GUILE or Lua? They where both made for exactly this purpose.

    Arthur Ulfeldt : the goal is to write event handlers in clojure that will be called form the C program when something happens.