Never been to DZone Snippets before?

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

About this user

karsten schmidt http://toxi.co.uk

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Customizable sigmoid function

/**
 * Calculates S-curve for point x in the interval 0 .. normV
 * 
 * @param x input coordinate
 * @param normV scale value which corresponds to 1.0 if x is normalized
 * @param sharpness adjusts steepness of curve (value of 1 equals undistorted sigmoid)
 *
 * @return sigmoid for point X
 */
public float sigmoid(float x, float normV, float sharpness) {
  x=(x/normV*2-1)*5*sharpness;
  return 1.0f / (1.0f + (float)Math.exp(-x));
}

public double sigmoid(double x, double normV, double sharpness) {
  x=(x/normV*2-1)*5*sharpness;
  return 1.0 / (1.0 + Math.exp(-x));
}

baseX converter

you can use this function to convert an integer into any number system upto base36 (e.g. for TinyURL generation coupled with a global ID counter)

function int2baseX($val,$base=16) {
  if (0==$val) return 0;
  $symbols='0123456789abcdefgihjklmnopqrstuvwxyz';
  $result='';
  $exp=$oldpow=1;
  while($val>0 && $exp<10) {
    $pow=pow($base,$exp++);
    $mod=($val % $pow);
    $result=substr($symbols,$mod/$oldpow,1).$result;
    $val-=$mod;
    $oldpow=$pow;
  }
  return $result;
}

create pre-styled/populated DOM elements

/*
 * create a new DOM element with (optionally) specified className, CSS and text/html content
 * if text contains any markup, it's used as innerHTML value - else a child text node is attached
 * if there's also a parent node given, the new element will be appended as child node
 */
function createStyledElement(tag, parent, cls, css, txt) {
    var el = document.createElement(tag);
    if(cls) el.className = cls;
    if(css) for(var s in css) el.style[s]=css[s];
    if(txt) {
        if (txt.indexOf('<')!=-1) el.innerHTML=txt;
        else el.appendChild(document.createTextNode(txt));
    }
    if(parent) parent.appendChild(el);
    return el;
}

// usage example...
// 1st define some style params
var style1={
    background: '#def',
    color: '#f00',
    padding: '0.5em',
    border: '1px black dotted'
};

createStyledElement(
  'div',
  document.getElementsByTagName('body').item(0),
  null,
  style1,
  'hello <em>world</em>!'
);
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS