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

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

date_select conversion

function to convert a value from a date_select into a more sql-friendly value

<%=date_select(:date,'',:start_year => 1950,:include_blank => false, :default => { :year => '1970' })%>

def convert_date(obj) 
  return “#{obj[‘(1i)’]}-#{obj[‘(2i)’]}-#{obj[‘(3i)’]}” 
end

PHP Select Form Helper

// takes an array of values and a value to match, and outputs formatted <option>s with the <option> matching $match selected
// must be manually wrapped in <select></select to allow for maximum flexibility

function selectHelper($values, $match)
{
  $keys = array_keys($values);
  $i = 0;
	
  foreach($values as $option)
  {
    $selected = null;
		
    if($match == $keys[$i])
      $selected = " selected";
			
    echo "	<option value=\"".$keys[$i]."\"$selected>".$option."</option>\n";
		
    $i++;
  }
}

//sample usage:
$values = array(
  "lb" => "Pounds",
  "ea" => "Each",
  "oz" => "Ounces");
				
  selectHelper($values, $product->unit);

Select DataBase Schema

// Select database schema.
//This could be used to recreate or test for existence of columns/tables
//or could also be used to create a database template system to enable the writing //of database schema into txt template file to be recreated again by reading the //txt file via an application
//
//You can also use SELECT * instead of defining each schema property (column)

SELECT TABLE_CATALOG
, TABLE_SCHEMA
, TABLE_NAME
, ORDINAL_POSITION
, COLUMN_DEFAULT
, IS_NULLABLE
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, COLLATION_NAME 
FROM 
INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = (N'Persons')

SQL -> Check Column exists in table, if not, add

// Check to see if column exists and then create if not

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME =TEST’ AND COLUMN_NAME =TEST_DATE’)
BEGIN
   ALTER TABLE TEST ADD TEST_DATE DATETIME
END

Use rails date_select without activerecord model

// In your view:
<%= date_select('range', 'start_date', :order => [:month, :day, :year])%>


// In your controller:
@start_date = Date.civil(params[:range][:"start_date(1i)"].to_i,params[:range][:"start_date(2i)"].to_i,params[:range][:"start_date(3i)"].to_i)


Credit: http://www.jonsthoughtsoneverything.com/2006/05/21/how-to-access-date_select-without-an-active-record-model/

Fast selection

Selectv returns the position of the nth smallest number in the list.

Selectv modifies the list.

#include <stdio.h>

typedef struct {
	int len;
	int e[102];
} List;

void printv(char *msg, List l) {
	printf("%s", msg);
	int i;
	for (i = 0; i < l.len; ++i)
		printf("%d ", l.e[i]);
	printf("\n");
}

int pivot(List *l, int p, int r) {
	int x = l->e[r];
	int i = p - 1;
	int j = r + 1;
	
	while (1) {
		do {
			++i;
		} while (l->e[i] < x);
		do {
			--j;
		} while (l->e[j] > x);
	
		//printf("%d %d\n", i, j);
		
		if (i < j) {
			int aux = l->e[i];
			l->e[i] = l->e[j];
			l->e[j] = aux;
		} else
			return i - 1;
	}
}


int selectv(List *l, int nrp, int p, int r) {
	//printf("p, r: %d, %d\n", p, r);
	//printf("nrp: %d\n", nrp);
	//printv("l: ", *l);
	
	if (p == r)
		return l->e[p];
	
	if (p < r) {
		int q = pivot(l, p, r);
		
		//getchar();
		
		if (q - p + 1< nrp)
			return selectv(l, nrp - (q - p) - 1, q + 1, r);
		return selectv(l, nrp, p, q);
	}
	return -1;
}

int main(int argc, char *argv[]) {
	List l;
	l.len = 100;
	int i;
	for (i = 0; i < l.len; ++i)
		l.e[i] = l.len - i;
	
	int nth = 56;
	printf("%d: %d\n", nth, selectv(&l, nth, 0, l.len - 1));
	
	//printv("L: ", l);
	
	return 0;
}

Selection //JavaScript Class




Retrieves and sets the cursor position, as well the selected text of inputs and textareas. After searching, I saw it's the only code which retrieves right information in textareas under Internet Explorer without damaging the "Ctrl+Z"

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/selection [v1.0]

Selection = function(input){
	this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
};
with({o: Selection.prototype}){
	o.setCaret = function(start, end){
		var o = this.input;
		if(Selection.isStandard)
			o.setSelectionRange(start, end);
		else if(Selection.isSupported){
			var t = this.input.createTextRange();
			end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
			start -= o.value.slice(0, start).split("\n").length - 1;
			t.move("character", start), t.moveEnd("character", end), t.select();
		}
	};
	o.getCaret = function(){
		var o = this.input, d = document;
		if(Selection.isStandard)
			return {start: o.selectionStart, end: o.selectionEnd};
		else if(Selection.isSupported){
			var s = (this.input.focus(), d.selection.createRange()), r, start, end, value;
			if(s.parentElement() != o)
				return {start: 0, end: 0};
			if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
				return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
			for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
			r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
			s.text = $, start = o.value.indexOf($);
			if(d.execCommand && d.queryCommandSupported("Undo"))
				for(r = 3; --r; d.execCommand("Undo"));
			return o.value = value, this.setCaret(start, end), {start: start, end: end};
		}
		return {start: 0, end: 0};
	};
	o.getText = function(){
		var o = this.getCaret();
		return this.input.value.slice(o.start, o.end);
	};
	o.setText = function(text){
		var o = this.getCaret(), i = this.input, s = i.value;
		i.value = s.slice(0, o.start) + text + s.slice(o.end);
		this.setCaret(o.start += text.length, o.start);
	};
	new function(){
		var d = document, o = d.createElement("input"), s = Selection;
		s.isStandard = "selectionStart" in o;
		s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
	};
}


Example

<form id="form">
	<fieldset>
		<legend>Selection Test</legend>
		<textarea name="text" rows="10" cols="30">
www.jsfromhell.com
Jonas Carlos Lalala
Bin Laden x Bush
		</textarea><br />
		<input name="getText" type="button" value="[Get selected text]" />
		<input name="getSel" type="button" value="[Get cursor]" />
		<br /><input name="setText" type="button" value="[Set selected text]" />
		<input name="setSel" type="button" value="[Set cursor]" />
	</fieldset>
</form>

<script type="text/javascript">
var f = document.forms.form;
var selection = new Selection(f.text);

f.getText.onclick = function(){
	alert(selection.getText());
	f.text.focus();
};
f.setText.onclick = function(){
	var s = prompt("New text:", selection.getText());
	s !== null && selection.setText(s);
	f.text.focus();
};
f.getSel.onclick = function(){
	var s = selection.getCaret();
	alert("Start: " + s.start + "\nEnd: " + s.end);
	f.text.focus();
};
f.setSel.onclick = function(){
	var s = selection.getCaret();
	selection.setCaret(+prompt("Start:", s.start) || 0, +prompt("End:", s.end) || 0);
	f.text.focus();
};
</script>

PHP: Create a SELECT input field

Creates a SELECT input field with an optional parameter to preselect an item

function selectfield($optionsarray, $selected = "") {
  $returnval = "";
  foreach ($optionsarray as $field=>$value) {
    if ($field == $selected) {
      $returnval .= "<option selected value='" . $field . "'>" . $value . "</option>\n";
    } else {
      $returnval .= "<option value='" . $field . "'>" . $value . "</option>\n";
    }
  }
  
  return $returnval;
}

MSSQL 2005 - Add ID value to ID column when INSERTING

// @TableName is obviously the TABLE name u use
// @ColumnName is obviously the COLUMN name u use

---Get next ID number
	DECLARE 
		@ID int
	
	IF (SELECT count(*) FROM @TableName ) > 0
		BEGIN
			SELECT @ID  = max(ColumnName ) from @TableName
			SET @ID = @ID + 1 
		END
	ELSE
	BEGIN
		SET @ID  = 1
	END

HTML/JavaScript - Select list - Add/Remove Options (DOM)

from http://www.mredkj.com/tutorials/tutorial005.html


Overview

* Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
* Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
* Append Last - No matter what is selected, a new option is added at the end.
* Remove Last - No matter what is selected, the last option is deleted from the list.


Explanation

According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed.


The JavaScript
<script language="JavaScript" type="text/javascript">
<!--
var count1 = 0;
var count2 = 0;

function insertOptionBefore(num)
{
  var elSel = document.getElementById('selectX');
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionSelected()
{
  var elSel = document.getElementById('selectX');
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
    }
  }
}

function appendOptionLast(num)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = 'Append' + num;
  elOptNew.value = 'append' + num;
  var elSel = document.getElementById('selectX');

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast()
{
  var elSel = document.getElementById('selectX');
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}
//-->
</script>



The HTML
<form>
<input type="button" value="o" onclick="insertOptionBefore(count1++);" />
Insert Before Selected<br />
<input type="button" value="o" onclick="removeOptionSelected();" />
Remove Selected<br />
<select id="selectX" size="10" multiple="multiple">
<option value="original1" selected="selected">Orig1</option>
<option value="original2">Orig2</option>
</select>
<br />
<input type="button" value="o" onclick="appendOptionLast(count2++);" />
Append Last<br />
<input type="button" value="o" onclick="removeOptionLast();" />
Remove Last
</form>

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