/ Gists

Gists

On gists

Curated list of useful gulp plugins for awesome and easy frontend web development.

Gulp

gulp-modules.md #

Curated list of useful gulp plugins for awesome and easy frontend web development.

Other lists

Tutorials

Notes

Global

  • main-bower-files - fetches all files that meet filter criteria from main bower dependencies. Usefull to filtering out font files '**/*.{eot,svg,ttf,woff,woff2}' and copy them to /dist/fonts/
  • wiredep - adds links to bower depencies files to html/js/css which hold the correct comment tag
  • gulp-sourcemaps - build source maps. Use this instead of building sass or minifier if you do more work to those files afterwards, for example autoprefix the css.
  • gulp-watch - better then gulp.watch, because listens to new files
  • gulp-cached - in-memory caching for faster builds
  • gulp-concat - concatenate files
  • gulp-rename - rename files
  • gulp-zip - zip files
  • gulp-remember - remembers files that have passed through it and only adds files that has ever seen back into the stream.

Javascript

CSS

HTML

  • gulp-useref - parses selected files, checks for build comments which when is used to combine files. Its possible to fetch multiple builds and then do some specific work with each of them for example minimize css and jshint javascript. Prefer this to gulp-inject
  • gulp-inject - A javascript, stylesheet and webcomponent injection plugin for Gulp, i.e. inject file references into your index.html
  • gulp-minify-html - minify html
  • gulp-substituter - replace matched strings in files for defined values

IMAGES

Helpers

Testing


On gists

jQuery - proxy

JavaScript jQuery

jquery-proxy.js #

// immediately invoke fn
// nahrazka

 $('#myElement').click(function() {  
      (function(el){
         setTimeout(function() {
              // Problem! In this function "this" is not our element!
            el.addClass('colorme');
        }, 1000);
      })($(this)); // self executing function   
    });

On gists

Gulp - example file

Gulp

gulp2.js #

var gulp = require('gulp');

var clean = require('gulp-clean');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');

var bases = {
 app: 'app/',
 dist: 'dist/',
};

var paths = {
 scripts: ['scripts/**/*.js', '!scripts/libs/**/*.js'],
 libs: ['scripts/libs/jquery/dist/jquery.js', 'scripts/libs/underscore/underscore.js', 'scripts/backbone/backbone.js'],
 styles: ['styles/**/*.css'],
 html: ['index.html', '404.html'],
 images: ['images/**/*.png'],
 extras: ['crossdomain.xml', 'humans.txt', 'manifest.appcache', 'robots.txt', 'favicon.ico'],
};

// Delete the dist directory
gulp.task('clean', function() {
 return gulp.src(bases.dist)
 .pipe(clean());
});

// Process scripts and concatenate them into one output file
gulp.task('scripts', ['clean'], function() {
 gulp.src(paths.scripts, {cwd: bases.app})
 .pipe(jshint())
 .pipe(jshint.reporter('default'))
 .pipe(uglify())
 .pipe(concat('app.min.js'))
 .pipe(gulp.dest(bases.dist + 'scripts/'));
});

// Imagemin images and ouput them in dist
gulp.task('imagemin', ['clean'], function() {
 gulp.src(paths.images, {cwd: bases.app})
 .pipe(imagemin())
 .pipe(gulp.dest(bases.dist + 'images/'));
});

// Copy all other files to dist directly
gulp.task('copy', ['clean'], function() {
 // Copy html
 gulp.src(paths.html, {cwd: bases.app})
 .pipe(gulp.dest(bases.dist));

 // Copy styles
 gulp.src(paths.styles, {cwd: bases.app})
 .pipe(gulp.dest(bases.dist + 'styles'));

 // Copy lib scripts, maintaining the original directory structure
 gulp.src(paths.libs, {cwd: 'app/**'})
 .pipe(gulp.dest(bases.dist));

 // Copy extra html5bp files
 gulp.src(paths.extras, {cwd: bases.app})
 .pipe(gulp.dest(bases.dist));
});

// A development task to run anytime a file changes
gulp.task('watch', function() {
 gulp.watch('app/**/*', ['scripts', 'copy']);
});

// Define the default task as a sequence of the above tasks
gulp.task('default', ['clean', 'scripts', 'imagemin', 'copy']);

On gists

PHP in the command line

PHP

commands.cmd #

# To parse and execute a php script:
php file
 
# To check syntax on (i.e. lint) a PHP script:
php -l file
 
# To run PHP interactively:
php -a
 
# To run PHP code (Notes: Don't use <? ?> tags; escape double quotes with backslash):
php -r "code"
 
# To start a PHP built-in web server in the current directory:
php -S host:port

On gists

PHP Method Chaining

PHP

PHP Method Chaining.php #

<?php
 
class QueryMaker
{
    $table = '';
$field = '';
 
    // this is a static method, it doesn't
    // run on an object, it only runs on a class
    public static function make()
    {
        // create an instance of class
        // QueryMaker and return it
        return new static();
    }
 
    // this is not static, it doesn't run on
    // a class, only on an object
    public function setTable($name)
    {
        $this->table = $name;
        return $this;
    }
 
    // this is also not static
    public function setField($name)
    {
        $this->field = $name;
        return $this;
    }
 
    // again, not static, just renders
    // the "query"
    public function flush()
    {
        return "select {$this->field} from {$this->table}";
    }
}
 
// Here is the implementation with method chaining
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
 
// Here is the implementation without method chaining
$object = new QueryMaker();
$object->setTable('users');
$object->setField('name');
$query = $object->flush();
// the output is: select name from users
 
// The methods setTable() and setField() return $this.
// In that context $this is the QueryMaker object that was created by make().
 
// Let's go step by step:
 
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
// The static method QueryMaker::make() returns an object instantiation of the QueryMaker class.
 
$query = $object->setTable('users')->setField('name')->flush();
// $object->table is set, setTable() returns the object instance.
 
$query = $object->setField('name')->flush();
// $object->field is set, setField() returns the object instance.
 
$query = $object->flush();
// The flush method is called on the object, returning the string.

On gists

Find Duplicate Entries in MySQL

MySql

Find Duplicate Entries in MySQL. #

-- =============================================================================
-- Find Duplicate Input With MySQL
-- http://kvz.io/blog/2013/03/04/find-duplicate-input-with-mysql/
--
-- At my company we have employees creating customer accounts every day.
-- Sometimes we make mistakes, for instance, we forget to check if the company
-- already was a customer (maybe 10y ago they may have had a product).
--
-- Duplicate accounts can cause all sorts of problems, so I wanted way to detect
-- them with SQL.
--
-- The problem was, the company names may have been entered with different
-- punctuation, whitespace, etc. So I needed similar names to surface from the
-- depths of our database, not just exact matches (that would have been too easy
-- :)
--
-- For the solution I turned to SOUNDEX for fuzzy matching similar sounding
-- company names, and then review the results myself (false positives are
-- possible, but since they would be few, it becomes a simple task to
-- doublecheck) and report back to our company.
--
-- I thought I'd share
--
-- * partly because it could be useful to others (obviously this could be used
--   to detect all kinds of user generated typos and similar entries);
-- * mostly because I'm curious to find if there is a better (more performant)
--   way to write this query.
-- =============================================================================
 
--
-- Select all the individual company names that have a
-- soundex_code that occurs more than once (I now use a subquery for that)
SELECT
  `id`,
  `customer_name`,
  SOUNDEX(`customer_name`) AS soundex_code
FROM `customers`
WHERE SOUNDEX(`customer_name`) IN (
  -- Subquery: select all soundex_codes that occur more than once,
  -- (this does not return the individual company names that share them)
  SELECT SOUNDEX(`customer_name`) AS soundex_code
  FROM `customers`
  WHERE 1 = 1
    AND `is_active` = 1
    -- More specific criteria to define who you want to compare
  GROUP BY soundex_code
  HAVING COUNT(*) > 1
)
ORDER BY
  soundex_code,
  `customer_name`
 
--
-- This e.g. returns:
--
-- -----|------------------|------------------
-- id      customer_name       soundex_code
-- -----|------------------|------------------
-- 291     F.S. Hosting        F2352
-- 1509    FS hosting          F2352
-- 9331    R  Schmit           R253
-- 9332    R Schmit            R253

On gists

MySQL delete dupes on multiple columns

MySql

delete-duplicite.sql #

# If you want to keep the row with the lowest id value:

DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name



# If you want to keep the row with the highest id value:

DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name

On gists

MySQL delete dupes, keep newer

MySql

MySQL delete dupes, keep newer.s #

DELETE mytable
    FROM mytable
    INNER JOIN (
            SELECT max(id) AS lastId, someColumnWithDupes
            FROM mytable
            GROUP BY someColumnWithDupes
            HAVING count(*) > 1
            ) duplic ON duplic.someColumnWithDupes = mytable.someColumnWithDupes
    WHERE mytable.id < duplic.lastId;

On gists

mysql command

MySql CLI

mysql command.cmd #

# To connect to a database:
mysql database_name
 
# To connect to a database, user will be prompted for a password:
mysql -u user --password database_name
 
# To connect to a database on another host:
mysql -h database_host database_name
 
# To connect to a database through a Unix socket:
mysql --socket path/to/socket.sock
 
# To execute SQL statements in a script file (batch file):
mysql database_name < script.sql
 
# ---
 
# To connect to a database
$ mysql -h localhost -u root -p
 
# To backup all databases
$ mysqldump --all-databases --all-routines -u root -p > ~/fulldump.sql
 
# To restore all databases
$ mysql -u root -p  < ~/fulldump.sql
 
# Create database with utf-8 collation and utf-8 charset
$ mysql> create database <database_name> character set utf8 collate utf8_general_ci;
 
# Create a table with an auto-incrementing primary key (id), w/ utf-8
$ mysql> create table <table_name> (`id` int unsigned auto_increment, primary key (`id`)) default character set utf8 collate utf8_general_ci;
 
# List all databases on the sql server.
$ mysql> show databases;

# To dump a database to a file (Note that your password will appear in your command history!):
mysqldump -uusername -ppassword the-database > db.sql
 
# To dump a database to a file:
mysqldump -uusername -p the-database > db.sql
 
# To dump a database to a .tgz file (Note that your password will appear in your command history!):
mysqldump -uusername -ppassword the-database | gzip -9 > db.sql
 
# To dump a database to a .tgz file:
mysqldump -uusername -p the-database | gzip -9 > db.sql
 
 # To dump all databases to a file (Note that your password will appear in your command history!):
mysqldump -uusername -ppassword --all-databases > all-databases.sql
 
# To dump all databases to a file:
mysqldump -uusername -p --all-databases > all-databases.sql
 
# To export the database structure only:
mysqldump --no-data -uusername -p the-database > dump_file
 
# To export the database data only:
mysqldump --no-create-info -uusername -p the-database > dump_file

On gists

Replace text in all string columns of a database

MySql

Replace text in all string colum #

Select Concat( 'update ', table_schema, '.', table_name,
               ' set ', column_name,
               '=replace(', column_name, ',''old_text'',''new_text'');'
             )
From information_schema.columns
Where (data_type Like '%char%' or data_type like '%text' or data_type like '%binary')
  And table_schema = 'dbname';