Rectangle 27 2593

Issues with change listeners:

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

So the real question is this: How many comparisons can you do on a browser in 50ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6ms. On InternetExplorer8 it takes about 40ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

@Mark - yes, in KO you just add .extend({ throttle: 500 }) to wait 500 milliseconds after the last change event before acting on it.

This entire answer is great other than "As long as they get 50 fps, any performance over that is a waste, since the human eye can not appreciate it, so you're better off drawing more stuff, than getting fps higher." That statement is completely incorrect depending on your application. The eye can definitely appreciate more than 50 fps, and as the various problems with VR show (read any of the latest from John Carmack or Michael Abrash, especially the latter's GDC 2013 VR talk), 50 fps is actually way too slow. Other than that, your answer is great. I just don't want misinformation spreading.

Just wondering, if your app is like Twitter or a comment thread/forum, and you implement infinite scrolling based on Angular, you could run into the "2000 pieces of info" "limit". A single comment could easily have several variables for the author's name, profile img, content, datetime, and etc. Also, say we have a giant array for storing all the comments/posts, every dirty checking would require scanning of this array, am I right? This would make the browser a bit laggy at times which is a bad user experience. What do you suggest we do in this case to ensure reasonable performance?

The statement could be easily said in reverse as "Dirty checking is a clever feature for a problem which knockout does not have". ES6 is using observables and angular is getting rid of dirty checking. The real world caught up to this answer and shown it to be false.

"Anything faster than 50 ms is imperceptible to humans" is not true. In testing we have found our customers can easily distinguish between 50ms update latency (20fps) and 16.6ms update latency (60fps). Scenes running at the former speed consistently get poorer overall "how did it feel" ratings even when people did not consciously register the framerate.

javascript - How does data binding work in AngularJS? - Stack Overflow

javascript angularjs data-binding
Rectangle 27 2564

Issues with change listeners:

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

So the real question is this: How many comparisons can you do on a browser in 50ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6ms. On InternetExplorer8 it takes about 40ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

@Mark - yes, in KO you just add .extend({ throttle: 500 }) to wait 500 milliseconds after the last change event before acting on it.

This entire answer is great other than "As long as they get 50 fps, any performance over that is a waste, since the human eye can not appreciate it, so you're better off drawing more stuff, than getting fps higher." That statement is completely incorrect depending on your application. The eye can definitely appreciate more than 50 fps, and as the various problems with VR show (read any of the latest from John Carmack or Michael Abrash, especially the latter's GDC 2013 VR talk), 50 fps is actually way too slow. Other than that, your answer is great. I just don't want misinformation spreading.

Just wondering, if your app is like Twitter or a comment thread/forum, and you implement infinite scrolling based on Angular, you could run into the "2000 pieces of info" "limit". A single comment could easily have several variables for the author's name, profile img, content, datetime, and etc. Also, say we have a giant array for storing all the comments/posts, every dirty checking would require scanning of this array, am I right? This would make the browser a bit laggy at times which is a bad user experience. What do you suggest we do in this case to ensure reasonable performance?

The statement could be easily said in reverse as "Dirty checking is a clever feature for a problem which knockout does not have". ES6 is using observables and angular is getting rid of dirty checking. The real world caught up to this answer and shown it to be false.

"Anything faster than 50 ms is imperceptible to humans" is not true. In testing we have found our customers can easily distinguish between 50ms update latency (20fps) and 16.6ms update latency (60fps). Scenes running at the former speed consistently get poorer overall "how did it feel" ratings even when people did not consciously register the framerate.

javascript - How does data binding work in AngularJS? - Stack Overflow

javascript angularjs data-binding
Rectangle 27 2561

Issues with change listeners:

AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.

The $apply() method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls $digest(). A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.

To contrast dirty-checking (AngularJS) vs change listeners (KnockoutJS and Backbone.js): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.

  • The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do POJO, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.
  • Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.
  • Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.

So the real question is this: How many comparisons can you do on a browser in 50ms? This is a hard question to answer as many factors come into play, but here is a test case: http://jsperf.com/angularjs-digest/6 which creates 10,000 watchers. On a modern browser this takes just under 6ms. On InternetExplorer8 it takes about 40ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.

It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.

@Mark - yes, in KO you just add .extend({ throttle: 500 }) to wait 500 milliseconds after the last change event before acting on it.

This entire answer is great other than "As long as they get 50 fps, any performance over that is a waste, since the human eye can not appreciate it, so you're better off drawing more stuff, than getting fps higher." That statement is completely incorrect depending on your application. The eye can definitely appreciate more than 50 fps, and as the various problems with VR show (read any of the latest from John Carmack or Michael Abrash, especially the latter's GDC 2013 VR talk), 50 fps is actually way too slow. Other than that, your answer is great. I just don't want misinformation spreading.

Just wondering, if your app is like Twitter or a comment thread/forum, and you implement infinite scrolling based on Angular, you could run into the "2000 pieces of info" "limit". A single comment could easily have several variables for the author's name, profile img, content, datetime, and etc. Also, say we have a giant array for storing all the comments/posts, every dirty checking would require scanning of this array, am I right? This would make the browser a bit laggy at times which is a bad user experience. What do you suggest we do in this case to ensure reasonable performance?

The statement could be easily said in reverse as "Dirty checking is a clever feature for a problem which knockout does not have". ES6 is using observables and angular is getting rid of dirty checking. The real world caught up to this answer and shown it to be false.

"Anything faster than 50 ms is imperceptible to humans" is not true. In testing we have found our customers can easily distinguish between 50ms update latency (20fps) and 16.6ms update latency (60fps). Scenes running at the former speed consistently get poorer overall "how did it feel" ratings even when people did not consciously register the framerate.

javascript - How does data binding work in AngularJS? - Stack Overflow

javascript angularjs data-binding
Rectangle 27 89

Other issues with URLs

There are many ways to format urls in Markdown. Parentheses work better with some methods than others.

  • Hyperlink - with parens

Note also that parenthetical sections in msdn links are optional, so:

See also The Problem With URLs for Jeff's blog post about coming up with a solution for Stack Overflow.

Sometimes URLs can fail to link correctly because they contain disallowed characters. In these cases encode the characters using the % notation. Previously characters such as () [] ' and * were not allowed but the server-side Markdown renderer has been modified to accept them now. Currently the only (known) characters that aren't accepted are ones with accents, graves, diaeresis etc. For example: or , although if it's a wikipedia link you can just use the unadorned character. (A suggestion to have these characters supported has been made on uservoice.)

Of course, the parentheticals are needed if you want to link to a page about an earlier release...

@NickChammas when you're commenting, click the help link to the right of the text box, that will show how to do links in comments.

@Sam - It's not clear from the help how to link to a URL with parentheses in a comment. Approaches 4, 7, and 8 above look like what I want (in-line linking of text to URL with parentheses), but none of them appear to work in comments.

http://hadoop.apache.org/docs/r2.3.0/api/org/apache/hadoop/mapreduce/lib/input/FileInputFormat.html#setInputPaths(org.apache.hadoop.mapreduce.Job, org.apache.hadoop.fs.Path...)

@NickChammas There's a "space" character in that URL. You need to encode it as "%20" thus: an example

[Android link](https://developer.android.com/reference/android/content/res/Resources.html#getColor%28int%29)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

support status-completed markdown hyperlinks
Rectangle 27 154

Security issues in similar approaches

This works similarly to the accepted answer, but is safe to use with untrusted user input.

As noted by Mike Samuel, doing this with a <div> instead of a <textarea> with untrusted user input is an XSS vulnerability, even if the <div> is never added to the DOM:

However, this attack is not possible against a <textarea> because there are no HTML elements that are permitted content of a <textarea>. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

// Safe, and returns the correct answer
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))

Doing this using jQuery's .html() and .val() methods instead of using .innerHTML and .value is also insecure* for some versions of jQuery, even when using a textarea. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to .html(). Hence code like this shows an alert in jQuery 1.8:

// Shows alert
$('<textarea>').html('<script>alert(1337)</script>').text()
decodedString = textArea.value;
textArea.remove();
return decodedString;
if ('remove' in Element.prototype) textArea.remove();

@Werner As soon as the function has exited, there will be no more variables holding a reference to it so it will be automatically removed by the garbage collector.

javascript - How to decode HTML entities using jQuery? - Stack Overflo...

javascript jquery html
Rectangle 27 153

Security issues in similar approaches

This works similarly to the accepted answer, but is safe to use with untrusted user input.

As noted by Mike Samuel, doing this with a <div> instead of a <textarea> with untrusted user input is an XSS vulnerability, even if the <div> is never added to the DOM:

However, this attack is not possible against a <textarea> because there are no HTML elements that are permitted content of a <textarea>. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

// Safe, and returns the correct answer
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))

Doing this using jQuery's .html() and .val() methods instead of using .innerHTML and .value is also insecure* for some versions of jQuery, even when using a textarea. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to .html(). Hence code like this shows an alert in jQuery 1.8:

// Shows alert
$('<textarea>').html('<script>alert(1337)</script>').text()
decodedString = textArea.value;
textArea.remove();
return decodedString;
if ('remove' in Element.prototype) textArea.remove();

@Werner As soon as the function has exited, there will be no more variables holding a reference to it so it will be automatically removed by the garbage collector.

javascript - How to decode HTML entities using jQuery? - Stack Overflo...

javascript jquery html
Rectangle 27 111

If You Still Have Issues/Questions:

Before I get to the "how it is done" part, here are some notes about my patch/hack/fix. Right from the start the major goals have been:

I was able to keep all those goals. Almost everything is done by creating symlinks. Only a single existing symlink had to be replaced and we'll back it up before replacement, just in case.

If you are no expert on terminal operations, I strongly advise you to copy/paste all terminal commands from my reply to your terminal, to avoid typos. Bear in mind that even spacing, quoting and especially capitalization can be important. Copy/paste them line by line, never more than one line at once and hit return after each pasted line to execute the command. Should any operation ever prompt you for a password, this will be the password of the currently logged in administrator user (your keystrokes are not displayed while typing, this is normal, don't worry, just keep typing the password and hit return; re-try if you had a typo and get prompted again).

Before we can start, make sure the following conditions are true:

  • You are logged in as an administrator user.
  • You have started Terminal.app (Applications/Utilities) and a terminal window is open.
  • You have a copy of the Xcode3 (e.g. 3.2.5) and Xcode4 disk image (DMG) or installer available.
  • If you already have either Xcode version installed, consider uninstalling it first, so you can start with a fresh/clean setup. Uninstalling Xcode will not remove your preferences, color scheme or key binding customizations. Ideally you'd start with a system that has no Xcode version (neither 3 nor 4) currently installed.

Important: Do not install "System Tools" or "Unix Development" package of Xcode3. Whether you want to install "Mac OS X 10.4 SDK" and/or "Documentation" is up to you. If that is a Xcode3 with iOS SDKs, whether you install those or not is also up to you.

You are free to choose any destination folder for your installation. For this guide I have chosen "/Xcode3", but feel free to pick a different one. Just make sure to alter all terminal commands accordingly.

The order of the steps given here is usually not really important, but I strongly advise you to not swap step 1 and step 2. Xcode always installs a couple of files outside of the chosen destination folder and trust me, in the end you want the Xcode4 versions of those files on your disk. By installing Xcode3 before Xcode4, you can be sure that Xcode4 will overwrite those files if necessary. I once swapped steps 1 and 2 and in the end I had some rather strange issues that might have been related to the incorrect order (I cannot say for sure, but after re-installing in the correct order the issues were gone).

Chose any packets you like. Installing "System Tools" is advisable, but not strictly necessary (though most people will sooner or later miss that functionality).

Again, feel free to pick any target folder you like. For this guide I chose the normal target folder "/Developer", if you take a different one, alter all terminal commands accordingly.

Switch to your terminal window and run the following commands:

Of course only run the command for 10.4u if you also installed SDK 10.4 in step 1.

This is enough to bring the SDKs 10.5 (and possibly 10.4) back to the selection list in Xcode4. Give it a try if you like. Fire up Xcode4, open a project, try changing the selected SDK. That was easy, huh? Be sure to close Xcode4 again (the application, not just the window) before proceeding with the next step.

If you have not installed MacOS 10.4 SDK or if you don't plan to ever use it, you can safely skip this step and proceed with step 5.

To use SDK 10.4, you'll have to use GCC 4.0, GCC 4.2 won't work. Apple claims that GCC 4.2 is not compatible with SDK 10.4, well, if you ask me, this is a hoax. I have already overwritten this limitations more than once and there was never the tiniest issue because of it. It would be easy to modify SDK 10.4 so that Xcode will allow you to use GCC 4.2 for it, but my goal was to avoid all file modifications, so we just add GCC 4.0 support back to Xcode, which is also a good thing, because some projects really depend on GCC 4.0 (e.g. there are some bugs in GCC 4.2 that prevent valid inline assembly code to compile without errors, while the same code compiles flawlessly on GCC 4.0 and GCC 4.4).

Right now we have restored full GCC 4.0 support except for the fact that GCC 4.0 is still not selectable in Xcode4. That is because Xcode4 has no GCC 4.0 compiler plug-in any longer. Fortunately the Xcode3 plug-in also works in Xcode4, only the position has radically changed. Apple now hides those plug-ins deep within a bundle and only plug-ins there seem to work, placing them to their old position seems to have no effect.

Now fire up Xcode4 again, open a project and try selecting the compiler. You should have GCC 4.0 back on the list. Now you can actually already select SDK 10.4 or 10.5, GCC 4.0 and you should have no issue to build a PPC binary. Just select "Other..." for the "Architecture" build setting and manually enter "ppc", then alter "Valid Architectures" to also include "ppc". We are almost done, except that trying to build a PPC binary using GCC 4.2 and SDK 10.5 will still fail.

Since Apple is only supporting Intel platforms in Xcode4, not all GCC 4.2 tools have been built with PPC support. There is one important tool that has no PPC support, the tool is named "as" and it is the GNU Assembler. To compile ppc/ppc64 binaries with GCC 4.2 we need to use an "as" version with ppc/ppc64 support. This is the one and only file (actually it also a symlink) we have to first move aside (making a backup copy) before we can replace it by a symlink:

That's all folks. Considering how easy that was, you can imagine that Apple has certainly not dropped SDK 10.4/10.5 or ppc/ppc64 or GCC 4.0 support because this was a necessity, they dropped all that because they wanted to drop it.

I hope this setup works as well for you as it does for me. I have been able to compile all my old projects in Xcode4 without any major changes, except for having to alter a search path here and there.

PS: It may look strange that I answer my own question here, but since I have found out how to solve this problem all by myself, I'd like to share my knowledge with the community, because I believe this is really valuable input to all MacOS developers out there. This question has been asked so many times in so many places and so far I have never seen anyone coming up with a similar fix. Share the wealth, spread the knowledge and so on, you know what I mean.

If you have additional questions regarding this topic or if you still have problems to build your old projects correctly, please do what Stack Overflow has been designed for: Click on "Ask Question" in the upper right corner of this page and create a new question. That way the whole community can help you solving those issues, since the issues may not directly (maybe not even indirectly) be related to this hack.

I would recommend you mention the fact that you did apply this hack at the very beginning of your question. Maybe you even want to directly link to this question, so that people, who never heard of this hack, can easily look it up. Otherwise most people will get rather confused when you mention SDK 10.4/10.5, PPC or GCC 4.0 in combination with Xcode4, which officially supports neither of these. You might get rather stupid comments instead of decent replies if you forget to mention this hack.

Please refrain from posting your questions or issues here either as replies or as comments. Posting them as replies makes no sense because they are no replies and there is no way how people can reply back to you, other then using comments, and comments may not offer enough room for a decent reply to your question or a decent solution to your problem. And posting them as comments means you are limited to very little room and tracking reply comments will be hard as comments have no tree-like hierarchy (further they will still offer to little room for decent replies/solutions). Thank you.

Of course other kind of comments as well as better replies to the original question are always welcome ;-)

Here's an upvote. I'll probably copy the old SDKs and compiler files instead of just symlinking them in order to be able to uninstall rest of Xcode3. Not because I love Xcode4; solely because I need the disk space. Thanks!

for SRC_FILE in /Xcode3/usr/bin/*4.0*; do sudo ln -s "$SRC_FILE" .; done
sudo ln -s /Xcode3/usr/bin/*4.0* .

@cullub Go to developer.apple.com, log in with your dev ID, choose "SDKs", scroll down and choose "Xcode", choose "Download", scroll down and choose "Additional Tools", search for "Xcode 3" in the search field.

xcode4 - How can we restore ppc/ppc64 as well as full 10.4/10.5 SDK su...

xcode xcode4 universal-binary osx-leopard ppc
Rectangle 27 111

If You Still Have Issues/Questions:

Before I get to the "how it is done" part, here are some notes about my patch/hack/fix. Right from the start the major goals have been:

I was able to keep all those goals. Almost everything is done by creating symlinks. Only a single existing symlink had to be replaced and we'll back it up before replacement, just in case.

If you are no expert on terminal operations, I strongly advise you to copy/paste all terminal commands from my reply to your terminal, to avoid typos. Bear in mind that even spacing, quoting and especially capitalization can be important. Copy/paste them line by line, never more than one line at once and hit return after each pasted line to execute the command. Should any operation ever prompt you for a password, this will be the password of the currently logged in administrator user (your keystrokes are not displayed while typing, this is normal, don't worry, just keep typing the password and hit return; re-try if you had a typo and get prompted again).

Before we can start, make sure the following conditions are true:

  • You are logged in as an administrator user.
  • You have started Terminal.app (Applications/Utilities) and a terminal window is open.
  • You have a copy of the Xcode3 (e.g. 3.2.5) and Xcode4 disk image (DMG) or installer available.
  • If you already have either Xcode version installed, consider uninstalling it first, so you can start with a fresh/clean setup. Uninstalling Xcode will not remove your preferences, color scheme or key binding customizations. Ideally you'd start with a system that has no Xcode version (neither 3 nor 4) currently installed.

Important: Do not install "System Tools" or "Unix Development" package of Xcode3. Whether you want to install "Mac OS X 10.4 SDK" and/or "Documentation" is up to you. If that is a Xcode3 with iOS SDKs, whether you install those or not is also up to you.

You are free to choose any destination folder for your installation. For this guide I have chosen "/Xcode3", but feel free to pick a different one. Just make sure to alter all terminal commands accordingly.

The order of the steps given here is usually not really important, but I strongly advise you to not swap step 1 and step 2. Xcode always installs a couple of files outside of the chosen destination folder and trust me, in the end you want the Xcode4 versions of those files on your disk. By installing Xcode3 before Xcode4, you can be sure that Xcode4 will overwrite those files if necessary. I once swapped steps 1 and 2 and in the end I had some rather strange issues that might have been related to the incorrect order (I cannot say for sure, but after re-installing in the correct order the issues were gone).

Chose any packets you like. Installing "System Tools" is advisable, but not strictly necessary (though most people will sooner or later miss that functionality).

Again, feel free to pick any target folder you like. For this guide I chose the normal target folder "/Developer", if you take a different one, alter all terminal commands accordingly.

Switch to your terminal window and run the following commands:

Of course only run the command for 10.4u if you also installed SDK 10.4 in step 1.

This is enough to bring the SDKs 10.5 (and possibly 10.4) back to the selection list in Xcode4. Give it a try if you like. Fire up Xcode4, open a project, try changing the selected SDK. That was easy, huh? Be sure to close Xcode4 again (the application, not just the window) before proceeding with the next step.

If you have not installed MacOS 10.4 SDK or if you don't plan to ever use it, you can safely skip this step and proceed with step 5.

To use SDK 10.4, you'll have to use GCC 4.0, GCC 4.2 won't work. Apple claims that GCC 4.2 is not compatible with SDK 10.4, well, if you ask me, this is a hoax. I have already overwritten this limitations more than once and there was never the tiniest issue because of it. It would be easy to modify SDK 10.4 so that Xcode will allow you to use GCC 4.2 for it, but my goal was to avoid all file modifications, so we just add GCC 4.0 support back to Xcode, which is also a good thing, because some projects really depend on GCC 4.0 (e.g. there are some bugs in GCC 4.2 that prevent valid inline assembly code to compile without errors, while the same code compiles flawlessly on GCC 4.0 and GCC 4.4).

Right now we have restored full GCC 4.0 support except for the fact that GCC 4.0 is still not selectable in Xcode4. That is because Xcode4 has no GCC 4.0 compiler plug-in any longer. Fortunately the Xcode3 plug-in also works in Xcode4, only the position has radically changed. Apple now hides those plug-ins deep within a bundle and only plug-ins there seem to work, placing them to their old position seems to have no effect.

Now fire up Xcode4 again, open a project and try selecting the compiler. You should have GCC 4.0 back on the list. Now you can actually already select SDK 10.4 or 10.5, GCC 4.0 and you should have no issue to build a PPC binary. Just select "Other..." for the "Architecture" build setting and manually enter "ppc", then alter "Valid Architectures" to also include "ppc". We are almost done, except that trying to build a PPC binary using GCC 4.2 and SDK 10.5 will still fail.

Since Apple is only supporting Intel platforms in Xcode4, not all GCC 4.2 tools have been built with PPC support. There is one important tool that has no PPC support, the tool is named "as" and it is the GNU Assembler. To compile ppc/ppc64 binaries with GCC 4.2 we need to use an "as" version with ppc/ppc64 support. This is the one and only file (actually it also a symlink) we have to first move aside (making a backup copy) before we can replace it by a symlink:

That's all folks. Considering how easy that was, you can imagine that Apple has certainly not dropped SDK 10.4/10.5 or ppc/ppc64 or GCC 4.0 support because this was a necessity, they dropped all that because they wanted to drop it.

I hope this setup works as well for you as it does for me. I have been able to compile all my old projects in Xcode4 without any major changes, except for having to alter a search path here and there.

PS: It may look strange that I answer my own question here, but since I have found out how to solve this problem all by myself, I'd like to share my knowledge with the community, because I believe this is really valuable input to all MacOS developers out there. This question has been asked so many times in so many places and so far I have never seen anyone coming up with a similar fix. Share the wealth, spread the knowledge and so on, you know what I mean.

If you have additional questions regarding this topic or if you still have problems to build your old projects correctly, please do what Stack Overflow has been designed for: Click on "Ask Question" in the upper right corner of this page and create a new question. That way the whole community can help you solving those issues, since the issues may not directly (maybe not even indirectly) be related to this hack.

I would recommend you mention the fact that you did apply this hack at the very beginning of your question. Maybe you even want to directly link to this question, so that people, who never heard of this hack, can easily look it up. Otherwise most people will get rather confused when you mention SDK 10.4/10.5, PPC or GCC 4.0 in combination with Xcode4, which officially supports neither of these. You might get rather stupid comments instead of decent replies if you forget to mention this hack.

Please refrain from posting your questions or issues here either as replies or as comments. Posting them as replies makes no sense because they are no replies and there is no way how people can reply back to you, other then using comments, and comments may not offer enough room for a decent reply to your question or a decent solution to your problem. And posting them as comments means you are limited to very little room and tracking reply comments will be hard as comments have no tree-like hierarchy (further they will still offer to little room for decent replies/solutions). Thank you.

Of course other kind of comments as well as better replies to the original question are always welcome ;-)

Here's an upvote. I'll probably copy the old SDKs and compiler files instead of just symlinking them in order to be able to uninstall rest of Xcode3. Not because I love Xcode4; solely because I need the disk space. Thanks!

for SRC_FILE in /Xcode3/usr/bin/*4.0*; do sudo ln -s "$SRC_FILE" .; done
sudo ln -s /Xcode3/usr/bin/*4.0* .

@cullub Go to developer.apple.com, log in with your dev ID, choose "SDKs", scroll down and choose "Xcode", choose "Download", scroll down and choose "Additional Tools", search for "Xcode 3" in the search field.

xcode4 - How can we restore ppc/ppc64 as well as full 10.4/10.5 SDK su...

xcode xcode4 universal-binary osx-leopard ppc
Rectangle 27 111

If You Still Have Issues/Questions:

Before I get to the "how it is done" part, here are some notes about my patch/hack/fix. Right from the start the major goals have been:

I was able to keep all those goals. Almost everything is done by creating symlinks. Only a single existing symlink had to be replaced and we'll back it up before replacement, just in case.

If you are no expert on terminal operations, I strongly advise you to copy/paste all terminal commands from my reply to your terminal, to avoid typos. Bear in mind that even spacing, quoting and especially capitalization can be important. Copy/paste them line by line, never more than one line at once and hit return after each pasted line to execute the command. Should any operation ever prompt you for a password, this will be the password of the currently logged in administrator user (your keystrokes are not displayed while typing, this is normal, don't worry, just keep typing the password and hit return; re-try if you had a typo and get prompted again).

Before we can start, make sure the following conditions are true:

  • You are logged in as an administrator user.
  • You have started Terminal.app (Applications/Utilities) and a terminal window is open.
  • You have a copy of the Xcode3 (e.g. 3.2.5) and Xcode4 disk image (DMG) or installer available.
  • If you already have either Xcode version installed, consider uninstalling it first, so you can start with a fresh/clean setup. Uninstalling Xcode will not remove your preferences, color scheme or key binding customizations. Ideally you'd start with a system that has no Xcode version (neither 3 nor 4) currently installed.

Important: Do not install "System Tools" or "Unix Development" package of Xcode3. Whether you want to install "Mac OS X 10.4 SDK" and/or "Documentation" is up to you. If that is a Xcode3 with iOS SDKs, whether you install those or not is also up to you.

You are free to choose any destination folder for your installation. For this guide I have chosen "/Xcode3", but feel free to pick a different one. Just make sure to alter all terminal commands accordingly.

The order of the steps given here is usually not really important, but I strongly advise you to not swap step 1 and step 2. Xcode always installs a couple of files outside of the chosen destination folder and trust me, in the end you want the Xcode4 versions of those files on your disk. By installing Xcode3 before Xcode4, you can be sure that Xcode4 will overwrite those files if necessary. I once swapped steps 1 and 2 and in the end I had some rather strange issues that might have been related to the incorrect order (I cannot say for sure, but after re-installing in the correct order the issues were gone).

Chose any packets you like. Installing "System Tools" is advisable, but not strictly necessary (though most people will sooner or later miss that functionality).

Again, feel free to pick any target folder you like. For this guide I chose the normal target folder "/Developer", if you take a different one, alter all terminal commands accordingly.

Switch to your terminal window and run the following commands:

Of course only run the command for 10.4u if you also installed SDK 10.4 in step 1.

This is enough to bring the SDKs 10.5 (and possibly 10.4) back to the selection list in Xcode4. Give it a try if you like. Fire up Xcode4, open a project, try changing the selected SDK. That was easy, huh? Be sure to close Xcode4 again (the application, not just the window) before proceeding with the next step.

If you have not installed MacOS 10.4 SDK or if you don't plan to ever use it, you can safely skip this step and proceed with step 5.

To use SDK 10.4, you'll have to use GCC 4.0, GCC 4.2 won't work. Apple claims that GCC 4.2 is not compatible with SDK 10.4, well, if you ask me, this is a hoax. I have already overwritten this limitations more than once and there was never the tiniest issue because of it. It would be easy to modify SDK 10.4 so that Xcode will allow you to use GCC 4.2 for it, but my goal was to avoid all file modifications, so we just add GCC 4.0 support back to Xcode, which is also a good thing, because some projects really depend on GCC 4.0 (e.g. there are some bugs in GCC 4.2 that prevent valid inline assembly code to compile without errors, while the same code compiles flawlessly on GCC 4.0 and GCC 4.4).

Right now we have restored full GCC 4.0 support except for the fact that GCC 4.0 is still not selectable in Xcode4. That is because Xcode4 has no GCC 4.0 compiler plug-in any longer. Fortunately the Xcode3 plug-in also works in Xcode4, only the position has radically changed. Apple now hides those plug-ins deep within a bundle and only plug-ins there seem to work, placing them to their old position seems to have no effect.

Now fire up Xcode4 again, open a project and try selecting the compiler. You should have GCC 4.0 back on the list. Now you can actually already select SDK 10.4 or 10.5, GCC 4.0 and you should have no issue to build a PPC binary. Just select "Other..." for the "Architecture" build setting and manually enter "ppc", then alter "Valid Architectures" to also include "ppc". We are almost done, except that trying to build a PPC binary using GCC 4.2 and SDK 10.5 will still fail.

Since Apple is only supporting Intel platforms in Xcode4, not all GCC 4.2 tools have been built with PPC support. There is one important tool that has no PPC support, the tool is named "as" and it is the GNU Assembler. To compile ppc/ppc64 binaries with GCC 4.2 we need to use an "as" version with ppc/ppc64 support. This is the one and only file (actually it also a symlink) we have to first move aside (making a backup copy) before we can replace it by a symlink:

That's all folks. Considering how easy that was, you can imagine that Apple has certainly not dropped SDK 10.4/10.5 or ppc/ppc64 or GCC 4.0 support because this was a necessity, they dropped all that because they wanted to drop it.

I hope this setup works as well for you as it does for me. I have been able to compile all my old projects in Xcode4 without any major changes, except for having to alter a search path here and there.

PS: It may look strange that I answer my own question here, but since I have found out how to solve this problem all by myself, I'd like to share my knowledge with the community, because I believe this is really valuable input to all MacOS developers out there. This question has been asked so many times in so many places and so far I have never seen anyone coming up with a similar fix. Share the wealth, spread the knowledge and so on, you know what I mean.

If you have additional questions regarding this topic or if you still have problems to build your old projects correctly, please do what Stack Overflow has been designed for: Click on "Ask Question" in the upper right corner of this page and create a new question. That way the whole community can help you solving those issues, since the issues may not directly (maybe not even indirectly) be related to this hack.

I would recommend you mention the fact that you did apply this hack at the very beginning of your question. Maybe you even want to directly link to this question, so that people, who never heard of this hack, can easily look it up. Otherwise most people will get rather confused when you mention SDK 10.4/10.5, PPC or GCC 4.0 in combination with Xcode4, which officially supports neither of these. You might get rather stupid comments instead of decent replies if you forget to mention this hack.

Please refrain from posting your questions or issues here either as replies or as comments. Posting them as replies makes no sense because they are no replies and there is no way how people can reply back to you, other then using comments, and comments may not offer enough room for a decent reply to your question or a decent solution to your problem. And posting them as comments means you are limited to very little room and tracking reply comments will be hard as comments have no tree-like hierarchy (further they will still offer to little room for decent replies/solutions). Thank you.

Of course other kind of comments as well as better replies to the original question are always welcome ;-)

Here's an upvote. I'll probably copy the old SDKs and compiler files instead of just symlinking them in order to be able to uninstall rest of Xcode3. Not because I love Xcode4; solely because I need the disk space. Thanks!

for SRC_FILE in /Xcode3/usr/bin/*4.0*; do sudo ln -s "$SRC_FILE" .; done
sudo ln -s /Xcode3/usr/bin/*4.0* .

@cullub Go to developer.apple.com, log in with your dev ID, choose "SDKs", scroll down and choose "Xcode", choose "Download", scroll down and choose "Additional Tools", search for "Xcode 3" in the search field.

xcode4 - How can we restore ppc/ppc64 as well as full 10.4/10.5 SDK su...

xcode xcode4 universal-binary osx-leopard ppc
Rectangle 27 49

Using StringTokenizer(For avoiding regular expression issues)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]
splitUsingTokenizer("Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ", "|")

java - Splitting string with pipe character ("|") - Stack Overflow

java regex
Rectangle 27 46

Using StringTokenizer(For avoiding regular expression issues)

String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters) 
{
     StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
     ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
     while(StrTkn.hasMoreTokens())
     {
       ArrLis.add(StrTkn.nextToken());
     }
     return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 ,  Service 3 ,  Atmosphere 3 ,  Value for money 1 ]
splitUsingTokenizer("Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ", "|")

java - Splitting string with pipe character ("|") - Stack Overflow

java regex
Rectangle 27 6

If there are additional issues

Before you do anything complicated, this might be a simple problem. Just unplug and plug back in.

And make sure that you either default to the USB device or the chooser dialog if you are going to be switching between devices on your emulator as well.

Android Studio doesn't see device - Stack Overflow

android android-studio adb device avd
Rectangle 27 6

Some issues in your code

(For a full Promise implementation, scroll down).

The are several issues, but I think the main mistake in your code is that you take the argument given to the then method and pass it as argument to a new promise:

this.then=function(resolve,reject) {
    var nextPromise=new Aaa(resolve,true);
    // ...

Although both arguments are call back functions, they have a different signature, and serve entirely different purposes:

  • The argument to the promise constructor is a call back function which is to be executed immediately, synchronously. A function is passed to it as first argument, with which you can resolve the promise you are creating.
  • The (first) argument to the the then method, is a call back function which will only get executed later, asynchronously, when the base promise is resolved, and to which the resolved value is passed as argument.

You can see the difference also in your code, where you store the argument to the constructor as the f property. You have both this:

t.thens[i].f(g);

...where g is the resolved value, but also this:

this.f(this.resolve,this.reject);

...where the arguments are functions. When you create the nextPromise you will in fact first call f with these two arguments, and then later, with the g argument.

We could build our own Promise implementation by following the requirements in the Promises/A+ specification:

There are only 2 state transitions allowed: from pending to fulfilled, and from pending to rejected. No other transition should be possible, and once a transition has been performed, the promise value (or rejection reason) should not change.

Here is a simple implementation that will adhere to the above restrictions. The comments reference the numbered requirements in the above specification:

Of course, this does not provide the then method, which is key to Promises:

This is the core of the specification. The above code can be extended to expose the then method, which returns a promise and provides asynchronous execution of the appropriate then callback, only once, providing for multiple then calls, turning exceptions to rejections, ...etc.

So the following code adds the then method, but also a broadcast function which is defined separately, because it must be called on any state change: this does not only include the effect of the then method (a promise is added to a list), but also of the resolve and reject methods (state and value change).

This covers almost everything, except that at the TODO: comment, the so-called Promise Resolution Procedure must be called:

This is a procedure that treats values that are thenables (or even promises) differently: instead of returning the value as-is, the procedure will execute the then method on that value and asynchronously fulfills the promise with the value received from that then callback. It is not mentioned in the specs, but this is interesting to perform not only in the then method, but also when the main promise is resolved with such a value.

So the existing resolve method should be replaced with this "Promise Resolution Procedure", which will call the original one. The original one could be called "fulfill", to indicate it will resolve the promise always as fulfilled:

function MyPromise(executor) {
    this.state = 'pending';
    this.value = undefined;
    // A list of "clients" that need to be notified when a state
    //   change event occurs. These event-consumers are the promises
    //   that are returned by the calls to the `then` method.
    this.consumers = [];
    executor(this.resolve.bind(this), this.reject.bind(this));
}

// 2.1.1.1: provide only two ways to transition
MyPromise.prototype.fulfill = function (value) {
    if (this.state !== 'pending') return; // 2.1.2.1, 2.1.3.1: cannot transition anymore
    this.state = 'fulfilled'; // 2.1.1.1: can transition
    this.value = value; // 2.1.2.2: must have a value
    this.broadcast();
}    

MyPromise.prototype.reject = function (reason) {
    if (this.state !== 'pending') return; // 2.1.2.1, 2.1.3.1: cannot transition anymore
    this.state = 'rejected'; // 2.1.1.1: can transition
    this.value = reason; // 2.1.3.2: must have a reason
    this.broadcast();
}    

// A promises then method accepts two arguments:
MyPromise.prototype.then = function(onFulfilled, onRejected) {
    var consumer = new MyPromise(function () {});
    // 2.2.1.1 ignore onFulfilled if not a function
    consumer.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
    // 2.2.1.2 ignore onRejected if not a function
    consumer.onRejected = typeof onRejected === 'function' ? onRejected : null;
    // 2.2.6.1, 2.2.6.2: .then() may be called multiple times on the same promise
    this.consumers.push(consumer);
    // It might be that the promise was already resolved... 
    this.broadcast();
    // 2.2.7: .then() must return a promise
    return consumer;
};

MyPromise.prototype.broadcast = function() {
    var promise = this;
    // 2.2.2.1, 2.2.2.2, 2.2.3.1, 2.2.3.2 called after promise is resolved
    if (this.state === 'pending') return;
    // 2.2.6.1, 2.2.6.2 all respective callbacks must execute
    var callbackName = this.state == 'fulfilled' ? 'onFulfilled' : 'onRejected';
    var resolver = this.state == 'fulfilled' ? 'resolve' : 'reject';
    // 2.2.4 onFulfilled/onRejected must be called asynchronously
    setTimeout(function() {
        // 2.2.6.1, 2.2.6.2 traverse in order, 2.2.2.3, 2.2.3.3 called only once
        promise.consumers.splice(0).forEach(function(consumer) {
            try {
                var callback = consumer[callbackName];
                // 2.2.1.1, 2.2.1.2 ignore callback if not a function, else
                // 2.2.5 call callback as plain function without context
                if (callback) {
                    // 2.2.7.1. execute the Promise Resolution Procedure:
                    consumer.resolve(callback(promise.value)); 
                } else {
                    // 2.2.7.3 resolve in same way as current promise
                    consumer[resolver](promise.value);
                }
            } catch (e) {
                // 2.2.7.2
                consumer.reject(e);
            };
        })
    });
};

// The Promise Resolution Procedure: will treat values that are thenables/promises
// and will eventually call either fulfill or reject/throw.
MyPromise.prototype.resolve = function(x) {
    var wasCalled, then;
    // 2.3.1
    if (this === x) {
        throw new TypeError('Circular reference: promise value is promise itself');
    }
    // 2.3.2
    if (x instanceof MyPromise) {
        // 2.3.2.1, 2.3.2.2, 2.3.2.3
        x.then(this.resolve.bind(this), this.reject.bind(this));
    } else if (x === Object(x)) { // 2.3.3
        try {
            // 2.3.3.1
            then = x.then;
            if (typeof then === 'function') {
                // 2.3.3.3
                then.call(x, function resolve(y) {
                    // 2.3.3.3.3 don't allow multiple calls
                    if (wasCalled) return;
                    wasCalled = true;
                    // 2.3.3.3.1 recurse
                    this.resolve(y);
                }.bind(this), function reject(reasonY) {
                    // 2.3.3.3.3 don't allow multiple calls
                    if (wasCalled) return;
                    wasCalled = true;
                    // 2.3.3.3.2
                    this.reject(reasonY);
                }.bind(this));
            } else {
                // 2.3.3.4
                this.fulfill(x);
            }
        } catch(e) {
            // 2.3.3.3.4.1 ignore if call was made
            if (wasCalled) return;
            // 2.3.3.2 or 2.3.3.3.4.2
            this.reject(e);
        }
    } else {
        // 2.3.4
        this.fulfill(x);
    }
}

This is now Promises/A+ compliant, at least it passes the test-suite. Yet, the Promise object exposes far too many methods and properties:

The above built constructor creates something that is more like a Deferred object, i.e. which exposes resolve and reject methods. Even worse, the status and value properties are writable. So, it would be more logical to regard this as a constructor for an unsecured Deferred object, and create a separate Promise constructor which builds on that, but only exposes what is needed: a then method and a constructor callback that can access resolve and reject.

The deferred object can then do without the constructor callback argument, and provide access to the pure promise object via a promise property:

function Deferred() {
    this.state = 'pending';
    this.value = undefined;
    this.consumers = [];
    this.promise = Object.create(MyPromise.prototype, {
        then: { value: this.then.bind(this) }
    });
}

// 2.1.1.1: provide only two ways to transition
Deferred.prototype.fulfill = function (value) {
    if (this.state !== 'pending') return; // 2.1.2.1, 2.1.3.1: cannot transition anymore
    this.state = 'fulfilled'; // 2.1.1.1: can transition
    this.value = value; // 2.1.2.2: must have a value
    this.broadcast();
}    

Deferred.prototype.reject = function (reason) {
    if (this.state !== 'pending') return; // 2.1.2.1, 2.1.3.1: cannot transition anymore
    this.state = 'rejected'; // 2.1.1.1: can transition
    this.value = reason; // 2.1.3.2: must have a reason
    this.broadcast();
}    

// A promises then method accepts two arguments:
Deferred.prototype.then = function(onFulfilled, onRejected) {
    var consumer = new Deferred();
    // 2.2.1.1 ignore onFulfilled if not a function
    consumer.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
    // 2.2.1.2 ignore onRejected if not a function
    consumer.onRejected = typeof onRejected === 'function' ? onRejected : null;
    // 2.2.6.1, 2.2.6.2: .then() may be called multiple times on the same promise
    this.consumers.push(consumer);
    // It might be that the promise was already resolved... 
    this.broadcast();
    // 2.2.7: .then() must return a promise
    return consumer;
};

Deferred.prototype.broadcast = function() {
    var promise = this;
    // 2.2.2.1, 2.2.2.2, 2.2.3.1, 2.2.3.2 called after promise is resolved
    if (this.state === 'pending') return;
    // 2.2.6.1, 2.2.6.2 all respective callbacks must execute
    var callbackName = this.state == 'fulfilled' ? 'onFulfilled' : 'onRejected';
    var resolver = this.state == 'fulfilled' ? 'resolve' : 'reject';
    // 2.2.4 onFulfilled/onRejected must be called asynchronously
    setTimeout(function() {
        // 2.2.6.1, 2.2.6.2 traverse in order, 2.2.2.3, 2.2.3.3 called only once
        promise.consumers.splice(0).forEach(function(consumer) {
            try {
                var callback = consumer[callbackName];
                // 2.2.1.1, 2.2.1.2 ignore callback if not a function, else
                // 2.2.5 call callback as plain function without context
                if (callback) {
                    // 2.2.7.1. execute the Promise Resolution Procedure:
                    consumer.resolve(callback(promise.value)); 
                } else {
                    // 2.2.7.3 resolve in same way as current promise
                    consumer[resolver](promise.value);
                }
            } catch (e) {
                // 2.2.7.2
                consumer.reject(e);
            };
        })
    });
};

// The Promise Resolution Procedure: will treat values that are thenables/promises
// and will eventually call either fulfill or reject/throw.
Deferred.prototype.resolve = function(x) {
    var wasCalled, then;
    // 2.3.1
    if (this.promise === x) {
        throw new TypeError('Circular reference: promise value is promise itself');
    }
    // 2.3.2
    if (x instanceof MyPromise) {
        // 2.3.2.1, 2.3.2.2, 2.3.2.3
        x.then(this.resolve.bind(this), this.reject.bind(this));
    } else if (x === Object(x)) { // 2.3.3
        try {
            // 2.3.3.1
            then = x.then;
            if (typeof then === 'function') {
                // 2.3.3.3
                then.call(x, function resolve(y) {
                    // 2.3.3.3.3 don't allow multiple calls
                    if (wasCalled) return;
                    wasCalled = true;
                    // 2.3.3.3.1 recurse
                    this.resolve(y);
                }.bind(this), function reject(reasonY) {
                    // 2.3.3.3.3 don't allow multiple calls
                    if (wasCalled) return;
                    wasCalled = true;
                    // 2.3.3.3.2
                    this.reject(reasonY);
                }.bind(this));
            } else {
                // 2.3.3.4
                this.fulfill(x);
            }
        } catch(e) {
            // 2.3.3.3.4.1 ignore if call was made
            if (wasCalled) return;
            // 2.3.3.2 or 2.3.3.3.4.2
            this.reject(e);
        }
    } else {
        // 2.3.4
        this.fulfill(x);
    }
}

function MyPromise(executor) {
    // A Promise is just a wrapper around a Deferred, exposing only the `then`
    // method, while `resolve` and `reject` are available in the constructor callback
    var df = new Deferred();
    // Provide access to the `resolve` and `reject` methods via the callback
    executor(df.resolve.bind(df), df.reject.bind(df));
    return df.promise;
}

There are several optimisations possible to this code, such as making Deferred methods private functions, and merging similar code into shorter code blocks, but as it stands now it shows quite clearly where each requirement is covered.

The best explanation of promise implementation that I've seen so far.

Basic Javascript promise implementation attempt - Stack Overflow

javascript promise
Rectangle 27 3

There are 3 issues here:

This is an old question, but I was not happy with any of the answers.

  • Extracting the hours, minutes and seconds from a duration in seconds
  • Formatting the numbers to have 2 digits

As the desired answer is in seconds, minutes and hours, the first step is to convert the "tick" value to seconds.

seconds = ticks / tickspersecond

For example, if the ticks were in milliseconds, then the conversion would be

seconds = ticks / 1000
hour = seconds / secondsperhour
hour = seconds / 3600
minute = seconds / secondsperminute modulus minutesperhour
minute = (seconds / 60) % 60)
second = seconds modulus secondsperminute
second = seconds % 60
  • There are a number of ways to format leading zeros on numbers, this one will use a simple function specific to this example (max of 2 digits).
function pad2(number){
   number = '0' + number;
   return number.substr(number.length - 2);
}

Note: Due to floating point errors, you need to apply Math.floor to both the hour and minute values. You could put Math.floor into the pad2 function if you want to shorten the main code.

// Assume milliseconds for now
var seconds = ticks / 1000; 
var hour = Math.floor(seconds / 3600);
var minute = Math.floor((seconds / 60) % 60);
var second = seconds % 60;

var result = pad2(hour) + ':' + pad2(minute) + ':' + pad2(second)

Note: For the sake of the demo I added % 24 (modulus hoursperday) to the hours display as the hours since 1971 is a "big" number - so will not format to 2 decimal places :)

Math.floor
pad2

javascript - Convert ticks to time format (hh:mm:ss) - Stack Overflow

javascript html time
Rectangle 27 3

There are 3 issues here:

This is an old question, but I was not happy with any of the answers.

  • Extracting the hours, minutes and seconds from a duration in seconds
  • Formatting the numbers to have 2 digits

As the desired answer is in seconds, minutes and hours, the first step is to convert the "tick" value to seconds.

seconds = ticks / tickspersecond

For example, if the ticks were in milliseconds, then the conversion would be

seconds = ticks / 1000
hour = seconds / secondsperhour
hour = seconds / 3600
minute = seconds / secondsperminute modulus minutesperhour
minute = (seconds / 60) % 60)
second = seconds modulus secondsperminute
second = seconds % 60
  • There are a number of ways to format leading zeros on numbers, this one will use a simple function specific to this example (max of 2 digits).
function pad2(number){
   number = '0' + number;
   return number.substr(number.length - 2);
}

Note: Due to floating point errors, you need to apply Math.floor to both the hour and minute values. You could put Math.floor into the pad2 function if you want to shorten the main code.

// Assume milliseconds for now
var seconds = ticks / 1000; 
var hour = Math.floor(seconds / 3600);
var minute = Math.floor((seconds / 60) % 60);
var second = seconds % 60;

var result = pad2(hour) + ':' + pad2(minute) + ':' + pad2(second)

Note: For the sake of the demo I added % 24 (modulus hoursperday) to the hours display as the hours since 1971 is a "big" number - so will not format to 2 decimal places :)

Math.floor
pad2

javascript - Convert ticks to time format (hh:mm:ss) - Stack Overflow

javascript html time
Rectangle 27 3

I'm sort of a noob and don't fully understand your problem, but maybe this simple solution will help you. I'm using jQuery UI Tabs and Galleria 1.2 beta as well (though not iframes) and had the same problem with my galleries not loading properly in inactive tabs. According to the jQuery UI Tabs documentation:

Why does my slider, Google Map, sIFR etc. not work when placed in a hidden (inactive) tab?

Any component that requires some dimensional computation for its initialization won't work in a hidden tab, because the tab panel itself is hidden via display: none so that any elements inside won't report their actual width and height (0 in most browsers).

There's an easy workaround. Use the off-left technique for hiding inactive tab panels. E.g. in your style sheet replace the rule for the class selector ".ui-tabs .ui-tabs-hide" with

.ui-tabs .ui-tabs-hide {
    position: absolute;
    left: -10000px;
}

ajax - Issues loading Jquery (Galleria) script from inside an i-frame ...

jquery ajax iframe jquery-ui-tabs galleria
Rectangle 27 22

Chrome Fixed the security issues on version 36.0.1985.125

From my observation, this update fixed the issue on using window.close() to close the popup window. You will see this in the console when it fail, "Scripts may close only the windows that were opened by it.". That means The hacky workarounds (Brock Adams's answer) may not work in the latest release.

So, in the previous Chrome released builds, the below code block may worked but not with this update.

window.open('', '_self', '');
window.close();

For this update, you have to update your code accordingly to close the popup window. One of the solution is to grab the popup window id and use

chrome.windows.remove(integer windowId, function callback)

Actually my chrome extension MarkView was facing this issue and I had to update my code to make it work for this Chrome Update. By the way, MarkView is tool to read and write Awesome Markdown Files, it provides features including Content Outline, Sortable Tables and code block syntax highlight with line number.

The correct hack is open(location, '_self').close(); -- note the use of the return value from open(). This still works on Chrome 36.0.1985.125 m

In my case, I just test again with open(location, '_self').close();, I got "Unauthorized" error on this. This error is different with 'window.close()(warning on this"Scripts may close only the windows that were opened by it."). It looked like open(location, '_self').close();` moved forward a little bit, but it can't complete in my case. Thanks @brock-adams for the comment.

I have typescript and when i put chrome.windows.remove it says could not find symbol chrome. how can i resolve this? do i need to add some sort of reference?

@devt chrome.windows.remove is Chrome extension API, your javascript should be recognized by your chrome extension program. You can try it inside background.js, in your chrome extension manifest.json you need to have: "background": { "scripts": ["background.js"], ... },

I had removed MarkView login function for users to access freely. So the example I mentioned in above is not available now.

javascript - window.close and self.close do not close the window in Ch...

javascript google-chrome greasemonkey tampermonkey
Rectangle 27 21

Issues with Swift/C# structs solved with Go pointers

Pointers are usefull for several reasons. Pointers allow control over memory layout (affects efficiency of CPU cache). In Go we can define a structure where all the members are in contiguous memory:

type Point struct {
  x, y int
}

type LineSegment struct {
  source, destination Point
}

In this case the Point structures are embedded within the LineSegment struct. But you can't always embed data directly. If you want to support structures such as binary trees or linked list, then you need to support some kind of pointer.

Java, Python etc doesn't have this problem because it does not allow you to embed composite types, so there is no need to syntactically differentiate between embedding and pointing.

A possible alternative to accomplish the same is to differentiate between struct and class as C# and Swift does. But this does have limitations. While you can usually specify that a function takes a struct as an inout parameter to avoid copying the struct, it doesn't allow you to store references (pointers) to structs. This means you can never treat a struct as a reference type when you find that useful e.g. to create a pool allocator (see below).

Using pointers you can also create your own pool allocator (this is very simplified with lots of checks removed to just show the principle):

type TreeNode {
  value int
  left  *TreeNode
  right *TreeNode

  nextFreeNode *TreeNode; // For memory allocation
}

var pool [1024]TreeNode
var firstFreeNode *TreeNode = &pool[0] 

func poolAlloc() *TreeNode {
    node := firstFreeNode
    firstFreeNode  = firstFreeNode.nextFreeNode
    return node
}

func freeNode(node *TreeNode) {
    node.nextFreeNode = firstFreeNode
    firstFreeNode = node
}

Pointers also allows you to implement swap. That is swapping the values of two variables:

func swap(a *int, b *int) {
   temp := *a
   *a = *b
   *b = temp
}

Java has never been able to fully replace C++ for systems programming at places such as Google, in part because performance can not be tuned to the same extend due to the lack of ability to control memory layout and usage (cache misses affect performance significantly). Go has aimed to replace C++ in many areas and thus needs to support pointers.

C# allows to pass structs by reference. See "ref" and "out" keywords.

What's the point of having pointers in Go? - Stack Overflow

pointers go
Rectangle 27 15

Known Issues with Entity Framework 4.x and .NET Framework 4.5

It took a lot of fiddling about and testing different things. I was clueless until I decided to make a new vanilla project with the similar data structure from scratch. And when I installed EntityFramework from NuGet, I was shown a message:

Entity Framework 4.1 thru 4.3 included additional data annotations in the System.ComponentModel.DataAnnotations namespace in the EntityFramework assembly. In .NET 4.5 these annotations were moved to be part of the .NET Framework in the System.ComponentModel.DataAnnotations.Schema namespace of the System.ComponentModel.DataAnnotations.dll assembly. If you are using EF 4.x and targeting .NET 4.5 this results in two data annotations with the same name in different assemblies. Because the annotations in the .NET Framework are in a different namespace we were not able to use type forwarding to avoid this conflict.

It is possible to use EF 4.x on .NET 4.5 but we recommend using the latest pre-release version of EF 5. If you are not using the affected data annotations there is no impact on your code. If you are using the data annotations in a C# project you can use the extern modifier to ensure your code uses the annotations from EntityFramework.dll (http://msdn.microsoft.com/en-us/library/e59b22c5(v=VS.80).aspx). If you use the new annotations from the System.ComponentModel.DataAnnotations.dll assembly in .NET 4.5 they will not be processed by Code First.

At that point I realised that my data project was freshly created in VS2012 and was by default targeting .Net 4.5 and the rest of my project in solutions were migrated from VS2010 and targeting .Net 4.0. So I have updated all the projects to target .Net 4.5 and got the pre-release of EntityFramework 5.0.

Make sure you update your projects first to Net4.5, after that do update EF to 5.0, otherwise it will hate you forever and many bunnies will die.

This screencast is a great starter for updating to EF5.0

package id="EntityFramework" version="5.0.0-rc" targetFramework="net40"

I have changed targetFrameworkto "net45" and now I'm getting the expected behavior from migrations. I guess there would be a better way to get nuget target .Net 4.5 with packages, but that's what worked for me.

@Slauma please see the update. If you ever have to do the update to EF5.0, make sure you do update your projects to Net4.5 BEFORE

Im in the situation that we updated to EF 5.0 (or rather 4.4) before we updated to .Net 4.5 and Alot of bunnies did indeed die. Still working on trying to get the damn shit to work one day later.

@CasperLeonNielsen emm.. once you know what is broken - it is easier. We have upgraded our product to EF5 without going to .Net 4.5. And there was not much trouble. Sorry to hear about your bunnies -(

Perfect Trailmax - this is still an issue. I had upgraded a dll library to .Net 4.5 and that brought the troubles. I had to remove EF 6.1.3 with Nuget and put it back on - and its working now.

c# - Use the ColumnAttribute or the HasKey method to specify an order ...

c# entity-framework entity-framework-4 database-migration
Rectangle 27 31

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

Given that, you have one of two solutions:

Go with the native HTMLHTTPRequest, here is the code to do what you need

var req = new XMLHttpRequest();
  req.open("GET", "/file.pdf", true);
  req.responseType = "blob";

  req.onload = function (event) {
    var blob = req.response;
    console.log(blob.size);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="Dossier_" + new Date() + ".pdf";
    link.click();
  };

  req.send();

Second solution, use the jquery-ajax-native plugin

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

$.ajax({
  dataType: 'native',
  url: "/file.pdf",
  xhrFields: {
    responseType: 'blob'
  },
  success: function(blob){
    console.log(blob.size);
      var link=document.createElement('a');
      link.href=window.URL.createObjectURL(blob);
      link.download="Dossier_" + new Date() + ".pdf";
      link.click();
  }
});

Doesn't seem to work in Firefox

To make it work in Firefox you have to add 'document.body.appendChild(link);' before clicking the link :)

javascript - Download pdf file using jquery ajax - Stack Overflow

javascript jquery ajax pdf