/ Gists

Gists

On gists

Nette - multiplier.php

Nette

form.latte #

{foreach ... as $row}
        {form order-$row}
              {input count}
              {input send}
          {/form}
{/foreach}

On gists

Nette download

Nette

nette-download.php #

	public function downloadFile($source, $fileName){
		$httpResponse = $this->context->getService('httpResponse');
		$httpResponse->setHeader('Pragma', "public");
		$httpResponse->setHeader('Expires', 0);
		$httpResponse->setHeader('Cache-Control', "must-revalidate, post-check=0, pre-check=0");
		$httpResponse->setHeader('Content-Transfer-Encoding', "binary");
		$httpResponse->setHeader('Content-Description', "File Transfer");
		$httpResponse->setHeader('Content-Length', filesize($source));
		$this->sendResponse(new FileResponse($source, $fileName));
	}
	
	
		public function handleQrCodeDownload($hash, $id)
	{
		$user = $this->model->find($id);

		if ($hash !== sha1($user->id . $user->slug))
		{
			$this->error();
		}

		// lepsi cesta k souboru? http://forum.nette.org/cs/21269-fileresponse-soubor-neexistuje#p145741
		$userWebalize = Nette\Utils\Strings::webalize($user->firstname . '-' . $user->lastname);
		$response = new Nette\Application\Responses\FileResponse(WWW_DIR.'/storage/images/200x200/'.$hash.'.png', 'qr-'.$userWebalize.'.png');
		$this->sendResponse($response);
 	}
 	
 	
 	
 	// https://forum.nette.org/cs/21269-fileresponse-soubor-neexistuje#p145741

On gists

Rainbow stripe mixin with SCSS + Compass

SCSS

pop-stripe.md #

Rainbow stripe mixin with SCSS + Compass

I'm trying to make a horizontal rainbow stripe background gradient mixin, but I feel like this is way too verbose. How can it be better?

Goals:

  1. [check] Use variables for colors so they can be swapped out for different colors.
  2. [check] The widths are hard coded for 8 colors. Can it be done smarter where it adjusts to the number of colors you add? Or is that asking too much?
  3. [check] The colors are defined twice for the color starts and stops. Can this be done better?
  4. [see below] Right now I define the colors as variables at the top level, then pass them in the mixin. Should they instead be created inside the mixin and then colors are brought in as arguments? Or does that matter?

Variables:

// You could set individual variables for each color as well.
// You would still pass them all as a single argument,
// or join them into a single variable before passing, as you see fit.
$mycolors: red orange yellow green blue indigo violet;

Function:

// Returns a striped gradient for use anywhere gradients are accepted.
// - $position: the starting position or angle of the gradient.
// - $colors: a list of all the colors to be used.
@function rainbow($position, $colors) {
  $colors: if(type-of($colors) != 'list', compact($colors), $colors);
  $gradient: compact();
  $width: 100% / length($colors);

  @for $i from 1 through length($colors) {
    $pop: nth($colors,$i);
    $new: $pop ($width * ($i - 1)), $pop ($width * $i);
    $gradient: join($gradient, $new, comma);
  }

  @return linear-gradient($position, $gradient);
}

Application:



.rainbow { 
  @include background-image(rainbow(left, $colors));
}

On gists

Move between two select

JavaScript jQuery

move.html #

<select id="from" style="float: left; width: 200px;" multiple>
	
	<option value="1">AA</option>
	<option value="2">BB</option>
	<option value="3">CC</option>
	<option value="4">DD</option>
	<option value="5">EE</option>

</select>

<button style="float: left; margin-left: 10px; margin-right: 10px;" id="a">&gt;</button>
<button style="float: left; margin-left: 10px; margin-right: 10px;" id="b">&lt;</button>
<select id="to" style="float: left;  width: 200px;" multiple></select>




<script>
	var $from = $("#from");
	var $to = $("#to");


	$("#a").click(function(){

		moveOptions($from, $to);
	});	

	$("#b").click(function(){

		moveOptions($to, $from);

	});


	function moveOptions(from, to)
	{
		$("option:selected", from).appendTo(to);
		var x = $("#from option").sort(function(a, b){

			a = a.value;
			b = b.value;

			return a-b;
		});	



		var y = $("#to option").sort(function(a, b){

			a = a.value;
			b = b.value;

			return a-b;
		});


		$("#from").html(x);
		$("#to").html(y);
	}

</script>

On gists

Self invoke function with public and private methods

JavaScript-OOP

sif.js #

	var log = {

		target: $("#message"),

		 pridej: function(text){

			this.target.append(text + "<br />");
		},
		clear: function()
		{
			this.target.empty()
		}

	};

	
	var pozdrav = (function(){

		var target = $("#message");

		var pridej = function(text){

			target.append(text + "<br />");
		};

		var clear = function()
		{
			target.empty();
		};


		return {

			x: pridej,
			clear: clear

		};

	})();

On gists

Use event with function and data // ukazka pouziti eventu, funkce, data

JavaScript jQuery

use-events-with-data.js #

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>TEST</title>
	<script src="jquery.js"></script>
	<style>
	


	</style>
</head>
<body>




<div id="result"></div>


<button id="button1" data-color="red">Červené</button>
<button id="button2" data-color="green">Zelené</button>




<script>

//------------------------------------------------------------
//1 zpusob - data atribut
$('button').on('click', function(){

	$("#result").text($(this).text()).css("color", $(this).data('color'));
});




//------------------------------------------------------------
//2 zpusob - vlastni funkci
var handler = function(text, color) {

	$("#result").text(text).css("color", color);
};

$('#button1').on('click', function(){
	handler('Červené', 'red'); // misto Červené muzu pouzit $(this).text(), ale demonstruji ukazku parametru viz dale
});

$('#button2').on('click', function(){
	handler('Zelené', 'green'); // misto Červené muzu pouzit $(this).text(), ale demonstruji ukazku parametru viz dale
});


//------------------------------------------------------------
//3 zpusob - vlastni funkci ale ne pomoci anonymni, ale trosku ugly
var handler = function(text, color) {

	return function() {

		$("#result").text(text).css("color", color);
	}
};

$('#button1').on('click', handler('Červené', 'red'));
$('#button2').on('click', handler('Zelené', 'green'));


//------------------------------------------------------------
//4 zpusob pres user data / bindovani / trigger
$("button").on("setColor", function(e, color, txt){

	$("#result").text(txt).css("color", color);

});

$("#button1").on("click", function(){

	$(this).trigger("setColor", ['red', 'Červené']);
});

$("#button2").on("click", function(){

	$(this).trigger("setColor", ['green', 'Zelené']);
});



//------------------------------------------------------------
//5 event data
var handler = function(e) {
	
	$("#result").text(e.data.text).css("color", e.data.color);
	
};

$("#button1").on("click", {text:'Červené', color:'red'}, handler);
$("#button2").on("click", {text:'Zelené', color:'green'}, handler);



//------------------------------------------------------------
// 6 event, ale ne v data ale rovnou do e.nazev
$("#button1").on("click", function(e){
	$("#result").text(e.text).css("color", e.color);
});

$("#button1").trigger({type:'click', text:'Červené', color:'red'});




//------------------------------------------------------------
// 7 $.event object, vlastni data soucasti eventu, @link: https://jsbin.com/memoriyate/edit?html,js


$('body').on('logged logged2', function(e) {

	console.log(e);
});

// 1 moznost
var event = jQuery.Event( "logged" );
event.user1 = "a";
event.pass1 = "b";
$( "body" ).trigger( event );

// 2 moznost
$( "body" ).trigger({
  type:"logged2",
  user:"a2",
  pass:"b2"
});



</script>

</body>
</html>

On gists

jquery simple plugins

jQuery-plugins

simplejquery-plugins.js #

(function( $ ){

	$.nette.init();

	// simple function
    $.extend( {
        swapArticleMaskClasses: function(obj, classAttr) 
        {
    		if (obj.hasClass(classAttr))
    		{
    			obj.removeClass(classAttr).addClass(classAttr + '--');
    		}   
        },      

        swapArticleMaskClassesRevert: function(obj, classAttr) 
        {
    		if (obj.hasClass(classAttr + '--'))
    		{
    			obj.removeClass(classAttr + '--').addClass(classAttr);
    		}   
        },


        exists: function(selector) {
        	return ($(selector).length > 0);
       	}

    });

    // jqury fn
    $.fn.extend({

	  swapClass: function(class1, class2) {
		    return this.each(function() {
		      var $element = $(this);
		      if ($element.hasClass(class1)) {
		        $element.removeClass(class1).addClass(class2);
		      }
		      else if ($element.hasClass(class2)) {
		        $element.removeClass(class2).addClass(class1);
		      }
		    
		    });

		},

		// simplier way if ( $('#myDiv')[0] ) ;)
		exists: function() {

			return ($(this).length > 0);
		},


		hasParent: function(a) {
		    return this.filter(function() {
		        return !!$(this).closest(a).length;
		    });
		}


    });


})( jQuery );

On gists

Get the share counts from various APIs

jQuery

gistfile1.md #

Share Counts

I have always struggled with getting all the various share buttons from Facebook, Twitter, Google Plus, Pinterest, etc to align correctly and to not look like a tacky explosion of buttons. Seeing a number of sites rolling their own share buttons with counts, for example The Next Web I decided to look into the various APIs on how to simply return the share count.

If you want to roll up all of these into a single jQuery plugin check out Sharrre

Many of these API calls and methods are undocumented, so anticipate that they will change in the future. Also, if you are planning on rolling these out across a site I would recommend creating a simple endpoint that periodically caches results from all of the APIs so that you are not overloading the services will requests.

Twitter

GET URL:

http://cdn.api.twitter.com/1/urls/count.json?url=http://stylehatch.co

Returns:

{
    "count":528,
    "url":"http://stylehatch.co/"
}

Facebook

GET URL:

http://graph.facebook.com/?id=http://stylehatch.co

Returns:

{
   "id": "http://stylehatch.co",
   "shares": 61
}

Pinterest

GET URL:

http://api.pinterest.com/v1/urls/count.json?callback=&url=http://stylehatch.co

Result:

({"count": 0, "url": "http://stylehatch.co"})

LinkedIn

GET URL:

http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json

Returns:

{
    "count":17,
    "fCnt":"17",
    "fCntPlusOne":"18",
    "url":"http:\/\/stylehatch.co"
}

Google Plus

POST URL:

https://clients6.google.com/rpc?key=YOUR_API_KEY

POST body:

[{
    "method":"pos.plusones.get",
    "id":"p",
    "params":{
        "nolog":true,
        "id":"http://stylehatch.co/",
        "source":"widget",
        "userId":"@viewer",
        "groupId":"@self"
        },
    "jsonrpc":"2.0",
    "key":"p",
    "apiVersion":"v1"
}]

Returns


[{
    "result": { 
        "kind": "pos#plusones", 
        "id": "http://stylehatch.co/", 
        "isSetByViewer": false, 
        "metadata": {
            "type": "URL", 
            "globalCounts": {
                "count": 3097.0
            }
        }
    } ,
    "id": "p"
}]

StumbledUpon

GET URL:

http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://stylehatch.co

Result:


{
    "result":{
        "url":"http:\/\/stylehatch.co\/",
        "in_index":true,
        "publicid":"1iOLcK",
        "views":39,
        "title":"Style Hatch - Hand Crafted Digital Goods",
        "thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/941\/72725941.jpg",
        "thumbnail_b":"http:\/\/cdn.stumble-upon.com\/bthumb\/941\/72725941.jpg",
        "submit_link":"http:\/\/www.stumbleupon.com\/submit\/?url=http:\/\/stylehatch.co\/",
        "badge_link":"http:\/\/www.stumbleupon.com\/badge\/?url=http:\/\/stylehatch.co\/",
        "info_link":"http:\/\/www.stumbleupon.com\/url\/stylehatch.co\/"
    },
    "timestamp":1336520555,
    "success":true
}

On gists

PHP - Sanitize a multidimensional array

JavaScript

php-sanitize-multidimensional-ar #

<?php

/**
 * Sanitize a multidimensional array
 *
 * @uses htmlspecialchars
 *
 * @param (array)
 * @return (array) the sanitized array
 */
function purica_array ($data = array()) {
	if (!is_array($data) || !count($data)) {
		return array();
	}

	foreach ($data as $k => $v) {
		if (!is_array($v) && !is_object($v)) {
			$data[$k] = htmlspecialchars(trim($v));
		}
		if (is_array($v)) {
			$data[$k] = purica_array($v);
		}
	}

	return $data;
}

On gists

Caret

jQuery

jquery.caret.js #

// Set caret position easily in jQuery
// Written by and Copyright of Luke Morton, 2011
// Licensed under MIT
(function ($) {
    // Behind the scenes method deals with browser
    // idiosyncrasies and such
    $.caretTo = function (el, index) {
        if (el.createTextRange) { 
            var range = el.createTextRange(); 
            range.move("character", index); 
            range.select(); 
        } else if (el.selectionStart != null) { 
            el.focus(); 
            el.setSelectionRange(index, index); 
        }
    };

    // The following methods are queued under fx for more
    // flexibility when combining with $.fn.delay() and
    // jQuery effects.

    // Set caret to a particular index
    $.fn.caretTo = function (index, offset) {
        return this.queue(function (next) {
            if (isNaN(index)) {
                var i = $(this).val().indexOf(index);
                
                if (offset === true) {
                    i += index.length;
                } else if (offset) {
                    i += offset;
                }
                
                $.caretTo(this, i);
            } else {
                $.caretTo(this, index);
            }
            
            next();
        });
    };

    // Set caret to beginning of an element
    $.fn.caretToStart = function () {
        return this.caretTo(0);
    };

    // Set caret to the end of an element
    $.fn.caretToEnd = function () {
        return this.queue(function (next) {
            $.caretTo(this, $(this).val().length);
            next();
        });
    };
}(jQuery));