<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Silveira Neto &#187; Python</title>
	<atom:link href="http://silveiraneto.net/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://silveiraneto.net</link>
	<description>the world is a pixel</description>
	<lastBuildDate>Sun, 08 Jan 2012 05:17:57 +0000</lastBuildDate>
	<language>pt-br</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Python, flatten a list</title>
		<link>http://silveiraneto.net/2011/10/08/python-flatten-a-list/</link>
		<comments>http://silveiraneto.net/2011/10/08/python-flatten-a-list/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 21:38:07 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[flatten]]></category>
		<category><![CDATA[lists]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3929</guid>
		<description><![CDATA[Surprisingly python doesn&#8217;t have a shortcut for flatten a list (more generally a list of lists of lists of&#8230;). I made a simple implementation that doesn&#8217;t use recursion and tries to be written clearly. I get a element from a &#8220;bad&#8221; list (a list that can have another lists). If the element is not a [...]]]></description>
			<content:encoded><![CDATA[<p>Surprisingly python doesn&#8217;t have a shortcut for flatten a list (more generally a list of lists of lists of&#8230;).</p>
<p>I made a simple implementation that doesn&#8217;t use recursion and tries to be written clearly.</p>
<p><script src="https://gist.github.com/1229108.js?file=flatten"></script></p>
<p>I get a element from a &#8220;bad&#8221; list (a list that can have another lists). If the element is not a list we store in our flat list. If the element is still a list we deal with him later. The flat list always have elements that are not a list.<br />
To preserve the original order we reverse the elements at the end.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2011/10/08/python-flatten-a-list/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Contando Algarismos Em Um Intervalo</title>
		<link>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/</link>
		<comments>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 23:21:59 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[compreensão de lista]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[programação funcional]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3142</guid>
		<description><![CDATA[Quantos zeros tem entre um e mil? É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a programação funcional e compreensão de lista que algumas linguagens como Python oferecem. Para contar os zeros de um número, transformamos ele em uma string e contamos quantas substrings &#8217;0&#8242; ele contém. Por exemplo o [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Quantos zeros tem entre um e mil?</strong></p>
<p>É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a <a href="http://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional">programação funcional</a> e <a href="http://pt.wikipedia.org/wiki/List_comprehension">compreensão de lista</a> que algumas linguagens como Python oferecem.</p>
<p>Para contar os zeros de um número, transformamos ele em uma string e contamos quantas substrings &#8217;0&#8242; ele contém. Por exemplo o 800:</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">800</span><span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2</span></pre>
</div>
</div>
<p>Para gerar uma lista ordenada com os elementos do intervalo entre um e mil, inclusive os valores um e mil:</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># [1, 2, ... , 999, 1000]</span></pre>
</div>
</div>
<p>Pegamos esse intervalo  e geramos uma outra lista onde cada elemento é a contagem dos zeros do número do intervalo.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: black;">&#91;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
<span style="color: #808080; font-style: italic;"># [0, 0, ... , 0, 3]</span></pre>
</div>
</div>
<p>Por exemplo, 1 não tem nenhum zero. Dois também não. 999 também não. 1000 tem três.</p>
<p>Somamos todos os elementos da lista temos o número de algarismos zero entre um e mil.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #008000;">sum</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>E a resposta é 192.</p>
<p>O mesmo poderia ser obtido contando quantos zeros há na representação de string da lista do intervalo.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>Mas essa abordagem apesar de menor é menos geral se você quiser modifica-la para contagens mais complexas.</p>
<p>A diferença do range pro xrange é que o range constrói a lista real do intervalo real em memória e o xrange uma representação da lista do intervalo. Em geral mas não sempre, a performasse do xrange é melhor.</p>
<p>De toda forma, em ambos os casos, o resultado é o mesmo.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Easily Sortable Date and Time Representation</title>
		<link>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/</link>
		<comments>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 01:55:26 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[ISO 8601]]></category>
		<category><![CDATA[Jochen Voss]]></category>
		<category><![CDATA[Markus Kuhn]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[representation]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3130</guid>
		<description><![CDATA[I was looking for a date and time representation useful for registering stock quotes in a simple plain file. I found that the standard ISO 8601 is just the answer for this, it&#8217;s called &#8220;Data elements and interchange formats — Information interchange — Representation of dates and times&#8221;. Here is a example: 2010-01-20 22:14:38 There&#8217;s this [...]]]></description>
			<content:encoded><![CDATA[<p>I was looking for a date and time representation useful for registering stock quotes in a simple plain file.</p>
<p>I found that the standard <a title="Wikipedia on ISO 8601" href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> is just the answer for this, it&#8217;s called &#8220;Data elements and interchange formats — Information interchange — Representation of dates and times&#8221;. Here is a example:</p>
<blockquote><p>2010-01-20 22:14:38</p></blockquote>
<p>There&#8217;s this good article from <a title="A summary of the international standard date and time notation" href="http://www.cl.cam.ac.uk/~mgk25/iso-time.html">Markus Kuhn, &#8220;A summary of the international standard date and time notation&#8221;</a>. <strong>This notation allow us to using simple lexicographical order the events.</strong></p>
<p>Some examples of how to do this in Python (thanks for the <a href="http://seehuhn.de/pages/pdate">Jochen Voss article &#8220;Date and Time Representation in Python&#8221;</a>) The first for displaying the current date and time:</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">time</span> <span style="color: #ff7700;font-weight:bold;">import</span> strftime
<span style="color: #ff7700;font-weight:bold;">print</span> strftime<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%Y-%m-%d %H:%M:%S&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2010-01-20 22:34:22</span></pre>
</div>
</div>
<p>Another possibility is using strftime from datetime object.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">datetime</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">datetime</span>
now = <span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">now</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> now.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%Y-%m-%d %H:%M:%S&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2010-01-20 22:12:31</span></pre>
</div>
</div>
<p>Is that. Using this notation in the begging of each line is easy to sort them in any language or using the unix <a href="http://en.wikipedia.org/wiki/Sort_%28Unix%29">sort</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extração de Dados e Fundos de Investimento do Banco do Brasil</title>
		<link>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/</link>
		<comments>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 00:02:42 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[ações]]></category>
		<category><![CDATA[aplicações]]></category>
		<category><![CDATA[Banco do Brasil]]></category>
		<category><![CDATA[bolsa de valores]]></category>
		<category><![CDATA[CRON]]></category>
		<category><![CDATA[Data Mining]]></category>
		<category><![CDATA[fundo de investimento]]></category>
		<category><![CDATA[fundos]]></category>
		<category><![CDATA[fundos de investimento]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Mineração de Dados]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[screen scraping]]></category>
		<category><![CDATA[Web Harvest]]></category>
		<category><![CDATA[web scraping]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[yaml]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3112</guid>
		<description><![CDATA[Eu não achei onde coletar os dados diários de rentabilidade dos fundos de investimento do Banco do Brasil em formato bem estruturado. Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta: http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&#38;saida=xml E ele cuspiria um XML com as informações da rentabilidade diária desse fundo, isso se eu não [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-3118 aligncenter" title="unicornio" src="http://silveiraneto.net/wp-content/uploads/2010/01/unicornio1.jpg" alt="" width="400" height="440" /></p>
<p>Eu não achei onde coletar os dados diários de rentabilidade dos <a title="Fundos de Investimento do Banco do Brasil" href="http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01">fundos de investimento do Banco do Brasil</a> em formato bem estruturado.</p>
<p>Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta:</p>
<blockquote><p>http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&amp;saida=xml</p></blockquote>
<p>E ele cuspiria um XML com as informações da rentabilidade diária desse fundo, isso se eu não especificasse através de outro parâmetro qual a data ou intervalo de datas desejado ou outro tipo de dados para saída como YAML ou JSON. Mas por enquanto não temos isso, nem unicórnios, então temos de fazer as coisas do jeito mais difícil, que é puxando os <a title="tabela dos fundos de investimento" href="http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01">dados feitos para humanos</a> e escrevendo um programa pra extrair à força os dados que desejamos e quem sabe usar eles para algum uso relacionado a <a href="http://pt.wikipedia.org/wiki/Minera%C3%A7%C3%A3o_de_dados">mineração de dados</a>.</p>
<p style="text-align: center;"><img class="size-full wp-image-3113 aligncenter" title="bb fundos de investimento" src="http://silveiraneto.net/wp-content/uploads/2010/01/bb_fundos_de_investimento.png" alt="" width="494" height="318" /></p>
<p>A primeira abordagem que eu tentei foi a de criar <a href="http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/">um desses pequenos parsers XML que eu já mostrei como fazer antes</a>, mas o código fonte desse documento se mostrou muito incompatível com o XML que o parser estava disposto a trabalhar. A solução alternativa foi tratar o documento linha a linha.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># abrimos o documento referenciado pela url</span>
url = <span style="color: #483d8b;">'http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01'</span>
documento = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># fundo de investimento que me interessa</span>
fundo = <span style="color: #483d8b;">'small caps'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estados</span>
INICIO = 0
ACHOU_FUNDO = <span style="color: #ff4500;">1</span>
FIM = <span style="color: #ff4500;">2</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estado inicial</span>
estado = INICIO
&nbsp;
<span style="color: #808080; font-style: italic;"># vamos analisar linha a linha do fluxo do documento</span>
<span style="color: #ff7700;font-weight:bold;">for</span> linha <span style="color: #ff7700;font-weight:bold;">in</span> documento:
	<span style="color: #808080; font-style: italic;"># simplificamos, tudo pra minusculas</span>
	linha = linha.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># no inicio, procura uma linha que tenha o fundo</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado == INICIO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span>fundo<span style="color: black;">&#41;</span> <span style="color: #66cc66;">!</span>= -<span style="color: #ff4500;">1</span>:
		estado = ACHOU_FUNDO
&nbsp;
	<span style="color: #808080; font-style: italic;"># depois, procuramos o proximo inicio de tabela html.</span>
	<span style="color: #808080; font-style: italic;"># dessa linha, pegamos o que vem depois do primeiro &amp;gt;</span>
	<span style="color: #808080; font-style: italic;"># e entao o que vem antes do primeiro &amp;lt;</span>
	<span style="color: #808080; font-style: italic;"># e trocamos a virgula por ponto.</span>
	<span style="color: #ff7700;font-weight:bold;">elif</span> estado == ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&gt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">','</span>,<span style="color: #483d8b;">'.'</span><span style="color: black;">&#41;</span>
		estado = FIM</pre>
</div>
</div>
<p>E para usar:</p>
<blockquote><p>$ python rendimento_small_caps.py<br />
0.881</p></blockquote>
<p>Geralmente estamos mais interessados em saber o valor da cota daquele fundo, daí podemos calcular o rendimento total sabendo a cota que compramos a ação inicialmente. Nesse caso o dado está na 11º coluna.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># abrimos o documento referenciado pela url</span>
url = <span style="color: #483d8b;">'http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01'</span>
documento = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># fundo de investimento que me interessa</span>
fundo = <span style="color: #483d8b;">'small caps'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estados</span>
INICIO = 0
ACHOU_FUNDO = <span style="color: #ff4500;">1</span>
FIM = <span style="color: #ff4500;">2</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estado inicial</span>
estado = INICIO
coluna = 0
&nbsp;
<span style="color: #808080; font-style: italic;"># vamos analisar linha a linha do fluxo do documento</span>
<span style="color: #ff7700;font-weight:bold;">for</span> linha <span style="color: #ff7700;font-weight:bold;">in</span> documento:
	<span style="color: #808080; font-style: italic;"># simplificamos, tudo pra minusculas</span>
	linha = linha.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># no inicio, procura uma linha que tenha o fundo</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado == INICIO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span>fundo<span style="color: black;">&#41;</span> <span style="color: #66cc66;">!</span>= -<span style="color: #ff4500;">1</span>:
		estado = ACHOU_FUNDO
&nbsp;
	<span style="color: #808080; font-style: italic;"># para cada coluna, conta a coluna, mas nao faz nada</span>
	<span style="color: #ff7700;font-weight:bold;">elif</span> estado == ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span>:
		coluna += <span style="color: #ff4500;">1</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># quando chegar na coluna onze, retira o conteudo entre os sinais &amp;gt; e &amp;lt;</span>
	<span style="color: #808080; font-style: italic;"># e troca virgula por ponto, transforma em float e joga na tela</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado==ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> coluna == <span style="color: #ff4500;">11</span>:
		<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">float</span><span style="color: black;">&#40;</span>linha.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&gt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">','</span>,<span style="color: #483d8b;">'.'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		estado = FIM</pre>
</div>
</div>
<blockquote><p>$ python cota_small_caps.py<br />
6.156906634</p></blockquote>
<p>Essa é uma abordagem que eu não gosto nem recomendo porque ela é muito frágil e está extremamente acoplada a formatação de dados para humanos. Esta formatação está interessada no saída gráfica que o usuário vai obter e não em facilitar a extração (não humana) desses dados. Isso torna a solução muito frágil:</p>
<ul>
<li>Se mudarem os nomes internos dos elementos, a solução pode falhar.</li>
<li>Se mudarem a formatação da tabela, a solução pode falhar.</li>
<li>Se mudarem a disposição interna dos elementos html, a solução pode falhar.</li>
<li>Se mudarem a url do documento, a solução vai falhar.</li>
<li>Se o documento não puder mais ser tratado linha a linha, a solução vai falhar feio.</li>
</ul>
<p>É provável que quando você estiver lendo isso ela nem funcione mais do jeito que está descrita aqui.</p>
<p>Por outro lado, a solução funciona e nesse caso é o que me interessa. Quando ela quebrar, se ainda for do meu interesse eu posso rapidamente conserta-la e os dados já coletados no passado continuam válidos.</p>
<p>Isso somado  a uma programa como o Cron pode se tornar uma ferramenta realmente poderosa.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python Fast XML Parsing</title>
		<link>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/</link>
		<comments>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/#comments</comments>
		<pubDate>Fri, 25 Dec 2009 18:04:50 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[dtd]]></category>
		<category><![CDATA[expat]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sax]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[urllib]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3081</guid>
		<description><![CDATA[Here is a useful tip on Python XML decoding. I was extending xml.sax.ContentHandler class in a example to decode maps for a Pygame application when my connection went down and I noticed that the program stop working raising a exception regarded a call to urlib (a module for retrieve resources by url). I noticed that [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-3082 aligncenter" title="monty python bunny toy" src="http://silveiraneto.net/wp-content/uploads/2009/12/monty_python_bunny_toy.jpg" alt="" width="175" height="178" /></p>
<p>Here is a useful tip on Python XML decoding.</p>
<p>I was extending <a title="Python Documentation on XML SAX" href="http://docs.python.org/library/xml.sax.html">xml.sax.ContentHandler</a> class in <a title="Tiled TMX Map Loader for Pygame" href="http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/">a example to decode maps for a Pygame application</a> when my connection went down and I noticed that the program stop working raising a exception regarded a call to <a title="Python Documentation on urllib" href="http://docs.python.org/library/urllib.html">urlib</a> (a module for retrieve resources by url). I noticed that the module was getting the remote <a title="Wikipedia on Document Type Definition" href="http://en.wikipedia.org/wiki/Document_Type_Definition">DTD schema</a> to validate the XML.</p>
<div class="wp_syntax">
<div class="code">
<pre class="xml xml" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE map SYSTEM &quot;http://mapeditor.org/dtd/1.0/map.dtd&quot;&gt;</span></pre>
</div>
</div>
<p>This is not a requirement for my applications and it&#8217;s a huge performance overhead when works (almost 1 second for each map loaded) and when the applications is running in a environment without Internet it just waits for almost a minute and then fail with the remain decoding. A dirty workaround is open the XML file and get rid of the line containing the DTD reference.</p>
<p>But the correct way to programming XML decoding when we are not concerned on validate a XML schema is just the <a href="http://docs.python.org/library/pyexpat.html">xml.parsers.expat</a>. Instead of using a interface you just have to set some callback functions with the behaviors we want. This is a example from the documentation:</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">xml</span>.<span style="color: black;">parsers</span>.<span style="color: black;">expat</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># 3 handler functions</span>
<span style="color: #ff7700;font-weight:bold;">def</span> start_element<span style="color: black;">&#40;</span>name, attrs<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Start element:'</span>, name, attrs
<span style="color: #ff7700;font-weight:bold;">def</span> end_element<span style="color: black;">&#40;</span>name<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'End element:'</span>, name
<span style="color: #ff7700;font-weight:bold;">def</span> char_data<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Character data:'</span>, <span style="color: #dc143c;">repr</span><span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>
&nbsp;
p = <span style="color: #dc143c;">xml</span>.<span style="color: black;">parsers</span>.<span style="color: black;">expat</span>.<span style="color: black;">ParserCreate</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
p.<span style="color: black;">StartElementHandler</span> = start_element
p.<span style="color: black;">EndElementHandler</span> = end_element
p.<span style="color: black;">CharacterDataHandler</span> = char_data
&nbsp;
p.<span style="color: black;">Parse</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;parent id=&quot;top&quot;&gt;&lt;child1 name=&quot;paul&quot;&gt;Text goes here&lt;/child1&gt;
&lt;child2 name=&quot;fred&quot;&gt;More text&lt;/child2&gt;
&lt;/parent&gt;&quot;&quot;&quot;</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>The output:</p>
<pre>
Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
</pre>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tiled TMX Map Loader for Pygame</title>
		<link>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/</link>
		<comments>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 10:15:48 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Qt]]></category>
		<category><![CDATA[Tiled]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3063</guid>
		<description><![CDATA[I&#8217;m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It&#8217;s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles. A map done with Tiled is stored in a file [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m using the <a href="http://mapeditor.org/">Tiled Map Editor</a> for a while, I even wrote <a href="http://silveiraneto.net/2009/01/11/game-map-edition-using-tiled/">that tutorial about it</a>. It&#8217;s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with <a title="pixel art work" href="http://silveiraneto.net/tag/pixelart">my set of free pixelart tiles</a>.</p>
<p><center><a href="../wp-content/uploads/2009/01/map_editor_tiles_tileset_game-deveopment.png"><img title="map editor tiles tileset game deveopment" src="../wp-content/uploads/2009/01/map_editor_tiles_tileset_game-deveopment-500x343.png" alt="map editor tiles tileset game deveopment" width="500" height="343" /></a></center></p>
<p>A map done with Tiled is stored in a file with TMX extension. It&#8217;s just a XML file, easy to understand.</p>
<p>As I&#8217;m creating a map loader for my owns purposes, the procedure I&#8217;m doing here works we need some simplifications. I&#8217;m handling orthogonal maps only. I&#8217;m not supporting tile properties as well. I also don&#8217;t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu <em>Edit → Preferences</em> and in the <em>Saving</em> tab unmark the options &#8220;Use binary encoding&#8221; and &#8220;Compress Layer Data (gzip)&#8221;, like this:</p>
<p style="text-align: center;"><img class="size-full wp-image-3064 aligncenter" title="Tiled Preferences Window" src="http://silveiraneto.net/wp-content/uploads/2009/12/Tiled_preferences.png" alt="Tiled Preferences Window" width="370" height="309" /></p>
<p>When saving a map it will produce a TMX file like this:</p>
<div class="wp_syntax">
<div class="code">
<pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #00bbdd;">&lt;!DOCTYPE map SYSTEM &quot;http://mapeditor.org/dtd/1.0/map.dtd&quot;&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;map</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">orientation</span>=<span style="color: #ff0000;">&quot;orthogonal&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">tilewidth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">tileheight</span>=<span style="color: #ff0000;">&quot;32&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Author&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Silveira Neto&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Year&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;2009&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tileset</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;mytiles&quot;</span> <span style="color: #000066;">firstgid</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">tilewidth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">tileheight</span>=<span style="color: #ff0000;">&quot;32&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;image</span> <span style="color: #000066;">source</span>=<span style="color: #ff0000;">&quot;free_tileset_version_10.png&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tileset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;layer</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;grass&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;261&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;260&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    ...
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;160&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;0&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/layer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre>
</div>
</div>
<p>For processing it on Python I&#8217;m using the <a href="http://docs.python.org/whatsnew/2.0.html#sax2-support">event oriented SAX approach for XML</a>. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a <a href="http://www.pygame.org/docs/ref/surface.html">Pygame surface</a> with the correct size. I&#8217;m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it&#8217;s a bunch of gids in the correct order. So it&#8217;s enough information to mount and draw a map.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Author: Silveira Neto</span>
<span style="color: #808080; font-style: italic;"># License: GPLv3</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>, pygame
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
<span style="color: #ff7700;font-weight:bold;">from</span> pygame <span style="color: #ff7700;font-weight:bold;">import</span> Rect
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">xml</span> <span style="color: #ff7700;font-weight:bold;">import</span> sax
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Tileset:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">file</span>, tile_width, tile_height<span style="color: black;">&#41;</span>:
        image = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>.<span style="color: black;">convert_alpha</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> image:
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Error creating new Tileset: file %s not found&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: #008000;">file</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = tile_width
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = tile_height
        <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> line <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>image.<span style="color: black;">get_height</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>/<span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">for</span> column <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>image.<span style="color: black;">get_width</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>/<span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span><span style="color: black;">&#41;</span>:
                pos = Rect<span style="color: black;">&#40;</span>
                        column<span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>,
                        line<span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>,
                        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>,
                        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> <span style="color: black;">&#41;</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>image.<span style="color: black;">subsurface</span><span style="color: black;">&#40;</span>pos<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get_tile<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, gid<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span><span style="color: black;">&#91;</span>gid<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> TMXHandler<span style="color: black;">&#40;</span>sax.<span style="color: black;">ContentHandler</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">width</span> = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">height</span> = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">lines</span>  = 0
        <span style="color: #008000;">self</span>.<span style="color: black;">properties</span> = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">None</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span> = <span style="color: #008000;">None</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> startElement<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name, attrs<span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;"># get most general map informations and create a surface</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> name == <span style="color: #483d8b;">'map'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'width'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">lines</span>  = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'height'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'tilewidth'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'tileheight'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">width</span> = <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> <span style="color: #66cc66;">*</span> <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">height</span> = <span style="color: #008000;">self</span>.<span style="color: black;">lines</span> <span style="color: #66cc66;">*</span> <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">image</span> = pygame.<span style="color: black;">Surface</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #008000;">self</span>.<span style="color: black;">width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">height</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>.<span style="color: black;">convert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># create a tileset</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name==<span style="color: #483d8b;">&quot;image&quot;</span>:
            source = attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'source'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span> = Tileset<span style="color: black;">&#40;</span>source, <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># store additional properties.</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'property'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">properties</span><span style="color: black;">&#91;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span> = attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'value'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># starting counting</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'layer'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">line</span> = 0
            <span style="color: #008000;">self</span>.<span style="color: black;">column</span> = 0
        <span style="color: #808080; font-style: italic;"># get information of each tile and put on the surface using the tileset</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'tile'</span>:
            gid = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'gid'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> - <span style="color: #ff4500;">1</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> gid <span style="color: #66cc66;">&lt;</span>0: gid = 0
            tile = <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span>.<span style="color: black;">get_tile</span><span style="color: black;">&#40;</span>gid<span style="color: black;">&#41;</span>
            pos = <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">column</span><span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">line</span><span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">image</span>.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>tile, pos<span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #008000;">self</span>.<span style="color: black;">column</span> += <span style="color: #ff4500;">1</span>
            <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">column</span><span style="color: #66cc66;">&gt;</span>=<span style="color: #008000;">self</span>.<span style="color: black;">columns</span><span style="color: black;">&#41;</span>:
                <span style="color: #008000;">self</span>.<span style="color: black;">column</span> = 0
                <span style="color: #008000;">self</span>.<span style="color: black;">line</span> += <span style="color: #ff4500;">1</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># just for debugging</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> endDocument<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">height</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">properties</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">image</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">!</span>=<span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Usage:<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\t</span>{0} filename'</span>.<span style="color: black;">format</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">sys</span>.<span style="color: black;">exit</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>
    pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">800</span>, <span style="color: #ff4500;">480</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span> = sax.<span style="color: black;">make_parser</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    tmxhandler = TMXHandler<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span>.<span style="color: black;">setContentHandler</span><span style="color: black;">&#40;</span>tmxhandler<span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span>.<span style="color: black;">parse</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> event <span style="color: #ff7700;font-weight:bold;">in</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">if</span> event.<span style="color: #008000;">type</span> == QUIT:
                <span style="color: #ff7700;font-weight:bold;">return</span>
            <span style="color: #ff7700;font-weight:bold;">elif</span> event.<span style="color: #008000;">type</span> == KEYDOWN <span style="color: #ff7700;font-weight:bold;">and</span> event.<span style="color: black;">key</span> == K_ESCAPE:
                <span style="color: #ff7700;font-weight:bold;">return</span>
        screen.<span style="color: black;">fill</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>tmxhandler.<span style="color: black;">image</span>, <span style="color: black;">&#40;</span>0,0<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        pygame.<span style="color: black;">display</span>.<span style="color: black;">flip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1000</span>/<span style="color: #ff4500;">60</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>Here is the result for opening a four layers map file:</p>
<p><center><a href="http://silveiraneto.net/wp-content/uploads/2009/12/netbeans_python_openning_map.png"><img src="http://silveiraneto.net/wp-content/uploads/2009/12/netbeans_python_openning_map-500x375.png" alt="netbeans python openning map" title="netbeans python openning map" width="500" height="375" class="alignnone size-medium wp-image-3067" /></a> </center></p>
<p>That&#8217;s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.</p>
<p><strong>Download:</strong><a href="http://silveiraneto.net/downloads/maploader.tar.bz2"><img src="http://silveiraneto.net/wp-content/uploads/2009/12/package_32x32.png" alt="package" title="package" width="32" height="32" class="alignnone size-full wp-image-3069" />maploader.tar.bz2</a> It&#8217;s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Pygame: Running Orcs</title>
		<link>http://silveiraneto.net/2009/12/11/pygame-running-orcs/</link>
		<comments>http://silveiraneto.net/2009/12/11/pygame-running-orcs/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 10:47:27 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[orc]]></category>
		<category><![CDATA[Pixelart]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3048</guid>
		<description><![CDATA[Here is a Pygame Sprite animation using the approach presented by Joe Wreschnig and Nicolas Crovatti. It&#8217;s not yet exactly what I need but is very suitable. import pygame, random from pygame.locals import * &#160; class Char&#40;pygame.sprite.Sprite&#41;: x,y = &#40;100,0&#41; def __init__&#40;self, img, frames=1, modes=1, w=32, h=32, fps=3&#41;: pygame.sprite.Sprite.__init__&#40;self&#41; original_width, original_height = img.get_size&#40;&#41; self._w = [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a <a href="http://www.pygame.org/docs/ref/sprite.html">Pygame Sprite</a> animation using the approach presented by <a href="http://www.sacredchao.net/~piman/writing/sprite-tutorial.shtml">Joe Wreschnig</a> and <a href="http://blog.shinylittlething.com/2009/07/21/pygame-and-animated-sprites/">Nicolas Crovatti</a>. It&#8217;s not yet exactly what I need but is very suitable.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> pygame, <span style="color: #dc143c;">random</span>
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Char<span style="color: black;">&#40;</span>pygame.<span style="color: black;">sprite</span>.<span style="color: black;">Sprite</span><span style="color: black;">&#41;</span>:
	x,y = <span style="color: black;">&#40;</span><span style="color: #ff4500;">100</span>,0<span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, img, frames=<span style="color: #ff4500;">1</span>, modes=<span style="color: #ff4500;">1</span>, w=<span style="color: #ff4500;">32</span>, h=<span style="color: #ff4500;">32</span>, fps=<span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>:
		pygame.<span style="color: black;">sprite</span>.<span style="color: black;">Sprite</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
		original_width, original_height = img.<span style="color: black;">get_size</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>._w = w
		<span style="color: #008000;">self</span>._h = h
		<span style="color: #008000;">self</span>._framelist = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span>original_width/w<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
			<span style="color: #008000;">self</span>._framelist.<span style="color: black;">append</span><span style="color: black;">&#40;</span>img.<span style="color: black;">subsurface</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>i<span style="color: #66cc66;">*</span>w,0,w,h<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">self</span>._framelist<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>
		<span style="color: #008000;">self</span>._start = pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>._delay = <span style="color: #ff4500;">1000</span> / fps
		<span style="color: #008000;">self</span>._last_update = 0
		<span style="color: #008000;">self</span>._frame = 0
		<span style="color: #008000;">self</span>.<span style="color: black;">update</span><span style="color: black;">&#40;</span>pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #ff4500;">100</span>, <span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> set_pos<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, x, y<span style="color: black;">&#41;</span>:
		<span style="color: #008000;">self</span>.<span style="color: black;">x</span> = x
		<span style="color: #008000;">self</span>.<span style="color: black;">y</span> = y
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> get_pos<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
		<span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">x</span>,<span style="color: #008000;">self</span>.<span style="color: black;">y</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> update<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, t, width, height<span style="color: black;">&#41;</span>:
		<span style="color: #808080; font-style: italic;"># postion</span>
		<span style="color: #008000;">self</span>.<span style="color: black;">y</span>+=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">y</span><span style="color: #66cc66;">&gt;</span>width<span style="color: black;">&#41;</span>:
			<span style="color: #008000;">self</span>.<span style="color: black;">x</span> = <span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0,height-<span style="color: #008000;">self</span>._w<span style="color: black;">&#41;</span>
			<span style="color: #008000;">self</span>.<span style="color: black;">y</span> = -<span style="color: #008000;">self</span>._h
&nbsp;
		<span style="color: #808080; font-style: italic;"># animation</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> t - <span style="color: #008000;">self</span>._last_update <span style="color: #66cc66;">&gt;</span> <span style="color: #008000;">self</span>._delay:
			<span style="color: #008000;">self</span>._frame += <span style="color: #ff4500;">1</span>
			<span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._frame <span style="color: #66cc66;">&gt;</span>= <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._framelist<span style="color: black;">&#41;</span>:
				<span style="color: #008000;">self</span>._frame = 0
			<span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">self</span>._framelist<span style="color: black;">&#91;</span><span style="color: #008000;">self</span>._frame<span style="color: black;">&#93;</span>
			<span style="color: #008000;">self</span>._last_update = t
&nbsp;
SCREEN_W, SCREEN_H = <span style="color: black;">&#40;</span><span style="color: #ff4500;">320</span>, <span style="color: #ff4500;">320</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
	pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>SCREEN_W, SCREEN_H<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	background = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;field.png&quot;</span><span style="color: black;">&#41;</span>
	img_orc = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;orc.png&quot;</span><span style="color: black;">&#41;</span>
	orc = Char<span style="color: black;">&#40;</span>img_orc, <span style="color: #ff4500;">4</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">32</span>, <span style="color: #ff4500;">48</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">while</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">poll</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: #008000;">type</span> <span style="color: #66cc66;">!</span>= KEYDOWN:
		screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>background, <span style="color: black;">&#40;</span>0,0<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>orc.<span style="color: black;">image</span>,  orc.<span style="color: black;">get_pos</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		orc.<span style="color: black;">update</span><span style="color: black;">&#40;</span>pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, SCREEN_W, SCREEN_H<span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">display</span>.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>Here is it working:</p>
<p><center><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/J3oSUa6oiuk&#038;hl=pt_BR&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/J3oSUa6oiuk&#038;hl=pt_BR&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></center></p>
<p><ins datetime="2011-08-24T18:33:48+00:00">Uptade: I put this source and images at the <a href="https://github.com/silveira/openpixels/tree/master/examples/python/running_orcs">OpenPixel project in Github</a></ins></p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/11/pygame-running-orcs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Pygame Simple Key Handling</title>
		<link>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/</link>
		<comments>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 03:50:39 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3029</guid>
		<description><![CDATA[Here&#8217;s a simple key handle in Pygame wheres you move a circle using keyboard. import pygame from pygame.locals import * &#160; def main&#40;&#41;: x,y = &#40;100,100&#41; pygame.init&#40;&#41; screen = pygame.display.set_mode&#40;&#40;400, 400&#41;&#41; while 1: pygame.time.delay&#40;1000/60&#41; # exit handle for event in pygame.event.get&#40;&#41;: if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a simple key handle in <a href="http://www.pygame.org/">Pygame</a> wheres you move a circle using keyboard.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> pygame
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
	x,y = <span style="color: black;">&#40;</span><span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span>
	pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">400</span>, <span style="color: #ff4500;">400</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
		pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1000</span>/<span style="color: #ff4500;">60</span><span style="color: black;">&#41;</span>
      <span style="color: #808080; font-style: italic;"># exit handle</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> event <span style="color: #ff7700;font-weight:bold;">in</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
			<span style="color: #ff7700;font-weight:bold;">if</span> event.<span style="color: #008000;">type</span> == QUIT:
				<span style="color: #ff7700;font-weight:bold;">return</span>
			<span style="color: #ff7700;font-weight:bold;">elif</span> event.<span style="color: #008000;">type</span> == KEYDOWN <span style="color: #ff7700;font-weight:bold;">and</span> event.<span style="color: black;">key</span> == K_ESCAPE:
				<span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
      <span style="color: #808080; font-style: italic;"># keys handle </span>
		key=pygame.<span style="color: black;">key</span>.<span style="color: black;">get_pressed</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_LEFT<span style="color: black;">&#93;</span>:
			x-=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_RIGHT<span style="color: black;">&#93;</span>:
			x+=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_UP<span style="color: black;">&#93;</span>:
			y-=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_DOWN<span style="color: black;">&#93;</span>:
			y+=<span style="color: #ff4500;">1</span>
&nbsp;
		<span style="color: #808080; font-style: italic;"># fill background and draw a white circle</span>
		screen.<span style="color: black;">fill</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">draw</span>.<span style="color: black;">circle</span><span style="color: black;">&#40;</span>screen, <span style="color: black;">&#40;</span>0,0,0<span style="color: black;">&#41;</span>, <span style="color: black;">&#91;</span>x,y<span style="color: black;">&#93;</span>, <span style="color: #ff4500;">30</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">display</span>.<span style="color: black;">flip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>Here&#8217;s a video of it working:</p>
<p><center><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/ehIqTEvAChI&#038;hl=pt_BR&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ehIqTEvAChI&#038;hl=pt_BR&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></center></p>
<p>Function <a href="http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed">pygame.key.get_pressed</a> Returns a sequence of boolean values representing the state of every key on the keyboard. It&#8217;s very useful because usually on others game platforms I have to create it by myself.</p>
<p>This approach allow me to handle more than one key at time. For example, left and up keys can be pressed and each one is handled separately creating a diagonal movement.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pygame, Simple Space Effect</title>
		<link>http://silveiraneto.net/2009/08/12/pygame-simple-space-effect/</link>
		<comments>http://silveiraneto.net/2009/08/12/pygame-simple-space-effect/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 10:14:53 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[game development]]></category>
		<category><![CDATA[game loop]]></category>
		<category><![CDATA[list comprehension]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SDL]]></category>
		<category><![CDATA[Simple Direct Layer]]></category>
		<category><![CDATA[sliding stars]]></category>
		<category><![CDATA[Space]]></category>
		<category><![CDATA[space effect]]></category>
		<category><![CDATA[stars]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=2705</guid>
		<description><![CDATA[This is a simple space effect of sliding stars using Pygame. Direct link to video: simple_space_effect_01.ogv We set some constants like the screen size and the number N of star we want. N = 200 SCREEN_W, SCREEN_H = &#40;640, 480&#41; Using list comprehension we create a list of random points in the screen, that will [...]]]></description>
			<content:encoded><![CDATA[<p>This is a simple space effect of sliding stars using <a href="http://pygame.org">Pygame</a>.</p>
<p><center><object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/TXGV6guTOno&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/TXGV6guTOno&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"></object></center></p>
<p><small>Direct link to video: <a href="http://silveiraneto.net/downloads/simple_space_effect_01.ogv">simple_space_effect_01.ogv</a></small></p>
<p>We set some constants like the screen size and the number N of star we want.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;">N = <span style="color: #ff4500;">200</span>
SCREEN_W, SCREEN_H = <span style="color: black;">&#40;</span><span style="color: #ff4500;">640</span>, <span style="color: #ff4500;">480</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>Using <a href="http://en.wikipedia.org/wiki/List_comprehension#Python">list comprehension</a> we create a list of random points in the screen, that will be our stars. The size of this list is N.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;">stars = <span style="color: black;">&#91;</span>
  <span style="color: black;">&#91;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_W<span style="color: black;">&#41;</span>,<span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_H<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
  <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>N<span style="color: black;">&#41;</span>
<span style="color: black;">&#93;</span></pre>
</div>
</div>
<p>Each star is represented by one tuple on the stars list. The first star is on stars[0] and is a touple with [x, y] positions.</p>
<p>At each step from the <a href="http://en.wikipedia.org/wiki/Game_programming#The_game_loop">game loop</a> we draw and update the position of each star. A star is draw as a white line of one pixel. See the <a href="http://www.pygame.org/docs/ref/draw.html#pygame.draw.line">pygame.draw.line doc</a>.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">for</span> star <span style="color: #ff7700;font-weight:bold;">in</span> stars:
  pygame.<span style="color: black;">draw</span>.<span style="color: black;">line</span><span style="color: black;">&#40;</span>background,
    <span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>, star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>, star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
  star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> = star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> - <span style="color: #ff4500;">1</span>
  <span style="color: #ff7700;font-weight:bold;">if</span> star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> <span style="color: #66cc66;">&lt;</span> 0:
      star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> = SCREEN_W
      star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span> = <span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_H<span style="color: black;">&#41;</span></pre>
</div>
</div>
<p>In this example we update the position of a star by decreasing its horizontal position. When the horizontal position is less than zero, it&#8217;s not displayed on the screen anymore so we replace its horizontal position (star[0]) by the screen width (SCREEN_W) and the vertical position (star[1]) by a new random position. This will be like create a new star and guarantee always a different pattern of sliding stars. </p>
<p>The complete code:</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># A simple effect of sliding stars to create a deep space sensation.</span>
<span style="color: #808080; font-style: italic;"># by Silveira Neto &lt;me@silveiraneto.net&gt;</span>
<span style="color: #808080; font-style: italic;"># Free under the terms of GPLv3 license</span>
<span style="color: #808080; font-style: italic;"># See http://silveiraneto.net/2009/08/12/pygame-simple-space-effect/</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>,<span style="color: #dc143c;">sys</span>,<span style="color: #dc143c;">random</span>
<span style="color: #ff7700;font-weight:bold;">import</span> pygame
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Constants </span>
N = <span style="color: #ff4500;">200</span>
SCREEN_W, SCREEN_H = <span style="color: black;">&#40;</span><span style="color: #ff4500;">640</span>, <span style="color: #ff4500;">480</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
	<span style="color: #808080; font-style: italic;"># basic start</span>
	pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>SCREEN_W,SCREEN_H<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	pygame.<span style="color: black;">display</span>.<span style="color: black;">set_caption</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Simple Space Effect by Silveira Neto'</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># create background</span>
	background = pygame.<span style="color: black;">Surface</span><span style="color: black;">&#40;</span>screen.<span style="color: black;">get_size</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	background = background.<span style="color: black;">convert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># generate N stars</span>
	stars = <span style="color: black;">&#91;</span>
		<span style="color: black;">&#91;</span><span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_W<span style="color: black;">&#41;</span>,<span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_H<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span>N<span style="color: black;">&#41;</span>
	<span style="color: black;">&#93;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># main loop</span>
	clock = pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">Clock</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
		clock.<span style="color: black;">tick</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">22</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> event <span style="color: #ff7700;font-weight:bold;">in</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
			<span style="color: #ff7700;font-weight:bold;">if</span> event.<span style="color: #008000;">type</span> == QUIT:
				<span style="color: #ff7700;font-weight:bold;">return</span>
			<span style="color: #ff7700;font-weight:bold;">elif</span> event.<span style="color: #008000;">type</span> == KEYDOWN <span style="color: #ff7700;font-weight:bold;">and</span> event.<span style="color: black;">key</span> == K_ESCAPE:
				<span style="color: #ff7700;font-weight:bold;">return</span>
		background.<span style="color: black;">fill</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>0,0,0<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> star <span style="color: #ff7700;font-weight:bold;">in</span> stars:
			pygame.<span style="color: black;">draw</span>.<span style="color: black;">line</span><span style="color: black;">&#40;</span>background,
				<span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>, star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#40;</span>star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>, star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
			star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> = star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> - <span style="color: #ff4500;">1</span>
			<span style="color: #ff7700;font-weight:bold;">if</span> star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> <span style="color: #66cc66;">&lt;</span> 0:
				star<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span> = SCREEN_W
				star<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span> = <span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span>0, SCREEN_H<span style="color: black;">&#41;</span>
		screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>background, <span style="color: black;">&#40;</span>0,0<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">display</span>.<span style="color: black;">flip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/08/12/pygame-simple-space-effect/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JavaFX, Retrieving non XML/JSON data from clouds</title>
		<link>http://silveiraneto.net/2009/05/31/javafx-retrieving-non-xmljson-data-from-clouds/</link>
		<comments>http://silveiraneto.net/2009/05/31/javafx-retrieving-non-xmljson-data-from-clouds/#comments</comments>
		<pubDate>Sun, 31 May 2009 15:34:42 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[HttpRequest]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[PullParser]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[Zembly]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=2631</guid>
		<description><![CDATA[Usuually on JavaFX we grab data using HttpRequest from external resources on formats like JSON or XML. I showed how to get it on the post Reading Twitter with JavaFX and how to parse it using PullParser on the post Parsing a XML sandwich with JavaFX. Another day I need to grab and interpret some [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-2640 aligncenter" title="weather overcast icon from the Tango Project" src="http://silveiraneto.net/wp-content/uploads/2009/05/tango_weather-overcast.png" alt="tango weather overcast" width="200" height="200" /></p>
<p>Usuually on JavaFX we grab data using <a title="JAVAFX API" href="http://java.sun.com/javafx/1/docs/api/javafx.io.http/javafx.io.http.HttpRequest.html">HttpRequest</a> from external resources on formats like JSON or XML. I showed how to get it on the post <a title="Reading Twitter with JavaFX" href="http://silveiraneto.net/2009/01/04/reding-twitter-with-javafx/">Reading Twitter with JavaFX</a> and how to parse it using <a href="http://java.sun.com/javafx/1/docs/api/javafx.data.pull/javafx.data.pull.PullParser.html">PullParser</a> on the post <a title="Parsing XML sandwich with JavaFX" href="http://silveiraneto.net/2008/12/25/parsing-xml-sandwich-with-javafx/">Parsing a XML sandwich with JavaFX</a>.</p>
<p>Another day I need to grab and interpret some plain results, not in XML nor JSON, while consuming a REST service. In this case we don&#8217;t have a well structure data so the PullParser won&#8217;t help us.</p>
<p><strong>Example 1: Reading Raw Data</strong></p>
<p>In this example we&#8217;ll load a plain text file served in a remote location.</p>
<div class="wp_syntax">
<div class="code">
<pre class="java java" style="font-family:monospace;">var planetsRequest <span style="color: #339933;">=</span> HttpRequest <span style="color: #009900;">&#123;</span>
    location<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;http://silveiraneto.net/downloads/planets&quot;</span>;
    onInput<span style="color: #339933;">:</span> function<span style="color: #009900;">&#40;</span>stream<span style="color: #339933;">:</span> <span style="color: #003399;">InputStream</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        var buff <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BufferedReader</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InputStreamReader</span><span style="color: #009900;">&#40;</span>stream<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
        var line <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span>;
        <span style="color: #000000; font-weight: bold;">while</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>line <span style="color: #339933;">=</span> buff.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">!=</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            println<span style="color: #009900;">&#40;</span>line<span style="color: #009900;">&#41;</span>;
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
planetsRequest.<span style="color: #006633;">enqueue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;</pre>
</div>
</div>
<p>This will produce the output:</p>
<blockquote><p>Mercury<br />
Venus<br />
Earth<br />
Mars<br />
Jupiter<br />
Saturn<br />
Uranus<br />
Neptune</p></blockquote>
<p><strong>Example 2: </strong><strong>Discovering your IP Address</strong></p>
<p>In this example we&#8217;ll examine how to integrate a request of a remote data in a running graphical program.</p>
<p>The best way to know your real IP address is asking for a remote server to look which IP made that request. It&#8217;s like calling for a friend and asking him which number appeared in his mobile. =) This <a href="http://en.wikipedia.org/wiki/Server-side">server side</a> Python script prints the IP address of who requested the page.</p>
<div class="wp_syntax">
<div class="code">
<pre class="python python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Content-type: text/html&quot;</span>
<span style="color: #ff7700;font-weight:bold;">print</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #dc143c;">os</span>.<span style="color: black;">environ</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'REMOTE_ADDR'</span><span style="color: black;">&#93;</span></pre>
</div>
</div>
<p>In the client side, with JavaFX, we&#8217;ll load the remote value into a local variable. The <em>ip</em> is assigned with the value &#8220;&#8230;&#8221; and later the ipRequest will replace it with a String with the IP. The <em>bind</em> feature will automatically fix the GUI String text.</p>
<p>For the user he will see the ellipsis for a few seconds and so their IP.</p>
<div class="wp_syntax">
<div class="code">
<pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javafx.stage.Stage</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javafx.scene.Scene</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javafx.scene.text.Text</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javafx.io.http.HttpRequest</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.*</span>;
&nbsp;
var ip <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;...&quot;</span>;
&nbsp;
Stage <span style="color: #009900;">&#123;</span>
    title<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;What is my IP?&quot;</span> width<span style="color: #339933;">:</span> <span style="color: #cc66cc;">250</span> height<span style="color: #339933;">:</span> <span style="color: #cc66cc;">80</span>
    scene<span style="color: #339933;">:</span> Scene <span style="color: #009900;">&#123;</span>
        content<span style="color: #339933;">:</span> Text <span style="color: #009900;">&#123;</span>
            x<span style="color: #339933;">:</span> <span style="color: #cc66cc;">10</span>, y<span style="color: #339933;">:</span> <span style="color: #cc66cc;">30</span>
            content<span style="color: #339933;">:</span> bind <span style="color: #0000ff;">&quot;My IP is {ip}&quot;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
var ipRequest <span style="color: #339933;">=</span> HttpRequest <span style="color: #009900;">&#123;</span>
    location<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;http://silveiraneto.net/scripts/myip.py&quot;</span>;
    onInput<span style="color: #339933;">:</span> function<span style="color: #009900;">&#40;</span>stream<span style="color: #339933;">:</span> <span style="color: #003399;">InputStream</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        var buff <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BufferedReader</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InputStreamReader</span><span style="color: #009900;">&#40;</span>stream<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
        ip <span style="color: #339933;">=</span> buff.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
ipRequest.<span style="color: #006633;">enqueue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;</pre>
</div>
</div>
<p>You can try this <a href="http://silveiraneto.net/downloads/javafx/myip/MyIP.html">JavaFX applet here</a>.</p>
<p><strong>Example 3: </strong><strong>Reading Integer values</strong></p>
<p>Until now we handled just plain Strings. But in some cases you want to get number as non structured data. In this case you need to know previously which type the data is. In the case of a web service this probably will be described in a <a href="http://www.w3.org/TR/wsdl">WSDL file</a>.</p>
<p>Here I&#8217;m writing a very simple service script at <a href="http://zembly.com">Zembly</a>, a great platform for cloud computing. It&#8217;s called aplusb, it justs add the first parameter A to the second B.</p>
<div class="wp_syntax">
<div class="code">
<pre class="javascript javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Parameters.<span style="color: #660066;">a</span> <span style="color: #339933;">!=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp;&amp;amp; <span style="color: #009900;">&#40;</span>Parameters.<span style="color: #660066;">b</span><span style="color: #339933;">!=</span> 0<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #000066; font-weight: bold;">return</span> Parameters.<span style="color: #660066;">a</span><span style="color: #339933;">+</span>Parameters.<span style="color: #660066;">b</span>;
<span style="color: #009900;">&#125;</span></pre>
</div>
</div>
<p>The service is <a href="http://zembly.com/things/1827f696529d4e6f940c36e8e79bea1c#">published at Zembly here</a> where you can see more details on how to invoke it.</p>
<p>A simple way to invoke it on JavaFX and than getting the value as an Integer:</p>
<div class="wp_syntax">
<div class="code">
<pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.*</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javafx.io.http.HttpRequest</span>;
&nbsp;
var a <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span>;
var b <span style="color: #339933;">=</span> <span style="color: #cc66cc;">200</span>;
var result <span style="color: #339933;">=</span> 0 on replace <span style="color: #009900;">&#123;</span>
    println<span style="color: #009900;">&#40;</span>result<span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span>
&nbsp;
var zemblyRequest <span style="color: #339933;">=</span> HttpRequest <span style="color: #009900;">&#123;</span>
    location<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;http://zembly.net/things/1827f696529d4e6f940c36e8e79bea1c;exec?a={a}&amp;amp;b={b}&quot;</span>;
    onInput<span style="color: #339933;">:</span> function<span style="color: #009900;">&#40;</span>stream<span style="color: #339933;">:</span> <span style="color: #003399;">InputStream</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        var buff <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">BufferedReader</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InputStreamReader</span><span style="color: #009900;">&#40;</span>stream<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
        result <span style="color: #339933;">=</span> <span style="color: #003399;">Integer</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>buff.<span style="color: #006633;">readLine</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
zemblyRequest.<span style="color: #006633;">enqueue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;</pre>
</div>
</div>
<p>The output will be:</p>
<blockquote><p>0<br />
300</p></blockquote>
<p>The first 0 is from the first assignment on the var result. The 300 is from the webservice itself.</p>
<p>The same approach can be used to convert the ASCII/Unicode result from the stream to the suitable type on a variable.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/05/31/javafx-retrieving-non-xmljson-data-from-clouds/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

