Shared posts

27 Mar 18:52

Beginners' Guide to Concurrency and Parallelism in Python

Discussions criticizing Python often talk about how it is difficult to use Python for multithreaded work, pointing fingers at what is known as the global interpreter lock (affectionately referred to as the “GIL”) that prevents multiple threads of Python code from running simultaneously. Due to this, the threading module doesn’t quite behave the way you would expect it to if you’re coming from other languages such as C++ or Java. It must be made clear that one can still write code in Python that runs concurrently or in parallel and make a stark difference resulting performance, as long as certain things are taken into consideration. If you haven’t read it yet, I suggest you take a look at Eqbal Quran’s article on concurrency and parallelism in Ruby here on the Toptal blog.

In this article, we will write a small Python script to download the top popular images from Imgur. We will start with a version that downloads images sequentially, or one at a time. As a prerequisite, you will have to register an application on Imgur. If you do not have an Imgur account already, please create one first.

The scripts in this article has been tested with Python 3.4.2. With some changes, they should also run with Python 2 - urllib is what has changed the most between these two versions of Python.

Getting Started

Let us start by creating a Python module, named “download.py”. This file will contain all the functions necessary to fetch the list of images and download them. We will split these functionalities into three separate functions:

  • get_links
  • download_link
  • setup_download_dir

The third function, “setup_download_dir”, will be used to create a download destination directory if it doesn’t already exist.

Imgur’s API requires HTTP requests to bear the “Authorization” header with the client ID. You can find this client ID from the dashboard of the application that you have registered on Imgur, and the response will be JSON encoded. We can use Python’s standard JSON library to decode it. Downloading the image is an even simpler task, as all you have to do is fetch the image by its URL and write it to a file.

This is what the script looks like:

import json
import logging
import os
from pathlib import Path
from urllib.request import urlopen, Request

logger = logging.getLogger(__name__)

def get_links(client_id):
   headers = {'Authorization': 'Client-ID {}'.format(client_id)}
   req = Request('https://api.imgur.com/3/gallery/', headers=headers, method='GET')
   with urlopen(req) as resp:
       data = json.loads(resp.readall().decode('utf-8'))
   return map(lambda item: item['link'], data['data'])

def download_link(directory, link):
   logger.info('Downloading %s', link)
   download_path = directory / os.path.basename(link)
   with urlopen(link) as image, download_path.open('wb') as f:
       f.write(image.readall())

def setup_download_dir():
   download_dir = Path('images')
   if not download_dir.exists():
       download_dir.mkdir()
   return download_dir

Next, we will need to write a module that will use these functions to download the images, one by one. We will name this “single.py”. This will contain the main function of our first, naive version of the Imgur image downloader. The module will retrieve the Imgur client ID in the environment variable “IMGUR_CLIENT_ID”. It will invoke the “setup_download_dir” to create the download destination directory. Finally, it will fetch a list of images using the get_links function, filter out all GIF and album URLs, and then use “download_link” to download and save each of those images to the disk. Here is what “single.py” looks like:

import logging
import os
from time import time

from download import setup_download_dir, get_links, download_link

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('requests').setLevel(logging.CRITICAL)
logger = logging.getLogger(__name__)

def main():
   ts = time()
   client_id = os.getenv('IMGUR_CLIENT_ID')
   if not client_id:
       raise Exception("Couldn't find IMGUR_CLIENT_ID environment variable!")
   download_dir = setup_download_dir()
   links = [l for l in get_links(client_id) if l.endswith('.jpg')]
   for link in links:
       download_link(download_dir, link)
   print('Took {}s'.format(time() - ts))

if __name__ == '__main__':
   main()

On my laptop, this script took 19.4 seconds to download 91 images. Please do note that these numbers may vary based on the network you are on. 19.4 seconds isn’t terribly long, but what if we wanted to download more pictures? Perhaps 900 images, instead of 90. With an average of 0.2 seconds per picture, 900 images would take approximately 3 minutes. For 9000 pictures it would take 30 minutes. The good news is that by introducing concurrency or parallelism, we can speed this up dramatically.

All subsequent code examples will only show import statements that are new and specific to those. For convenience, all of these Python scripts can be found in this GitHub repository.

Using Threads

Threading is one of the most well known approaches to attaining concurrency and parallelism. Threading is a feature usually provided by the operating system. Threads are lighter than processes, and share the same memory space.

Here, we will write a new module to replace “single.py”. This module will create a pool of 8 threads, making a total of 9 threads including the main thread. I chose 8 worker threads, because my computer has 8 CPU cores and one worker thread per core seemed a good number for how many threads to run at once. In practice, this number is chosen much more carefully based on other factors, such as other applications and services running on the same machine.

This is almost the same as the previous one, with the exception that we now have a new class, DownloadWorker, that is a descendent of the Thread class. The run method has been overridden, which runs an infinite loop. On every iteration, it calls “self.queue.get()” to try and fetch an URL to from a thread-safe queue. It blocks until there is an item in the queue for the worker to process. Once the worker receives an item from the queue, it then calls the same “download_link” method that was used in the previous script to download the image to the images directory. After the download is finished, the worker signals the queue that that task is done. This is very important, because the Queue keeps track of how many tasks were enqueued. The call to “queue.join()” would block the main thread forever if the workers did not signal that they completed a task.

from queue import Queue
from threading import Thread

class DownloadWorker(Thread):
   def __init__(self, queue):
       Thread.__init__(self)
       self.queue = queue

   def run(self):
       while True:
           # Get the work from the queue and expand the tuple
           directory, link = self.queue.get()
           download_link(directory, link)
           self.queue.task_done()

def main():
   ts = time()
   client_id = os.getenv('IMGUR_CLIENT_ID')
   if not client_id:
       raise Exception("Couldn't find IMGUR_CLIENT_ID environment variable!")
   download_dir = setup_download_dir()
   links = [l for l in get_links(client_id) if l.endswith('.jpg')]
   # Create a queue to communicate with the worker threads
   queue = Queue()
   # Create 8 worker threads
   for x in range(8):
       worker = DownloadWorker(queue)
       # Setting daemon to True will let the main thread exit even though the workers are blocking
       worker.daemon = True
       worker.start()
   # Put the tasks into the queue as a tuple
   for link in links:
       logger.info('Queueing {}'.format(link))
       queue.put((download_dir, link))
   # Causes the main thread to wait for the queue to finish processing all the tasks
   queue.join()
   print('Took {}'.format(time() - ts))

Running this script on the same machine used earlier results in a download time of 4.1 seconds! Thats 4.7 times faster than the previous example. While this is much faster, it is worth mentioning that only one thread was executing at a time throughout this process due to the GIL. Therefore, this code is concurrent but not parallel. The reason it is still faster is because this is an IO bound task. The processor is hardly breaking a sweat while downloading these images, and the majority of the time is spent waiting for the network. This is why threading can provide a large speed increase. The processor can switch between the threads whenever one of them is ready to do some work. Using the threading module in Python or any other interpreted language with a GIL can actually result in reduced performance. If your code is performing a CPU bound task, such as decompressing gzip files, using the threading module will result in a slower execution time. For CPU bound tasks and truly parallel execution, we can use the multiprocessing module.

While the de facto reference Python implementation - CPython - has a GIL, this is not true of all Python implementations. For example, IronPython, a Python implementation using the .NET framework does not have a GIL, and neither does Jython, the Java based implementation. You can find a list of working Python implementations here.

Spawning Multiple Processes

The multiprocessing module is easier to drop in than the threading module, as we don’t need to add a class like the threading example. The only changes we need to make are in the main function.

To use multiple processes we create a multiprocessing Pool. With the map method it provides, we will pass the list of URLs to the pool, which in turn will spawn 8 new processes and use each one to download the images in parallel. This is true parallelism, but it comes with a cost. The entire memory of the script is copied into each subprocess that is spawned. In this simple example it isn’t a big deal, but it can easily become serious overhead for non-trivial programs.

from functools import partial
from multiprocessing.pool import Pool

def main():
   ts = time()
   client_id = os.getenv('IMGUR_CLIENT_ID')
   if not client_id:
       raise Exception("Couldn't find IMGUR_CLIENT_ID environment variable!")
   download_dir = setup_download_dir()
   links = [l for l in get_links(client_id) if l.endswith('.jpg')]
   download = partial(download_link, download_dir)
   with Pool(8) as p:
       p.map(download, links)
   print('Took {}s'.format(time() - ts))

Distributing to Multiple Workers

While the threading and multiprocessing modules are great for scripts that are running on your personal computer, what should you do if you want the work to be done on a different machine, or you need to scale up to more than the CPU on one machine can handle? A great use case for this is long-running back-end tasks for web applications. If you have some long running tasks, you don’t want to spin up a bunch of subprocesses or threads on the same machine that need to be running the rest of your application code. This will degrade the performance of your application for all of your users. What would be great is to be able to run these jobs on another machine, or many other machines.

A great Python library for this task is RQ, a very simple yet powerful library. You first enqueue a function and its arguments using the library. This pickles the function call representation, which is then appended to a Redis list. Enqueueing the job is the first step, but will not do anything yet. We also need at least one worker to listen on that job queue.

The first step is to install and run a Redis server on your computer, or have access to a running Redis server. After that, there are only a few small changes made to the existing code. We first create an instance of an RQ Queue and pass it an instance of a Redis server from the redis-py library. Then, instead of just calling our “download_link” method, we call “q.enqueue(download_link, download_dir, link)”. The enqueue method takes a function as its first argument, then any other arguments or keyword arguments are passed along to that function when the job is actually executed.

One last step we need to do is to start up some workers. RQ provides a handy script to run workers on the default queue. Just run “rqworker” in a terminal window and it will start a worker listening on the default queue. Please make sure your current working directory is the same as where the scripts reside in. If you want to listen to a different queue, you can run “rqworker queue_name” and it will listen to that named queue. The great thing about RQ is that as long as you can connect to Redis, you can run as many workers as you like on as many different machines as you like; therefore, it is very easy to scale up as your application grows. Here is the source for the RQ version:

from redis import Redis
from rq import Queue

def main():
   client_id = os.getenv('IMGUR_CLIENT_ID')
   if not client_id:
       raise Exception("Couldn't find IMGUR_CLIENT_ID environment variable!")
   download_dir = setup_download_dir()
   links = [l for l in get_links(client_id) if l.endswith('.jpg')]
   q = Queue(connection=Redis(host='localhost', port=6379))
   for link in links:
       q.enqueue(download_link, download_dir, link)

However, RQ is not the only Python job queue solution. RQ is easy to use and covers simple use cases extremely well, but if more advanced options are required, other job queue solutions (such as Celery) can be used.

Conclusion

If your code is IO bound, both threading and multiprocessing will work for you. Multiprocessing is a easier to just drop in than threading, but has a higher memory overhead. If your code is CPU bound, multiprocessing is most likely going to be the better choice - especially if the target machine has multiple cores or CPUs. For web applications, and when you need to scale the work across multiple machines, RQ is going to be better for you.

Expanded from Toptal Blog by Feed Readabilitifier.
23 Mar 11:53

Tattoo 2: Tattooed Too

by nedroid

Tattoo 2: Tattooed Too

23 Mar 11:49

Comic for 2015.03.21

23 Mar 11:49

Comic for March 21, 2015

23 Mar 11:33

jedavu:Frozen Lakes PatternsWith the fall of temperatures, we...


Bubbles Under The Ice of Abraham Lake by Emmanuel Coupe.


Bubbles in The Ice of Abraham Lake by Phillips Chip.


Frozen Pond by Adam Rifkin.


Ice Rider in Siberia by Matthieu Paley.


Baikal Lake in Russia by Daniel Kordan.


Lake Druzhby in Antarctica by Stu Shaw.


Blue Pond in Japan by Kent Shiraishi.


Frost Flowers in the Arctic Ocean by Matthias Wietz.


Frost Flowers in the Arctic Ocean by Matthias Wietz.


Pond in Switzerland by Dartai.

jedavu:

Frozen Lakes Patterns

With the fall of temperatures, we have gathered for you the most beautiful photographs of frozen lakes and ponds from all around the world : Russia, Switzerland, Japan or also in Canada, their frozen surfaces are full of aesthetic and graphic patterns.

20 Mar 22:19

Last Words

by Greg Ross

http://commons.wikimedia.org/wiki/File:Amelia_earhart_1937.jpg

Amelia Earhart left behind what she called “popping off letters,” to be opened in the event of her death. This one, discovered by her husband and biographer, George Putnam, was addressed to her father:

May 20, 1928

Dearest Dad:

Hooray for the last grand adventure! I wish I had won, but it was worth while anyway. You know that.

I have no faith we’ll meet anywhere again, but I wish we might.

Anyway, good-by and good luck to you.

Affectionately, your doter,

Mill

Another, addressed to her mother, read simply, “Even though I have lost, the adventure was worth while. Our family tends to be too secure. My life has really been very happy, and I don’t mind contemplating its end in the midst of it.”

The post Last Words appeared first on Futility Closet.

20 Mar 22:17

The Children

by Reza

the-children

20 Mar 20:41

Twitter de embaixador

Em 2012, circulou a ideia de uma intervenção na Síria. O argumento desidratou-se logo, levando ao consenso oposto: não há vitória possível contra o Estado Islâmico sem a cooperação de Damasco. O Brasil acertou, opondo-se à ideia da intervenção desde o início.

No entanto, ao explicar os porquês da decisão, o Itamaraty não coordenou a mensagem entre seus embaixadores. Uns apresentaram arrazoados plausíveis a seus interlocutores. Outros não.

Numa capital europeia, um deles disse: "O que há de errado com Assad? Nada." Quem ouviu concluiu que a diplomacia brasileira pouco se importa com os mortos do regime Assad.

Problemas de comunicação como esse acontecem com frequência. Mesmo quando o Brasil tem motivos defensáveis, muitas vezes sua maneira de apresentar as próprias prioridades e intenções deixa a desejar.

O motivo disso é a ausência de uma política de comunicação social. Faltam mecanismos para produzir uma mensagem coerente capaz de resistir bem a críticas dentro e fora das fronteiras e, além disso, mobilizar toda a rede diplomática com eficácia.

Existe agora uma oportunidade para reverter essa situação. Afinal, as redes sociais estão transformando a maneira como se conduz a diplomacia.

Do uso do WhatsApp para coordenar a resposta ao ebola à campanha no Twitter para eleger Roberto Azevêdo para a OMC, as redes viraram instrumento valioso de política externa. No Twitter, a conta @ItamaratyGovBr já conta com mais de 100 mil seguidores.

Os consulados brasileiros com presença ativa no Facebook vêm tendo enormes ganhos de eficiência, atendendo melhor a milhares de brasileiros todo dia. Só que esse progresso ainda não se traduziu numa política institucionalizada com força suficiente para disciplinar a tropa, mobilizar recursos humanos e integrar a comunicação do Estado brasileiro no exterior.

Muitas postagens do Itamaraty nas redes sociais ainda são escritas em burocratês. Testa-se a paciência do internauta com fotos do encontro do chanceler brasileiro com a ministra de Educação da Irlanda.

O uso do YouTube, promissor, está muito aquém do que demanda uma sociedade como a nossa, que vive online. A presença de diplomatas nas redes traz riscos, claro.

A embaixada britânica nos EUA foi obrigada a se desculpar depois de celebrar num tuíte o dia que as forças da coroa puseram fogo na Casa Branca. Numa visita à China, Cristina Kirchner postou comentário grosseiro sobre o sotaque chinês quando tentava uma piada.

Nada disso deveria impedir a diplomacia brasileira de se adaptar à nova realidade. O ministro Mauro Vieira ganharia ao abrir uma conta no Twitter e usá-la.

Num momento de relativo declínio de nossa presença internacional, não há espaço para grandes lances. Mas dá para fazer ginástica na cela.

Uns vão reclamar. Para eles, a lembrança de Lord Palmerston. Em 1840, ao ver um telégrafo pela primeira vez, exclamou: "Meu Deus! Isto é o fim da diplomacia!"

20 Mar 20:39

neil-gaiman: upworthy: There Were Too Many Deer In The Forest....



neil-gaiman:

upworthy:

There Were Too Many Deer In The Forest. So They Unleashed The Wolves Without Any Idea What Would Happen.

When the deer killed off the forest, they decided to let the wolves loose to fix it. We had no idea what exactly we had done.

If you haven’t seen this video, take a few minutes and watch it. You will be happy you did.

20 Mar 20:00

Perros salchicha jugando a Policías y Ladrones

by Troy

Estos dos simpáticos perros salchicha son hermanos, y se lo pasan de miedo jugando a "Policías y Ladrones" convenientemente equipados.

Por lo que se puede apreciar en el video, el que más disfruta es el que lleva el disfraz de policía, con su gorra y su coche con sirenas y luces incluidas.

Visto en NothingToDoWithAbroath

Ver más: disfraces, perros, policía
Síguenos: @NoPuedoCreer - @QueLoVendan - @QueLoVendanX


20 Mar 18:27

Photo



20 Mar 18:25

Artists, TV Series and Movie Directors Luciano Laborde





















Artists, TV Series and Movie Directors Luciano Laborde

20 Mar 18:03

Saturday Morning Breakfast Cereal - Brains vs. Supercomputers

by admin@smbc-comics.com

Hovertext:


New comic!
Today's News:

 New exclusive comic over at The Nib!

20 Mar 15:05

Yahoo vai nos livrar das senhas, mas há um porém.

by Carlos Cardoso

a113-terminator

Eu tenho um problema sério de senhas. Bem antes de ter idiotas todo dia tentando invadir minhas contas achando que minha senha do Gmail é “vendramini”, eu já era paranóico. WarGames, Quebra de Sigilo, os seriados da infância, tudo contribuiu para que minhas senhas fossem seguras. Em alguns casos em nem sei a senha, guardo em arquivos offline.

Esta é uma senha típica que uso.

t5ffT$G(15IwxN*JUp7dWqF"Jt2GUQmCUp+

Aí eu vou instalar um equipamento novo, não tem como conectar e copiar o arquivo, sou obrigado a digitar essa desgraça.

A proposta do Yahoo, que já está rolando nos EUA, se propõe a resolver isso, de uma forma bem criativa. A idéia é simples: você usa aquela senha monstruosa para entrar no Yahoo, se autentica, prova que você é você.

Daí vai nas configurações de segurança e habilita “Senhas On-Demand”. Insere seu número de celular, confirma e pronto.

Quando você for usar um computador suspeito (e todos são) em um evento, na casa de um conhecido, num hotel, acesse o Yahoo com seu username e clique “envie minha senha”.

O sistema mandará um SMS para seu celular com uma senha temporária de uso único. Você a digitará e pronto, seu acesso garantido, sua senha de verdade protegida, pois nunca passou pela rede suspeita.

De um certo ponto de vista é melhor, ou pelo menos mais prático do que a autenticação em dois níveis. É algo que eu gostaria de ver nos principais serviços online, e o único porém da idéia é que para nós que moramos no mato (da linha do Equador pra baixo) é complicado confiar nas operadoras de celular, corre risco do código não chegar nunca.

Fonte: WC.

The post Yahoo vai nos livrar das senhas, mas há um porém. appeared first on Meio Bit.








20 Mar 12:32

Glassy Pools of Used Motor Oil Reflect the Architectural Splendor of a Swiss Church

by Christopher Jobson

romain-crelier-1
La Mise en Abîme (2013, used oil, metal) / All photos courtesy We Find Wildness

romain-crelier-2

romain-crelier-3

romain-crelier-4

romain-crelier-5

romain-crelier-6

romain-crelier-7

Created by Swiss artist Romain Crelier, La Mise en Abîme (an idiom that communicates the same thing as “a curveball,” but means, roughly, “to have put into an abyss”) was a visually arresting artwork installed on the floor of the Bellelay Abbey in Switzerland back in 2013. The piece is comprised of two shallow pools of used motor oil that function as mirrors, reflecting the architectural details of the surrounding interior. The crude juxtaposition of recycled oil and the impeccably preserved aesthetic of a 12th century church wasn’t lost on the artist who referred to the piece as “monochrome paintings using a despised substance.” You can see more photos on We Find Wildness. (via We Find Wildness, This Isn’t Happiness, thnx Kathy!)

20 Mar 12:02

What Your Email Domain Says About You

by DOGHOUSE DIARIES

What Your Email Domain Says About You

This is obviously to say nothing of what precedes the @ symbol.

If an incomplete sentence lands in a forest

— Ray Yamartino (@rayyamartino) March 20, 2015
20 Mar 00:11

(photo via taikuus)



(photo via taikuus)

20 Mar 00:11

Tree Canopy Walkway Path in Cape Town

by Donnia

En Afrique du Sud, nous célébrons les cent ans du Kirstenbosch National Botanical Garden, où on peut voir un pont construit 12 mètres au-dessus du sol et étendant la balade sur 130 mètres environ, au milieu des arbres. Ce pont propose une marche au-dessus des feuillages et de la verdure pour laisser les visiteurs admirer la vue sur les montagnes.

tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-15 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-14 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-13 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-12 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-8 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-6 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-4 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-2 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-1 tree-canopy-walkway-path-kirstenbosch-national-botanical-garden-0
19 Mar 21:52

sopranish:blackbarmitzvahs:Can you imagine the conversation...

by aishiterushit


sopranish:

blackbarmitzvahs:

Can you imagine the conversation though?

Queen: I’m going

Chief of Staff: But, Your Majesty, the security risks…

Queen: I’m going I want cake 

Chief of Staff:

Queen: 

Chief of Staff: 

Queen: I want cake

Bride: Eh, it’s fine, it’s not like the Queen is coming

Groom: Totally

Queen: Heyoooo

19 Mar 21:00

Love Potion

Love Potion
19 Mar 20:59

Inspirational Dad

by tga

grand_canyon

19 Mar 20:51

20:20, por Richard Wilson. Basicamente, ambientes cheios de...

Adam Victor Brandizzi

Mais impressionatne que a igreja. Dica do Igor Santos.









20:20, por Richard Wilson. Basicamente, ambientes cheios de óleo.

Em Saatchi Gallery, Londres.

Via Igor Santos.

19 Mar 19:58

Saturday Morning Breakfast Cereal - DIE OPPRESSORS!

by admin@smbc-comics.com

Hovertext:


New comic!
Today's News:

 OH MY GOD IT'S HAPPENING

19 Mar 13:15

Todos os arquivos

by André Farias

Vida de Suporte

Quem já passou por algo parecido levanta o mouse °\0


Todos os arquivos é um post do blog Vida de Suporte.
19 Mar 11:30

Colorful Psychedelic Installations of Sugar and Candy by Pip & Pop

by Johnny Strategy
pip-and-pop (1)

“I saw a dream like this” at Australian Experimental Art Foundation, Adelaide 2013. Photos by Andre Castellucci and Pip & Pop

pip-and-pop (7)

“I saw a dream like this” at Australian Experimental Art Foundation, Adelaide 2013. Photos by Andre Castellucci and Pip & Pop

pip-and-pop (2)

“Through a hole in the mountain” at MT Kurashiki, Japan 2014. Photos by Keizo Kioku

pip-and-pop (5)

“Through a hole in the mountain” at MT Kurashiki, Japan 2014. Photos by Keizo Kioku

pip-and-pop (3)

“Candy Lab” at Mediamatic, Amsterdam, Netherlands 2014. Photos by Willem Velthoven and Pip & Pop

pip-and-pop (4)

“Candy Lab” at Mediamatic, Amsterdam, Netherlands 2014. Photos by Willem Velthoven and Pip & Pop

pip-and-pop (6)

“Candy Lab” at Mediamatic, Amsterdam, Netherlands 2014. Photos by Willem Velthoven and Pip & Pop

Australian artist Tanya Schultz creates immersive wonderlands using the sweetest materials: colorful sugar and candy. But along with the hundreds of pounds of sugar, the miniature worlds, which are reminiscent of mythological lands made from food, often incorporate as many ingredients as there are colors. Working under the pseudonym Pip & Pop, Schultz uses everything from glitter and pipe cleaners to beads and figurines to create her psychedelic installations, which have been exhibited all around the world.

Pip and Pop began as a duo in 2007 but since 2011 Schultz has been working alone, or sometimes collaborating with other artist or creative companies, to create her elaborate installations. Check out what she’s been up to recently and allow yourself to be transported to imaginary worlds where sugar rains from the sky and streets are paved with candies. (via Cross Connect)

19 Mar 11:20

taikonaut:humanoidhistory:Fifty years ago today, cosmonaut...







taikonaut:

humanoidhistory:

Fifty years ago today, cosmonaut Alexei Leonov made history when he stepped outside the Voshkod 2 spacecraft and became the first person ever to walk in space. As a small step, as a great leap, Leonov’s 12-minute spacewalk was an adventure for the ages — and it almost killed him.

The BBC has the story of how his spacesuit started inflating into a death trap:

At this point the cosmonaut realised something was wrong. The lack of atmospheric pressure in space had slowly caused his spacesuit to inflate like a balloon. He recalls:
"My suit was becoming deformed, my hands had slipped out of the gloves, my feet came out of the boots. The suit felt loose around my body. I had to do something.”
"I couldn’t pull myself back using the cord. And what’s more with this misshapen suit it would be impossible to fit through the airlock."
In five minutes he would be in the Earth’s shadow, and plunged into total darkness. Without telling ground control, the cosmonaut decided to bleed half of the air out of his spacesuit through a valve in its lining. This risked starving his body of oxygen, but if he couldn’t get back inside the capsule, he’d be dead anyway.
Leonov let out a little oxygen at a time to reduce the pressure. But as he did so, he started to feel the first hints of decompression sickness.
“I began to get pins and needles in my legs and hands. I was entering the danger zone, I knew this could be fatal.”
He started coiling the cord in order to haul himself back. When he finally reached the airlock, he pushed the camera in, grabbed the sides and lurched through head first.
The extreme physical exertion had caused his temperature to soar; he was now at risk of heatstroke and sweating uncontrollably. The globules filled his helmet, obscuring his vision.
Leonov was supposed to re-enter the airlock feet first. Getting in the wrong way meant he had to turn himself around in the cramped space to make sure the umbilical cord was inside and the hatch was locked.
He says: “It was the most difficult thing: I’m in this suit and I had to turn around in the airlock. But with the perspiration, I couldn’t see anything.”
"I don’t normally sweat much, but on that day I lost 6kg in weight.”
After curling around in his bulky suit, in such a narrow space, Leonov finally made it back inside the craft.

(BBC)

Jesus Christ that’s most of my phobia list right there.

18 Mar 20:00

Impeachment

Adam Victor Brandizzi

Aliás, interessante esse fivefilters.org!

No dia 25/8/1999, primeiro ano do segundo mandato do FHC, meu pai, Mario Prata, que tinha votado no Lula, publicou no "Estadão" a crônica "UNE ou desune". Cito abaixo alguns trechos.

"Eu, a princípio, achei que tinha lido errado. Mas li de novo. O erro não era meu. Era de um moleque de 22 anos. (...) Ele é o novo presidente da União Nacional dos Estudantes. Sabe qual é a meta dele? Derrubar o Fernando Henrique Cardoso. (...) Ir pra rua e derrubar o presidente. (...) Será que esse moleque (...) sabe o que a UNE fez durante anos contra a ditadura para agora, finalmente, a gente colocar lá o Fernando Henrique? (...) Eu posso até não concordar com o nosso presidente. Mas vivemos numa democracia. (...) Você não viveu a ditadura, menino. Dê graças a Deus por termos o Fernando Henrique como nosso presidente. É um homem digno, íntegro, honesto e não mata estudante. (...) Se está errando aqui ou ali não é de propósito. (...) Foram muitos mortos, moleque, para conseguirmos a democracia."

No mesmo dia 25, na coluna Joyce Pascowitch, na Folha: "Pode haver nos próximos dias uma revoada de políticos que apoiam o governo para partidos de oposição (...)." "A pedido do próprio Palácio do Planalto, o mago das pesquisas do PSDB [Antonio Lavareda] tem dado várias entrevistas. Tudo para explicar que existe um outro lado das pesquisas de opinião -a população não estaria assim tão insatisfeita com a performance do presidente."

No dia seguinte, 26 de agosto de 1999, a oposição faria em Brasília a Marcha dos 100 mil, gritando "Fora, FHC!". Brizola pregaria a renúncia do presidente e do vice e a convocação de novas eleições. MST e CUT exigiriam impeachment. "O líder do maior partido da oposição, Luiz Inácio Lula da Silva (PT), disse no Rio que o objetivo do movimento é pedir a abertura de uma CPI para apurar suposto crime de responsabilidade de FHC na privatização das teles. 'Pode-se até chegar ao impeachment, a partir do que for apurado pela CPI'", publicou a Folha.

Neste domingo, a mesma história será reencenada, mas com os atores invertendo-se nos personagens. Manifestantes do centro à direita (Dez mil? Cem mil? Dois milhões?) vão às ruas pedir a cabeça da petista. Eu venho ao jornal repetir as palavras do meu pai: "Posso até não concordar com o [a] nosso [a] presidente. Mas vivemos numa democracia".

É inegável que há muita coisa podre em Brasília -e em São Paulo, no Rio, em Birigui e em Santa Rita do Passa Quatro. Somos um país corrupto, da quitanda ao agrobusiness. O petrolão, contudo, está sendo investigado. O Ministério Público é independente. A imprensa é livre -livre, inclusive, para ter o rabo preso com quem bem entende.

Veja: após o mensalão, o presidente do PT, o tesoureiro e o ministro da Casa Civil foram julgados pelo STF (um colegiado cuja maioria foi indicada durante os anos petistas) e mandados pra cadeia. Se isso é a "venezuelização" do Brasil, não precisamos mais nos preocupar com a Venezuela.

Protestos contra o governo são justos e não só dor de cotovelo da "elite branca", mas enquanto não houver provas que envolvam a presidente com a corrupção, qualquer um que falar em impeachment não passará, como disse há 16 anos nosso grande cronista, de um "moleque".

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

18 Mar 19:54

Fofo

by Daniel Lafayette

tirinha---fofo

18 Mar 19:47

Tutorial

by ricardo coimbra
Clique na imagem para aumentar
18 Mar 19:19

Sobre o debate político: "Don't be a dick"

by Carlos Orsi
Quem acompanha este blog há algum tempo sabe que tenho algum envolvimento com o que se poderia chamar de "movimento" cético, que fundamentalmente busca oferecer um pouco de racionalidade e senso crítico ao debate público sobre questões relacionadas a ciência e saúde. Ponho "movimento" assim, entre aspas, porque, ao menos no Brasil, a iniciativa é muito mais voluntarista e desorganizada do que a palavra sugere. Nos Estados Unidos, onde existe um movimento cético assim, sem aspas, que se organiza em comitês, associações, publica revistas e promove convenções, houve, há alguns anos, uma grande polêmica provocada por uma palestra dada pelo astrônomo Phil Plait. O título da intervenção foi Don't Be a Dick, algo que em português poderíamos traduzir como Não Seja Escroto.

Há algo de intrigante nesse título, mas para quem está dentro do movimento -- com ou sem aspas, agora tanto faz -- a questão é bem clara: depois de ouvir a bilionésima defesa apaixonada da homeopatia, depois da milésima manifestação de fé na astrologia, depois quaquilionésima argumentação falaciosa em prol do criacionsimo ou contra a vacina de sarampo, é muito fácil sucumbir à tentação de imaginar que todo mundo que está do outro lado da conversa é ou imbecil ou mal intencionado, e reagir de acordo.

O bônus é que há maneiras extremamente inteligentes de ser escroto, o que gratifica o ego -- ironia e sarcasmo podem ser finos como um florete ou brutais como um cutelo -- e, se você não estiver se sentindo especialmente inspirado, mesmo uma escrotice clássica, curta e grossa, haverá de atrair os aplausos dos colegas: é muito legal ver um colega dando aos charlatões e aos idiotas exatamente o que merecem.

Exceto que: talvez não mereçam. Talvez não sejam todos idiotas e charlatões. No mínimo, se o objetivo final do movimento é educar o público e trazer sanidade para o debate, fazer o público se sentir cretinizado e insultado pode não ser uma boa ideia.

Claro, existe o arquétipo do Velho Professor Britânico, o mestre irascível cujos insultos cuidadosamente calculados  e sarcasmos poético-filosóficos não só estimulam o desenvolvimento intelectual dos pupilos como conquistam seu amor e admiração. O Velho Professor Britânico é a versão escolástica do Sargento Durão, o militar de cara fechada e coração (secretamente) aberto que, por meio da aplicação judiciosa de bullying, ameaça, palavrões e tortura forja meninos assustados e egoístas em homens corajosos e solidários.

Veja bem, não digo que é impossível que ambos os arquétipos possam funcionar. Talvez haja situações em que pessoas que se enquadram neles sejam até mesmo necessárias e essenciais para a sobrevivência da civilização.  Mas me parece extremamente provável que funcionem muito menos, e sejam muito menos necessários, do que quem se identifica com eles gostaria de imaginar.

Bom, dei toda essa volta para falar sobre o debate poplítico brasileiro, principalmente da forma como é travado nas redes sociais. Em sua palestra, Plait em certo momento pergunta à plateia algo como, "quantos de vocês abandonaram uma crença falsa ao serem chamados de idiotas?" Traduzindo a questão para o universo do Facebook, ela poderia ser: "Quantos de vocês desistiram de apoiar um impeachment ao serem chamados de fascistas golpistas?" Ou, do outro lado: "Quantos de vocês passaram a criticar Dilma ao serem chamados de petralhas corruptos?"

Na palestra, algumas pessoas levantaram a mão em resposta à provocação de Plait -- e não nego que, de vez em quando, um tapa da orelha retórico pode levar alguém a prestar mais atenção nos argumentos e a rever suas posições, mas o número de pés-de-ouvido simbólicos distribuídos a torto e a direito por aí supera toda e qualquer necessidade real.

A esmagadora maioria das comunicações sobre política que flutuam na rede é escrota e reiterativa: faz pouco caso dos adversários, desestimula a interrogação, reforça dogmas. O que é ótimo para aquilo que os gringos chamam de shouting matches -- "campeonatos de gritaria" -- mas não serve para mais nada.

Mesmo quando tenta se revestir de um caráter argumentativo, a carga de condescendência e pressuposta superioridade ("precisamos conversar sobre" = "senta aí e me escuta, seu retardado"), somada à dose cavalar de premissas "óbvias" não examinadas -- afinal, por que o PT é "uma quadrilha"? Por que a mídia é "golpista"? -- simplesmente esmagam o propósito.

O pior é que isso não funciona nem mesmo se supusermos que os diferentes grupos estejam, não tentando travar um diálogo, mas apresentar seus pontos para a massa indecisa e perplexa. Cada vez mais, escreve-se para cortejar o aplauso de quem já está no coro, reforçar a fé dos convertidos e, eventualmente, destilar bile, não para validar posições e gerar clareza. O que é um enorme desperdício.