Tuesday, December 26, 2017

What's the simplest way to strip trailing whitespace from all lines in a file?

What's the simplest way to strip trailing whitespace from all lines in a file?

The "simplest" way is to just use :substitute:

:%s/\s\+$//e

:%s to run :substitute over the range %, which is the entire buffer.
\s t match all whitespace characters.
\+ to repeat them 1 or more times.
$ to anchor at the end of the line.
The e flag to not give an error if there is no match (i.e. the file is already without trailing whitespace).

However, this is probably not the "best" way as it causes two side-effects:

1. it moves the cursor to the last match;
2. it resets the last search term.

You can fix both items by turning this into a function:

fun! TrimWhitespace()
    let l:save = winsaveview()
    %s/\s\+$//e
    call winrestview(l:save)
endfun

And then use it like:

:call TrimWhitespace()

The winsaveview() will save the current "view", which includes the cursor position, folds, jumps, etc. The winrestview() at the end will restore this from the saved variable.
The last-used search term is automatically restored after leaving a function, so we don't have to do anything else for this.
Since this is somewhat annoying to type :call all the time, you can define a command:

command! TrimWhitespace call TrimWhitespace()

Which can be be used without the :call:

:TrimWitespace

And you can of course bind it to a key:

:noremap <Leader>w :call TrimWhitespace()<CR>

Some people like to automatically do this before they write a file to disk, like so:

autocmd BufWritePre * :call TrimWhitespace()

I don't like it, as some formats require trailing whitespace (such as Markdown), and on some other occasions you even want trailing whitespace in your code (such as formatting an email, and using the -- marker to indicate the start of a signature).

Reference:

https://vi.stackexchange.com/questions/454/whats-the-simplest-way-to-strip-trailing-whitespace-from-all-lines-in-a-file?newreg=dfad440fc0e14ac1b0afde5ce4e41e27

Sunday, December 24, 2017

SSH clients for Windows

SSH clients for Windows

MobaXterm supports MOSH

https://mobaxterm.mobatek.net/

Xshell 5

https://www.netsarang.com/products/xsh_overview.html

How to get Git to clone into current directory

How to get Git to clone into current directory

# git init .
# git remote add origin <repository-url>
# git pull origin master

Reference:

https://stackoverflow.com/questions/9864728/how-to-get-git-to-clone-into-current-directory/16811212

Vim restore opened files

Vim restore opened files

Add these in ~/.vimrc:

# vim ~/.vimrc

" Save the current vim sessions
noremap <F2> :mksession! ~/vim_session <cr>

" Load the saved vim sessions
noremap <F3> :source ~/vim_session <cr>

Reference:

https://stackoverflow.com/questions/1416572/vi-vim-restore-opened-files

Turning off auto indent when pasting text into vim

Method 1:

:set paste
:set nopaste

or in ~/.vimrc

set pastetoggle=

Method 2:

:r! cat

Then ctrl-insert to paste
Then enter
Then ctrl-d (twice) to end of file.

Monday, December 11, 2017

Web sessions

Web sessions

The most common method is to store a token, or session ID, in a browser cookie. Based on that token, the server then loads the session data from a data store. Over the years, a number of best practices have evolved that make cookie-based web sessions reasonably safe. The OWASP organization lists a number of recommendations aimed at reducing common attacks such as session hijacking or session fixation.

Sticky sessions

https://stackoverflow.com/questions/10494431/sticky-and-non-sticky-sessions/13641836#13641836

Reference:

https://blog.gopheracademy.com/advent-2017/web-sessions-and-users/

https://en.wikipedia.org/wiki/Session_hijacking

https://en.wikipedia.org/wiki/Session_fixation

https://github.com/rivo/sessions

https://en.wikipedia.org/wiki/HTTP_cookie#Cookie_theft_and_session_hijacking

https://en.wikipedia.org/wiki/Cross-site_request_forgery

https://en.wikipedia.org/wiki/Representational_state_transfer#Stateless

https://en.wikipedia.org/wiki/Source_routing

Saturday, December 9, 2017

perl: warning: Setting locale failed.

perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = "en_US.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").

# locale-gen
# dpkg-reconfigure locales

Position absolute but relative to parent

Position absolute but relative to parent


#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

Reference:

https://stackoverflow.com/questions/10487292/position-absolute-but-relative-to-parent

How to place div side by side

How to place div side by side

Method 1:

.container{
    display: flex;
}
.fixed{
    width: 200px;
}
.flex-item{
    flex-grow: 1;
}

<div class="container">
  <div class="fixed"></div>
  <div class="flex-item"></div>
</div>

Method 2:

<div style="width: 100%; overflow: hidden;">
    <div style="width: 600px; float: left;"> Left </div>
    <div style="margin-left: 620px;"> Right </div>
</div>

Method 3:

<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>

Reference:

https://stackoverflow.com/questions/2637696/how-to-place-div-side-by-side

docker ubuntu /bin/sh: 1: locale-gen: not found

docker ubuntu /bin/sh: 1: locale-gen: not found

In Dockerfile:

RUN apt-get install -y locales
RUN locale-gen en_US.UTF-8

Reference:

https://stackoverflow.com/questions/39760663/docker-ubuntu-bin-sh-1-locale-gen-not-found

get data between html and

get data between html <tag> and </tag>

$regex = '`<code>(.*?)</code>`s';

Reference:

https://stackoverflow.com/questions/9253027/get-everything-between-tag-and-tag-with-php/9253072

PDO Transaction syntax with try catch

PDO Transaction syntax with try catch


if ($dbh->beginTransaction()) 
{
  try 
  {
    //your db code
    $dbh->commit();
  } 
  catch (Exception $ex) 
  {
    if ($dbh->inTransaction())
    {
       $dbh->rollBack();
    }        
  }
}

Reference:

https://stackoverflow.com/questions/24408434/pdo-transaction-syntax-with-try-catch

How to raise PDOException?

How to raise PDOException?

Set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, as soon as you init your pdo object:

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource

APIs are the threads that let you stitch together a rich web experience. But this experience has a hard time translating to the browser, where the options for cross-domain requests are limited to techniques like JSON-P (which has limited use due to security concerns) or setting up a custom proxy (which can be a pain to set up and maintain).

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data.

As you can see from this example, CORS support requires coordination between both the server and client. Luckily, if you are a client-side developer you are shielded from most of these details. The rest of this article shows how clients can make cross-origin requests, and how servers can configure themselves to support CORS.

Method 1:

On the remote server, add:

<?php
header('Access-Control-Allow-Origin: http://symfony.cent-dev.local');
#header('Access-Control-Allow-Headers: X-Requested-With');
#header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS');
?>

Then, go observe the response in the browser at client side. You will see the three lines above.

Method 2:

On the remote server, edit your Apache configuration file:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: http://symfony.cent-dev.local
</ifModule>

Note: you can replace http://symfony.cent-dev.local to a wildcard *.

Note: and don't forget to load module: a2enmod headers

Method 3:

Add a proxy script on your server, ex: proxy.php then having your client side script to access the proxy.php script.

The proxy.php script then send the request to the remote server.

Method 4:

On your server, set up proxy on Apache:

<LocationMatch "/api">
   ProxyPass http://remote-server.com:8000/api/
   #Header add "Access-Control-Allow-Origin" "*"
   Header add "Access-Control-Allow-Origin" "http://symfony.cent-dev.local"
</LocationMatch>

Note: You need to enable mod_proxy and mod_headers.

Reference:

http://www.html5rocks.com/en/tutorials/cors/
http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-cors
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
http://www.andlabs.org/html5.html
https://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity

Thursday, December 7, 2017

How to access the service in a custom console command?

How to access the service in a custom console command?

You can use Dependency Injection in commands with ease since Symfony 3.3 (May 2017).

Use PSR-4 services autodiscovery in the services.yml:

services:
    _defaults:
        autowire: true

    App\Command\:
        resource: ../Command

Then use common Constructor Injection and finally even Commands will have clean architecture:

final class MyCommand extends Command
{
    /**
     * @var SomeDependency
     */
    private $someDependency;

    public function __construct(SomeDependency $someDependency)
    {
        $this->someDependency = $someDependency;

        // this is required due to parent constructor, which sets up name 
        parent::__construct(); 
    }
}

Alternative method is to extend Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand:

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class MyCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine')->getEntityManager();
    }
}

Reference:

https://stackoverflow.com/questions/19321760/symfony2-how-to-access-the-service-in-a-custom-console-command

https://www.tomasvotruba.cz/blog/2017/05/07/how-to-refactor-to-new-dependency-injection-features-in-symfony-3-3/#4-use-psr-4-based-service-autodiscovery-and-registration

http://symfony.com/blog/new-in-symfony-3-4-lazy-commands