Friday, April 8, 2011

Add new templates in Xcode

How to add new templates in Xcode for iPhone application developement?

From stackoverflow
  • For some advices, I suggest to take a look at answers to a related question: Change templates in Xcode.

    In particular, if you want your modifications not to be lost whenever you upgrade Xcode, put your templates in ~/Library/Developer/Shared/Xcode, not under /Developer.

  • From my answer to this question:

    XCode uses template files for file and project templates and does variable expansion in both at creation time.

    XCode 3.0-3.1 templates can be found in [Dev Installation]/Library/Xcode/, likely /Developer/Library/XCode. If you want to modify these templates or add your own, use the following directories to save your new/modified templates so that they are not wiped out by future Developer Tool upgrades:

    • File templates: ~/Library/Developer/Shared/Xcode/File Templates/
    • Target templates: ~/Library/Developer/Shared/Xcode/Target Templates/
    • Project templates: ~/Library/Developer/Shared/Xcode/Project Templates/

    I think that you can also use the /Library/Developer/Shared/Xcode/[File|Target|Project] Templates/ directory for templates shared by all users.

    A good tutorial on writing file templates is here [MacResearch.org].

  • If it helps, i've created a tutorial to demonstrate how you can change the existing project templates. The method i use prevents that the templates are overwritten upon installing a new version of Xcode. I've tested this method using Xcode version 3.2.2 and 3.2.3 (beta)

    http://www.sodeso.nl/?p=895

  • I wrote an article on how to create a new Xcode template from an existing project here.

    It covers:

    • specifying your project files are relative to the project path
    • using the commandline to search / replace & fiddle file permissions
    • excluding info.plist from the target membership
    • giving your template an icon

    It doesn't cover where to put the template. That information is covered in other answers.

Type parameters versus member types in Scala

I'd like to know how do the member types work in Scala, and how should I associate types.

One approach is to make the associated type a type parameter. The advantages of this approach is that I can prescribe the variance of the type, and I can be sure that a subtype doesn't change the type. The disadvantages are, that I cannot infer the type parameter from the type in a function.

The second approach is to make the associated type a member of the second type, which has the problem that I can't prescribe bounds on the subtypes' associated types and therefore, I can't use the type in function parameters (when x : X, X#T might not be in any relation with x.T)

A concrete example would be:

I have a trait for DFAs (could be without the type parameter)

trait DFA[S] { /* S is the type of the symbols in the alphabet */
  trait State { def next(x : S); }
  /* final type Sigma = S */
}

and I want to create a function for running this DFA over an input sequence, and I want

  • the function must take anything <% Seq[alphabet-type-of-the-dfa] as input sequence type
  • the function caller needn't specify the type parameters, all must be inferred
  • I'd like the function to be called with the concrete DFA type (but if there is a solution where the function would not have a type parameter for the DFA, it's OK)
  • the alphabet types must be unconstrained (ie. there must be a DFA for Char as well as for a yet unknown user-defined class)
  • the DFAs with different alphabet types are not subtypes

I tried this:

def runDFA[S, D <: DFA[S], SQ <% Seq[S]](d : D)(seq : SQ) = ....

this works, except the type S is not inferred here, so I have to write the whole type parameter list on each call site.

def runDFA[D <: DFA[S] forSome { type S }, SQ <% Seq[D#Sigma]]( ... same as above

this didn't work (invalid circular reference to type D??? (what is it?))

I also deleted the type parameter, created an abstract type Sigma and tried binding that type in the concrete classes. runDFA would look like

def runDFA[D <: DFA, SQ <% Seq[D#Sigma]]( ... same as above

but this inevitably runs into problems like "type mismatch: expected dfa.Sigma, got D#Sigma"

Any ideas? Pointers?

Edit:

As the answers indicate there is no simple way of doing this, could somebody elaborate more on why is it impossible and what would have to be changed so it worked?

The reasons I want runDFA ro be a free function (not a method) is that I want other similar functions, like automaton minimization, regular language operations, NFA-to-DFA conversions, language factorization etc. and having all of this inside one class is just against almost any principle of OO design.

From stackoverflow
  • Scala's type inference sometimes leaves much to be desired.

    Is there any reason why you can't have the method inside your DFA trait?

    def run[SQ <% Seq[S]](seq: SQ)
    

    If you don't need the D param later, you can also try defining your method without it:

    def runDFA[S, SQ <% Seq[S]](d: DFA[S])(seq: SQ) = ...
    
  • First off, you don't need the parameterisation SQ <% Seq[S]. Write the method parameter as Seq[S]. If SQ <% Seq[S] then any instance of it is implicitly convertable to Seq[S] (that's what <% means), so when passed as Seq[S] the compiler will automatically insert the conversion.

    Additionally, what Jorge said about type parameters on D and making it a method on DFA hold. Because of the way inner classes work in Scala I would strongly advise putting runDFA on DFA. Until the path dependent typing stuff works, dealing with inner classes of some external class can be a bit of a pain.

    So now you have

    trait DFA[S]{
      ...
    
      def runDFA(seq : Seq[S]) = ...
    }
    

    And runDFA is all of a sudden rather easy to infer type parameters for: It doesn't have any.

Equivalent of double-clickable .sh and .bat on Mac?

I am distributing a Java program where I want a double-clickable file to run

java -cp MyProgram.jar;MyLib.jar my.program.Main

On Windows I simply distribute a .bat file, for *nix an executable .sh file. Problem is, double-clicking the .sh file just opens it up in a text editor on Mac. What should I do for Mac?

From stackoverflow
  • You can use a .sh (Shell Script), after all MacOSX is Unix!

  • On mac, there is a specific extension for executing shell scripts by double clicking them: this is .command.

    Epaga : works like a charm!
  • For Java applications on Mac, you really should use Apple's Jar Bundler (in the Developer Tools/Applications/Utilities folder; really a symlink to /usr/share/java/Tools/Jar Bundler). It lets you make a proper OS X double-clickable app, including setting preferences for e.g. using the Mac toolbar, JVM version, graphics system, OS X app metadata and classpath/resources.

  • The answer about using the Jar Bundler tool is correct, but if you want to use a .sh file, make sure the unix permissions are set properly to something like 755 with CHMOD, and make sure the first line contains the path to a shell installed by default on Mac OS X. Also note that even with the +x bit set, it may still ask the user whether they want to open it or run it.

Google Translation API

Has anyone used Google translation API ? What is the max length limit for using it?

From stackoverflow
  • 500 characters

    source

    Ken Browning : it could be. i just googled for you. i have never used the service.
    duffymo : Wrong. See the comment in the link you cited right under the one that quoted 500 chars.
    Ken Browning : I don't argue that I might be wrong. However, that comment is talking about a wrapper which removes character limitations. Apples and oranges imho.
  • I've used it to translate Japanese to English.

    I don't believe the 500 char limit is true if you use http://code.google.com/p/jquery-translate/, but one thing that is true is you're restricted as to the number of requests you can make within a certain period of time. They also try to detect whether or not you're sending a lot of requests with a similar period, almost like a mini "denial of service" attack.

    So when I did this I wrote a client with a random length sleep between requests. I also ran it on a grid so all the requests didn't come from a single IP address.

    I had to translate ~2000 Java messages from a resource bundle from Japanese to English. It worked out pretty nicely, as long as the text was single words. Longer phrases with context came out awkwardly.

  • The limit was 500... now it is 5000 chars.

Problem with php function to catch error on saving image

I have a method to save an image, which is meant to deal gracefully with an error, setting $imageSrc to a particular image in the event of failure. My method works fine if the image is present, but no error conditions seems to be handled correctly.

$imageSrc = save_pic($PIC_URL, $pk);

function save_pic($pic_url, $pk) {
    $imageDir = './';
    if (!strlen($pic_url))
            return "removed.jpg";
    if (!is_dir($imageDir) || !is_writable($imageDir)) {
     return "removed.jpg";
    }
    $image = file_get_contents($pic_url);
    if (empty($image)) {
     return "removed.jpg";
    }
    $r = file_put_contents($imageDir.$pk.".jpg", $image);
    if ($r) {
            return "./$pk.jpg"; 
    } else {
            return "removed.jpg";
    }
}

If the image does not exist, I get :

Warning: getimagesize(http://127.0.0.1/555.jpg) [function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in C:\Program Files\EasyPHP 2.0b1\www\get_auction.php on line 144

Array (
 [type] => 2 [message] => getimagesize(http://127.0.0.1/555.jpg)
 function.getimagesize]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
 [file] => C:\Program Files\EasyPHP 2.0b1\www\get_auction.php
 [line] => 144
) 1

returned.jpg is never returned in any event.

edit: added imageResize code:

function imageResize($imageURL, $maxWidth, $maxHeight)

{

global $outputWidth, $outputHeight, $maxWidth, $maxHeight;

$size = getimagesize($imageURL);

if ($size) {

    $imageWidth  = $size[0];

    $imageHeight = $size[1];

    $wRatio = $imageWidth / $maxWidth;

    $hRatio = $imageHeight / $maxHeight;

    $maxRatio = max($wRatio, $hRatio);



    if ($maxRatio > 1) {

        $outputWidth = $imageWidth / $maxRatio;

        $outputHeight = $imageHeight / $maxRatio;

    } else {

        $outputWidth = $imageWidth;

        $outputHeight = $imageHeight;

    }

} else {

    die(print_r(error_get_last()));

}

}
From stackoverflow
  • Are you sure you're writing to the root folder? Because I can't see any problem with your code. file_get_contents and file_put_contents don't seem to be failing, so your image is being written somewhere.

    Joshxtothe4 : but it doesnt deal with the file not existing in order to get
    Can Berk Güder : so file_get_contents *should* return FALSE but doesn't, is that correct?
    Joshxtothe4 : Exactly, The problem is not with the folder being writable, but with the image not existing at the url
  •  $image = file_get_contents("http://example.com/test.png");
     list($ver, $retcode, $message) = explode(' ', $http_response_header[0], 3);
     if ($retcode != 200) {
       return "removed.jpg";
     }
    

    $retcode will contain HTTP response code.

    Please post this $retcode here and what your strlen($image) returns, it might help to resolve your problem.

    Joshxtothe4 : the error code is 404, it states it in the error message
    Quassnoi : Yes, and he can parse it in the code.
    Joshxtothe4 : I put this in my code as you suggest, and only the file_Get_contens error is output, nothing after that.
    Quassnoi : Does it ever get after file_get_contents? Put an echo right after file_get_contents and see if it gets there.
    Dominic Rodger : ah... the wonder that is debugging PHP
  • Try this:

    <?php
    $imageSrc = save_pic($PIC_URL, $pk);
    
    function save_pic($pic_url, $pk) 
    {
        $imageDir = './';
    
        if (!strlen($pic_url))
        {
            return 'removed.jpg';
        }
    
        if(!is_dir($imageDir) || !is_writable($imageDir)) 
        {
            return 'removed.jpg';
        }
    
        if(!file_exists($pic_url))
        {
            return 'removed.jpg';
        }
    
        if (file_put_contents($imageDir . $pk . '.jpg', file_get_contents($pic_url))) 
        {
                return $imageDir . $pk . '.jpg'; 
        } 
        else 
        {
                return 'removed.jpg';
        }
    }
    
    Joshxtothe4 : Hi Bart, this had the same exact behavior.
    Bart S. : Can you post the code from C:\Program Files\EasyPHP 2.0b1\www\get_auction.php around line 144? Because that is what's causing this error: C:\Program Files\EasyPHP 2.0b1\www\get_auction.php on line 144
    Joshxtothe4 : line 144 is just $imageSrc = save_pic($PIC_URL, $pk);
  • Debug?

    Get an IDE that includes a debugger, like Eclipse or Netbeans, rtm for functions to see how the respond, or do bad-old inline debugging to echo the value of code at runtime.

  • It seems to me you're not posting your complete code?

    The warning message says getimagesize(), yet nowhere is getimagsize() used in your example. To receive better help I would include the whole method or an updated error message of your current efforts. Please also include the PHP version you're using.

    file_get_contents() will return false in case of errors and does so on 404 HTTP errors, as demonstrated:

    mfischer@testing01:~$ php -r 'var_dump(file_get_contents("http://stackoverflow.com/i_do_not_exist.jpg"));'
    
    Warning: file_get_contents(http://stackoverflow.com/i_do_not_exist.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
     in Command line code on line 1
    
    Call Stack:
        0.0002      51884   1. {main}() Command line code:0
        0.0002      51952   2. file_get_contents() Command line code:1
    
    bool(false)
    mfischer@testing01:~$ php -v
    PHP 5.2.6-5 with Suhosin-Patch 0.9.6.2 (cli) (built: Oct  5 2008 13:07:13)
    

    Trying out your code it works perfectly fine for me here:

    $ cat test.php
    <?php
    $PIC_URL="http://stackoverflow.com/i_dont_exist.jpg";
    $pk = "test";
    $imageSrc = save_pic($PIC_URL, $pk);
    var_dump($imageSrc);
    
    function save_pic($pic_url, $pk) {
        $imageDir = './';
        if (!strlen($pic_url))
                return "removed.jpg";
        if (!is_dir($imageDir) || !is_writable($imageDir)) {
            return "removed.jpg";
        }
        $image = file_get_contents($pic_url);
        if (empty($image)) {
            return "removed.jpg";
        }
        $r = file_put_contents($imageDir.$pk.".jpg", $image);
        if ($r) {
                return "./$pk.jpg";
        } else {
                return "removed.jpg";
        }
    }
    $ php test.php
    
    Warning: file_get_contents(http://stackoverflow.com/i_dont_exist.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
     in /home/mfischer/tmp/532480/test.php on line 14
    
    Call Stack:
        0.0005      59824   1. {main}() /home/mfischer/tmp/532480/test.php:0
        0.0005      60176   2. save_pic() /home/mfischer/tmp/532480/test.php:4
        0.0006      60444   3. file_get_contents() /home/mfischer/tmp/532480/test.php:14
    
    string(11) "removed.jpg"
    

    PHP functions have the bad habit of just spilling out warning messages right in your code, if you don't like this you can silence them with the '@' operate as suggested before or you can alternatively use a HTTP Client library as provided by PEAR_HTTP or Zend_HTTP_Client to have better control of error handling. Rolling your own thing with sockets, fsockopen, etc. would also be possible.

    But back to the point: if it's still not working, I think there's some information missing.

    Joshxtothe4 : I have updated my question to show the ImageResize function. The problem seems to be with the 404 error however.
  • Should you not be testing for file_get_contents errors? I mean with something like

    if( false == ($image = file_get_contents($pic_url))){
            return "removed.jpg";
        }
    
    • Send HTTP HEAD to given URL
    • Check returncode == 200 (file is there) else it's removed
    • Check that Content-Type header is image/* (for example image/png) else it's removed
    • If server sent Content-Length header, read that to variable
    • file_get_contents(URL)
    • If server sent that Content-Length see if size matches else it's removed
    • Save image
    • Try getimagesize(), if it gives errors remove it via unlink() and it's removed else keep it
    • Success!
  • You are having path issues. You should store the full path to the pic in a define.

    Make sure this file is sourced from the save_pic function.

    DEFINE("RemovedPicUrl", "http://" . $_SERVER['SERVER_NAME'] . "/path/to/removed/image/removed.jpg")
    

    then change all occurances of

    "Removed.jpg"
    

    to

    RemovedPicUrl
    

    And I'll bet you a dollar that fixes your issue.

  • The problem was not a code issue, but was caused by file corruption. This was determined while testing on other machines.

Does a form reset button fire a select elements onChange event?

I have a form with some select elements that have onChange events attached to them. I would like the event to fire even when someone clicks the form reset button.

My question is: does resetting a form fire a select elements onChange event?

Here is a simple example in jQuery

<script type="text/javascript">
    $('.myselect').change(function() {
        // do something on change
    });
</script>

<form action="/" method="post">
    <select class="myselect" name="select1">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <select class="myselect" name="select2">
        <option value="1">First</option>
        <option value="2">Second</option>
    </select>
    <!-- When this is clicked I would like it fire the change event -->
    <input type="reset" value="Reset" /> 
    <input type="submit" value="Save" />
</form>

Thanks!

From stackoverflow
  • There is an onReset tag for forms, so you could do something like:

    <script type="text/javascript">
        var changeFunc = function() {
            // do something on change.
        };
        $('.myselect').change(changeFunc);
    </script>
    
    <form onReset="changeFunc()" action="/" method="post">
        <select class="myselect" name="select1">
            <option value="1">First</option>
            <option value="2">Second</option>
        </select>
        <select class="myselect" name="select2">
            <option value="1">First</option>
            <option value="2">Second</option>
        </select>
        <!-- When this is clicked I would like it fire the change event -->
        <input type="reset" value="Reset" /> 
        <input type="submit" value="Save" />
    </form>
    

    This method is called before the reset happens, though so it can be tricky. I guess so you can do an "Are you sure?" box. Tossing a setTimeout in the reset function seems to do the trick.

How do I set the format of toString methods with ToStringBuilder in commons-lang?

how do I configure the setting of the format for toString

From stackoverflow