/ Gists

Gists

On gists

Insert into ... Select ... (cross join)

MySql MySql tricks

insert-select-join.sql #

INSERT INTO `article_tag_lang` (article_tag_id, language_id, tag)
(
    SELECT i.id, l.id, i.tag
    FROM `language` AS l
    JOIN `article_tag` AS i
);


On gists

Parsing og tags

PHP PHP-PHPDOM

parser.php #

<?php 


function autoUTF($s)
{
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s)) // detect UTF-8
    {
        return $s;
    }
    elseif (preg_match('#[\x7F-\x9F\xBC]#', $s)) // detect WINDOWS-1250
    {
        return iconv('WINDOWS-1250', 'UTF-8', $s);
    }
    else // assume ISO-8859-2
    {
        return iconv('ISO-8859-2', 'UTF-8', $s);
    }
}
 

$url = 'https://navratdoreality.cz/uzdraveny-fotbalista-8853.html';

$html = file_get_contents($url);

libxml_use_internal_errors(true); // Yeah if you are so worried about using @ with warnings
$doc = new DomDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$query = '//*/meta[starts-with(@property, \'og:\')]';
$metas = $xpath->query($query);
$rmetas = array();
foreach ($metas as $meta) {
    $property = $meta->getAttribute('property');
    $content = $meta->getAttribute('content');
    $rmetas[$property] = html_entity_decode(autoUTF($content));
}
var_dump($rmetas);



// $pattern='/<\s*meta\s+property="og:([^"]+)"\s+content="([^"]*)/i';
// preg_match_all($pattern, $html, $out);
// var_dump(array_combine($out[1], $out[2]));

On gists

Jsonp, json, js to html from another domain

JavaScript jQuery JSON

index.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='//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>

    <!-- https://www.sitepoint.com/jsonp-examples/ -->

    <div style="background: goldenrod; padding: 1rem;">
        <script src="http://lab.rjwebdesign.cz/jsonp/js.php"></script>
    </div>

    <div style="background: burlywood; padding: 1rem;" id="jsonp">
    
    </div>
    <script>
   
        // 1 zpusob
        $.getJSON('http://lab.rjwebdesign.cz/jsonp/jsonp.php?callback=?', function(json){
            console.log(json);
        });

        // 2 zpusob
        function logResults(json) {
            console.log(json);
        }

        $.ajax({
        url: "http://lab.rjwebdesign.cz/jsonp/jsonp.php",
        dataType: "jsonp",
        jsonpCallback: "logResults"
        });
    </script>

</body>
</html>

On gists

Array multisort

PHP

example1.php #

<?php


$hodnoty = array(
                
                "baku" => array(3, 4, 7),
                "kcko" => array(2, 5, 7),
                "guest" => array(1, 2, 2)
                );

$data = array();

foreach ($hodnoty as $pole => $k)
 {
   $counter = 0;
   foreach ($k as $i)
    {
      $counter++;
      //echo "$pole - $i [$counter] <br />";
      $data[$pole]["komentar" . $counter] = $i;
      if ($counter ==3 )
       {
        $data[$pole]["komentarCelkem"] = array_sum($hodnoty[$pole]);
       }
    }
 }


print_r($data);

$dataSort = valuesToColumns($data); 

 array_multisort(
                 
                 $dataSort["komentarCelkem"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar1"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar2"], SORT_NUMERIC, SORT_DESC,
                 $dataSort["komentar3"], SORT_NUMERIC, SORT_DESC
                 
                 );



print_r($dataSort);

$tab = "<table border=1>";
$tab .= "<tr><th>Nick</th> <th>Komentář Celkem</th> <th>Komentář 1</th> <th>Komentář 2</th> <th>Komentář 3</th> </tr>";

foreach ($dataSort["komentar1"] as $K => $V)
{
 
 $tab .= "<tr>";
 $tab .= "<td>$K</td>";
 $tab .= "<td>". $data[$K]["komentarCelkem"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar1"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar2"] ."</td>";
 $tab .= "<td>". $data[$K]["komentar3"] ."</td>";
 $tab .= "</tr>";
 
}
$tab .= "</table>";


echo $tab;




function valuesToColumns($array_to_sort)
{

   $sort_arr = array();
   foreach($array_to_sort AS $uniqid => $row)
   {
       foreach($row AS $key=>$value){
           $sort_arr[$key][$uniqid] = $value;
       }
   }
   
   return $sort_arr;

}

?>

On gists

El Dragon - table on the fly

1oldies

table.php #

<?php

/**
 * Umozni prepocitat tabulku za zapas, za kolo, souhrně
 */ 
class TableResult
{
	
	public $data;
  
  /**
   * Konstruktor
   */     
  function __construct($soutezID = 0, $date = '0000-00-00 00:00:00', $home_team = 0, $away_team = 0)
  {
  	
    $this->soutezID  = $soutezID;
    $this->date      = $date;
    $this->home_team = $home_team;
    $this->away_team = $away_team;

  }  
  
   
  function reCount($match_data, $round, $round_type = 'before')
  {
    

    
    if (count($match_data))
    {

        foreach ($match_data as $index => $r)
        {

           if ($r->schvaleno != '1') continue;
		   if ($round_type == 'before' && $r->kolo >= $round) break;	
           if ($round_type == 'after' && $r->kolo > $round) break;	
           if ($round_type == 'jaro' && $r->kolo > 11) break;
           if ($round_type == 'podzim' && $r->kolo <= 11) continue;

          // nastaveni promennych
          $domaci 		= $r->id_domaci;
          $hoste  		= $r->id_hoste;
          $g1     		= $r->g1;
          $g2     		= $r->g2;
          $kontumace 	= 0;
          $trest1 		= 0;
          $trest2 		= 0;
          $seo          = $r->seo;
          
          // vypocet
          
          
          $this->data[$domaci]["ID"] = $domaci;
          $this->data[$hoste]["ID"]  = $hoste;
          
          $this->data[$domaci]['seo'] = $seo;
          $this->data[$hoste]['seo']  = $seo;
          
          // domaci vyhrali
          if ($g1 > $g2 && $kontumace != 3)
          {
            // nastavime domaci
            $this->data[$domaci]["pz"]++;
            $this->data[$domaci]["v"]++;
            //$this->data[$domaci]["r"]++;
            //$this->data[$domaci]["p"]++;
            $this->data[$domaci]["gf"] += $g1;
            $this->data[$domaci]["ga"] += $g2;
            $this->data[$domaci]["pts"] += 3 - $trest1;
            $this->data[$domaci]["trest"] += $trest1;
            $this->data[$domaci]["diff"] += $g1 - $g2;
            
            
            
            // nastavime hosty
            $this->data[$hoste]["pz"]++;
            //$this->data[$hoste]["v"]++;
            //$this->data[$hoste]["r"]++;
            $this->data[$hoste]["p"]++;
            $this->data[$hoste]["gf"] += $g2;
            $this->data[$hoste]["ga"] += $g1;
            $this->data[$hoste]["pts"] += 0 - $trest2;
            $this->data[$hoste]["trest"] += $trest2;
            $this->data[$hoste]["diff"] += $g2 - $g1; 
            
          }
         // vyhrali hoste 
         elseif ($g1 < $g2 && $kontumace != 3)
         {
            // nastavime domaci
            $this->data[$domaci]["pz"]++;
            //$this->data[$domaci]["v"]++;
            //$this->data[$domaci]["r"]++;
            $this->data[$domaci]["p"]++;
            $this->data[$domaci]["gf"] += $g1;
            $this->data[$domaci]["ga"] += $g2;
            $this->data[$domaci]["pts"] += 0 - $trest1;
            $this->data[$domaci]["trest"] += $trest1;
            $this->data[$domaci]["diff"] += $g1 - $g2;
            
			// nastavime hosty
            $this->data[$hoste]["pz"]++;
            $this->data[$hoste]["v"]++;
            //$this->data[$hoste]["r"]++;
            //$this->data[$hoste]["p"]++;
            $this->data[$hoste]["gf"] += $g2;
            $this->data[$hoste]["ga"] += $g1;
            $this->data[$hoste]["pts"] += 3 - $trest2; 
            $this->data[$hoste]["trest"] += $trest2;  
			$this->data[$hoste]["diff"] += $g2 - $g1;     
         } 
        // remiza 
        elseif ($g1 == $g2 &&  $kontumace != 3)
        {
            // nastavime domaci
            $this->data[$domaci]["pz"]++;
            //$this->data[$domaci]["v"]++;
            $this->data[$domaci]["r"]++;
            //$this->data[$domaci]["p"]++;
            $this->data[$domaci]["gf"] += $g1;
            $this->data[$domaci]["ga"] += $g2;
            $this->data[$domaci]["pts"] += 1 - $trest1;
            $this->data[$domaci]["trest"] += $trest1;
            $this->data[$domaci]["diff"] += $g1 - $g2;
            
            // nastavime hosty
            $this->data[$hoste]["pz"]++;
            //$this->data[$hoste]["v"]++;
            $this->data[$hoste]["r"]++;
            //$this->data[$hoste]["p"]++;
            $this->data[$hoste]["gf"] += $g2;
            $this->data[$hoste]["ga"] += $g1;
            $this->data[$hoste]["pts"] += 1 - $trest2; 
            $this->data[$hoste]["trest"] += $trest2;  
			$this->data[$hoste]["diff"] += $g2 - $g1;               
        }
        // kontumace pro oba 
        elseif ($g1 == $g2 &&  $kontumace == 3)
        {
            // nastavime domaci
            $this->data[$domaci]["pz"]++;
            //$this->data[$domaci]["v"]++;
            //$this->data[$domaci]["r"]++;
            $this->data[$domaci]["p"]++;
            $this->data[$domaci]["gf"] += 0;
            $this->data[$domaci]["ga"] += 3;
            $this->data[$domaci]["pts"] += 0 - $trest1;
            $this->data[$domaci]["trest"] += $trest1;
            $this->data[$domaci]["diff"] += $g1 - $g2;
            
            // nastavime hosty
            $this->data[$hoste]["pz"]++;
            //$this->data[$hoste]["v"]++;
            //$this->data[$hoste]["r"]++;
            $this->data[$hoste]["p"]++;
            $this->data[$hoste]["gf"] += 0;
            $this->data[$hoste]["ga"] += 3;
            $this->data[$hoste]["pts"] += 0 - $trest2;
            $this->data[$hoste]["trest"] += $trest2;  
			$this->data[$hoste]["diff"] += $g2 - $g1;              
        }        
          
      } // while end
 }
    

    	
    	//print_r($data);
    
    	return true;
  
  } // method end




 
 /**
  * Init, nastavi vsem 0-0-0 ..
  */    
 function init($tymy = array())
 {
   
   $tabulkoveHodnoty = array(
                              "pz", "v", "r", "p", "gf", "ga", "pts", "trest", "diff", "ID", "logo", "nazev"
                            );
   $data = array();
   foreach ($tymy as $tym_id => $tym_nazev)
   {
      foreach ($tabulkoveHodnoty as $hodnota)
      {

		   if ($hodnota == "ID")
			$data[$tym_id][$hodnota] = $tym_id;
		   
		   elseif ($hodnota == "logo")
			$data[$tym_id][$hodnota] = 0;
		   
		   elseif ($hodnota == "nazev")
			$data[$tym_id][$hodnota] = $tym_nazev;						
	       
		   else
		   	$data[$tym_id][$hodnota] = 0;
		  	
      }
   }
   
   return $data; 
 } 
 
 
 
	function getTableData()
	{

	 	$sort_arr = array();
	    foreach($this->data AS $uniqid => $row)
		{
	        foreach($row AS $key=>$value)
			{
	            $sort_arr[$key][$uniqid] = $value;
	        }
	    }
	    

	  
	    // ORDER BY  PTS DESC, ROZDIL_GOLU DESC, G1 DESC, zapasy DESC, G2 ASC
	    array_multisort($sort_arr['pts'], SORT_NUMERIC, SORT_DESC, 
	    				$sort_arr['diff'], SORT_NUMERIC, SORT_DESC, 
						$sort_arr['gf'], SORT_NUMERIC, SORT_DESC,
						$sort_arr['pz'], SORT_NUMERIC, SORT_DESC,
						$sort_arr['ga'], SORT_NUMERIC, SORT_ASC,
						$sort_arr['ID'], SORT_NUMERIC, SORT_ASC
						);
	
	
		$tym = $sort_arr;
		
		return $tym;
	
	}
	
	 function sortItAndShow()
	 {
	 	
	 	$sort_arr = array();
	    foreach($this->data AS $uniqid => $row)
		{
	        foreach($row AS $key=>$value)
			{
	            $sort_arr[$key][$uniqid] = $value;
	        }
	    }
	  
	    // ORDER BY  PTS DESC, ROZDIL_GOLU DESC, G1 DESC, zapasy DESC, G2 ASC
	    array_multisort($sort_arr['pts'], SORT_NUMERIC, SORT_DESC, 
	    				$sort_arr['diff'], SORT_NUMERIC, SORT_DESC, 
						$sort_arr['gf'], SORT_NUMERIC, SORT_DESC,
						$sort_arr['pz'], SORT_NUMERIC, SORT_DESC,
						$sort_arr['ga'], SORT_NUMERIC, SORT_ASC,
						$sort_arr['ID'], SORT_NUMERIC, SORT_ASC
						);
	
	
		$tym = $sort_arr;
	/*
		echo "<table class='tabulka left' style='width: 520px; margin: 0 auto;'>";
		echo "<tr>";
		echo "<th>#</th>";
		echo "<th>Tým</th>";
		echo "<th>PZ</th>";
		echo "<th>V</th>";
		echo "<th>R</th>";
		echo "<th>P</th>";
		echo "<th>Skóre</th>";
		echo "<th>PTS</th>";
		echo "</tr>"; 
	*/	
		$counter = 1;
		$positions = array();
		foreach ($tym['ID'] as $value => $key )
		{
			
			/*
		
			$logo 		= $this->data[$key]['logo'];
			$logo_img   = is_file("img/kluby-small/$logo") ?  $logo : 'nologo.gif';
			$nazev		= $this->data[$key]['nazev'];
			$style      = '';
			
			if (in_array($this->data[$key]['ID'], array($this->home_team, $this->away_team)))
			{
				$nazev = "<strong>" . $this->data[$key]['nazev'] . "</strong>";
				$style = "style='background: #FFECEC'";
			}
			*/
			
	/*
			echo "<tr $style>";
			echo "<td>".$counter++.".</td>";
			echo "<td>". "<img src='/img/kluby-small/$logo_img' />" . " " . $nazev ."</td>";
			echo "<td>".$this->data[$key]['pz']."</td>";
			echo "<td>".$this->data[$key]['v']."</td>";
			echo "<td>".$this->data[$key]['r']."</td>";
			echo "<td>".$this->data[$key]['p']."</td>";
			echo "<td>".$this->data[$key]['gf']." : ";
			echo "".$this->data[$key]['ga']."</td>";
			echo "<td><span class=\"pts_bold\">".$this->data[$key]['pts']."</span></td>";
			echo "</tr>";
		}
		
		echo "</table>";
		
	*/	
	
			$positions[$this->data[$key]['ID']] = $counter;	
			$counter++;
		}
		
		return $positions;
		
	
	}
 
 	

} // class end




?>

On gists

Toyota (php reference)

1oldies PHP

store.php #

<?php

class Store
{
  function Store($db)
  {
    $this->db = &$db;
    $this->lang = 'cz';
    $this->itemsOff();
    
    $this->cars = array(
                       "toyota" => 1,
                       "lexus" => 2,
                       "scion" => 3,
                       "daihatsu" => 4
                     );
    
  }
 
 
 // definuje IDcka kategorii
 function itemsOff()
 {
  // bazar 49, 63, 77, 91
  // demo 48, 62, 76, 90
   $this->itemOff = array( 
                           "bazar" => array (49, 63, 77, 91),
                           "demo" => array (48, 62, 76, 90)
                         );
 }
 
 
 /**
  * Prida polozku do pole
  */   
 function addItemToArray(& $array, $key, $value)
 {
   if ($key != 0)
     $array[$key] = $value;
   else
     $array[] = $value;  
 }
 
 // vypise sklad podle typu auta a kategorie
 // sekce demo ma navic Najeto
 // sekce bazar navic Najeto + Rok vyroby
 function dump($car, $cat)
 {
   $sql  = " SELECT * FROM sklad WHERE auto = ".$this->cars[$car];
   $sql .= " AND kategorie = $cat ";
   $sql .= " AND aktivni = 'ano' ";
   $sql .= " ORDER BY ID DESC ";
   
   $sql = $this->db->query($sql);
   
   if ($this->db->numRows($sql))
   {
   
   
   echo "<table style='border: 1px solid black; margin: 0 auto; width: 850px; border-collapse: collapse;'>";
   $this->thNames = array(1 => "Foto", 2 => "Model", 3=> "Barva", 4 => "Motor");
   
   // zapinam polozku pro demo
    if (in_array($_GET["pid"], $this->itemOff["demo"]))
     { 
       $this->addItemToArray($this->thNames, 5, "Najeto");
     }
    // zapinam polozku pro bazar  
    if (in_array($_GET["pid"], $this->itemOff["bazar"]))
     { 
       $this->addItemToArray($this->thNames, 5, "Rok výroby");
       $this->addItemToArray($this->thNames, 6, "Najeto");
     }  
     
     // Cena
    $this->addItemToArray($this->thNames, 0,  "Cena");
   
   
   // cena je az na konci
   
   echo "<tr>";
   foreach ($this->thNames as $v)
    {
     echo "<th style='text-align: left; padding: 5px;'>".$v."</th>";
    }
   echo "</tr>";
   while ($r = $this->db->fetch($sql))
    {
    
    $this->tdNames = array(
                         1 => "<a href='./images/sklad/foto_popup_{$r->ID}_thumb.jpg' rel=\"lightbox\"><img src='./images/sklad/foto_thumb_{$r->ID}_thumb.jpg' /></a>", 
                         2 => $r->model,
                         3 => $r->barva,
                         4 => $r->motor
                          );


      // zapinam polozku pro demo
    if (in_array($_GET["pid"], $this->itemOff["demo"]))
     { 
       $this->addItemToArray($this->tdNames, 5, $r->najeto);
     }
    // zapinam polozku pro bazar  
    if (in_array($_GET["pid"], $this->itemOff["bazar"]))
     { 
       $this->addItemToArray($this->tdNames, 5, $r->rok_vyroby);
       $this->addItemToArray($this->tdNames, 6, number_format($r->najeto, 0, "", ".") . " Km");
     }  
     
     // Cena
     //number_format($number, 2, ',', ' ');
    $this->addItemToArray($this->tdNames, 0,  number_format($r->cena, 0, "", ".") . " Kč");

      echo "<tr>";

          foreach ($this->tdNames as $v)
          {
            echo "<td style='text-align: left; border-bottom: 1px dotted black; padding: 5px'>".$v."</td>";
          }
          echo "</tr>";
      
    } 
    echo "</table><br />";
  }
 }
 
 
  
} // class
?>

On gists

Find in array - recursive

PHP

find-in-array.php #

<?php


$arr = [
    'name' => 'Php Master',
    'subject' => 'Php',
    'type' => 'Articles',
    'items' => [
        'one' => 'Iteration',
        'two' => 'Recursion',
        'methods' => [
            'factorial' => 'Recursion',
            'fibonacci' => 'Recursion',
        ],
    ],
    'parent' => 'Sitepoint',
];



echo find_in_arr('one', $arr, 'devka');


print_r($arr);


function find_in_arr($key,  &$arr, $replace) {
    foreach ($arr as $k => &$v) {
        if ($k == $key) {
			$arr[$k] = $replace;
            return $v;
        }
        if (is_array($v)) {
            $result = find_in_arr($key, $v, $replace);
            if ($result != false) {
                return $result;
            }
        }
    }	
    return false;
}

On gists

Swap two columns values

MySql MySql tricks MySql - advanced

swap.sql #

UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;

-- tipliga
UPDATE
 _tipliga_tipy_hracu t1, 
 _tipliga_tipy_hracu t2  
SET t1.g1=t1.g2, t1.g2=t2.g1 WHERE t1.id=t2.id
AND (t1.id_zapasu = 1462)

On gists

Document, element, outside click, propagation

JavaScript jQuery

example.js #

// 1
$(document).click(function(e){

   if($(e.target).closest('#dropdownID').length != 0) return false;
   $('#dropdownID').hide();
});


// 2
$('body').click(function(e) {
    if ($(e.target).closest('.notification-container').length === 0) {
        // close/animate your div
    }
});


//3, https://www.tutorialrepublic.com/faq/hide-dropdown-menu-on-click-outside-of-the-element-in-jquery.php
$(document).ready(function(){
        // Show hide popover
        $(".dropdown").click(function(){
            $(this).find(".dropdown-menu").slideToggle("fast");
        });
    });
    $(document).on("click", function(event){
        var $trigger = $(".dropdown");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $(".dropdown-menu").slideUp("fast");
        }            
    });

// 4, http://benalman.com/projects/jquery-outside-events-plugin/
$(document).ready(function(){
    $(".notification-button").click(function(){
        $('.notification-container').toggle().animate({"margin-top":"0px"}, 75); 
    }); 

    $('.notification-wrapper').bind('clickoutside', function (event) {
        $('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
    });
});

On gists

Visual Studio Code Settings Sync Gist

Nette-Forms

cloudSettings #

{"lastUpload":"2019-10-25T08:28:32.767Z","extensionVersion":"v3.4.3"}