Search posterous

Search all posts and users. Type a name, type a favorite song title, whatever! See what comes up.
  

More posterous blogs











More recommended blogs »

Here are posterous posts filed under code...

what2day says...

Will it show as an attachment with the non-breaking space codes written out?

 

         _
       ('v')
       (   )       "Birdie" by Susie Oviatt
      ~/'~'~~

Filed under: code, posterous-meta

what2day says...

Because what I really need to do is learn yet another programing language I'm taking an iPhone Development class at machine project with Chandler McWilliams as the instructor.

He recommended the book Cocoa Programming for Mac OS X and since fellow-student Matthew Iadarola got it out of the library we decided to give the first example a shot: the random number generator.

It had to be adapted some for the iPhone since this is not an iPhone book, but we got it done.

I posted the code for M.I., heavily commented, here. I also uploaded the Buttons example from class b/c I reference it in my comments. 

There are two versions, functionally virtually identical, but the UI layout in one is much more streamlined. It's all about design.

images: v2, v1, icons

     
Click here to download:
Hello_Random_Number_on_the_iPh.zip (454 KB)

Filed under: code, iPhone, Objective C, Xcode

unugurn says...

DPX TimeCode Editor 1.10: Increment time code in multiple DPX files http://bit.ly/45qVDo

Filed under: code, files, time

assbach says...

http://flowplayer.org/tools/index.html

jQuery Tools is a collection of the most important user-interface components for today's websites. This single JavaScript file weighs only 5.72 Kb

tabs, tooltips, overlay (modal / pic-zoom), expose, scrollable, flashembed

Filed under: code, javascript, jquery

Japo says...

   
Click here to download:
The_Konami_Code_on_Facebook_ta.zip (14 KB)
You don't have to start with a lot of money to get wealthy. Facebook proves it.

Facebook was created in a college dorm room. Here is an excerpt from wikipedia:

Mark Zuckerberg founded Facebook with his college roommates and fellow computer science students Eduardo Saverin, Dustin Moskovitz andChris Hughes while he was a student at Harvard University. The website's membership was initially limited to Harvard students, but was expanded to other colleges in the Boston area, the Ivy League, and Stanford University. It later expanded further to include any university student, then high school students, and, finally, to anyone aged 13 and over. The website currently has more than 300 million active users worldwide.

Because of the massive growth in the number of users they received investments left and right.

Facebook was started by a kid in his 20s. He now has a net worth of $2 billion. A multibillionaire.

So what's your BIG idea?

================

Being an 80s kid, Zuckerberg also played video games. And so entered the Konami Code in Facebook.

Try this while on Facebook: 

On your keyboard, press UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A, ENTER and then scroll up OR down. 
You'll see something nice. Reload the page to get rid of it. :)

================

Filed under: code, facebook, konami, rich

trapo says...

Sometime ago I was fighting with Hibernate Validator, trying to implement an unique constraint and I could not figure out how to create one that requires database access:

The problem is that your validators can't access sessionFactory or any other interface to the database. I know that I can break some rules and instantiate a sessionFactory/session/connection directly inside the Validator, but I dislike to do wrong things consciously. So, I looking for alternatives.

Then, while studying the new validation support offered by Spring, I just discovery that using Spring I can inject any bean inside my ConstraintValidators. From Spring documentation:

By default, the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. This allows your custom ConstraintValidators to benefit from dependency injection like any other Spring bean.

And here is how you can use that Spring feature to implement unique constraint.

THE UNIQUE ANNOTATION

It is very simple and direct. You can see details about implementing your custom annotations in Hibernate Validator docs.

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=UniqueConstraintValidator.class)
@Documented
public @interface Unique {
    String message() default "{constraints.unique}";
    Class<?> entity();
    String field();
    Class<?>[] groups() default {};   
    Class<? extends Payload>[] payload() default {};
}

You can also see the code at GitHub, where trapo is hosted. If I decide to change something, you can get an updated version there. Once you have the @Unique annotation, you must implement the ConstraintValidator referenced by "validationBy" property in @Constraint annotation above. Here is the code using a bean injected by Spring:

public class UniqueConstraintValidator implements ConstraintValidator<Unique, String> {

    @Autowired private SessionFactory sessionFactory;
   
    private Class<?> entity;
    private String field;
   
    public void initialize(Unique annotation) {
        this.entity = annotation.entity();
        this.field = annotation.field();
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isEmpty(value)) {
            return false;
        }
        return query(value).intValue() == 0;
    }

    private Number query(String value) {
        HibernateTemplate template = new HibernateTemplate(sessionFactory);
        DetachedCriteria criteria = forClass(entity)
                                   .add(eq(field, value))
                                   .setProjection(count(field));
        return (Number)template.findByCriteria(criteria).iterator().next();
    }

}

Just like the @Unique annotation, you can find the code in GitHub. Now you just need a Validator bean that can be injected in the classes that need it.

<bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

Voilá!

THE UGLY PART

Right now, Hibernate Validor don't offer any way to know from where your annotations are coming. If you take some time to think about the ConstraintValidator above, you will notice that I manually configure the entity class and field information that were annotated. I need that information to know what query I must execute in order to validate the uniqueness of the field. Bad to me. Really bad. Now I have to provide this information by myself annotating the field like the code highlighted below:

    @NotEmpty @Unique(entity = Forum.class, field = "name")
    private String name;

I can even hear the DRY concept crying! I can't also find a way to reflect this to my schema. Maybe Hibernate Validator can offer some interfaces that we can use to implement all this stuff.

Filed under: code, hibernate, spring, unique, validation

appsfire says...

Behind the curtains, we have created and started to develop a unique link shortener technology for your Apps: the idea is simple

Instead of using the typical iTunes link, usually hard to memorize and dumb in terms analytics. 

So what we give you is a simple URL getAp.ps/YourAPP instead that will give you some more juice (eg: http://getAp.ps/TuneWiki )

  • easy to remember and share
  • live analytics on clicks
  • conversion analytics on paid apps (how sales are generated)
  • full referrer analytics (where your link has been used)
  • on-the-fly campaign creation: create as many campaign as you want > getAp.ps/YourAPP/emailsignature or /Seesmic (to measure analytics from a certain source)
  • no setup, not coding, no nothing. Instantly available.

Today we are introducing a new tool: easy promo-code distribution. TapTapTap has pointed some of you to the problem: distributing promo codes to users to try your App is painfull both for senders (need to include instructions) and for the recipient (need to find where the redeem section is, and good luck with that on the mobile app store). They give you also a trick to add the code in the URL you are sending.

Today we are introducing some new stuff.

With getAp.ps developers will be able to manage their promo code very simply: 
  • we'll set a campaign URL for you (getap.ps/yourApp/promo
  • you ll just add the code and you're done. 
  • A counter will tell you how this code is used in real time. 
  • The advantage is that the recipient does not have to input the promo code in the App store (computer or mobile)
  • No more need to include explanations in your email
  • works from your iPhone and can be used on the go
  • All this is semi automatic and very soon fully self served

This is a free service. It is currently tested by Top apps in the App Store and we ll be happy to sign you up.

Interested? Contact us at Contact (a) Appsfire (dot) com

Filed under: app store, code, getap.ps, link, promo, promotion, redeem, url

juke says...

template news_short
this->date ersetzen mit
parseDate('d', $this->timestamp); ?>
parseDate('M', $this->timestamp); ?>
parseDate('Y', $this->timestamp); ?>

Filed under: code, php, Typolight

bibale says...

Bibale was started roughly a year ago.

Today I though it would be interesting to share some of the stats
generated by StatSVN on the Subversion repository that hosts Bibale's
source code.

These statistics do not include code generated by thrift.

         
Click here to download:
Bibale_Code_Statistics_tags_sv.zip (92 KB)

Filed under: code, svn

gltss says...

Feeds 101

Feeds 101

Oct 27th in Other by Siddharth

Feeds. RSS. Atom. Syndication. Subscribers. These are some of the keywords floating around the web and have gained notorious prominence over the years. In this guide, we'll take a look at a number of things including what feeds are, why you need to have a feed for your site, how to set up one and then publish it.

PG

Author: Siddharth

Hi! I am Siddharth, a web developer/ designer based in Chennai with expertise in C#, Python, CSS and JavaScript . I resort to using jQuery when I don't feel like writing raw JS. I am passionate about web technologies and video games and I really think code *is* art. You can follow me if you want.

What are Feeds?

Feed image

In this digital age, users no longer have the luxury of time to check for new content manually each time or more importantly remember each site they want to get information from. Web feeds, news feeds or feeds helps the user simplify this process drastically.

Feeds, to put it simply, are a way to publish frequently updated content. Your feed is a XML formatted document which lets you share content with other users on the web. Users, subscribers in this lingo, can use your feed to read updated information on your site if and when it is posted.

Why you Should Publish Feeds

From a web developer's perspective, one of the main reason for publishing a feed is user convenience. With a feed for users to subscribe to, they don't have to check for new content manually each time. They can just subscribe to your feed and get notified new content is posted. No hassles! If you fear you'll lose your advertisement revenues in this process, you can just as easily include ads in the feed.

Publishing a feed also means that it is easier for third party content providers to syndicate your content thus gaining more exposure and traffic in the process.

Feed Formats

As with any hot technology, there are a few well established, competing protocols for creating web feeds.

RSS

Feed image

RSS is the dominant format for publishing web feeds and stands for Really Simple Syndication. RSS has a number of variants each branching out from RSS 1.x and RSS 2.x versions. A lot of services, including WordPress use RSS for creating its feeds.

Despite it's massive user base, RSS does suffer from some drawbacks, some significant, the most important one being its inability to handle HTML. Nevertheless, we'll be creating our feed today in the RSS format.

Atom

Atom logo

Atom was created in order to mitigate a lot of RSS' drawbacks including the ability to include properly formatted XML or XHTML in your feeds. But since RSS has almost become synonymous with feeds, Atom has always been the much more feature rich and flexible little brother.

RSS's Format

In the interest of keeping it simple, we'll just stick with RSS today instead of trying out each format out there.

Each and every RSS feed out there follows this general format:

Defining the version and encoding

RSS is a subset of XML which means we need to make sure it is marked so appropriately.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <rss version="2.0">   
  3. ..   
  4. </rss>  
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"> 
.. 
</rss>

The first line is the XML declaration. We define the version so that it validates correctly as XML. The encoding part is purely optional.

The second line defines the version of RSS we are going to use today. We are going to use RSS 2 today.

Each feed need to be inside a channel so that goes inside the markup. Thus far our feed looks like so.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <rss version="2.0">   
  3. <channel>  
  4. ..   
  5. </channel>  
  6. </rss>  
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"> 
<channel>
.. 
</channel>
</rss>

Filling in the feed's source information

This is where you fill in all the important details like the name of the feed, the URL and a description of the site.

  1. <title>My feed</title>  
  2.  <link>http://www.somesite.com</link>  
  3.  <description>Random ravings :)</description>  
<title>My feed</title>
 <link>http://www.somesite.com</link>
 <description>Random ravings :)</description>

You aren't limited to these fields alone. There are a number of other optional fields including the language of your feed, an image for the logo, when the feed was updated last and many more.

Adding the content

Each item in the feed has to be enclosed by an <item> element. An item can be anything: a news post, a status update, new products: anything. Each item requires a title and a corresponding link. As with before, you can make use of a number of optional elements including description and author fields.

A sample item would look like so:

  1. <item>  
  2. <title>Feeds 101</title>  
  3.  <link>http://www.net.tutsplus.com</link>  
  4.  <description>Let's create an RSS feed from scratch!</description>  
  5.  <author>Siddharth</author>  
  6. </item>  
<item>
<title>Feeds 101</title>
 <link>http://www.net.tutsplus.com</link>
 <description>Let's create an RSS feed from scratch!</description>
 <author>Siddharth</author>
</item>

Building a Static RSS Feed

Now that we know all the individual parts of a RSS file and how they all gel together, it's time to see a complete RSS file.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <rss version="2.0">   
  3. <channel>  
  4.     <title>My feed</title>  
  5.    <link>http://www.somesite.com</link>  
  6.    <description>Random ravings :)</description>  
  7.    <item>  
  8.         <title>Feeds 101</title>  
  9.         <link>http://www.net.tutsplus.com</link>  
  10.         <description>Let's create an RSS feed from scratch!</description>  
  11.         <author>sid@ssiddharth.com</author>  
  12.     </item>  
  13. </channel>  
  14. </rss>  
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"> 
<channel>
	<title>My feed</title>
   <link>http://www.somesite.com</link>
   <description>Random ravings :)</description>
   <item>
		<title>Feeds 101</title>
 		<link>http://www.net.tutsplus.com</link>
 		<description>Let's create an RSS feed from scratch!</description>
 		<author>sid@ssiddharth.com</author>
	</item>
</channel>
</rss>

It may not look like much but gents, this is a working RSS feed. We've defined everything that needs to be defined and if you are inclined to do so, you can put this on the web.

Building a Dynamic RSS Feed

Happy about building your first RSS feed? You should be! But the problem with this is that the feed is completely static: something which is completely counter intuitive as compared to the concept of feeds. We'll rectify this now by building a simple PHP script that mooches off data from a database and updates the RSS feed when needed.

Since I like having pretty URLs, I am going to name this file index.php and place it in a folder called feed so my feed can be accessed at www.mysite.com/feed

For the sake of simplicity, I am going to assume you already have a database containing your articles. I am also assuming the database has columns named title>, link, description and date in a table called posts.

Building the base

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <rss version="2.0">   
  3. <channel>  
  4.     <title>My feed</title>  
  5.    <link>http://www.somesite.com</link>  
  6.    <description>Random ravings :)</description>  
  7.   
  8.  <?php  
  9.     // Code here  
  10.  ?>  
  11.   
  12. </channel>  
  13. </rss>  
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"> 
<channel>
	<title>My feed</title>
   <link>http://www.somesite.com</link>
   <description>Random ravings :)</description>

 <?php
    // Code here
 ?>

</channel>
</rss>

Since the XML declarations and feed information are going to be pretty static, we'll keep them static. You'd want to keep them dynamic if you were writing a PHP class for generating RSS feeds but for our purposes, this should do.

Defining database information and connecting

  1. DEFINE ('DB_USER''some_username');    
  2. DEFINE ('DB_PASSWORD''some_unusually_weak_password');    
  3. DEFINE ('DB_HOST''localhost');    
  4. DEFINE ('DB_NAME''database');   
DEFINE ('DB_USER', 'some_username');  
DEFINE ('DB_PASSWORD', 'some_unusually_weak_password');  
DEFINE ('DB_HOST', 'localhost');  
DEFINE ('DB_NAME', 'database'); 

Simple as it looks. We just note down a bunch of information for use later.

  1. $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or   
  2. die('Connection to the specified database couldn't be established');   
  3. mysql_select_db(DB_NAME)  or  
  4. die ('Specified database couldn't be selected');    
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or 
die('Connection to the specified database couldn't be established');  
mysql_select_db(DB_NAME)  or 
die ('Specified database couldn't be selected');  

Pretty generic connection code. We try to connect using the credentials noted earlier. If nothing hitches up, we select the relevant database for use later.

Querying the database

  1. $query = "SELECT * FROM posts ORDER BY date DESC";    
  2. $result = mysql_query($queryor die ("Query couldn't be executed");    
$query = "SELECT * FROM posts ORDER BY date DESC";  
$result = mysql_query($query) or die ("Query couldn't be executed");  

This isn't really a SQL oriented tutorial and so I'll skim over it. We just grab all the posts from the table so that we can add it to the feed. Nothing else fancy going on over there.

Populating the items list

  1. while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {  
  2. echo '<item> 
  3.          <title>'.$row['title'].'</title> 
  4.          <link>'.$row['link'].'</link> 
  5.          <description>'.$row['description'].'</description> 
  6.        </item>';  
  7. }  
while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {
echo '<item>
		 <title>'.$row['title'].'</title>
		 <link>'.$row['link'].'</link>
		 <description>'.$row['description'].'</description>
	   </item>';
}

We grab each individual record and then print it inside the relevant element to create the items list. Note that since I wanted a hash to work with I set the result type to MYSQL_ASSOC.

And with that the PHP part is done. The complete code should look like below.

  1. <?php  
  2.     header("Content-Type: application/rss+xml; charset=utf-8");    
  3. ?>  
  4.   
  5. <?xml version="1.0" encoding="utf-8"?>  
  6. <rss version="2.0">   
  7. <channel>  
  8. <title>My feed</title>  
  9.   <link>http://www.somesite.com</link>  
  10.   <description>Random ravings :)</description>  
  11.   
  12. <?php  
  13.    DEFINE ('DB_USER''some_username');    
  14.  DEFINE ('DB_PASSWORD''some_unusually_weak_password');    
  15.  DEFINE ('DB_HOST''localhost');    
  16.  DEFINE ('DB_NAME''database');   
  17.   
  18.  $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or   
  19.  die('Connection to the specified database couldn't be established');   
  20.  mysql_select_db(DB_NAME)  or  
  21.  die ('Specified database couldn't be selected');    
  22.   
  23.  $query = "SELECT * FROM posts ORDER BY date DESC";    
  24.  $result = mysql_query($queryor die ("Query couldn't be executed");    
  25.   
  26.  while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {  
  27.     echo '<item>  
  28.             <title>'.$row['title'].'</title>  
  29.             <link>'.$row['link'].'</link>  
  30.             <description>'.$row['description'].'</description>  
  31.           </item>';  
  32.  }  
  33. ?>  
  34.   
  35. </channel>  
  36. </rss>  
 <?php
     header("Content-Type: application/rss+xml; charset=utf-8");  
 ?>
 
 <?xml version="1.0" encoding="utf-8"?>
 <rss version="2.0"> 
 <channel>
	<title>My feed</title>
   <link>http://www.somesite.com</link>
   <description>Random ravings :)</description>

 <?php
    DEFINE ('DB_USER', 'some_username');  
	 DEFINE ('DB_PASSWORD', 'some_unusually_weak_password');  
	 DEFINE ('DB_HOST', 'localhost');  
	 DEFINE ('DB_NAME', 'database'); 

	 $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or 
	 die('Connection to the specified database couldn't be established');  
	 mysql_select_db(DB_NAME)  or 
	 die ('Specified database couldn't be selected');  

	 $query = "SELECT * FROM posts ORDER BY date DESC";  
	 $result = mysql_query($query) or die ("Query couldn't be executed");  

	 while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {
		echo '<item>
			 	<title>'.$row['title'].'</title>
		 		<link>'.$row['link'].'</link>
		 		<description>'.$row['description'].'</description>
	  	 	  </item>';
	 }
 ?>

 </channel>
 </rss>

You should now be able to access your feed at www.yoursite.com/feed.

>

Validate your Feed

Feed image

Just like with xHTML, RSS/XML needs to be well-formed and without errors. There are a number of validators to help you with this. Here are some of my often used ones.

Since RSS can only handle escaped HTML, make sure you use &lt; lt; for < and &lt; gt; for > respectively. Also make sure you replace special characters to their respective HTML codes. Forgetting to do so will probably result in invalid markup and break the feed.

All Done! Publish that Feed

Feed image

Now that we've created the feed and made sure it validates, we can now go publish it. You can use a service like Feedburner to manage your feeds. This lets you glean a lot of information including how many subscribers you have. Or you can take the easy way out and just link to your feed on your site.

Have you ever noticed the feed icon on your browser lighting up for certain pages alone? This means the browser has been notified that a feed of the current page is available for subscription. In order for the user's browser to automatically detect the feed's presence you need to add this small snippet to the head section of your page:

  1. <link rel="alternate" type="application/rss+xml" title="Article RSS Feed"   
  2. href="http://www.yoursite.com/feed" />  
<link rel="alternate" type="application/rss+xml" title="Article RSS Feed" 
href="http://www.yoursite.com/feed" />

You need not limit yourself to one feed. You may have a feed for each author or a feed for each category of the products you sell. Feel free to add as many feeds you want to the head section.

Conclusion

And that brings us to an end to this joy ride. We've gone over what feeds are, what purpose they serve and the different formats available. Next we looked at RSS, its skeleton structure and then learned how to create a simple dynamic RSS feed. Hopefully you've found this tutorial interesting and this has been useful to you.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!


Filed under: code, feeds, rss, web development, xml