Date post: | 22-Jan-2018 |
Category: |
Software |
Upload: | carlos-vences |
View: | 380 times |
Download: | 1 times |
SEMANTIC WEAPONS
PHP Conf 2016
HELLO STRANGER
SEMANTIC WEAPONS
$ id -un
– tweet me @cvences
– Founded a 4yo development shop
– semanticweapons.com
#phpconmx
and we’re hiring!
HELLO STRANGER
SEMANTIC WEAPONS
SEMANTIC WEAPONS
PHP for Python Developers
SEMANTIC WEAPONS
PHP for Python Developers
Web Development & General Scripting
SEMANTIC WEAPONS
$ membership operator _
$inArray = in_array(5, range(0, 10)) === TRUE;
SEMANTIC WEAPONS
$ membership operator _
in_array = 5 in range(10) == True
SEMANTIC WEAPONS
$ membership operator _
in_array = 5 in range(10) == True >>> in_array False
SEMANTIC WEAPONS
$ default values _
# counting dictionary keys from collections import defaultdict
log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', 'warn'] stats = defaultdict(int)
for entry in log: stats[entry] += 1
SEMANTIC WEAPONS
$ default values _
// counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = []; foreach ($log as $entry){ $stats[$entry] = $stats[$entry]++ ?: 0; }
SEMANTIC WEAPONS
$ default values _
// counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = []; foreach ($log as $entry){ $stats[$entry]++; }
SEMANTIC WEAPONS
$ default values _
// counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = []; foreach ($log as $entry){ $stats[$entry]++; }
# counting dictionary keys from collections import defaultdict
log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn']
stats = defaultdict(int) for entry in log: stats[entry] += 1
SEMANTIC WEAPONS
Memory consumption
– C’s pointers
– SQL’s LIMIT statement
– strcmp, strcpy, strcat
– strncmp, strncpy, strncat
– buffer overflow
SEMANTIC WEAPONS
Memory consumption
– C’s pointers
– SQL’s LIMIT statement
– strcmp, strcpy, strcat
– strncmp, strncpy, strncat
– buffer overflow
¿Quién agregó la clausula LIMIT a mini SQL 1.x?
SEMANTIC WEAPONS
$ Array
function myRange($max = 10) { $numeros = []; $num = 1;
while ($num < $max) { array_push($numeros, $num); $num++; }
return $numeros; }
function sum($max = 10) { $sumatoria = 0;
foreach (myRange($max) as $num) { $sumatoria += $num; }
echo $sumatoria; }
sum(1000000);
SEMANTIC WEAPONS
$ Iterator
class NumberIter implements Iterator { private $position = 0; private $array = [];
public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; }
public function current() { return $this->array[$this->position]; }
public function key() { return $this->position; }
public function next() { ++$this->position; }
public function valid() { return isset($this->array[$this->position]); } }
function sum($max = 10) { $sumatoria = 0; $numberIter = new NumberIter($array = range(1, ($max - 1)));
foreach ($numberIter as $num) { $sumatoria += $num; }
echo $sumatoria; }
sum(1000000);
SEMANTIC WEAPONS
$ PHP Arrays vs Iterators
foreach (myRange($max) as $num) { $sumatoria += $num; }
foreach ($numberIter as $num) { $sumatoria += $num; }
SEMANTIC WEAPONS
Entering Generators
SEMANTIC WEAPONS
$ Generators
function myRange($max = 10) { // $numeros = [];
$num = 1;
while ($num < $max) { yield $num; $num++; }
// return $numeros; }
function sum($max = 10) { $sumatoria = 0;
foreach (myRange($max) as $num) { $sumatoria += $num; }
echo $sumatoria; }
sum(1000000);
SEMANTIC WEAPONS
Generators
– Implement Iterators
– DRY
– Can traverse with foreach
– foreach does not use IAP (>7.0.0)
– Uses hashtable iterators now
– Does not build an array in-memory
– Also speeds time to generate
Note: – Calling range(0, 1000000) will result in well over 100 MB of memory being used.
SEMANTIC WEAPONS
$ Iterators, Generators and Arrays
class NumberIter implements Iterator { private $position = 0; private $array = [];
public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; }
public function current() { return $this->array[$this->position]; }
public function key() { return $this->position; }
public function next() { ++$this->position; }
public function valid() { return isset($this->array[$this->position]); } }
function myRange($max = 10) { $num = 1;
while ($num < $max) { yield $num; $num++; } }
array range ($start, $end, $step)
SEMANTIC WEAPONS
$ Iterators, Generators and Arrays
class NumberIter implements Iterator { private $position = 0; private $array = [];
public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; }
public function current() { return $this->array[$this->position]; }
public function key() { return $this->position; }
public function next() { ++$this->position; }
public function valid() { return isset($this->array[$this->position]); } }
function myRange($max = 10) { $num = 1;
while ($num < $max) { yield $num; $num++; } }
SEMANTIC WEAPONS
Case of Study
SEMANTIC WEAPONS
$ PHP 7.1.0 RC2_
SEMANTIC WEAPONS
Using Generators
SEMANTIC WEAPONS
$ PHP 7.1.0 RC2_
SEMANTIC WEAPONS
Using Iterators
SEMANTIC WEAPONS
HELLO STRANGER
PHP 7.1.0 RC2
SEMANTIC WEAPONS
$ time
SEMANTIC WEAPONS
To be or not to be
– Using iterators is great
– foreach in 7.0.0 rocks!
– lists are fat, sequences evaluate lazily
– Lazy is good
SEMANTIC WEAPONS
Warning: sort() expects parameter 1 to be array, object given
SEMANTIC WEAPONS
But…
– Python iterators introduced in 2.2 (2001)
– range -> xrange -> range
– PHP yield introduced in 5.5.0+ (2013)
– Iterator name space may clash
– What’s wrong with iterator_to_array?
– PHP ArrayAccess
Blog Post: SPL Iterators against the performance
PHP Manual: /language.generators.overview.php
SEMANTIC WEAPONS
Readability
SEMANTIC WEAPONS
$ unpacking a list _
sum_of_numbers = sum([x**3 for x in range(10000)])
SEMANTIC WEAPONS
$ unpacking an array _
$sumOfNumbers = 0;
foreach (range(1, 10000) as $num) { $sumOfNumbers += pow($num, 3); }
SEMANTIC WEAPONS
$ unpacking an array _
// second try $processArray = function($method, $array) { return array_map($method, $array); };
$sumOfNumbers = array_sum( $processArray( $method = function($x){return pow($x, 3);}, $array = range(0, 10000) ) );
SEMANTIC WEAPONS
One liners
– means something in English
– easy to understand at first glance
SEMANTIC WEAPONS
$ unpacking an array _
$sumOfNumbers = 0;
foreach (range(1, 10000) as $value) { $sumOfNumbers += pow($value, 3); }
// second try $processArray = function($method, $array) { return array_map($method, $array); };
$sumOfNumbers = array_sum( $processArray( $method = function($x){return pow($x, 3);}, $array = range(0, 10000) ) );
// third try $sumOfNumbers = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
SEMANTIC WEAPONS
$ readability _
sum_of_numbers = sum([x**3 for x in range(10000)])
$y = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
SEMANTIC WEAPONS
$ looping over two collections _
speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos'] talks = ['Ansible', 'Loopless', 'Deploy', 'Python']
for speaker, talk in zip(speakers, talks): print(speaker, talk)
SEMANTIC WEAPONS
$ looping over two collections _
$speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos']; $talks = ['Ansible', 'Loopless', 'Deploy', 'Python'];
$max = min(count($speakers), count($talks));
foreach(range(0, $max-1) as $i){ echo($speakers[$i] .' '. $talks[$i]); }
SEMANTIC WEAPONS
$ looping over two collections _
// second approach $speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos']; $talks = ['Ansible', 'Loopless', 'Deploy', 'Python'];
$meetupTalks = array_combine($speakers, $talks);
foreach($meetupTalks as $speaker => $talk){ echo "$speaker $talk"; }
SEMANTIC WEAPONS
$ looping over two collections _
for speaker, talk in zip(speakers, talks): print(speaker, talk)
foreach(array_combine($speakers, $talks) as $speaker => $talk) echo "$speaker $talk";
SEMANTIC WEAPONS
$ python iterators magic, tweet .@cvences
# dado un array asociativo, elimina todos los nombres que empiecen con la letra “c”meetup_info = { 'Javier': 'Ansible', 'Joe': 'Loopsless', 'Rasmus': 'Deploy', 'Carlos': 'Python', } meetup_info = {key: meetup_info[key] for key in meetup_info if not key.lower().startswith('c')}
# dado un modelo con relationships, filtra los blogs cuyos autores tengan o no # un nombre asignado. El título no incluye la palabra python y ordénalos por fecha # de creación descendente. Blog.objects .filter(entry__authors__isnull=False, entry__authors__name__isnull=True) .exclude(entry__title__icontains=‘python’) .order_by(‘-created’)
SEMANTIC WEAPONS
$ python iterators magic
def fib(n): return (4 << n * (3 + n)) // ((4 << 2 * n) - (2 << n) - 1) & ((2 << n) - 1)
def get_fibonacci_by_position(pos): """ Returns the fibonacci number at pos """ a, b = 1, 1 for _ in range(pos): a, b = a + b, a return b