/ Gists

Gists

On gists

Promises

jQuery

promises.html #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js'></script>
</head>
<body>
    
<table border=1>
    <tr>
        <td>Num</td>
        <td>State</td>
    </tr>
    <tr>
        <td><a href="">1</a></td><td></td>
    </tr>
    <tr>
        <td><a href="">2</a></td><td></td>
    </tr>
    <tr>
        <td><a href="">3</a></td><td></td>
    </tr>
</table>

<script>
var promises = [];
var $a = $('a');
$.each($a, function() {
    var $this = $(this);

    var promise = $.get('/rq.php?num=' + $this.text());
    promise.done(function() {
        $this.parent().next().text('done!');
    });
    promises.push(promise);
});



if (jQuery.when.all===undefined) {
    jQuery.when.all = function(deferreds) {
        var deferred = new jQuery.Deferred();
        $.when.apply(jQuery, deferreds).then(
            function() {
                deferred.resolve(Array.prototype.slice.call(arguments));
            },
            function() {
                deferred.fail(Array.prototype.slice.call(arguments));
            });

        return deferred;
    }
}


$.when.all(promises).then(function(schemas) {
     console.log("DONE", this, schemas); // 'schemas' is now an array
}, function(e) {
     console.log("My ajax failed");
});


// $.when.apply($, promises).then(function() {
//    console.log(arguments);
//    console.log('DONE');
   
   
// });
</script>

</body>
</html>

On gists

PHP Factory

PHP

factory.php #

<?php 
 

$arr = [
    'company' => 'AMI',
    'employeeCount' => 25,
    'years' => 12,
    'bankInfo' => [
        'account' => 'xxxx',
        'money' => '2 billions'
    ]
];


echo F::create()->getResource($arr)->formatToXml();

class F
{
    private $resource;

    public static function create()
    {
        return new self;
    }

    public function getResource($resource)
    {
        $this->resource = $resource;
        return $this;
    }

    public function formatToJson()
    {
        return json_encode($this->resource);
    }

    public function formatToArray()
    {
        return $this->resource;
    }

    public function formatToXml()
    {
        $xml = new SimpleXMLElement('<root/>');
        array_walk_recursive($this->resource, array ($xml, 'addChild'));
        return $xml->asXML();
    }


}

On gists

JS / jQuery: Caching selectors

JavaScript

caching.js #

function Selector_Cache() {
    var collection = {};
    function get_from_cache( selector ) {
        if ( undefined === collection[ selector ] ) {
            collection[ selector ] = $( selector );
        }
        return collection[ selector ];
    }
    return { get: get_from_cache };
}

var selectors = new Selector_Cache();

// Usage $( '#element' ) becomes
selectors.get( '#element' );

On gists

JS - round, floor, ceil obj - Decimal precision

JavaScript-OOP JavaScript

decimalperecision.js #

var DecimalPrecision = (function(){
	if (Number.EPSILON === undefined) {
		Number.EPSILON = Math.pow(2, -52);
	}
	this.round = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.round((n + r) * o) / o;
	}
	this.ceil = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.ceil((n + r) * o) / o;
	}
	this.floor = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.floor((n + r) * o) / o;
	}
	return this;
})();

On gists

Foreach vs array_reduce

PHP

gistfile1.aw #

<?php

$arr = array(
	array('a', '1'),
	array('b', '2'),
);


// klasicky
$out = array();
foreach ($arr as $v) {
	$out[$v[0]] = $v[1];
}

// funkcionalne
$out2 = array_reduce($arr, function($out2, $v) {
	$out2[$v[0]] = $v[1];
	return $out2;
});

echo ($out === $out2) . "\n";
print_r($out);
print_r($out2);

/* vystup:

1
Array
(
    [a] => 1
    [b] => 2
)
Array
(
    [a] => 1
    [b] => 2
)

*/

On gists

Insert A Random String from List in MySQL

MySql MySql tricks

gistfile1.txt #

UPDATE tablename 
SET columnname  = ELT(0.5 + RAND() * 6, 'value 1','value 2','value 3','value 4','value 5','value 6') 

On gists

Change URL - pushstate

JavaScript

example.html #

<html>
<head>
<link rel="stylesheet" type="text/css" href="url_style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function changeurl(url)
{
 var new_url="/Your URL/"+url;
 window.history.pushState("data","Title",new_url);
 document.title=url;
}
</script>
</head>
<body>
<div id="wrapper">

<div id="url_link">
 <p id="url_label">Click On Languages To Change URL</p>
 <li onclick="changeurl('PHP');">PHP</li>
 <li onclick="changeurl('HTML');">HTML</li>
 <li onclick="changeurl('CSS');">CSS</li>
 <li onclick="changeurl('JavaScript');">JavaScript</li>
 <li onclick="changeurl('jQuery');">jQuery</li>
</div>

</div>
</body>
</html>

On gists

Dekorator - Response

Nette

decorator-nette.php #

<?php
# https://forum.nette.org/cs/31783-mazanie-suboru-po-samotnej-akcii-stiahnut-subor#p202279

use Nette\Application\Responses\FileResponse;
use Nette\Http\IRequest;
use Nette\Http\IResponse;

final class DownloadAndDeleteFileResponse implements Nette\Application\IResponse
{
    private $response;

    public function __construct(FileResponse $response)
    {
        $this->response = $response;
    }

    public funcion send(IRequest $request, IResponse $response)
    {
        $this->response->send($request, $response);
        unlink($this->response->getFile());
    }

On gists

Zyla simple parser

PHP

parser.php #

<?php

$x = file_get_contents($file);

$final = preg_match("~<tr[^>]*>(.+)</tr>~si", $x, $match);

$lastTr = strpos($match[0], '</tr>');
$match[0] = substr($match[0], $lastTr + 8,  strlen($match[0]));


file_put_contents("frag.txt", $match[0]);

$f = fopen("frag.txt", "r");

$cols = array("kolo", "datum", "cas", "domaci", "hoste", "skore", "strelci_karty");

//$in_td = false;
$rows = array();

while (!feof($f))
{
   $r = fgets($f);
   # preskocit prazdne radky
   if ( trim($r) != '' )
   {
      if (strpos($r, '<tr') !== false)
      {
        // $in_td=true;
         $rows = array();
      }
      else
      {
         if (strpos($r, '</tr') !== false)
         {
            //$in_td = false;
            #zpracuju $rows

            if (count($rows) == 8)
            {
               #mam v prvni bunce kolo
               $kolo = array_shift($rows);
            }
            zapis_insert($kolo, $rows);
            //print_r($rows);

         }
         else
         {
            if (strpos($r, '<td') !== false)
            {
               $t = preg_replace('/<[^>]*>/', '', trim($r));
               $rows[] = $t;
            }
         }
      }
   }
}

On gists

Rand number between (start, end)

MySql MySql tricks

random-number-between.sql #

-- For range (min..max( (min inclusive, max exclusive) it is:
FLOOR( RAND() * (max-min) + min )

-- For range (min..max) (min+max inclusive) it is:
FLOOR( RAND() * (max-min+1) + min )