/ Gists

Gists

On gists

Mysql update join

MySql

update-join.sql #

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}
Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

On gists

jQuery - keyup with delay (timeout)

jQuery Helpers-Filters-Plugins jQuery-plugins

keyup-delay1.js #

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();


$('input').keyup(function() {
    delay(function(){
      alert('Time elapsed!');
    }, 1000 );
});

On gists

CSS - full height with resizable header & footer with TABLE LAYOUT

CSS CSS trick

layout.css #

html, body {
    height: 100%;
    margin: 0;

}
.container {
    display: table;
    height: 100%;
    /*border-spacing: 10px;
    margin: 0 -10px;
    */
    width: 100%;
}
.nav, .content, .footer {
    display: table-row;
}
.cell {
    display: table-cell;
}
.nav div, .footer div {
    background-color: #1565C0;
}
.content div {
    height: 100%; /* Nutné, aby obsah dominantne zaberal všetko voľné miesto. */
    border: 1px solid;
}
p {
    padding: 1em;
    margin: 0;
}

On gists

Very simple autosave functionality using local storage

JavaScript Helpers-Filters-Plugins jQuery-plugins

test.html #

<html>
    <body>    
        <textarea rows=24 cols=80></textarea>
        <script type="text/javascript" src="autosave.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                AutoSave.start();
            })

            $(window).unload(function(){
                AutoSave.stop();
            });
        </script>
    </body>
</html>

On gists

Client-side Autosave Using localStorage with jQuery in textarea

JavaScript

autosave.js #

$(document).ready(function() {

///////////////////////
//
// Recovery Below
//
///////////////////////

  // Retrieve the object from storage onReady
  var autosave = localStorage.getItem('file');

  // parses the string (btw. its UTF-8)
  var text = JSON.parse(autosave);

  //modifies the textarea with the id="inputTextArea" 
  $("textarea#inputTextArea").val(text);

////////////////////////
//
//  Autosaver below
//
////////////////////////

  // Autosave on keystroke works in offline mode
  $("textarea#inputTextArea").change (function(){

     // pulls the value from the textarea
     var file = $('textarea#inputTextArea').val();

     // sets the file string to hold the data
     localStorage.setItem('file', JSON.stringify(file));
  });

});

On gists

MathUtils

jQuery Helpers-Filters-Plugins jQuery-plugins

mathutils.jquery.js #

(function($) {
  $.mathUtils = {
    sum: function(array) {
      var total = 0;

      $.each(array, function(index, value) {
        total += $.mathUtils.parseCzechFloat(value);
      });
      return total;
    },
    parseCzechFloat: function(string) {
      var value = $.trim(string);
      return parseFloat(value.replace(' ', '').replace(',', '.')) || 0;
    },
    formatCzechFloat: function(number) {
      return String(number).replace('.', ',');
    },
    average: function(array) {
      if ($.isArray(array)) {
        return $.mathUtils.sum(array) / array.length;
      }
      return '';
    }
  };
})(jQuery);

On gists

On responsive no hover etc

JavaScript Helpers-Filters-Plugins

on-responsive-no-hover.js #


      if ('createTouch' in document)
      {
          try
          {
              var ignore = /:hover/;
              for (var i=0; i<document.styleSheets.length; i++)
              {
                  var sheet = document.styleSheets[i];
                  for (var j=sheet.cssRules.length-1; j>=0; j--)
                  {
                      var rule = sheet.cssRules[j];
                      if (rule.type === CSSRule.STYLE_RULE && ignore.test(rule.selectorText))
                      {
                          sheet.deleteRule(j);
                      }
                  }
              }
          }
          catch(e){}
      }

On gists

Nette CSV response

Nette Nette-Tricks

NetteCsvResponse.php #

<?php

namespace Nette\Application\Responses;

use Nette;

/**
 * CSV download response.
 * Under New BSD license.
 *
 * @property-read string $name
 * @property-read string $contentType
 * @package Nette\Application\Responses
 */
class CsvResponse extends Nette\Object implements Nette\Application\IResponse
{
	/** @var array */
	private $data;

	/** @var string */
	private $name;

	/** @var bool */
	public $addHeading;

	/** @var string */
	public $glue;

	/** @var string */
	private $charset;

	/** @var string */
	private $contentType;


	/**
	 * @param array[]|\Traversable $data
	 * @param string $name
	 * @param bool $addHeading
	 * @param string $glue
	 * @param string $charset
	 * @param string $contentType
	 * @throws \InvalidArgumentException
	 */
	public function __construct($data, $name = NULL, $addHeading = TRUE, $glue = ';', $charset = 'utf-8', $contentType = NULL)
	{
		if (is_array($data)) {
			if (count($data) && !is_array(reset($data))) {
				$invalid = TRUE;
			}
		} elseif (!$data instanceof \Traversable) {
			$invalid = TRUE;
		}
		if (isset($invalid)) {
			throw new \InvalidArgumentException(__CLASS__.": data must be array of arrays or instance of Traversable.");
		}
		if (empty($glue) || preg_match('/^[\n\r]+$/s', $glue) || $glue === '"') {
			throw new \InvalidArgumentException(__CLASS__.": glue cannot be an empty or reserved character.");
		}

		$this->data = $data;
		$this->name = $name;
		$this->addHeading = $addHeading;
		$this->glue = $glue;
		$this->charset = $charset;
		$this->contentType = $contentType ? $contentType : 'text/csv';
	}


	/**
	 * Returns the file name.
	 * @return string
	 */
	final public function getName()
	{
		return $this->name;
	}


	/**
	 * Returns the MIME content type of a downloaded content.
	 * @return string
	 */
	final public function getContentType()
	{
		return $this->contentType;
	}


	/**
	 * Sends response to output.
	 * @param Nette\Http\IRequest $httpRequest
	 * @param Nette\Http\IResponse $httpResponse
	 */
	public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
	{
		$httpResponse->setContentType($this->contentType, $this->charset);

		if (empty($this->name)) {
			$httpResponse->setHeader('Content-Disposition', 'attachment');
		} else {
			$httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"');
		}

		$data = $this->formatCsv();

		$httpResponse->setHeader('Content-Length', strlen($data));
		print $data;
	}


	protected function formatCsv()
	{
		if (empty($this->data)) {
			return '';
		}

		$csv = array();

		if (!is_array($this->data)) {
			$this->data = iterator_to_array($this->data);
		}
		$firstRow = reset($this->data);

		if ($this->addHeading) {
			if (!is_array($firstRow)) {
				$firstRow = iterator_to_array($firstRow);
			}

			$labels = array();
			foreach (array_keys($firstRow) as $key) {
				$labels[] = ucfirst(str_replace(array("_", '"'), array(' ', '""'), $key));
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $labels).'"';
		}

		foreach ($this->data as $row) {
			if (!is_array($row)) {
				$row = iterator_to_array($row);
			}
			foreach ($row as &$value) {
				$value = str_replace(array('"'), array('""'), $value);
			}
			$csv[] = '"'.join('"'.$this->glue.'"', $row).'"';
		}

		return join("\r\n", $csv);
	}
}

On gists

Modal object with private functions

jQuery jQuery-plugins

modal.js #

    function feedbackModalFn(selector){

        //var feedbackModal = $('.feedback-modal');
        var feedbackModal = $(selector);
        var winH;
        var topPane;
        var feedbackModalHeight;

        // private scope
        function init()
        {
            winH                = $(window).height();
            //topPane             = $('.top-pane').height();
            topPane             = 0;
            feedbackModalHeight = winH - topPane;

            feedbackModal.height(feedbackModalHeight);
        
        }

        // private scope
        function show()
        {
            init();

            feedbackModal.animate({
                bottom: 0
            }, 600);
        }

        // private scope
        function hide()
        {

            init();

            feedbackModal.animate({
                bottom: "-" + feedbackModalHeight
            }, 600);
        }


        return {

            'init': init,
            'show': show,
            'hide': hide
        };

    }

On gists

Wrap text into paragraphs

PHP Helpers-Filters-Plugins

text-in-para.php #

<?php


$text = <<<TEXT
Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non

congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed
TEXT;

$paragraphedText = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $text ) ) . "</p>";


echo $paragraphedText;