DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    This function takes a time and returns a relative date string (it does, however, ignore the time of day). For instance: "yesterday", "in 2 days", "1 day ago", "March 12", or "May 5, 1992".

function relative_date($time) {
    $today = strtotime(date('M j, Y'));
    $reldays = ($time - $today)/86400;
    if ($reldays >= 0 && $reldays < 1) {
        return 'today';
    } else if ($reldays >= 1 && $reldays < 2) {
        return 'tomorrow';
    } else if ($reldays >= -1 && $reldays < 0) {
        return 'yesterday';
    }
    if (abs($reldays) < 7) {
        if ($reldays > 0) {
            $reldays = floor($reldays);
            return 'in ' . $reldays . ' day' . ($reldays != 1 ? 's' : '');
        } else {
            $reldays = abs(floor($reldays));
            return $reldays . ' day'  . ($reldays != 1 ? 's' : '') . ' ago';
        }
    }
    if (abs($reldays) < 182) {
        return date('l, F j',$time ? $time : time());
    } else {
        return date('l, F j, Y',$time ? $time : time());
    }
}
                
                    Add to .vimrc so you can un comment blocks of text quickly and easily.

" ,cc clear the comments
map ,cc :s/^\/\/\\|^--\\|^> \\|^[#"%!;]//<CR><Esc>:nohlsearch<CR>
                
                    Add to .vimrc so you can comment blocks of text in perl/java/etc.

Highlight a block of text and hit ,# and it is commented out in perl.

" , #perl # comments
map ,# :s/^/#/<CR>

" ,/ C/C++/C#/Java // comments
map ,/ :s/^/\/\//<CR>

" ,< HTML comment
map ,< :s/^\(.*\)$/<!-- \1 -->/<CR><Esc>:nohlsearch<CR>

" c++ java style comments
map ,* :s/^\(.*\)$/\/\* \1 \*\//<CR><Esc>:nohlsearch<CR>
                
                    >>> import os

>>> os.getcwd()     # get current working directory
'C:\\lang\\python23'

>>> os.chdir('C:/')  # change directory
>>> os.chdir('lang')  # again

>>> os.listdir('.')  # list
['dotnet', 'try', 'editplus', 'python23', 'leo', 'mingw', 'perl', 'gtk', 'ironpy', 'java142']
>>>                 
                    
# dpkg --force-depends --purge exim4-daemon-light
# dpkg -i qmail_1.03-36_i386.deb
                
                    module Jsfx
  
  # by Matt Lyon, sanehatter@gmail.com
  # written on 17 April, after I spent an hour hunting down a missing apostraphe

  # f.e. <%= link_to_function thing.title, Jsfx.toggle("thing-#{thing.id}-insides") %>
  # or multiples: Jsfx.toggle(["id-1","id-2"])
  def Jsfx.toggle(ids=[])
    s = ids.collect {|i| "\'#{i.to_s}\'"}.join(', ')
    "Toggle.display(#{s});"
  end
  
  # insert anywhere you'd put the equivalent javascript.
  # f.e.:
  # form_remote_tag(:url => "/c/a/i", :update => "id", :complete => Jsfx.highlight("thing-#{thing.id}")
  #
  # You can combine multiple effects like so: 
  # Jsfx.highlight("thing-#{thing.id}") + Jsfx.toggle("thing-#{thing.id}-insides")
  def Jsfx.highlight(id)
    "new Effect.Highlight(\'#{id}');"
  end
  def Jsfx.fade(id)
    "new Effect.Fade(\'#{id}\');"
  end
  def Jsfx.scale(id,percent)
    "new Effect.Scale(\'#{id}\',#{percent});"
  end
  def Jsfx.squish(id)
    "new Effect.Squish(\'#{id}\');"
  end
  def Jsfx.puff(id)
    "new Effect.Puff(\'#{id}\')"
  end
  def Jsfx.appear(id)
    "new Effect.Appear(\'#{id}\')"
  end
  
  # Non-Prototype DOM manipulation
  # f.e. Jsfx.change("thing-#{thing.id}-description","Saving...")
  def Jsfx.change(id,new)
    "$(\'#{id}\').innerHTML = '#{new}'"
  end
  
  # Form Helpers
  def Jsfx.form_disable(id)
    "Form.disable(\'#{id}\');"
  end
  def Jsfx.form_reset(id)
    "Form.reset(\'#{id}\');"
  end
  def Jsfx.form_focus(id)
    "Form.focus_first(\'#{id}\');"
  end
end                
                    
mysql -uroot -p
mysql> CREATE DATABASE staff_hieraki;
mysql> GRANT ALL PRIVILEGES ON staff_hieraki.* TO staff@localhost IDENTIFIED BY 'password-goes-here' WITH GRANT OPTION;
                
                    Preview what you type in an input or a textarea out of them (in a html tag, like a p, hx...)

Seen here: http://amuchamu.bitacoras.com/archivos/2005/02/17/previsualizacion_de_comentarios (spanish explain).

javascript code:

function preview(id1, id2){
	  		var NewText = document.getElementById(id1).value;
	  		splitText = NewText.split(/\n/).join("<br />");
	  		var DivElement = document.getElementById(id2);
	  		DivElement.innerHTML = splitText;
}


html code:

<form action="#">
<label>Name:</label>
<input type="text" id="nombre" onkeyup="preview('name', 'preview-name');" />

<label>Phone:</label>
<input type="text" id="phone" onkeyup="preview('phone', 'preview-phone');" />
</form>

<h2>Preview</h2>
<dl>
	<dt>Name:</dt>
	<dd id="preview-name"></dd>
	<dt>Phone:</dt>
	<dd id="preview-phone"></dd>

</dl>
                
                    This function transforms an HTTP request path (ie, $_SERVER['PATH_INFO']) into its canonical form, removing empty path elements and relative path elements (//, /./, /../). It assumes that there is a trailing slash on the path if it's a directory.

function canonical_path($path) {
    $canonical = preg_replace('|/\.?(?=/)|','',$path);
    while (($collapsed = preg_replace('|/[^/]+/\.\./|','/',$canonical,1)) !== $canonical) {
        $canonical = $collapsed;
    }
    $canonical = preg_replace('|^/\.\./|','/',$canonical);
    return $canonical;
}
                
                    The following code is for loading Velocity resources (i.e. Velocity files) from a web application's ServletContext.

import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

public class WebAppResourceLoader extends ResourceLoader {

    private static ServletContext context = null;

    public void init(ExtendedProperties extendedProperties) {

    }

    private static ServletContext getServletContext() {
        return context;
    }

    public static void setServletContext(ServletContext context) {
        WebAppResourceLoader.context = context;
    }

    /**
     * @see org.apache.velocity.runtime.resource.loader.ResourceLoader#getResourceStream(java.lang.String)
     */
    public InputStream getResourceStream(String name)
            throws ResourceNotFoundException {
        InputStream result = null;

        if (name == null || name.length() == 0) {
            throw new ResourceNotFoundException("No template name provided");
        }

        try {
            if (!name.startsWith("/"))
                name = "/" + name;

            result = getServletContext().getResourceAsStream(name);
        } catch (NullPointerException npe) {
            throw new ResourceNotFoundException("ServletContext not found");
        } catch (Exception fnfe) {
            throw new ResourceNotFoundException(fnfe.getMessage());
        }

        return result;
    }

    public boolean isSourceModified(Resource arg0) {
        return false;
    }

    public long getLastModified(Resource arg0) {
        return 0;
    }

}

Then to initialize Velocity:

    WebAppResourceLoader.setServletContext(servletContext);
    Properties props = new Properties();
    props.setProperty("resource.loader", "webapp");
    props.setProperty("webapp.resource.loader.description", 
        "Load from the ServletContext");
    props.setProperty("webapp.resource.loader.class",
        "package.WebAppResourceLoader");
    Velocity.init(props);

From then on out you can use #parse directives such as:

#parse("/WEB-INF/something.vm")