instruction
stringlengths
0
30k
JQuery & Objects, trying to make a ligthwight widget.
|javascript|jquery|
Trying to make a make generic select "control" that I can dynamically add elements to but I am having trouble getting functions to work right. This is what I started with. $select = $("<select></select>"); $select.addOption = function(value,text){ $(this).append($("<option></option>").val(value).text(text)); }; This workd fine alone but anytime $select is .clone(true)'ed the addOption function is lost. This is my object approach but still the function does not work. function $selectX() { return $("<select></select>"); } $selectX.prototype.addOption() = function(value,text){ $(this).append($("<option></option>").val(value).text(text)); }; Hack solution is to add the function manually after creation. $nameSelect= new $selectX; $nameSelect.addOption = function(value,text){ $(this).append($("<option></option>").val(value).text(text)); }; Am I barking up the wrong tree? Thanks for the help
A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as well choose a distro on other criteria... perhaps how comfortable you are with it, how easy package management is, and if the look & feel suit your development habits are all big factors. So, to answer your question more directly, a Java developer would do well with any major linux distro that they are comfortable with using in general. If you want some Java goodness out of the box, Fedora 9 and Ubuntu 8.04 have OpenJDK (and NetBeans) according to [a recent announcement][1]. [1]: http://www.vnunet.com/vnunet/news/2215568/open-source-java-added-linux
nginx is great but if you don't fancy a whole new web server, apache 2.2 with mod proxy balancer will do the same job
A magic number can also be a number with special, hardcoded semantics. For example, I once saw a system where record IDs > 0 were treated normally, 0 itself was "new record", -1 was "this is the root" and -99 was "this was created in the root". 0 and -99 would cause the WebService to supply a new ID. What's bad about this is that you're reusing a space (that of signed integers for record IDs) for special abilities. Maybe you'll never want to create a record with ID 0, or with a negative ID, but even if not, every person who looks either at the code or at the database might stumble on this and be confused at first. It goes without saying those special values weren't well-documented. Arguably, [22, 7, -12 and 620][1] count as magic numbers, too. ;-) [1]: http://thedailywtf.com/Articles/Classic-WTF-The-Phantom-of-The-System.aspx
It may be just me, but the way I'd get into this is by creating a code generator - using reflection at runtime is a bit costly and untyped. Creating classes that would get generated according to your latest code and copy everything in a strongly typed manner would mean that you will catch these errors at build-time. For instance, a generated class may look like this: static class AtoBCopier { public static B Copy(A item) { return new B() { Prop1 = item.Prop1, Prop2 = item.Prop2 }; } } If either class doesn't have the properties or their types change, the code doesn't compile. Plus, there's a huge improvement in times.
You and `String.Format()` will be new best friends! <http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax> Looking at this, I didn't realize Sun's documentation was almost as bad as Microsoft's.. ouch.
Use [DecimalFormat][1]. [1]: http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html
I like [Terminus][1] for some command line stuff, at least scrolling log files and irssi/irc ([TTF versions available][2]). [1]: http://fractal.csie.org/~eric/wiki/Terminus_font [2]: http://misc.nybergh.net/pub/fonts/terminus/ttf/
I like [Terminus][1] for some command line stuff, at least scrolling log files and irssi/irc ([TTF versions available][2]). Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled). ![Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled).][3] [1]: http://fractal.csie.org/~eric/wiki/Terminus_font [2]: http://misc.nybergh.net/pub/fonts/terminus/ttf/ [3]: http://misc.nybergh.net/pub/fonts/terminus/2008-09-08_terminus_ttf_in_gnu_nano_putty_windows_xp_cleartype_screenshot.png
I like [Terminus][1] for some command line stuff, at least scrolling log files and irssi/irc ([TTF versions available][2]). Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled). ![Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled).][3] [1]: http://www.is-vn.bg/hamster/ [2]: http://misc.nybergh.net/pub/fonts/terminus/ttf/ [3]: http://misc.nybergh.net/pub/fonts/terminus/2008-09-08_terminus_ttf_in_gnu_nano_putty_windows_xp_cleartype_screenshot.png
I like [Terminus][1] for some command line stuff, at least scrolling log files and irssi/irc ([TTF versions available][2]). Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled). ![Screenshot of the terminus.ttf in action below (PuTTY on Windows XP with ClearType enabled).][3] [1]: http://www.is-vn.bg/hamster/ [2]: http://misc.nybergh.net/pub/fonts/terminus/ [3]: http://misc.nybergh.net/pub/fonts/terminus/2008-09-08_terminus_ttf_in_gnu_nano_putty_windows_xp_cleartype_screenshot.png
My application also had a similar problem and this is how I solved it: 1) <code>WEB-INF/classes/application.properties</code> contains the entry: <pre> ds.jndi=java:comp/env/jdbc/tcds </pre> 2) On the WLS machine, I have an entry in the <code>/etc/sysenv</code> file: <pre> ds.jndi=wlsds </pre> 3) I configured spring to lookup the JNDI vis the property <code>${ds.jndi}</code>, using a <code>PropertyPlaceholderConfigurer</code> bean with <code>classpath:application.properties</code> and <code>file:/etc/sysenv</code> as locations. I also set the <code>ignoreResourceNotFound</code> to <code>true</code> so that developers need not have <code>/etc/sysenv</code> on their machines. 4) I run an integration test using Cargo+Jetty and I could not properly set up a JNDI environment there. So I have a fallback <code>BasicDataSource</code> configured too using the <code>defaultObject</code> property of <code>JndiObjectFactoryBean</code>.
How to develop categories of controllers in MVC Routing?
Categories of controllers in MVC Routing? (Duplicate Controller names in seperate Namespaces)
>> The switch statement does a constant time branch regardless of how many cases you have. Since the language allows the *string* type to be used in a switch statement I presume the compiler is unable to generate code for a jump table style implementation for this type and needs to generate an if-then style. I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The *typeof* keyword returns an object so this is accessible at run-time only.
>Lomaxx wrote: >> "The switch statement does a constant time branch regardless of how many cases you have." Since the language allows the *string* type to be used in a switch statement I presume the compiler is unable to generate code for a constant time branch implementation for this type and needs to generate an if-then style. I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The *typeof* keyword returns an object so this is accessible at run-time only.
> wrote: >> "The switch statement does a constant time branch regardless of how many cases you have." Since the language allows the *string* type to be used in a switch statement I presume the compiler is unable to generate code for a constant time branch implementation for this type and needs to generate an if-then style. @mweerden - Ah I see. Thanks. I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The *typeof* keyword returns an object so this is accessible at run-time only.
WebDAV query trouble - unable to read body of e-mail
|webdav|
Our group(corporate environment) needs to monitor a couple of faceless accounts' Outlook inbox for specific types of bounced e-mails. WebDAV(using C# 2.0) is one of the paths we've traveled and we're almost there ... except for one minor problem -- we're getting the response below for the e-mail body element <a:propstat> <a:status>HTTP/1.1 404 Resource Not Found</a:status> - <a:prop> <a:htmldescription /> <a:textdescription /> </a:prop> </a:propstat> The only real commonality is that it only happens on messages that our Exchange server is returning to us as "Undeliverable". Note: All other e-mails come across just fine. Any thoughts?
Have never worked out how to do it without a round trip, so it depends on what your goal is. If they have to have javascript to proceed, then I have (in .net) done things like disabling the login button at the server side, then enabled it client side it with javascript, and used a noscript tag to show an error message. If it has to work either way, you can use progressive enhancement, and / or use js to set a hidden field and then set a session variable, but this means that you don't know until they get to the second request.
I'd also have to add another vote for Android's "Droid Sans Mono". It's a very crisp, clear coding font.
Dereks solution is probably the best, but here's an alternative anyway: Recent Linux kernel version allow you to pipe core dumps to a script or program. You could write a script to catch the core dump, collect any extra information you need and mail everything back. This is a global setting though, so it'd apply to any crashing program on the system. It will also require root rights to set up. It can be configured through the /proc/sys/kernel/core_pattern file. Set that to something like ' | /home/myuser/bin/my-core-handler-script'. The Ubuntu people use this feature as well.
>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Really? What computer are you using? It's taking a long time at 44, but the stack is not overflowing. In fact, your going to get a value bigger than an integer can hold (~4 billion unsigned) before the stack is going to over flow.
>The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Really? What computer are you using? It's taking a long time at 44, but the stack is not overflowing. In fact, your going to get a value bigger than an integer can hold (~4 billion unsigned, ~2 billion signed) before the stack is going to over flow (Fibbonaci(46)). This would work for what you want to do though (runs wiked fast) class Program { public static readonly Dictionary<int,int> Items = new Dictionary<int,int>(); static void Main(string[] args) { Console.WriteLine(Fibbonacci(46).ToString()); Console.ReadLine(); } public static int Fibbonacci(int number) { if (number == 1 || number == 0) { return 1; } var minus2 = number - 2; var minus1 = number - 1; if (!Items.ContainsKey(minus2)) { Items.Add(minus2, Fibbonacci(minus2)); } if (!Items.ContainsKey(minus1)) { Items.Add(minus1, Fibbonacci(minus1)); } return (Items[minus2] + Items[minus1]); } }
Markdown is a play on words because it is markup. "Markdown" is a proper noun. Markup is just a way of providing functionality above plain text. For example: formatting, links, images, etc.
- [Markup][1] is a generic term for a language that describes a document's formatting - [Markdown][2] is a specific markup library: [http://daringfireball.net/projects/markdown/][3] [1]: http://en.wikipedia.org/wiki/Markup_language [2]: http://en.wikipedia.org/wiki/Markdown [3]: http://daringfireball.net/projects/markdown/
The Safari Back Button Problem
|javascript|safari|
I do some minor programming and web work for a local community college. Work that includes maintaining a very large and soul destroying website that consists of a hodge podge of VBScript, javascript, Dreamweaver generated cruft and a collection of add-ons that various conmen have convinced them to buy over the years. A few days ago I got a call "The website is locking up for people using Safari!" Okay, step one download Safari(v3.1.2), step two surf to the site. Everything appears to work fine. Long story short I finally isolated the problem and it relates to Safari's back button. The website uses a fancy-pants javascript menu that works in every browser I've tried including Safari, the first time around. But in Safari if you follow a link off the page and then hit the back button the menu no longer works. I made a pared down webpage to illustrate the principle. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>Safari Back Button Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body onload="alert('Hello');"> <a href="http://www.codinghorror.com">Coding Horror</a> </body> </html> Load the page and you see the alert box. Then follow the link off the page and hit the back button. In IE and Firefox you see the alert box again, in Safari you do not. After a vigorous googling I've discovered others with similar problems but no really satisfactory answers. So my question is how can I make my pages work the same way in Safari after the user hits the back button as they do in other browsers? If this is a stupid question please be gentle, javascript is somewhat new to me.
Not that I know of, but pretty much all you need is: * a split container * a user control containing your actual form * a grid view Now you just hook up the grid view's item selection events with a controller that loads data into the user control's child controls. From what I can tell, there Access Split Form doesn't do a lot more.
There are **many** flash mp3 players that you can use that do this. Usually, you just have to edit a text file to point at the mp3s you want to have available. Here is the first one that showed up on a google search for `flash mp3 player`: [http://www.flashmp3player.org/demo.html][1] [1]: http://www.flashmp3player.org/demo.html
Can you please clarify? Is the WebClient class you speak of the one in HTTPUnit/Java? If so, your session should be saved automatically.
It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface. As simple as that.
To expand on [Rytmis's comment][1], you can't use the *as* keyword for structs (Value Types), as they have no null value. [1]: http://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype#2487
Getting the ID of the element that fired an event using JQuery
|javascript|jquery|
Is there any way to get the ID of the element that fires an event? I'm thinking something like: <html> <head> <script type="text/javascript" src="starterkit/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click( function(){ var test = caller.id; alert(test.val()); } ); }); </script> </head> <body> <form class="item" id="aaa"><input class="title"></input></form> <form class="item" id="bbb"><input class="title"></input></form> </body> </html> Except ofcourse that the var test should contain the id "aaa", if the event is fired from the first form, and bbb, if the event is fired from the second form. Can anyone help with this? /Jonas
How can I upsert a bunch of ActiveRecord objects and relationships in Rails?
|ruby-on-rails|activerecord|
I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop. I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data. I believe that the way I'm doing it now is very inefficient: # routes is an array of [number, destination] that I build while iterating over the data routes.uniq.each do |route| number = route[0] destination = route[1] r = Route.find_by_number_and_destination(number, destination) if !r r = Route.new :number => number, :destination => destination r.save end # I have to check if it already exists because I can't find a way # to create a uniqueness constraint on the join table with 2 foreign keys r.stops << stop unless r.stops.include? stop end Basically, I have to do 2 things for every route I find: 1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist. Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?
The exact definitions of "vsize," "rss," "rprvt," "rshrd," and other obscure-looking abbreviations vary from OS to OS. The manual pages for the "top" and "ps" commands will have some sort of description, but all such descriptions are simplified greatly (or are based on long-extinct kernel implementations). "Process size" as a concept is fiendishly difficult to pin down in the general case. Answers in specific instances depend heavily on the actual memory management implementation in the OS, and are rarely as satisfying as the tidy "process size" concept that exists in the minds of most users (and most developers). For example, none of those numbers (nor, likely, any combination of them) can be used to tell you exactly how many such processes can run at once in a given amount of free memory. But really, your best bet is to come at it from that end: why do you want this number, and what will you use it for? Given that information, I think you'll get more useful answers.
The **Publish to Provider** functionality has worked great for me. See [Scott Gu's Blog Entry](http://weblogs.asp.net/scottgu/archive/2006/12/22/recipe-deploying-a-sql-database-to-a-remote-hosting-environment-part-1.aspx). If you need something really robust look at redgate software's tools [here](http://www.red-gate.com/)...if you are doing much SQL at all, these are worth the $$.
Wild guess here: If you don't want to modify the third party's tables, Can you create a view and then put a trigger on that view?
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... [JSON](http://en.wikipedia.org/wiki/JSON)?
This is a useless ternary expression. This would be equivalent: $canMerge = ($condition1 && $condition2);
This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: $canMerge = ($condition1 && $condition2);
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is slightly more accurate for most situations, I wish I could come up with a more accurate way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code *PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)* returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate RelativeTimeMessage { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>(); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one second ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return timeDelta.Seconds + " seconds ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one minute ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return timeDelta.Minutes + " minutes ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one hour ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return timeDelta.Hours + " hours ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "yesterday"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return timeDelta.Days + " days ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one month ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return Convert.ToInt32(Math.Floor((double)timeDelta.Days / 30)) + " months ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one year ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), RelativeTimeMessage = delegate(TimeSpan timeDelta) { return "one month ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, RelativeTimeMessage = delegate(TimeSpan timeDelta) { return Convert.ToInt32(Math.Floor((double)timeDelta.Days / 365.24D)) + " years ago"; } }); timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.RelativeTimeMessage(ago); } }
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is slightly more accurate for most situations, I wish I could come up with a more accurate way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code *PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)* returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate RelativeTimeMessage { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>(); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), RelativeTimeMessage = (delta) => { return "one second ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), RelativeTimeMessage = (delta) => { return delta.Seconds + " seconds ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), RelativeTimeMessage = (delta) => { return "one minute ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), RelativeTimeMessage = (delta) => { return delta.Minutes + " minutes ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), RelativeTimeMessage = (delta) => { return "one hour ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), RelativeTimeMessage = (delta) => { return delta.Hours + " hours ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), RelativeTimeMessage = (delta) => { return "yesterday"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), RelativeTimeMessage = (delta) => { return delta.Days + " days ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), RelativeTimeMessage = (delta) => { return "one month ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), RelativeTimeMessage = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 30)) + " months ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), RelativeTimeMessage = (delta) => { return "one year ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, RelativeTimeMessage = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 365.24D)) + " years ago"; } }); timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.RelativeTimeMessage(ago); } }
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code *PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)* returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate RelativeTimeMessage { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>(); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), RelativeTimeMessage = (delta) => { return "one second ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), RelativeTimeMessage = (delta) => { return delta.Seconds + " seconds ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), RelativeTimeMessage = (delta) => { return "one minute ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), RelativeTimeMessage = (delta) => { return delta.Minutes + " minutes ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), RelativeTimeMessage = (delta) => { return "one hour ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), RelativeTimeMessage = (delta) => { return delta.Hours + " hours ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), RelativeTimeMessage = (delta) => { return "yesterday"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), RelativeTimeMessage = (delta) => { return delta.Days + " days ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), RelativeTimeMessage = (delta) => { return "one month ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), RelativeTimeMessage = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 30)) + " months ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), RelativeTimeMessage = (delta) => { return "one year ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, RelativeTimeMessage = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 365.24D)) + " years ago"; } }); timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.RelativeTimeMessage(ago); } }
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code *PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)* returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate MessageCreator { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>(); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), MessageCreator = (delta) => { return "one second ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), MessageCreator = (delta) => { return delta.Seconds + " seconds ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), MessageCreator = (delta) => { return "one minute ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), MessageCreator = (delta) => { return delta.Minutes + " minutes ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), MessageCreator = (delta) => { return "one hour ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), MessageCreator = (delta) => { return delta.Hours + " hours ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), MessageCreator = (delta) => { return "yesterday"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), MessageCreator = (delta) => { return delta.Days + " days ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), MessageCreator = (delta) => { return "one month ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), MessageCreator = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 30)) + " months ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), MessageCreator = (delta) => { return "one year ago"; } }); timeRanges.Add(new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, MessageCreator = (delta) => { return Convert.ToInt32(Math.Floor((double)delta.Days / 365.24D)) + " years ago"; } }); timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.MessageCreator(ago); } }
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code *PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago)* returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate MessageCreator { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>{ new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), MessageCreator = (delta) => { return "one second ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), MessageCreator = (delta) => { return delta.Seconds + " seconds ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), MessageCreator = (delta) => { return "one minute ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), MessageCreator = (delta) => { return delta.Minutes + " minutes ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), MessageCreator = (delta) => { return "one hour ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), MessageCreator = (delta) => { return delta.Hours + " hours ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), MessageCreator = (delta) => { return "yesterday"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), MessageCreator = (delta) => { return delta.Days + " days ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), MessageCreator = (delta) => { return "one month ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 30) + " months ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), MessageCreator = (delta) => { return "one year ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 365.24D) + " years ago"; } } }; timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.MessageCreator(ago); } }
@Peter Coulton -- you don't read Knuth, you study it. For me, and my work... _Purely Functional Data Structures_ is great for thinking and developing with functional languages in mind.
In .NET, enumeration values are (by default) serialized into xml with the name. For instances where you can have multiple values ([flags](http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx)), then it puts a space between the values. This works because the enumeration doesn't contain spaces, so you can get the value again by splitting the string (ie. "Invoice Contract SignedWorkOrder", using lubos's example). You can control the serialization of values of in asp.net web services using the [XmlEnumAttribute](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlenumattribute.aspx), or using the [EnumMember](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.enummemberattribute.aspx) attribute when using WCF.
this is a total hack but you could use an iframe inside the noscript tag to trigger an HTTP GET on a url to tell the server that a user doesn't have javascript enabled. <body> ... ... <noscript> <iframe src ="/nojs.aspx?SOMEIDENTIFIER=XXXX&NOJS=TRUE" style="display: none;"> </iframe> </noscript> ... ... </body>
Take a look at Apache's [Axis][1] project. It's well supported on C++ (and Java) and if you have the good fortune to start with a good WSDL for the target service you'll be home-free. [1]: http://ws.apache.org/axis/index.html
I primarily use [Microsoft Enterprise Library Data Access Block][1] to access stored procedures in MS SQL Server databases. [1]: http://msdn.microsoft.com/en-us/library/cc309504.aspx
inline lists with graphical links in css
|html|css|xhtml|list|
given this html: <ul id="topnav"> <li id="topnav_galleries"><a href="#">Galleries</a></li> <li id="topnav_information"><a href="#">Information</a></li> </ul> and this css: #topnav_galleries a, #topnav_information a { background-repeat: no-repeat; text-indent: -9000px; padding: 0; margin: 0 0; overflow: hidden; height: 46px; width: 136px; display: block; } #topnav { list-style-type: none; } #topnav_galleries a { background-image: url('image1.jpg'); } #topnav_information a { background-image: url('image2.jpg'); } how would I go about turning the topnav list into an inline list?
See Apache Commons' [DateUtils][1]. There's a `parseDate` method that takes your `String` and multiple patterns to try and spits out a `Date` instance. [1]: http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/DateUtils.html
How do I return an array of strings from an ActiveX object to JScript
|com|activex|javascript|
I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JScript. This is for script that runs on local machine for administration scripts, not for the web browser. My IDL file for the COM object has the interface that I am calling into as: <pre> HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray); </pre> The function returns correcty, but the strings are getting 'lost' when they are being assigned to a variable in JScript. The question is: What is the proper way to get the array of strings returned to a JScript variable?
Depends what you mean by a generic Windows CE installation. Windows CE itself is a modularised operating system, so different devices can have different modules included. Therefore each Windows CE device can have a radically different OS installed (headless even). Coredll is the standard "common" library that gets included in a Windows CE installation, however it can contain different components depending on the other modules in the system. If you want to target a relatively standard version of Windows CE either target the Standard SDK set of components, or go for a Windows Mobile platform. If you have an SDK then install and use that. If none is available then you can generate an SDK using Platform Builder and the OS project files. To get your application to work on a non-Windows Mobile installation of Windows CE you just have to remove the code that uses the aygshell library, and not link to those libraries.
I think I misunderstood your question. What you're asking for is not in scope of how the application handles its key storage, but rather how your company will store it. In that case, you have two obvious choices: - Physical: Write to USB drive, burn to CD, etc. Store in physically secure location. But you run into the recursive problem: where do you store the key to the vault? Typically, you delegate 2 or more people (or a team) to hold the keys. - Software: [Cyber-Ark][1] Private Ark is what my company uses to store its secret digital information. We store all our admin passwords, license keys, private keys, etc. It works by running a Windows "vault" server that is not joined to a domain, firewalls all ports except its own, and stores all its data encrypted on disk. Users access through a web interface that first authenticates the user, then securely communicates with the vault server via explorer-like interface. All changes and versions are logged. But, this also has the same recursive problem... a master admin access CD. This is stored in our physical vault with limited access. [1]: http://www.cyber-ark.com/
How to implement file upload progress bar on web?
|javascript|ajax|
I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have?
|javascript|ajax|
I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? *Edit: I am using .Net but I don't mind if somebody shows me platform agnostic version.*
|.net|javascript|ajax|
Round numbers, yes. This is the [main example source][1]. /* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.*; import java.text.*; public class DecimalFormatDemo { static public void customFormat(String pattern, double value ) { DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output); } static public void localizedFormat(String pattern, double value, Locale loc ) { NumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); String output = df.format(value); System.out.println(pattern + " " + output + " " + loc.toString()); } static public void main(String[] args) { customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); customFormat("\u00a5###,###.###", 12345.67); Locale currentLocale = new Locale("en", "US"); DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale); unusualSymbols.setDecimalSeparator('|'); unusualSymbols.setGroupingSeparator('^'); String strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4); String bizarre = weirdFormatter.format(12345.678); System.out.println(bizarre); Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"), new Locale("fr", "FR") }; for (int i = 0; i < locales.length; i++) { localizedFormat("###,###.###", 123456.789, locales[i]); } } } [1]: http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html#numberpattern
One way would be through automating a browser -- you mentioned WebClient, so I'm guessing you might be referring to WebClient in .NET.<p>Two main points:<ul><li>There's nothing special about https related to WebClient - it just works</li><li>Cookies are typically used to carry authentication -- you'll need to capture and replay them</li></ul> Here's the steps I'd follow:<ol><li>GET the login form, capture the the cookie in the response.</li><li>Using Xpath and HtmlAgilityPack, find the "input type=hidden" field values.</li><li>POST to login form's action with user name, password, and hidden field values in the request body. Include the cookie in the request headers. Again, capture the cookie in the response.</li><li>GET the pages you want, again, with the cookie in the request headers.</li></ol> On step 2, I mention a somewhat complicated method for automating the login. Usually, you can post with username and password directly to the known login form action without getting the initial form or relaying the hidden fields.<p>HtmlAgilityPack is a .NET library that allows you to turn ill-formed html into an XmlDocument so you can XPath over it. Quite useful.
One way would be through automating a browser -- you mentioned WebClient, so I'm guessing you might be referring to WebClient in .NET.<p>Two main points:<ul><li>There's nothing special about https related to WebClient - it just works</li><li>Cookies are typically used to carry authentication -- you'll need to capture and replay them</li></ul> Here's the steps I'd follow:<ol><li>GET the login form, capture the the cookie in the response.</li><li>Using Xpath and HtmlAgilityPack, find the "input type=hidden" field names and values.</li><li>POST to login form's action with user name, password, and hidden field values in the request body. Include the cookie in the request headers. Again, capture the cookie in the response.</li><li>GET the pages you want, again, with the cookie in the request headers.</li></ol> On step 2, I mention a somewhat complicated method for automating the login. Usually, you can post with username and password directly to the known login form action without getting the initial form or relaying the hidden fields. Some sites have form validation (different from field validation) on their forms which makes this method not work.<p>HtmlAgilityPack is a .NET library that allows you to turn ill-formed html into an XmlDocument so you can XPath over it. Quite useful.<p>Finally, you may run into a situation where the form relies on client script to alter the form values before submitting. You may need to simulate this behavior.<p>Using a tool to view the http traffic for this type of work is extremely helpful - I recommend ieHttpHeaders, Fiddler, or FireBug (net tab).
You can use `(this)` to reference the object the fired the function. `'this'` is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.
It isn't clear from your question which WebClient class (or language) you are referring to. If have a Java Runtime you can use the Apache HttpClient class; here's an example I wrote using Groovy that accesses the delicious API over SSL: def client = new HttpClient() def credentials = new UsernamePasswordCredentials( "username", "password" ) def authScope = new AuthScope("api.del.icio.us", 443, AuthScope.ANY_REALM) client.getState().setCredentials( authScope, credentials ) def url = "https://api.del.icio.us/v1/posts/get" def method = new PostMethod( url ) method.addParameter( "tag", tag ) client.executeMethod( method )
Team Explorer on codeplex anonymously
|version-control|tfs|codeplex|
I was on codeplex and trying to connect to their source control using team explorer. No joy though. I tried connecting with https or http, using the server name and the project name. As I do not have a user on codeplex I could not login. I am just trying to check out some code without changing it. My question is: How can you connect team explorer to a codeplex server anonymously? Cheers, Oded
Sorry for the late response, I was out of office. If that's the expected functionality I think it's not so usefull, at least there should be a reset. I fixed it now just using the FLASHW_ALL | FLASHW_TIMERNOFG combination. Btw, can't rate your answers, not enough rep yet.
Memcache control panel?
|memcached|cache|controlpanel|eaccelerator|
We've been running [eAccelerator][1] on each of 3 webservers and are looking to move to a [memcache][2] pool across all 3, hopefully reducing by about 2/3 our db lookups. One of the handy things about eAccelerator is the web-based control interface ([control.php][3]), which has proved very useful when we've had to flush the cache unexpectedly, quickly monitor which scripts are in cache, etc. We've been looking but haven't found anything that offers the same type of functionality for memcache - does anyone know if such a thing exists? Obviously flushing cache etc is easy enough with memcache on the console, but our particular set-up means we may have guys monitoring our front-end and needing to flush the cache who will not necessarily have shell access on the servers. [1]: http://eaccelerator.net/ "eAccelerator" [2]: http://www.danga.com/memcached/ "memcache" [3]: http://eaccelerator.net/browser/eaccelerator/tags/0.9.5-rc1/control.php "control.php"
|caching|memcached|controlpanel|eaccelerator|
I recommend [nose](http://www.somethingaboutorange.com/mrl/projects/nose/). It is the most Pythonic of the unit test frameworks. The test runner runs both doctests and unittests, so you are free to use whatever style of test you like.
Before you start searching for duplicate addresses in your database, you should first make sure you store the addresses in a standard format. Most countries have a standard way of formatting addresses, in the US it's the USPS CASS system: <http://www.usps.com/ncsc/addressservices/certprograms/cass.htm> But most other countries have a similar service/standard. Try this site for more international formats: <http://bitboost.com/ref/international-address-formats.html> This not only helps in finding duplicates, but also saves you money when mailing you customers (the postal service charges less if the address is in a standard format). Depending on your application, in some cases you might want to store a "vanity" address record as well as the standard address record. This keeps your VIP customers happy. A "vanity" address might be something like: 62 West Ninety First Street Apartment 4D Manhattan, New York, NY 10001 While the standard address might look like this: 62 W 91ST ST APT 4D NEW YORK NY 10024-1414
>.NET Strings are Immutable >Therefore having an instance method makes absolutely no sense. By that logic the string class should have no instance methods which return modified copies of the object, yet it has _plenty_ (Trim, ToUpper, and so on). Furthermore, lots of other objects in the framework do this too. I agree that if they were to make it an instance method, `Format` seems like it would be a bad name, but that doesn't mean the functionality shouldn't be an instance method. Why not this? It's consistent with [the rest of](http://msdn.microsoft.com/en-us/library/8wch342y.aspx) [the .NET framework](http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx) "Hello {0}".ToString("Orion");
I have no idea what's causing the problem but I know who might be able to help you. Safari is built on [Webkit][1] and short of Apple (who are not so community minded) the [Webkit team][2] might know what the issue is. It's not a stupid question at all. [1]: http://webkit.org/ [2]: http://webkit.org/contact.html
Today's web browsers only handle GETS + POSTS. In Rails, for example, PUTS + DELETES are "faked" through hidden form fields. Unless your framework has some workaround to "support" PUTS + DELETES, don't worry about them for now.
I've noticed something very similar. I think it is because Firefox and IE, when going back, are retrieving the page from the server again and Safari is not. Have you tried adding a page expiry/no cache header? I was going to look into it when I discovered the behaviour but haven't had time yet.
An iframe solves the problem: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>Safari Back Button Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body onload="alert('Hello');"> <a href="http://www.codinghorror.com">Coding Horror</a> <iframe style="height:0px;width:0px;visibility:hidden" src="about:blank"> this prevents back forward cache </iframe> </body> </html> more [details](http://developer.apple.com/internet/safari/faq.html#anchor5)
To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the "closure" and what's so "closure" about it. I recommend you give up looking for any logic behind the choice of term. Anyway, here's my explanation: def foo(): x = 3 def bar(): print x x = 5 return bar f = foo() f() # print 5 A key idea here is that the function object returned from foo retains a hook to the local var 'x' even though 'x' has gone out of scope and should be defunct. This hook is to the var itself, not just the value that var had at the time, so when bar is called, it prints 5, not 3. Also be clear that Python 2.x has limited closure: there's no way I can modify 'x' inside 'bar' because writing 'x = bla' would declare a local 'x' in bar, not assign to 'x' of foo. This is a side-effect of Python's assignment=declaration. To get around this, Python 3.0 introduces the nonlocal keyword: def foo(): x = 3 def bar(): print x def ack(): nonlocal x x = 7 x = 5 return (bar, ack) f, g = foo() g() f() # print 7
Stream data (such as music) using PHP (or another language)
|stream|mp3|php|sockets|
For years, I've been investigating how to create music streams from my computer. I've seen programs, but anything useful I've seen is windows only (I use a Mac). Eventually, I got interested in *how* streams work. Is there any way I could create my *own* stream, possibly using socket functions in PHP? Is there a PHP library for this? Thanks,<br /> Jason
|php|sockets|mp3|stream|
There's also red5 ([http://osflash.org/red5][1]) that is pretty much dedicated to streaming and shared objects on the server - it is java though. However, weborb ([http://www.themidnightcoders.com/weborb/][2]) has some awesome benefits on the data access side if you're looking to do some AMF as well as streaming video it could be a very decent option (and has a php and .net version). On the python side I found ([http://rtmpy.org/][3]) but couldn't say too much about it as I have never used it... [1]: http://osflash.org/red5 [2]: http://www.themidnightcoders.com/weborb/ [3]: http://rtmpy.org/