Ussing Cygwin's ssh-agent in Windows

posted Sep 29, 2016, 6:45 AM by Juan Jose Garcia-Ripoll   [ updated Oct 9, 2016, 3:40 AM ]

When you want to log in to a Unix machine or some other kind of server, one of the favourite protocols is SSH. In public key authentication, you can generate a pair of keys, a private one called id_rsa and a public one id_rsa.pub These keys are usually stored in your HOME directory, with sufficient permissions so that no one can read the private key.

Unfortunately this may not always be the case. I have had machines that have been hacked, or I sometimes like to store my private-public key pairs in some backup device which may be in a not too secure location (for instance Dropbox). Under those circumstances it is useful to store the private key with a password, the so called "passphrase". Then, whenever you want to log-in to another machine using SSH you only have to type the passphrase.

ssh-agent is a program that stores your public and private keys in memories. Using it, you only have to introduce the passphrase once at the beginning of your session. It is convenient, it works under Linux but Windows does not have it built in.

Step 1: install ssh and ssh-agent

Your first stop for these programs in Windows will be cygwin. Get it from https://www.cygwin.com/ I use the 64-bit version, which works fine enough. After installation I recommend the following two changes:
  1. Edit the PATH environment variable to include the directory c:/cygwin64 or c:/cygwin depending on the version you chose.
  2. Create a HOME environment variable pointing to your favorite directory. I normally rely on the Windows one %HOMEDRIVE%%HOMEPATH%
Both changes together have the nice side effect that you can use SSH from anywhere, including Windows terminals.

Step 2: Create your public and private keys

Open a terminal and type
ssh-keygen -t rsa
and enter a long password as your passphrase. The longer the better. I usually rely on stupid sentences, like "the cow jumped over the 27th wall street", which have no meaning but have enough entropy and are easy to remember.

Step 3: Ensure ssh-agent is run when you log in

Press Windows key + R (both keys simultaneously) and enter shell:startup This will open a folder where you can create programs that run at boot time. Click with the right button and create a new "Text document". Enter the following text and save it with the name "run-ssh-agent.cmd" Note the different extension!
@echo off
rem Start ssh-agent in the background. It will not be closed
start /b ssh-agent > %HOME%\.ssh-agent-env
echo We need to ask you the password with which the SSH key is encoded
echo After that we will update the environment variable so that you
echo do not need to enter it again
pause
bash -c ". ~/.ssh-agent-env; setx SSH_AUTH_SOCK "$SSH_AUTH_SOCK"; setx SSH_AGENT_PID "$SSH_AGENT_PID"; ssh-add"

This step is quite critical because it is on charge of starting the agent that keeps the passwords in the background, decoding the SSH keys with the password you provide and notifying the whole of the system (via the environment variables SSH_AUTH_SOCK and SSH_AGENT_PID) that the SSH keys are available for use.

Step 4: Configure cygwin to use ssh-agent

Edit your profile file ~/.bash_profile and add the following lines at the end
SSHAGENT=/usr/bin/ssh-agent
SSHAGENTARGS="-s"
if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
    if test -f ~/.ssh-agent-env; then
eval `cat ~/.ssh-agent-env`
    else
eval `$SSHAGENT $SSHAGENTARGS`
trap "kill $SSH_AGENT_PID" 0
    fi
fi

Step 5: Optional - Configure Emacs to use cygwin SSH

This is tricky. The problem is that Cygwin's SSH expect to be run from a Cygwin or MS-DOS terminal and does not like to run from within Emacs. There is a simple solution for this, which involves installing a package called fakecygpty from github (https://github.com/d5884/fakecygpty)

Step 6: Optional - Configure Emacs to use ssh-agent

I added the following function to my .emacs file (see here for configuration details) to read the location of ssh-agent and pass it to other functions, such as ssh or tramp.
(let ((filePath "~/.ssh-agent-env"))
  (with-temp-buffer
    (insert-file-contents filePath)
    (let (ssh-auth-sock ssh-agent-pid)
      (and (progn
    (goto-char (point-min))
    (re-search-forward "SSH_AUTH_SOCK=\\([^;]*\\)" nil t))
  (setq ssh-auth-sock (match-string 1))
  (progn
    (goto-char (point-min))
    (re-search-forward "SSH_AGENT_PID=\\([^;]*\\)" nil t))
  (setq ssh-agent-pid (match-string 1))
  (setenv "SSH_AUTH_SOCK" ssh-auth-sock)
  (setenv "SSH_AGENT_PID" ssh-agent-pid)))))

Hacking BibTeX

posted Sep 12, 2016, 6:52 AM by Juan Jose Garcia-Ripoll   [ updated Sep 12, 2016, 6:52 AM ]

I needed to use the Cambridge LaTeX style for books, which is very pretty and compact, but I wanted to produce PDF's where clicking on the title of articles or books would open a browser with that paper. See for example the blue text below, which links to the Physical Review A article


This is a trick that I used in my own thesis, as well as with other people's thesis as well. The trick is very simple. In this case I copied the cambridgeauthordate.bst file into cambridgeauthordateurl.bst and enlarged the list of allowed fields to include URL

ENTRY
  { address
    author
    booktitle
    chapter
    edition
    editor
    howpublished
    institution
    journal
    key
    month
    note
    number
    organization
    pages
    publisher
    school
    series
    title
    type
    volume
    year
    URL
  }
  {}
  { label extra.label sort.label }

and then I edited the section that starts with FUNCTION { format.title ... so that it read

FUNCTION {format.title}
{ title empty$
    { "" }
    { URL empty$
      { title }
      { "\href{" URL * "}{" * title * "}" * }
      if$
    }
  if$
}

Save the file and include it with \bibliographystyle{cambridgeauthordateurl} Notice how the sixth line simply concatenates, using the postfix operator *, five different strings into the final text that forms the title.

Extracting images from PDFs with Inkscape

posted Aug 30, 2016, 3:51 AM by Juan Jose Garcia-Ripoll   [ updated Aug 30, 2016, 3:55 AM ]

My work as a scientist and also as an occasional outreach communicator has put me in a situation where I need to extract graphical material from publications and other documents. The two alternatives I normally found were
  1. Go to a webpage and pray for a high-resolution image that can be used. In many journals this is rarely the case. Bandwidth considerations force the journals to place mediocre size pictures that are sometimes ok for presentations, unless you really use a good projector or a big screen. In most cases they are not ready for printed reproduction.
  2. Use the PDF of a publication and capture a screenshot. You would typically open the document in Acrobat, zooming in until the region you are interested in fills the screen, and then use the "screenshot" or "camera" icon to capture that region. This normally improves the quality of the resulting image, but it is still limited by the resolution of your screen!
I have rediscovered a third method that was probably invented by one of my PhD students. The idea is to open the PDF as if it was a drawing, using some vector graphic program, of which I recommend and detail Inkscape. This is a drawing program which is available for Windows, Mac and Linux, and which is very powerful -perhaps too powerful for many much simpler designs.

Recent versions of Inkscape can open a wide variety of formats, including PDFs. The workflow I would therefore suggest to you is the following one

  1. Open Inkscape and press Ctrl-O to open the PDF you want to work with. In the import window you should select "import via Poppler". Make also sure you select the page where the resource you wish to copy lives
  2. Once the page is imported, you can begin editing. Start by selecting "Ungroup" by clicking with the right button on top of the imported page. After this, all elements will be editable and you will be able to strip down the image to your desired minimum. Notice below how I deleted several portions of text.

  3. Finally, save the image in your desired format. I normally use SVG for archival and PDF to embed in other publications.
Two final remarks: First, make use you have the rights for a fair use of the image. I assume that in talks giving credit is enough, while in publications you would have to contact the journal. Second, beware of how you build images for your paper! This way of proceding can reveal hacks in your images, text that is underlying your original plots, etc. Just a warning. Curious PhD students may have a lot of fun with your work otherwise.

Focused work

posted Aug 8, 2016, 8:16 AM by Juan Jose Garcia-Ripoll   [ updated Aug 8, 2016, 8:29 AM ]

I must confess I have become a bit obsessed with the amount of distraction that I get at work. I am not talking about social media, but handling of multiple bureaucratic lines of action, competing for funding, taking care of people's projects, interaction with students, etc. This has been more damaging or at least more obvious in the light of specific projects that I wanted to accomplish, such as for instance, completing my lectures notes. As a kind of escape I have ended up reading quite a lot of self-help literature around organization and other ideas. What follows is an excerpt of the things I have found useful from various sources I do not remember or do not dare to cite. Well, maybe "Deep Work" by Cal Newport is an acceptable reference, specially due to its connection to academia, but in many other cases they were less respectable sources that, despite everybody's warning, still contained some bits of wisdom. Here they go in a very disorganized way. At the very least they will give you an idea of why I behave how I do in the last months.

General ideas

  • Acting by reacting: we work on an input-output based activity
    • We react to emails, which cause interruptions and change our workflow. Reacting immediately to email is a way of letting other people sort our priorities. Allocating email-only time and moving those tasks to a to-do list to be considered in the appropriate slots frees our time for our own priorities. This is an example in a broader category of problems that could be sorted out with minimal organization.
    • Allocating bureaucracy-first time causes a disruption of work because we are left in the busy mode of reacting to lists of tasks. The impact of this on creativity cannot be underrated. Decision fatigue is a real issue.
  • Choices:
    • Be more selective on the topics, tasks and projects you embark on. Measure cost of those projects, but do not be too short-sighted: some projects are long-term investments, while some others seem short-term wins but the load outweighs the rewards.
    • Clearly separate projects and tasks which originate outside from your own priorities. There are unavoidable things that have to be carried on for your own curriculum, job position, collaboration network, etc. Find stable slots of time that you allocate for those tasks and concentrate them in that area of your day.
    • Be clear about your priorities when interacting with other people. Casual commitments on your side may be taken as more serious collaborations that may complicate your life, or vice versa. Do not embark on more tasks or projects than you can handle or, as they say, do not bite more than you can safely swallow.
  • Strategies:
    • Find a personal time for your own projects, ideas, crafts, but above all, also for thinking and planning what you want to do. My personal ideal day based on may different guidelines
      • 8:00-8:30 Plan of the day. Minimal note-taking and revision of to-do lists, separating tasks in different time slots.
      • 8:30-10:00 Creative stuff. This is early time where most people and interruptions still did not have time to appear.
      • 10:00-10:30 Coffee and email. Answer if brief, sort out to other time-slots if possible.
      • 10:30-13:00 Bureaucracy and non-creative stuff. This is the time where you may get most interruptions, specially from administration.
      • 13:00-14:00 Lunch break.
      • 14:00-15:00 Work time.
      • 15:00-15:30 Email verification to gather reactions from previous period. Try to sort out task for further days. Do not answer emails today.
      • 16:00-17:30 Easy work time.
      • 17:30- Go home and disconnect.
    • Minimize the number of projects you work on simultaneously and ideally devote each day to a single project. Note that here I refer to projects as opposed to bureaucracy or externally induced tasks, which may be unfortunately more abundant. Define your day with the project you wanted to do, not with the 10:30-13:00 period above.
    • Decide each day what you want to do at the beginning of the day, not along the way. If possible, integrate that decision taking along or at the end of a well defined morning ritual, such as coffee, brief exercising, journalling, etc.
    • Minimize external inputs in the early part of the day, at least until the first email break. News checking, social networks, etc., all these things hijack your time and your willpower to structure the day decreases dramatically.
    • Try to be as predictable as possible, both for yourself and your coworkers. It is better if you constrain interaction and discussions to a certain part of the day, ideally from 10:30 to lunch time or at the end of the day. In the first case because it is already a period where interruptions are already frequent, and in the second case because productivity decreases along the day and discussions are usually less taxing than other tasks.
  • Avoid redundancies and interruptions:
    • Group similar tasks: have a paper or notepad to write down reactions that appear along your work, such as
      • Emails that have to be sent
      • Things to be delivered or picked up
      • Documents to print, read, etc
    • Delay those tasks to the appropriate time slots. For instance, if you are working on your projects and you realize it would be nice to send an email to somebody about the idea you just had, note it down on the to-do and continue working on your project.
    • Grouping is relevant because you may realize that many things are related. For instance, if you are writing a project that coordinates with different partners, you may want to ask them about certain bits of information. If you note down those questions, you may find that along the day similar questions pop up and you only have to send each partner one email, instead of one message for each question. Remember: email is not the same as chatting.
    • Grouping might also be useful in other parts of your leisure time: reading news, TV time, internet browsing, shopping, etc. For instance, it is better to have a time for scanning a few news sources than having Twitter + BBC News open all day on your desktop. Separate different activities clearly with small “rituals” like stretching, taking a coffee, walking, etc. Make the change more dramatic between work-time and leisure-time.
  • Be efficient in your communications: this is very important.
    • Ask precise questions, with suitable alternatives and anticipate reactions. Examples:
      • “Shall we meet in your office tomorrow or on Wednesday at 3pm? If this is not possible, suggest two or three alternative times.”
      • “Dear X, I need your bank account information -- Bank name, address, number account, IBAN and SWIFT -- as well as your personal information -- scan (jpeg or pdf) of ID, address and recent CV --. Please provide all the information in a single email before …”
    • Let people explicitly know that you are not 24/7. Include in your email signature a statement about the usual times where you can react to email, suggesting a phone call only for urgent matters. But do not provide personal phones to the general public: most things are not that urgent.

Caveats

  • All the ideas above are more easily implementable the less you depend on others’ expectations, to avoid saying “bosses”. If you work in a rigid structure, or you have permanent input on tasks and projects from higher instances, it might help to apply the ideas above to giving structure to that interaction. For instance, you could:
    • Ask your supervisor or boss to make your list of projects better defined or more “sequential”, as opposed to working in many topics in parallel.
    • Try to allocate periodic interaction with your colleagues or supervisor in well defined slots of time. This periodicity and definition will also benefit the persons you interact with.
    • Make those meetings as efficient as possible, bringing well defined ideas or questions to the meeting and defining also the expectations of that meeting: is it a report, a brainstorming session, are you needing help?
    • Be proactive. Do not work on act-by-reaction mode or expect supervision on the external topics. You do not want to suffer back the friction that this causes on others.
  • You will find resistance, bear with it.
    • People will expect 24/7 availability, in particular through email, which paradoxically is the least resilient method of communication. The breaks indicated above are designed to break these expectations, but if this does not work, talk to the offended party and clarify your motivation.
    • You will yourself expect 24/7 availability. Nothing truly horrible happens if you do not answer an email in the weekend. Or probably in a week. And if it happens, either it is because of bad planning, or you should be willing to pay the price for a more organized and independent life.

Updated guide: writing LaTeX on Windows with Emacs

posted Jul 13, 2016, 12:18 AM by Juan Jose Garcia-Ripoll   [ updated Sep 9, 2016, 4:58 AM ]

These are the steps I followed to work with Emacs on Windows and be able to code LaTeX, view the resulting PDFs and use reverse search, that is, clicking on the PDF and telling emacs to move to the right point in the text.

Step 1: Install Emacs, AucTeX and SumatraPDF

This is not painless, but it is ok for anybody familiar with computers.
  1. SumatraPDF can be downloaded from its web page, It has a simple installer. The appearance may be simplistic, but it is very lean and I recommend it for Windows and tablets in particular.
  2. Emacs 24.5 or later can be downloaded from the GNU page, but I personally use the 64-bit optimized recompilation. You should unpack it under the "Program files" folder.

Step 2: Configure SumatraPDF

Open SumatraPDF and click on the top-left corner menu you have to make two changes:
  • Select "Settings" and "Advanced Options" and ensure that there is a line saying
EnableTeXEnhancements = true
  • Select "Settings" and then "Options" and enter the following text 
"C:\Program Files\emacs\bin\emacsclientw.exe" -n +%l "%f"
Make sure the path c:\Program Files\emacs corresponds to the folder where you unzipped your emacs installation. 

Step 3: Configure Emacs

This is the way I configure my Emacs.
  • Before opening Emacs, define an environment variable "HOME" to point to your user directory. This can be done in the Control Panel > System and Security > System > Advanced System Settings > Advanced tab. Alternatively, enter "Environment variables" in the Cortana search box and edit the values. I show you below my own settings. Sorry, it's in Spanish.
  • Go to the folder where you unzipped the Emacs distribution. In the "bin" directory you will find an executable "runemacs.exe". Click with the right button and select "Pin to Start" to have that program available at all times. The outcome should be as follows
  • Open "runemacs.exe" by clicking on the icon on the Start page. Press Ctrl+x followed by Ctr+f and type ~/.emacs to open the file "~/.emacs". Store the following settings in it and save them pressing Ctrl-x followed by Ctrl-s
;;
;; 1) Package repository
;;
(require 'package)

(add-to-list 'package-archives '("melpa-stable" . "http://stable.melpa.org/packages/"))
(package-initialize)

;;
;; 2) AUCTex customization
;;
(setq TeX-PDF-mode t)

(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-view-program-list
 '(("Sumatra PDF" ("\"C:/Program Files/SumatraPDF/SumatraPDF.exe\" -reuse-instance" (mode-io-correlate " -forward-search %b %n ") " %o"))))
(setq TeX-view-program-selection
'(((output-dvi style-pstricks)
"dvips and start")
(output-dvi "Yap")
(output-pdf "Sumatra PDF")
(output-html "start")))

(add-hook 'LaTeX-mode-hook
  (lambda ()
    
(assq-delete-all 'output-pdf TeX-view-program-selection)
    
(add-to-list 'TeX-view-program-selection '(output-pdf "Sumatra PDF"))))
  • The first part of the customization instructs Emacs where to look for additional software. The second set of customizations are intended for AUCTex, once we install it. With this you should be able to open the PDF associated to a latex file and click twice in Sumatra PDF to go back to the emacs window, right at the paragraph or line where you clicked.
  • Now press Esc followed by X and then type package-install. You should be offered with a rather large list of software. Look for AUCTex and select it, and then click Install. You will see some warnings, but installation should proceed smoothly and the package will be available the next time you open Emacs.

Writing LaTeX with Emacs on Windows

posted Jul 13, 2016, 12:18 AM by Juan Jose Garcia-Ripoll   [ updated Aug 8, 2016, 2:52 AM ]

These are the steps I followed to work with Emacs on Windows and be able to code LaTeX, view the resulting PDFs and use reverse search, that is, clicking on the PDF and telling emacs to move to the right point in the text.

Step 1: Install Emacs, AucTeX and SumatraPDF

This is not painless, but it is ok for anybody familiar with computers.
  1. SumatraPDF can be downloaded from its web page, It has a simple installer. The appearance may be simplistic, but it is very lean and I recommend it for Windows and tablets in particular.
  2. Emacs 24.5 or later can be downloaded from the GNU page, but I personally use the 64-bit optimized recompilation.
  3. AucTeX is Emacs' best plug-in for working with TeX and LaTeX files. You can download a precompiled version that matches your emacs version from their web page. Make sure you unpack it in the right place.

Step 2: Configure SumatraPDF

Open SumatraPDF and click on the top-left corner menu you have to make two changes:
  • Select "Settings" and "Advanced Options" and ensure that there is a line saying
EnableTeXEnhancements = true
  • Select "Settings" and then "Options" and enter the following text 
"C:\Program Files\emacs\bin\emacsclientw.exe" -n +%l "%f"
Make sure the path c:\Program Files\emacs corresponds to the folder where you unzipped your emacs installation. 

Step 3: Configure Emacs

This is the way I configure my Emacs.
  1. Before opening Emacs, define an environment variable "HOME" to point to your user directory. This can be done in the Control Panel > System and Security > System > Advanced System Settings > Advanced tab.
  2. Go to the folder where you unzipped the Emacs distribution. In the "bin" directory you will find an executable "runemacs.exe". Click with the right button and select "Pin to Start" to have that program available at all times.
  3. Open "runemacs.exe" and open the file "~/.emacs". Store the following settings in it
(setq TeX-PDF-mode t)
(setq TeX-source-correlate-mode t)
(setq TeX-source-correlate-method 'synctex)
(setq TeX-view-program-list
 '(("Sumatra PDF" ("\"C:/Program Files/SumatraPDF/SumatraPDF.exe\" -reuse-instance" (mode-io-correlate " -forward-search %b %n ") " %o"))))
(setq TeX-view-program-selection
'(((output-dvi style-pstricks)
"dvips and start")
(output-dvi "Yap")
(output-pdf "Sumatra PDF")
(output-html "start")))


(defun my-latex-mode ()
  (visual-line-mode +1)1
  (assq-delete-all 'output-pdf TeX-view-program-selection)
  (add-to-list 'TeX-view-program-selection '(output-pdf "Sumatra PDF")))

(add-hook 'LaTeX-mode-hook 'my-latex-mode)

With this you should be able to open the PDF associated to a latex file and click twice in Sumatra PDF to go back to the emacs window, right at the paragraph or line where you clicked.

Analyzing your email inbox with Python and Jupyter

posted Jun 16, 2016, 1:44 AM by Juan Jose Garcia-Ripoll   [ updated Jun 16, 2016, 1:59 AM ]

I am learning Jupyter, Python and Julia as alternatives to my usual Matlab and Mathematica workflows for protyping scientific ideas and projects. In this blog post I use them as a tool to analyze the inflow of email at the office, with the hope that it will help me decide how to manage (and reduce) attention span to emails.

The notebook produces a plot like the one below, which shows the percentage of emails that arrive at certain hours of the day. In my case the distribution is rather uniform from 10am to 6pm, so probably my best strategy would be to concentrate attention around 9am to prepare for the day.


To use this notebook in Windows or Mac:
  1. Download Anaconda from https://www.continuum.io/downloads Focus on the latest Python 3 version.
  2. Install Jupyter using conda install jupyter from a terminal.
  3. Download the notebook to some folder.
  4. Open a terminal, change directory to that folder and type jupyter notebook 'Email analysis.ipynb' to open the notebook in a browser.
  5. The notebook can be evaluated much like a Mathematica file.

Studying spin squeezing in Mathematica

posted Jun 14, 2016, 9:16 AM by Juan Jose Garcia-Ripoll   [ updated Jun 14, 2016, 9:18 AM ]

I made a simple Mathematica file for simulating spin squeezing numerically and creating density plots of the Husimi Q function, as the one shown below. At the very least it is an interesting exercise on using Mathematica's sparse matrices, sparse matrix exponentiation and multiplication with a vector, and colored density plots in 3D.


Deterioro de la firma electrónica en España

posted Jan 20, 2016, 1:01 PM by Juan Jose Garcia-Ripoll   [ updated Jan 20, 2016, 2:30 PM ]

La firma electrónica es un procedimiento por el que certificamos nuestra identidad al enviar un documento, típicamente en el contexto de la Administración del Estado y las Comunidades Autónomas. Este concepto se introdujo con bastante precocidad en España alrededor de 2003 y tras unos años de dificultades, parece que con el tiempo se estabilizó, se mejoró su uso, y llegó a ser posible realizar trámites como la declaración de la Renta, concursos de oposiciones, pagos de tasas y aduanas, alguna solicitud de beca, convocatorias de postdoc Ramón y Cajal, solicitud de proyectos del Plan Nacional, etc.

En aquellos años no era demasiado fácil realizar el trámite, pero éste no pasaba de instalar una extensión llamada Java, importar el certificado de la Fábrica de Moneda y Timbre, y cruzar los dedos. En un principio sólo Internet Explorer funcionaba, luego Firefox comenzó a funcionar y yo llegué a realizar la firma en un Mac con Safari sin mayores problemas.

En general parece que la "cosa" funcionaba, de forma que el trámite se convirtió en obligatorio o hasta esencial:
  • Es obligatoria, por ejemplo, para la firma de proyectos de investigación.
  • Es esencial, por ejemplo, para los investigadores que residen en el extranjero, no tienen acceso a consulados y desean presentar solicitudes al Ramón y Cajal u otros trámites.
  • Está presente en múltiples otros trámites como concursos de oposiciones y traslados, o pago de impuestos, que se dirigen a un público más amplio y sin conocimientos técnicos.
El problema es que desde entonces el sistema no se ha mantenido al día. Los ordenadores y navegadores han evolucionado, Java ya no es una extensión aceptable, ni para Chrome, ni para Firefox, ni para Windows 10. En los ordenadores Apple con Mac OS X, los requisitos de seguridad hacen que la instalación de Java esté "desaconsejada" y resulta bastante traumática, si es posible en absoluto. En Linux encontramos problemas similares, aunque este sistema nunca funcionó demasiado bien. Y, lo que es peor, en los dispositivos móviles y tablets sospecho que es imposible realizar un trámite así, a pesar de que el 50% de los españoles posee un smartphone.

Como consecuencia de ello, no es extraño que gente confiada en la administración intente concluir uno de estos trámites y se encuentre que no es posible. Ante esa situación, la propia administración responde con una total falta de sensibilidad y sensatez, asumiendo que es ella y no el entorno la que puede definir el status quo.

Mira, mamá, un ordenador de hace 30 años que me sirve para firma electrónica!
Sirva de muestra el correo adjunto más abajo, recibido por un colega investigador que intentó, sin éxito, presentar una solicitud de Ramón y Cajal desde el extranjero. Las instrucciones de ese correo son cuatro páginas desordenadas que hacen referencia a un documento de 15 páginas o más, donde se proponen parches y agujeros de seguridad para solventar el hecho de que la aplicación de firma del Estado y de las Autonomías está obsoleta. Dicho documento no está disponible en ninguno de los enlaces facilitados, que dan errores, enlazan a páginas genéricas o no estamos autorizados a ver. Las propias instrucciones no sirven para un ordenador más reciente con Windows 10. Nada de esta información está disponible en la propia convocatoria de Ramón y Cajal, donde los enlaces apuntan a una página del extinto Ministerio de Ciencia, y que hace referencia a Internet Explorer (abandonado por Microsoft), Firefox 3.0 (que ya no soporta Java) y otras instrucciones obsoletas.

Esta situación es patética y conduce, por ejemplo, a que institutos de investigación mantengan un ordenador obsoleto, sin actualizar, con un sistema operativo obsoleto y lleno de parches de seguridad, sólo para atender a los procedimientos de firma. Pero, ¿qué pasa con un investigador que se encuentra desplazado por trabajo y debe de hacer frente a un trámite urgente desde su portátil?

O de forma más sencilla, ¿qué pasa con los ciudadanos normales que tienen que lidiar con la Administración? La Agencia Tributaria ha comenzado a implantar sistemas de identificación alternativas, con SMS y teléfono móvil. ¿Por qué no se extiende su uso a otros ámbitos, donde los trámites son bastante menos sensibles y críticos que presentar una declaración de la Renta correcta?

Optimize a PDF or extract part of it with ghostscript

posted Nov 9, 2015, 11:58 AM by Juan Jose Garcia-Ripoll   [ updated Nov 9, 2015, 11:59 AM ]

I am writing some largish lecture notes, which now are around 120 pages long. The problem with this document is that it is full of attractive images that are needed to make the content more clear and amenable, and these images are not optimized in size: they come from papers, simulations, drawings, etc, and each of them has been produced with different means and the final size of the image might be much smaller than what the resolution allows for.

So, the result is that I have this large file which is 16Mb large, which I will call notes.pdf I need to send a few chapters of this file to my colleagues and students and when I cut the file, it still is too large, 12-13Mb, as Adobe or OS X are not  able to really trim the size.

Here is what you can do:
  1. If you run Windows, install Ghostscript, either directly (look for it) or from Cygwin.
  2. Open a command line and type
gs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -sOutputFile=small-notes.pdf notes.pdf
 
This reduces the size quite significantly by (i) reducing the size of figures to the resolution that is needed for the given device (screen), (ii) eliminating fonts that are already standard and which are included by PDFLaTex, (iii) compressing the output. In my case, down from 34Mb to 13Mb.

If I need to select a few pages, tell that to Ghostscript:

gs -dFirstPage=1 -dLastPage=73 -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dBATCH -dNOPAUSE -dPDFSETTINGS=/screen -sOutputFile=small-notes.pdf notes.pdf

1-10 of 21