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 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()
    call winrestview(l:save)

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:


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).



Sunday, December 24, 2017

SSH clients for Windows

SSH clients for Windows

MobaXterm supports MOSH


Xshell 5


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



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>



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











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;



How to place div side by side

How to place div side by side

Method 1:

    display: flex;
    width: 200px;
    flex-grow: 1;

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

Method 2:

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



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



get data between html and

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

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



PDO Transaction syntax with try catch

PDO Transaction syntax with try catch

if ($dbh->beginTransaction()) 
    //your db code
  catch (Exception $ex) 
    if ($dbh->inTransaction())



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:


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:

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

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"

Note: You need to enable mod_proxy and mod_headers.



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:

        autowire: true

        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 

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();