Thursday, May 29, 2008

Recover a deleted file in Subversion

May 29th, 2008 By: brian
SVN is great for keeping our projects under tight control. Occasionally, we have the need to get something back that was deleted in a previous revision. So I can remember how to do it next time, here it is:
$ svn copy -r 1234 url/to/deleted/file path/to/recovered/file
This will copy the file at the revision specified to the new file in the “restore to path” part. You can find the revision by doing an ’svn log –verbose’ of the directory it was in. That’s all there is to it!
My theme seems to be restoring and recovering… is that a bad thing?

6 Responses to “Recover a deleted file in Subversion”

  1. Tarun Says:
    If you are giving the repository url, the -r or –revision parameter doesnt work.
    instead specify the old revision by appending @revision-number to end of the old file url.
    svn copy svn://repo-path/file-path@old-revision-number relative-path-to-new-location
    example -
    cd working-copy/mydir
    svn copy svn://www.example.com/myproject/mydir/myfile@21 .
    will copy the the file ‘myfile’ from revision 21 into the current directory.
  2. Clifton Says:
    Your forgot a hyphen in the svn log command:
    svn log –verbose
    Thanks!
  3. Frank Says:
    I was not able to use the @revision syntax, but -r worked just fine.
    The following command restored a deleted README file (with log entries back to 1993!) in my current working directory:
    svn copy -r http:////README .
    – Thanks for the help!
  4. Frank Says:
    Sorry, but that last post got scrambled; blame it on careless use of angle brackets.
    Hopefully, this version of the command will come through unscathed:
    svn copy -rrevision_number_where_deletedhttp://svn_machine_name/svn_repository_path/README .
  5. Shiv Says:
    Do you happen to know if there’s a difference between doing it the way you proposed versus using TortoiseSVN right-click feature as mentioned here?
    I tried the TSVN way, and it seemed to work for me. That is, all of the log history is still retained.

Tuesday, May 13, 2008

Flash AS3 Loading Fonts

May 13th, 2008 By: dan
Create a Flash AS3 application that loads an external font at runtime… Sounds easy enough… But it is a little tricky. I needed to create a flash app that allowed users to choose a font from a list and load that into a player. I wanted to offer several fonts but did not want to bloat the load-time with unused fonts. I could not find much help on this topic… Luckily I found betriebsraum and with that I was able to hack up something that worked for me.

Step 1: Created an external swf with the font I needed. (I created separate ones for each font I was going to offer.)
  • Created a new Fla and add a font to the library.
  • In the Library pane(F11), click the options dropdown, and choose ‘New Font’
  • Select a font, size and style–size is not important (arguably)–however, I believe you will have to create separate fonts for each style you require. The name is not important really either.
  • Right click the new font in the Library and select ‘Linkage…’
    • Check ‘Export for ActionScript’ and ‘Export in first frame’.
    • Give it a Class:–this name is important and you will need to remember it. I used ‘EFont01′ fig. 1
  • Publish the swf as ‘/font-Fontname.swf’.
Step 2: Create the Application:
  • Create a new Flash CS3/As3 application set the Document class as ‘Main’ and save it as ‘/myapp.fla’
  • Create a new AS3 script and save it as ‘/Main.as’
Main.as
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package {
  import flash.display.Sprite;
  import flash.text.*;
  import flash.events.*;
  public class Main extends Sprite {
    var t:TextField = new TextField();
    var f = new TextFormat();
    public function Main() {
      var font = new LoadFont("font-Zapfino.swf",["EFont01"]);
      font.addEventListener(LoadFont.COMPLETE, successLoadFont);
      font.addEventListener(LoadFont.ERROR, failLoadFont);
     }
    private function failLoadFont(e:Event){
      f.font="Arial"; //default font if load fails.
      t.embedFonts = false;
      post();
    }
    private function successLoadFont(e:Event){
      var embeddedFonts:Array = Font.enumerateFonts(false);
      f.font=embeddedFonts[0].fontName;
      t.embedFonts = true;
      post();
    }
    public function post(){
      f.size = 36;
      t.defaultTextFormat = f;
      t.x = 100;
      t.y = 100;
      t.background = true;
      t.autoSize = TextFieldAutoSize.LEFT;
      t.text = "We are in loaded Font";
      addChild(t);
    }
  }
}
  • Create a new AS3 script and save it as ‘/LoadFont.as’
LoadFont.as
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package {
  import flash.display.*;
  import flash.events.*;
  import flash.text.*;
  import flash.errors.*;
  import flash.system.*;
  import flash.net.*;
  public class LoadFont extends EventDispatcher {
    public static const COMPLETE:String = "complete";
    public static const ERROR:String = "error loading font";
    private var loader:Loader = new Loader();
    private var _fontsDomain:ApplicationDomain;
    private var _fontName:Array;
    public function LoadFont(url:String,fontName:Array):void {
      _fontName = fontName;
      trace("loading");
      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, font_ioErrorHandler);
      loader.contentLoaderInfo.addEventListener(Event.COMPLETE,finished);
      loadAsset(url);
    }
    private function loadAsset(url:String):void {
      var request:URLRequest = new URLRequest(url);
      loader.load(request);
     }
    function finished(evt:Event):void {
      _fontsDomain = loader.contentLoaderInfo.applicationDomain;
      registerFonts(_fontName);
      dispatchEvent(new Event(LoadFont.COMPLETE));
    }
    function font_ioErrorHandler(evt:Event):void {
      dispatchEvent(new Event(LoadFont.ERROR));
     }
    public function registerFonts(fontList:Array):void {
      for (var i:uint = 0; i < fontList.length; i++) {
        Font.registerFont(getFontClass(fontList[i]));
      }
    }
    public function getFontClass(id:String):Class {
      return _fontsDomain.getDefinition(id)  as  Class;
     }
    public function getFont(id:String):Font {
      var fontClass:Class = getFontClass(id);
      return new fontClass    as  Font;
    }
  }
}

27 Responses to “Flash AS3 Loading Fonts”

  1. Patrick Bay Says:
    Fonts are a tricky thing in ActionScript but they’ve come a long way in ActionScript 3.
    One of the best new additions for dealing with dynamic fonts is the ability to search for them dynamically in memory space. Here is some code that would complement the example shown here; it retrieves a font dynamically at runtime, allowing you to get a list of available fonts and then use one of them for a text field:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    public function setFont(fontName:String, field:TextField) {    
     //Use two methods to find the associated font. 
     //Step 1: Search through enumerated fonts, including system fonts for a match:   
     var realFontName:String=new String();
     var fontArray:Array=Font.enumerateFonts(true);
     for (var item in fontArray) {
      if (fontArray[item].fontName==fontName) {
       realFontName=fontArray[item].fontName;
       break;
      }//if
     }//for
     //Step 2: If not found, try getting it via a linkage through the class definition:
     if ((realFontName=='') || (realFontName==null)) {
      try {
       var fontClass:*=getDefinitionByName(fontName);
      } catch (err:ReferenceError) {
       //There was an error...no such font found!
       return;
      }//catch
      var tempInstance=new fontClass();
      realFontName=tempInstance.fontName;    
      tempInstance=null;
     }//if   
     var format:TextFormat = new TextFormat();
     format.font=realFontName;
     field.embedFonts=true;
    }//set font
    This method will attempt to find the font based on the name and assign it to the specified text field instance. All that remains after that is simply to set the text in the field!
    To retrieve a list of available fonts, the magic line of code is: var fontArray:Array=Font.enumerateFonts(true);
    Note that the method being invoked is a singleton so no Font instance is required.
    For more tips, tricks, tutorials, and expert-level advice on ActionScript 3, visithttp://www.peabee.com/
  2. Patrick Bay Says:
    …slight update, the method name should be “setFont”, not “set font” (it was copied from an existing class and was originally used as a setter).
  3. admin Says:
    Patrick – I’ve edited your code block with the update you mentioned, and wrapped it in code tags for readability.
  4. John Breakey Says:
    I found your article very interesting. I do have one question.
    Are loaded fonts able to be used by SWF’s on other pages other than the webpage the font was loaded on.
  5. The Field » Archive » Loading fonts at runtime in Flash Says:
    [...] Looks useful – if you like this kind of thing Add to your fave social site: [...]
  6. Vaughn Says:
    Line 35 has an html error in it. ( the less than sign ) :P
  7. tox Says:
    thanks a lot, finally one solution that works. great, kudos!
    tox
  8. DouG Molidor Says:
    Just what I was looking for. The Class worked great right off the bat too for what I need.
  9. lam0r Says:
    Very useful, so tutorial i searched for weeks.
    Thanks a lot men. U did a great work.
    Cya
  10. DP Says:
    Very nice work, works like a charm.
  11. Eric Says:
    With this approach you can’t embed a subset of characters (like you would using the Embed button). There is another way similar but more superior than your approach.
  12. Brian Says:
    Eric – what is the more superior approach?
  13. frfc1908 Says:
    Many thanks! Comes in very handy!
  14. frfc1908 Says:
    Oh yeah… why Futura? Luckily I could change the font in firebug, so the page was a little readable!
  15. TomGold Says:
    Hallo, great class with one, i hope, simple problem. I try to use this class in an AIR project. When i load the font.swf from the application folder it works. When i load the font.swf from the application-storage folder, registerFonts trow the error [Fault] exception, information=ArgumentError: Error #1508: The value specified for argument font is invalid.
    I hope (need) 4 help.
    Sorry for my spelling, i’m not a native speaker.
    THX f reading
    Tom
  16. ActionScript 3 Text Field Alpha « Bauhouse Says:
    [...] Flash AS3 Loading Fonts [...]
  17. Gonzalo Says:
    Thank you very much for the LoadFont class. It works perfectly. Only two corrections:
    line 17:
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, font_ioErrorHandler); // adding contentLoaderInfo
    line 34:
    for (var i:uint = 0; i < fontList.length; i++) { // the &lt simbol
    Thank you and sorry for my English :)
  18. A85 Says:
    Thanks for such a good article of runtime font embedding .I am able to implement this in my project ,fonts are coming from swf but what i’m trying to do is that getting the different font from different swf but in Font.enumerateFonts(false) does not return all of the font embed it’s just repeat the 2 or 3 fonts and sometimes just add only one . here is my code which i’m using in my project with your loadFont and other class .Thanks
    public function fontupload()
    {
    for (var i:Number = 0; i < 4 ; i++)
    {
    var coantainerfonts:Coantainerfonts = new Coantainerfonts()/seprate class for fonts with-in library
    coantainerfonts.mc.width = coantainerfonts.txt.width
    coantainerfonts.name = “fontconatiner”+i
    coantainerfonts.x = 0
    coantainerfonts.y=i*(18)
    fontsMC.addChild(coantainerfonts)
    var tempStr:String = “_fontembed” + (i + 1) + “.swf” //refernce to differnt swf
    var tempname:String = “EFont0″+(i+1)
    var font = new LoadFont(tempStr, [tempname]);
    font.addEventListener(LoadFont.COMPLETE, successLoadFont);
    font.addEventListener(LoadFont.ERROR, failLoadFont);
    }
    )
    }
    private function successLoadFont(e:Event)
    {
    var mc:MovieClip = fontsMC.getChildAt(_counter) as MovieClip
    var TxtRef:TextField = mc.txt as TextField
    var embeddedFonts:Array = Font.enumerateFonts(false);
    var txtformat:TextFormat = new TextFormat()
    txtformat.font = embeddedFonts[_counter].fontName
    trace(embeddedFonts[_counter].fontName)//trace similar font names
    TxtRef.embedFonts = true
    TxtRef.text =embeddedFonts[_counter].fontName
    TxtRef.setTextFormat(txtformat)
    _counter++;
    }
  19. BlazeTheFire » Blog Archive » External fonts without Flex Says:
  20. watcher Says:
    Per the mysterious commenter ‘Eric’, this indeed will not solve the “embed subset problem”.
    I suspect he did not post the ’superior’ method cos he doesn’t have it! neither do I sadly. But rest assured once I’ve cracked it I’m going to share it with the world! Stupid, stupid, stupid Adobe. It’s amazing what we let them get away with…
  21. RipX Says:
    When compiling in FlashDevelop I get the following Reference error:
    [Fault] exception, information=ReferenceError: Error #1065: Variable swf is not defined.
    since at compile time ‘fontsDomain’ has no targeted swf reference. Anyone know how to correct this problem?
    RipX
  22. RipX Says:
    The above post was due to a typo in the font name. Please disregard but be aware that this error shows if the name of the font is incorrect and effort should be made to catch this.
    RipX
  23. Pradeep Says:
    hi
    i have use your font loading classes. this is good but i m facing problem with Arial font……
    i have check other system fonts, all r working perfectly with styling but when i use Arial this code is break. this is not working, text is not visible aftre using Arial font with this class
    so pls give me suggestiong about this
  24. SurferDude Says:
    How would you go about using an external .CSS file to control a few different font classes?
    That way a client could make updates to say.. an XML file using HTML/CSS tags to decide which embedded font to use?
  25. Kevin Says:
    Shot Dan. I found this very handy. Thanks for sharing.
  26. Liu Says:
    I have made an util lib to load ttf font file directly and register it. please see Load and register TTF font in runtime.
  27. webworks Says:
    is a good article, it works perfectly .. but I just dont get it… why so many functions ? why 2 .as files and not just 1 ?

Tuesday, April 22, 2008

How Can I Improve My Site’s Ranking?

April 22nd, 2008 By: andrew

This question has entered the minds of website owners hundreds of times. Being on the first page of results within a search engine can mean the difference between success and failure.
In response to the question “How can I improve my site’s ranking?” Google has given the answer. “In general, webmasters can improve the rank of their sites by increasing the number of high-quality sites that link to their pages.”
Hundreds of factors go into determining a sites rank within a search engine, however, possibly the most important is the number of high-quality inbound links to your website. By high-quality we mean sites that themselves rank high in search engines, and are relevant and similar to your websites content.
A simple search on “Link Submission” on Google will turn up thousands of websites that will accept, and dispay a link to your site on their site. You could go about submitting to hundreds of these sites, but it will likely not increase you position within any search engine. These submissions can actually hurt your site’s ranking, not improve it.
So who should I submit my link to?
While trying to avoid submitting your link to a hundred places, there are a few key places that you should submit to. You will want to add your site to the Google Index. Yahoo also provides a free site submission into their index here. You may want to consider adding your site to DMOZ.org. DMOZ is a web directory which is human edited. Getting your site listed here will also get your site listed in the Google Directory (Google uses DMOZ.org’s directory). You can submit your site to DMOZ here.
Great. Now What?
After you have submitted your site to the major search engines, you’ll want to trade links with websites that are well placed within your industry. Do a google search on a few keywords that pertain to your website. Lets say “poodle puppies.” Get the list of the top 15-20 websites that currently appear on Google or Yahoo under that keyword. Next, write an individual email to each of them asking to trade links with them. You may even consider buying a link on their site.
As soon as they add the links and the search engines become aware that they link to your site, your site’s ranking will dramatically increase.
The key to success here is not to give up. You should be continually trying to get high quality links to your site as you grow. My Next article will deal with internally improving your website to increase your ranking on Search Engines. We’ll talk about layoutstructuremeta tagsalt tags and title tags that will affect your site’s ranking.
Stay Tuned!

Thursday, April 17, 2008

10 Things You Need to Know When Hiring a Web Designer:

April 17th, 2008 By: dan

  1. Choosing a firm (or freelancer):
    • Recommendations - When choosing a web designer, recommendations are your best guide. If you do not know anyone who can make a recommendation, you’ll need to find one on your own.
    • Local – If you do not have a computer or email, a local web developer may be your best bet. You can easily stop by to sign-off on conceptuals or progress. However, local shops -- depending on where you live -- may be more expensive than having the work done out of town.
    • Out of country - Out of country can cost less, but web designers out of country are harder to communicate with because of different timezones or language barriers. Some in-country firms hire out of country developers providing a buffer to the communication problem, but note that a one-day turnaround for a bug-fix may be impossible.
    • Locating a designer – Searching the web is a good way to find a design house. Try to find a firm who’s portfolio has some examples similar to your requirements. If they can leverage past work it may bring down your cost/time to deployment. Say you find a designer who has done some work similar to your needs, except that you do not like look or functionality of what they have done. Remember, that particular example may not be an exact representation of their talents; the client may have wanted the site to look or function just as it does and the developer may have suggested otherwise… or it may be a low budget site. To help evaluate their design skills, take a look at ALL the prospective designer’s portfolio examples, even if they are in a different market then you. If they have work you like then they are probably capable of designing your site to your liking.
    • Freelancers – Freelancers are okay to use and many are quite good. The only problem is that they are typically one person and may not have the bandwidth to meet your time constraints. Or after they have done your work they are booked up and cannot make time to fix/update your site.
  2. Your Budget: Know about how much you are willing to spend at this time. Every website is different, there are countless options and each case has it’s own requirements and solutions. If your friend had a website built for $1000, do NOT expect that your site is going to cost the same.
  3. Technical Knowledge: You DO NOT need to be an expert on the Internet, websites, or even computers. Let the experts at your prospective firm be the experts. Ask them questions if you do not know how it all works—hopefully they will be able to explain it to you without all the techno mumbo-jumbo.
  4. Your Needs: Tell the web designer all your plans and web needs for present and future… You may not be able to squeeze all your wants and wishes into your current budget or time frame, but knowing them upfront can help developers make decisions today that make future implementations less costly.
  5. Be prepared:
    • Information – Have some information about your company if available… current site, brochures, mission statements, or even ideas scribbled on a napkin. The more the designer understands your business the better the end result.
    • Target Audience – Let the designer know about who your customer or clients are. The designer may be an expert on web development, but they may have no or little knowledge of your widget or service. Educating them about your target audience will help in the design and presentation phase.
    • Examples – If you can provide examples of sites in the same or similar industries the designer can add these to his research to improve the design of your site.
  6. Web Domain: This is your address where your clients can find you on the web… yourcompany.com. .COM is the standard [identifier] for commercial businesses—not the only identifier but arguably the preferred one; unfortunately, most names are taken… even names you think no one else in this world could have wanted, quite often are taken. If you do not already own your domain be prepared with alternative choices or your web firm can help with common alternatives.Normally a domain name costs about $15 per year—multi-year plans are available and even recommended. If it is in your budget to spend the $100 or so for a 10 year domain you should do it; It will help bump up your ratings in search engines—more on this later.
  7. Content: Content is king. Your site is only as good as the content you put on it. Images, Text, Sections, etc. Not only what that information is, but how that information is presented to your audience is important. The developer you choose should be adept at information design, that is, they should be able to help organize and present your content to your customer in an orderly intuitive way. Web surfers are accustomed to certain things and when you don’t have things where they are expected to be they will be lost and your site will be a failure. (Have you ever gone to a site looking for information and after searching for a while given up?)
    • Brevity â€“ It had been my experience that it is not the quantity of content, but the quality of content. Try to make your point as clear as possible in as few words as possible.
    • Copywriter – Most designers will offer to help spell and grammar check your content. Some will have a copywriter on staff who can turn your text into gold… for a fee.
  8. Marketing and Search Engine Optimization: You can put up your site and be done with it… but if you need customers driven to your site then you will need to market it. Unfortunately web-sites are not baseball covered corn-fields… if you build it, they won’t come. Your site will NOT be effective if you do not market it; Your designers should also have some ideas on how to generate traffic to your site.
    • SEO – One of the best ways to market your site and important component to the success of your site is Search Engine Optimization or SEO. SEO are techniques to help your site appear if a more favorable position on search engine results. Your designer should employ at least the basic rules of good SEO; but do not expect to be on page one search results, it’s probably not realistic.
  9. Cost of a web-site: Buying a web-site is like buying a dog, there is the initial cost of the dog… then you need to get shots, collar, food dish, etc. Plus now continuing payments on food and what not. Once you pay for the site development there are add-ons and recurring costs that are part of owning a website, and they should be planned in your budget.
    • Development â€“ This is the cost of designing, developing and deploying your site. Expect to pay 50% upfront and 50% upon completion… though payment plans vary and are negotiable.
    • Domain â€“ This can be an annual payment that should be in the range of $10-$15 per year. It is recommended you get the $100 every 10 years plan if you can afford it (this option provides higher page scores). Here is a catch besides yourname.com, you may consider—not required—purchasing other common domains (such as .net, .biz, .org) to help protect your brand. These are basically another $10/year each.
    • Hosting â€“ When you build a website you need to put it on a computer somewhere so people can access it—not just any old computer, but one connected to a fast secure data-pipe. This is generally done by paying someone to host your site. This is another one of those grey areas… for an average brochure site, look to pay $10 per month–quarterly and yearly payments are usually available. For complex sites it can cost much more. They should come with email, yourname@yourcompany.com, and other services.Your designer can recommend a good host, probably themselves.
    • Maintenance â€“ Your site may require regular updates… You may have to pay either a monthly rate to include updating your site with new or improved content, or you can pay as you go.
    • Marketing â€“ As mentioned earlier you will need to budget to market your site. If this is your first site, there are initial costs that need to be considered into your budget such as re-printing all your business cards and brochures to include your web address, sending out email notifications to your customers telling them about your site, or a marketing campaign to introduce your new site. It of course is not required and you can just put up your site so its available for customers who are looking.
  10. The Process:
    • Call or email a prospective designer. Let them know that you are gathering quotes to build your web-site. Tell them what your needs are and ask questions. Set-up a more detailed meeting. If you’re a large company you may have to generate a RFP (Request for Proposal) to send to several designers to bid on.
    • Have a details meeting. If possible, make sure you invite all the decision makers and content owners, and technical/IS staff (if applicable) to this meeting. This is where you iron out most of the needs and requests.
    • The designer will put together a bid. The bid will probably include tasks, requirements, time-lines, milestones, payment schedule, and other details needed to complete your site.
    • You make any necessary changes to the bid. When you both come to terms you like, sign and accept the bid.
    • Make sure any content/approvals required by you or your team are met quickly and within plan… this will help keep things running smoothly.
    • Review any drafts or milestones. Make any corrections within the scope of the proposed bid.
There you have it… A few simple guidelines to make your web designer search a breeze.

Highlighting Active Rows in Forms

April 17th, 2008 By: Daniel

What can be done to make the ubiquitous form element a little more usable and appealing? That was a question we asked ourselves on a recent project and one of our answers was to highlight the active row. It’s easy to change the appearance of the active input element with the focus pseudo-class in css, but a quick Google search didn’t reveal an easy way to highlight the containing tr element and so I ended up rolling my own implementation.
First I added the following javascript to public/javascripts/application.js:
/* For highlighting active rows */
function highlight_row_on_focus(e) {
  $(e).up("tr").addClassName("focused_row");
}
function unhighlight_row_on_blur(e) {
  $(e).up("tr").removeClassName("focused_row");
}
And then I styled my rows in public/stylesheets/application.css:
.evenrow {
  background-color: #f1f5fa;
}
tr.focused_row {
  background-color: #d7e0ea;
}
To make the view a little cleaner I added a quick helper to helpers/application_helper.rb:
def element_options_with_highlight(opts = {})
  {:onfocus => "highlight_row_on_focus(this.parentNode)", :onblur => "unhighlight_row_on_blur(this.parentNode)"}.merge(opts)
end
So now in your views all you have to do is add an element_options_with_highlight to the input elements in your forms:
<table>
  <tbody>
    <tr class="<%= cycle('oddrow', 'evenrow') %> required">
      <td><label for="username">Username:</label></td>
      <td><%= text_field_tag :username, @username, element_options %></td>
    </tr>
  </tbody>
</table>
Then check your layouts to make sure the Scriptaculous libraries are being loaded and your javascript and stylesheet is being sourced and voilá! you now have a form that highlights the active row as you tab through.