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

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

« Newer Snippets
Older Snippets »
Showing 1-10 of 4857 total  RSS 

Javascript sleep

Imitate sleep in javascript

function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
}
} 

Google Maps - GDirections [getMileage]

When the user clicks a button the suggest_allocations() function runs.

When it reaches gdir.load() there is a GEvent.addListener function that runs displayDistTimeResults()

function suggest_allocations(){
	
	$("#pop_out_placeholder").empty();
	$("#pop_out_placeholder").show();
	
	$("#pop_out_placeholder").append('<B>Suggested Vehicle Allocations</B><br/>');

	var number_of_avail_vehicles = vehicles_avail.length;
	var customer_origin = document.getElementById("booking_origin").value;
	
	for(num = 0; num < number_of_avail_vehicles; num++){
	
		var current_item = vehicles_avail[num].split("{*}");
		var current_vehicle_id = current_item[0];
		var current_vehicle_loc= current_item[1];
		var current_vehicle_nam= current_item[2];
			
		var locale		= "en-gb";

		$("#current_vehicle").val("");
		$("#current_vehicle").val(current_vehicle_nam);

		gdir.load("from: " + current_vehicle_loc + " to: " + customer_origin, { "locale": locale});
		
		alert('');
	}
}

function displayDistTimeResults(){

	var current_vehicle = document.getElementById("current_vehicle").value;
	var mileage 	= gdir.getDistance().meters / 1609.344;
				
	$("#pop_out_placeholder").append(current_vehicle + ' is ' + mileage + '<br/>');

}

Recording audio using Asterisk

Copied from Asterisk™: The Future of Telephony | Chapter 13. Managing Your Asterisk System Customizing System Prompts [leifmadsen.com]

This little addition to your dialplan will allow you to easily create recordings, which will be placed in your system’s /tmp/ folder (from there, you can rename them and move them wherever you’d like):
exten => _66XX,1,Wait(2)
exten => _66XX,n,Record(/tmp/prompt${EXTEN:2}:wav)
exten => _66XX,n,Wait(1)
exten => _66XX,n,Playback(/tmp/prompt${EXTEN:2})
exten => _66XX,n,Wait(2)
exten => _66XX,n,Hangup()

This snippet will allow you to dial from 6600 to 6699, and it will record prompts in the /tmp/ folder using the names prompt00.wav to prompt99.wav. After you complete recording (by pressing the # key), it will play your prompt back to you and hang up.

Be sure to move your prompts out of the /tmp/ dir to the Asterisk sounds directory.

Ruby simple SMTP email

By Ian Purton and found at http://jiploo.com/blog/simple-email-send-function-in-ruby/
def send_email(from, from_alias, to, to_alias, subject, message)
	msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}
	
#{message}
END_OF_MESSAGE
	
	Net::SMTP.start('localhost') do |smtp|
		smtp.send_message msg, from, to
	end
end

Rails 2.1.0 monkey patch to add the recognized or matched rails route to the request

This was based on code I found here from Chris Cruft - http://cho.hapgoods.com/wordpress/?p=151

Enhanced to support rails 2.1.0 and also allows alias method chains for recognize from other plugins still to work.

module ActionController
  class AbstractRequest
    attr_reader :recognized_route
    
    def init_recognized_route_from_path_parameters
      recognized_route = path_parameters.delete(:recognized_route) 
    end
  end

  module Routing
    
    class RouteSet
      def recognize_with_route(request)
        result = recognize_without_route(request)
        request.init_recognized_route_from_path_parameters
        result
      end
      alias_method_chain :recognize, :route

      def write_recognize_optimized_with_route
        tree = segment_tree(routes)
        body = generate_code(tree)
        instance_eval %{
          def recognize_optimized(path, env)
            segments = to_plain_segments(path)
            index = #{body}
            return nil unless index
            while index < routes.size
              result = routes[index].recognize(path, env) and result[:recognized_route] = routes[index] and return result
              index += 1
            end
            nil
          end
        }, __FILE__, __LINE__
      end
      alias_method_chain :write_recognize_optimized, :route

    end
  end
end

updated version of _paginate.rhtml partial

// updated version of _paginate.rhtml partial to work with
// http:/www.igvita.com/2006/09/10/faster-pagination-in-rails
// and the (changed) css pagination at
//http://www.dynamicdrive.com/style/csslibrary/item/css_pagination_links/

<% if collection.page_count != collection.first_page -%>
<div class="pagination">
  <ul>
    <li><%= link_to '&#171; previous', { :page => collection.previous_page } , {:class => "prevnext#{' disablelink' if !collection.previous_page?}"}%></li>
    <% last_page = 0 -%>
    <% windowed_pagination_links(collection, :window_size => 2, :link_to_current_page => true, :always_show_anchors => true) do |n| -%>
	      <li><%= "..." if last_page+1 < n %><%= link_to n, {:id => params[:id], :page => n}, {:class => (collection.page == n ? 'currentpage' : nil)} %></li>
	      <% last_page = n -%>
	  <% end -%>
    <li><%= link_to 'next &#187;', { :page => collection.next_page } , {:class => "prevnext#{' disablelink' if !collection.next_page?}"}%></li>
  </ul>
</div>
<% end -%>
 

jsp生成验证码

random.jsp jsp生成验证码

<%@ page language="java" contentType="image/jpeg; charset=gb2312" 
pageEncoding="gb2312"%> 
<%@ page import="java.awt.*,java.awt.image.*" %> 
<%@ page import="java.util.*,javax.imageio.*" %> 
<%! 
Color getRandColor(int fc,int bc){ 
Random r=new Random(); 
if(fc>255) fc=255; 
if(bc>200) bc=255; 
int red=fc+r.nextInt(bc-fc); 
int green=fc+r.nextInt(bc-fc); 
int blue=fc+r.nextInt(bc-fc); 
return new Color(red,green,blue); 
}%> 
<% //设置页面不缓存 
response.setHeader("Pragma","No-cache"); 
response.setHeader("cache-Control","no-cache"); 
response.setDateHeader("Expires",0); 
//创建随机类 
Random r=new Random(); 
//在内存中创建图像,宽度,高度 
int width=80,height=30; 
BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 
//获取图形上下文环境 
Graphics gc=pic.getGraphics(); 
//设定背景颜色并进行填充 
gc.setColor(getRandColor(200,250)); 
gc.fillRect(0,0,width,height); 
//设定图形上下文环境字体 
gc.setFont(new Font("Times New Roman",Font.PLAIN,20)); 
//画边框 
//gc.setColor(new Color(1)); 
//gc.drawRect(0,0,width-1,height-1); 

//随机产生200条干扰直线,使图像中的认证码不易被其他分析程序探测 
gc.setColor(getRandColor(160,200)); 
for(int i=0;i<200;i++) 
{ 
int x1=r.nextInt(width); 
int y1=r.nextInt(height); 
int x2=r.nextInt(15); 
int y2=r.nextInt(15); 
gc.drawLine(x1,y1,x1+x2,y1+y2); 
} 
//随即产生100个干扰点 
gc.setColor(getRandColor(120,240)); 
for(int i=1;i<100;i++){ 
int x=r.nextInt(width); 
int y=r.nextInt(height); 
gc.drawOval(x,y,0,0); 
} 
//随机产生四位数字的验证码 
String RS=""; 
String rn=""; 
for(int i=0;i<4;i++) 
{ 
//产生十以内随机数字 
rn=String.valueOf(r.nextInt(10)); 
RS+=rn; 
//将认证码用drawString函数显示到图像里 
gc.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));//使字体颜色效果明显 
gc.drawString(rn,13*i+16,16); 
} 
//释放图形上下文环境 
gc.dispose(); 
//将认证码RS存入session中共享 
session.setAttribute("random",RS); 

//输出生成后的图象到页面 
ImageIO.write(pic,"JPEG",response.getOutputStream()); 

out.clear(); 
out = pageContext.pushBody(); 

%> 

Disk/flash benchmark

Adapted from a LKML posted program. I think I added write support, this for benchmarking random access writes on flash.

/* Simple multi-threaded I/O benchmark program.
 * Copyright (C) Michael Tokarev, mjt@tls.msk.ru
 * Public domain.
 *
 * To compile:
 *   gcc -o iot iot.c -lpthread
 * To run:
 *   Either with disk device or with pre-existing file.
 *    ./iot [options] filename
 *   Filename is the file or device to test on.
 *   By default it uses 8Kb I/O blocks and does sequential read test
 *   until interrupted.
 *   To indicate when to stop:
 *     -t sec - run for this many seconds, say, 30, to eliminate random
 *       noise.
 *     -i num - perform this many I/O operations
 *   To indicate R/W mode:
 *     -wn, -Wn, -rn, -Rn --
 *       perform linear or random write (note: all data will be lost!),
 *       or linear or random read, using given number of threads (n).
 *   I/O modes:
 *    -s - syncronous write (O_SYNC)
 *    -d - direct I/O (O_DIRECT)
 *    -b bs - block size in bytes
 *   And finally:
 *    -h - display usage.
 * Example:
 *   ./iot -t30 -W4 -R4 -d -b8192 /dev/sdb
 * perform random read/write test (4 readers and 4 writers)
 * for 30 seconds using direct I/O and block size of 8Kb.
 *
 * Note: for small blocksize (<64Kb at least) and using direct random I/O,
 * nowadays drives sometimes gives transfer rates below 1Mb/sec - this is
 * expectable, don't be afraid of so low numbers.  The reason is simple:
 * in order to access a given block of data, a disk drive has to seek to the
 * right track (average seek time) and wait for the right sector to be near
 * the head (rotation latency).  Sum up the two, and divide 1 sec to the
 * result -- you'll have max number of requests/sec a drive can perform,
 * not counting the actual data transfer (which reduces this number further).
 * With, say, 5ms seek time + rotation latency, we'll have 200 requests/sec,
 * which, with 4Kb request size, will be about 800Kb/sec - which is below
 * 1Mb/sec, not counting the actual transfer...
 *
 */

#define _GNU_SOURCE
#define _BSD_SOURCE
#define _LARGEFILE_SOURCE
#define _FILE_OFFSET_BITS 64

//#define USE_DEV_URANDOM       /* was not a good idea */

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <pthread.h>
#include <string.h>

#ifndef BLKGETSIZE64
#define BLKGETSIZE64 _IOR(0x12,114,size_t)
 /* linux-specific. return device size in bytes (u64 *arg) */
#endif

static void edie(const char *what) {
  fprintf(stderr, "%s: %m \n", what);
  exit(1);
}

#ifdef USE_DEV_URANDOM
static int randfd;
#endif
static int oflags;              // open flags
static char *fn;                // filename
static unsigned bs = 8192;      // block size
static unsigned bc;             // block count (device size in blocks)
static unsigned bm;             // blocks to do

#define MFrnd   1
#define MFwrt   2
#define LinRd   0
#define RndRd   MFrnd
#define LinWr   MFwrt
#define RndWr   (MFrnd|MFwrt)

struct state {
  int fd;
  char *buf;
  unsigned ioc;         // I/O count
  int (*workfn)(struct state *, unsigned blocknr);
  unsigned (*posfn)(struct state *s);
  unsigned opi;         // operation index
  unsigned i;           // curidx
  double stime;         // start time
  unsigned bn;          // current block number for linear i/o
};
static unsigned int alternate;
static unsigned tioc;   // total i/o count
static struct state *states;
static unsigned nt[4];
static unsigned ntt;
static volatile unsigned running;
static const char *const ion[4] = { "LinRd", "RndRd", "LinWr", "RndWr" };

static pthread_mutex_t rnmtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t rncond = PTHREAD_COND_INITIALIZER;

static double curtime(void) {
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec + tv.tv_usec / 1000000.0;
}

static unsigned randpos(struct state *s) {
  unsigned n;
#ifdef USE_DEV_URANDOM
  read(randfd, &n, sizeof(n));
#else
  n = lrand48();
#endif
  s = s;
  if(alternate == 1) {
    if(n > bc/2) {
      return bc-1;
    } else {
      return 0;
    }
  }
  return n % bc;
}

static unsigned linpos(struct state *s) {
  if (s->bn >= bc)
    s->bn = 0;
  return s->bn++;
}

static int wwriter(struct state *s, unsigned b) {
  return pwrite(s->fd, s->buf, bs, (off_t)b * bs);
}
static int wreader(struct state *s, unsigned b) {
  return pread(s->fd, s->buf, bs, (off_t)b * bs);
}

static void pst(FILE *f) {
  double ct = curtime();
  double r[4] = { 0, 0, 0, 0 };
  unsigned c[4] = { 0, 0, 0, 0 };
  unsigned i;
  double d;
  for(i = 0; i < ntt; ++i) {
    d = ct - states[i].stime;
    r[states[i].opi] += states[i].ioc / d;
    c[states[i].opi] += states[i].ioc;
  }
#if 1
  for(i = 0; i < 4; ++i)
    if (c[i])
      fprintf(f, " %s %u %.2f", ion[i], c[i], r[i] * bs / 1024 / 1024);
#endif
}

static void incc() {
  if (!(++tioc % 1000))
    pthread_cond_signal(&rncond);
}
static void decnr() {
  pthread_mutex_lock(&rnmtx);
  --running;
  pthread_mutex_unlock(&rnmtx);
  pthread_cond_broadcast(&rncond);
}

static volatile int term;

void *worker(void *arg) {
  struct state *s = arg;
  s->workfn = s->opi & MFwrt ? wwriter : wreader;
  s->posfn  = s->opi & MFrnd ? randpos : linpos;
  s->fd = open(fn, (s->opi & MFwrt ? O_WRONLY : O_RDONLY) | oflags);
  if (s->fd < 0) {
    int e = errno;
    decnr();
    errno = e;
    edie(fn);
  }
  s->stime = curtime();
  for(;;) {
    if (term) break;
    if (s->workfn(s, s->posfn(s)) < 0) {
      perror(ion[s->opi]);
      break;
    }
    ++s->ioc;
    incc();
    if (bm && s->ioc >= bm) break;
  }
  decnr();
  return 0;
}

static void sig(int s) {
  term = s;
}

int main(int argc, char **argv) {
  int c;
  unsigned i, j;
  unsigned tm = 0;
  struct state *s;
  char *buf;
  struct timeval  first,
                second,
                lapsed;

  while((c = getopt(argc, argv, "r::R::w::W::adsb:n:i:t:h")) != EOF) switch(c) {
  case 'r': nt[LinRd] = optarg ? atoi(optarg) : 1; break;
  case 'R': nt[RndRd] = optarg ? atoi(optarg) : 1; break;
  case 'w': nt[LinWr] = optarg ? atoi(optarg) : 1; break;
  case 'W': nt[RndWr] = optarg ? atoi(optarg) : 1; break;
  case 'd': oflags |= O_DIRECT; break;
  case 's': oflags |= O_SYNC; break;
  case 'b': bs = atoi(optarg); break;
  case 'n': bc = atoi(optarg); break;
  case 'i': bm = atoi(optarg); break;
  case 't': tm = atoi(optarg); break;
  case 'a': alternate = 1; break;
  case 'h':
    puts(
"iotest: perform I/O speed test\n"
"Usage is: iotest [options] device-or-file\n"
"options:\n"
" -r[n] - linear read test (n readers)\n"
" -R[n] - random read test (n readers)\n"
" -w[n] - linear write test (n writers)\n"
" -W[n] - random write test (n writers)\n"
" -d - use direct I/O (O_DIRECT)\n"
" -s - use syncronous I/O (O_SYNC)\n"
" -b bs - blocksize (default is 8192)\n"
" -n bc - block count (default is whole device/file)\n"
" -i nb - number of I/O iterations to perform\n"
" -t sec - time to spend on all I/O\n"
" -h - this help\n"
"It's ok to specify all, one or some of -r,-R,-w and -W\n"
);
    return 0;
  default: fprintf(stderr, "try `iotest -h' for help\n"); exit(1);
  }

  if (optind + 1 != argc) {
    fprintf(stderr, "exactly one device/file argument expected\n");
    return 1;
  }
  fn = argv[optind];

  ntt = nt[0] + nt[1] + nt[2] + nt[3];
  if (!ntt)
    nt[LinRd] = ntt = 1;

  c = open(fn, (nt[LinWr] + nt[RndWr] ? O_RDWR : O_RDONLY) | oflags);
  if (c < 0) edie(fn);
  if (!bc) {
    unsigned long long sz;
    struct stat st;
    fstat(c, &st);
    if (st.st_size) sz = st.st_size;
    else ioctl(c, BLKGETSIZE64, &sz);
    bc = sz / bs;
    fprintf(stderr, "size = %lld (%u blocks)\n", sz, bc);
  }
  close(c);
  if (nt[RndRd] || nt[RndWr]) {
#ifdef USE_DEV_URANDOM
    randfd = open("/dev/urandom", O_RDONLY);
    if (randfd < 0) edie("/dev/urandom");
#else
#if 0
    struct timeval tv;
    gettimeofday(&tv, NULL);
    srand48(tv.tv_usec ^ getpid());
#else
    srand48(0xfeda432); // arbitrary, to get repeated values on repeated runs
#endif
#endif
  }

  gettimeofday(&first, NULL);

  states = calloc(ntt, sizeof(*states));
  s = states;

  buf = valloc(ntt * bs);
  if (tm) {
    signal(SIGALRM, sig);
    alarm(tm);
  }
  running = ntt;
  for(j = 0; j < 4; ++j)
    for(i = 0; i < nt[j]; ++i) {
      pthread_t t;
      s->buf = buf; buf += bs;
      s->opi = j;
      s->i = i;
      pthread_create(&t, NULL, worker, s++);
    }
  while(running) {
    pthread_cond_wait(&rncond, &rnmtx);
    putc('\r', stderr);
    pst(stderr);
  }

  putc('\r', stderr);
  pst(stdout);
  putc('\n', stdout);

  gettimeofday(&second, NULL);

  if (first.tv_usec > second.tv_usec) {
    second.tv_usec += 1000000;
    second.tv_sec--;
  }

  lapsed.tv_usec = second.tv_usec - first.tv_usec;
  lapsed.tv_sec  = second.tv_sec  - first.tv_sec;



  if (nt[RndRd] || nt[RndWr]) {
        printf("I/O latency: %f\n", (lapsed.tv_sec*1000+(lapsed.tv_usec/1000))/(float)tioc);

  }

  return 0;
}

ant 脚本

ant 构架部署web应用脚本

build.properties:
=====================================
appserver.home=d:/tomcat
deploy.path=${appserver.home}/webapps

tomcat.manager.url=http://localhost:8080/manager

tomcat.manager.username=spring
tomcat.manager.password=spring
=====================================

<?xml version="1.0" encoding="gb2312"?>

<project name="springapp" basedir="." default="usage">

	<property file="build.properties"/>	
	<property name="src.dir" value="src"/>
	<property name="extlib.dir" value="lib"/>	
	<property name="web.dir" value="war"/>
	<property name="config.dir" value="config"/>	
	<property name="class.dir" value="${web.dir}/WEB-INF/classes"/>
	<property name="lib.dir" value="${web.dir}/WEB-INF/lib"/>	
	<property name="name" value="springapp"/>

	<path id="master-classpath">
		<fileset dir="${lib.dir}">
			<include name="*.jar"/>
		</fileset>

		<fileset dir="${appserver.name}/common/lib">
			<include name="servlet*.jar"/>
		</fileset>

		<pathelement path="${class.dir}"/>
	</path>

	<target name="usage" description="脚本包含的可执行命令">
		<echo message="【帮助信息】${name}工程可用命令:"/>		
		<echo message="使用方法:在ant 命令后加下列命令"/>
		<echo message=""/>
		<echo message="build:-->(编译工程)build the application"/>
		<echo message="deploy:-->(发布应用)deploy application as directory"/>
		<echo message="deploywar:-->(打包成war文件)deploy application as a war file"/>
		<echo message="install:-->(将应用安装到tomcat)Install application in tomcat"/>
		<echo message="reload:-->(重新装入应用)reload application in tomcat"/>
		<echo message="start:-->(开始tomcat应用)start tomcat application"/>
		<echo message="stop:-->(停止tomcat应用)stop tomcat application"/>
		<echo message="list:-->(列表tomcat的应用)list tomcat application"/>
	</target>

	<!--[初始化]
		1.建立目录
		2.拷贝外部引用包web-inf/lib
		3.拷贝配置文件(web.xml等)至web-inf	
	-->
	<target name="init">
		<mkdir dir="${class.dir}" />
		<mkdir dir="${lib.dir}" />
		
		<copy todir="${lib.dir}">
			<fileset dir="${extlib.dir}">
				<include name="*.jar"/>
			</fileset>			
		</copy>

		<copy todir="${web.dir}/WEB-INF">
			<fileset dir="${config.dir}">
				<include name="web.xml"/>
			</fileset>			
		</copy>	
	</target>

	<!-- [编译程序] -->
	<target name="build" depends="init" description="build the application">
		<javac srcdir="${src.dir}" destdir="${class.dir}" debug="true" deprecation="true">
			<classpath refid="master-classpath" />
		</javac>

		<copy todir="${class.dir}">
			<fileset dir="${src.dir}">
				<include name="**/*.gif" /> 
				<include name="**/*.jpg" /> 
				<include name="**/*.png" /> 
				<include name="**/*.wav" /> 
				<include name="**/*.dtd" /> 
				<include name="**/*.properties" /> 
			</fileset>
		</copy>		
	</target>
	
	<!-- [发布目录到tomcat]
		1.建立tomcat目录
		2.拷贝war目录下所有内容到tomcat目录
	-->
	<target name="deploy" description="Deploy application to servlet container">		 
		 <mkdir dir="${deploy.path}/${name}"/>
		 <copy todir="${deploy.path}/${name}">
			<fileset dir="${web.dir}"/>
		 </copy>
	</target>
	
	<!--[发布应用为war包]-->
	<target name="deploywar">
		<war destfile="${name}.war" webxml="${web.dir}/WEB-INF/web.xml">
			<fileset dir="${web.dir}"/>
		</war>
	</target>

	<!--[删除tomcat应用]-->
	<target name="clean">
		<delete dir="${deploy.path}/${name}"/>
	</target>

	<target name="start">
		<java jar="${appserver.home}/bin/bootstrap.jar" fork="true">
			<jvmarg value="-Dcatalina.home=${appserver.home}"/>
			<arg line="start"/>
		</java>
	</target>

	<target name="stop">
		<java jar="${appserver.home}/bin/bootstrap.jar" fork="true">
			<jvmarg value="-Dcatalina.home=${appserver.home}"/>
			<arg line="stop"/>
		</java>
	</target>
	
</project>

Get Form Element's Value in FCKeditor

FCKeditorAPI.GetInstance('form_element').GetHTML();
« Newer Snippets
Older Snippets »
Showing 1-10 of 4857 total  RSS