snippsat 661 Master Poster

The same for me "InBox" and "Send Message" has not work after change to Dazah.
Both give Rate limit exceeded: Please try your request again in a few minutes..
Same on all pc.

Has to copy cookie to from working login,to other computer just to get login to work.
So not been happy with this Dazah change,have not been active here for a while to.

snippsat 661 Master Poster

To set it up more,correct and fix error.
Capitale letters in method == 'POST'
Have remove GET to avoid to confusion.

foo\
app.py
    templates\
    index.htm

app.py

from flask import Flask,redirect,url_for,request,render_template

app = Flask (__name__)
@app.route('/')
def my_form():
    return render_template("index.html")

@app.route('/suc/<name>')
def suc(name):
    return "hello Boss %s" % name

@app.route('/login', methods=['POST'])
def log():
    if request.method == 'POST':
        user = request.form['nm']
        return redirect(url_for('suc', name=user))

if __name__ == '__main__' :
    app.run(debug=True)

index.html

<html>
   <body>
      <form action = "http://localhost:5000/login" method="post">
         <p>Enter Name:</p>
         <p><input type="text" name="nm" /></p>
         <p><input type="submit" value="submit" /></p>
      </form>
   </body>
</html>
snippsat 661 Master Poster

Your pasting of xml is a mess:)
The best is to use Beautiful Soup/lxml.
E.g

from bs4 import BeautifulSoup

xml ='''\
<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Hello</to>
  <from>wold</from>
  <msg timestamp="20160817 12:46:42.520" level="INFO">Info on CPU</msg>
</note>'''

#soup = BeautifulSoup(open("your.xml"), 'html.parser') #Read from a file
soup = BeautifulSoup(xml, 'html.parser')
msg = soup.find('msg')
print(msg.text) #--> Info on CPU
print(msg.get('timestamp')) #--> 20160817 12:46:42.520

Now i use html.parser which in the standard library.
If lxml is installed,use always this parser soup = BeautifulSoup(xml, 'lxml-xml') or BeautifulSoup(xml, 'lxml')
Not that matter for you,because you have not use old BS.
New is BS you have to specify as parser as i have shown here.

Now you have posted this under Hardware and Software Cloud-based Applications
Which is not what this is about.

snippsat 661 Master Poster

Do you see any possible glues in the error messages as to what might be going on?

Not easy to say,Udemy can have a own setup that you should follow.
Udemy Should help you with this.
So i guess they have a forum or a place on there site you can get help.

snippsat 661 Master Poster

Use wheel as posted bye Gribouillis.
PyMongo has C depencies so to avoid this Installing from source on Windows
Go here,when dowloaded your version.
Do e.g pip install pymongo-3.3.0-cp35-cp35m-win32.whl
Wheel(.whl) has all C depencies packed,no need to compile.

snippsat 661 Master Poster

No are you mixing stuff up.
Do you get Flask running on our local system?
http://127.0.0.1:5000/ is your computer's loopback address(locahost).
Do stuff as simple as possible,Virtualenv is ok but this you can add later.

On a remote host like DigitalOceans you have to follow step how to setup on that host.
Flask with uWSGI and Nginx or Flask with Gunicorn and Nginx
No you are not using a locahost(127.0.0.1),you are using a host to share your stuff on the web.

You should start to learn Flask on you local system,
when or if you want to share your stuff then think of a host and deploying.

snippsat 661 Master Poster

It's part of standar library,so it should work.
Here a run in Python 3.4.

>>> from http import cookies
>>> a_cooike = cookies.SimpleCookie()
>>> a_cooike['Base'] = 'cream'
>>> print(a_cooike)
Set-Cookie: Base=cream

The default placement for python 3.5 is terrible,what are developers thinking about?
C:\Users\hohait\AppData\Local\Programs\Python\Python35-32
I know the answer and it security relatet,but i don't like it.

Follow this,the you get better placement C:\Python35-32
Make sure under installation that you mark for Path and pip.
Test pip and upgrade pip.
Here a run and use virtualenv,so you see how pip work from clean setup.

C:\test\Scripts
λ activate

(test) C:\test\Scripts
λ python -m pip install --upgrade pip
Requirement already up-to-date: pip in c:\test\lib\site-packages

(test) C:\test\Scripts
λ pip -V
pip 8.1.2 from c:\test\lib\site-packages (python 3.4)

(test) C:\test\Scripts
λ pip install requests
Collecting requests
  Downloading requests-2.11.0-py2.py3-none-any.whl (514kB)
    100% |################################| 522kB 1.0MB/s
Installing collected packages: requests
Successfully installed requests-2.11.0

(test) C:\test\Scripts
λ python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.__version__
'2.11.0'

#And also test cookies
>>> from http import cookies
>>>
snippsat 661 Master Poster

I actually like the LAMP stack and I wanted to use Python

LAMP make no sense for Python and it use CGI.
CGI is tankfully totally dead for Python.

Python use WSGI which is an all Python soltion.
All modern Python frameworks use WSGI.

I was open to trying Flask or Django but I've had such a terrible time setting them up. I might give it another try. By the way, your site looks gorgeous!

The site is just a demo from code in previos post.
Pictures are mine made in 3D Studio Max.

You can try yourself if you have difficulty berfore setting stuff up.
Here is the full setup.
You need of course Flask pip install flask

The folder setup.

image_show \
server.py
    templates\
    index.html
    static\
        images\
        <your images>

The 2 files that shall in these folders.
Find some images and put in images folder.
server.py

from flask import Flask, render_template
import os

app = Flask(__name__,static_url_path='')

@app.route('/')
def img():
    pics = os.listdir('static/images')
    return render_template('index.html', pics=pics)

if __name__ == '__main__':
  app.run(debug=True)

index.html

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background: radial-gradient(#E0D9C6, #4B3A40);
    }
    h1 {
      text-align: center;
      font-weight: bold;
      color: #663333;
      font-size:60px;
    }
    .thumbnail {
      float: left;
      width: auto;
      margin: 2% 2% 30px 7%;
      height: 600px;
    }
  </style>
</head>
  <body>
     <h1>Image viewer</h1>
     {% for pic in pics %}
       <img class='thumbnail' src="{{ url_for('static', filename='images/'+ pic) }}"></img>
     {% endfor %}
  </body>
</html>

No you can start server.py,you …

snippsat 661 Master Poster

It's in http.cookie for Python 3.x.
So import is from http import cookies

For all about HTTP use Requests

>>> import requests
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies='are good to eat')
>>> r = requests.get(url, cookies=cookies)
>>> print(r.text)
{
  "cookies": {
    "cookies": "are good to eat"
  }
}
snippsat 661 Master Poster

I like python and I wanted to give it a try at web programming but the setup and management is too difficult. I'll just go back to php.

It's not so difficult,and you do not need stuff like LAMP.
Django and Flask has build in web-server this you use for all development local.

Try Flask is as easy as it get,try hello world example on the front page.
Run the 7 lines hello.py then it's a server,and you go to http://localhost:5000/ in browser to see result.

I use Flask for all my web-development,the simplicity and power it has to build all from small to bigger web apps is great.
Just a example of an simple image viewer,
i just iterate over some of my images and use CSS to organize little.
And i delpoy to web,you can see result here Image viewer

So it's like 40 lines of code and never used LAMP or any other stuff,just the build in web-server.
I talk more deploy and this stuff in this post.

server.py

from flask import Flask, render_template, jsonify
import os

app = Flask(__name__,static_url_path='')    
@app.route('/')
def img():
    pics = os.listdir('mysite/static/images')
    return render_template('img1.html', pics=pics)

if __name__ == '__main__':
  app.run()

index.html

 <!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background: radial-gradient(#E0D9C6, #4B3A40);
    }
    h1 {
      text-align: center;
      font-weight: bold;
      color: #663333;
      font-size:60px;
    }
    .thumbnail {
      float: left;
      width: auto;
      margin: 2% 2% 30px 7%;
      height: 600px;
    }
  </style>
</head>
  <body>
     <h1>Image viewer</h1> …
snippsat 661 Master Poster

what if I need to take seperate nosetests html report for each file.. How can I do that ?

Yes as bash script looping over files will work,or a Python script with subprocess.
There are build into nose to test all files that start test.
So naming your files test_a.py test_b.py... will work.

But this give you on report at end,
there are soultion like tappy

I use pytest,not tested but this should work,
py.test --files --html=report.html test all file in a folder,
and each files get own report.

snippsat 661 Master Poster

Command you has to be string and you concatenate "line" inside os.system().
So if i have i list of words and want to now lenght of each word,
i can use linux command expr length.
The command get executed on each line of words.txt.

import os
import time

f = open('words.txt')
for line in f:
    line = line.strip()
    time.sleep(5)
    os.system('expr length ' + line)
f.close()    
snippsat 661 Master Poster

The problem can be solved before give data to Pandas.
As mention over there are lot of cases to think about.
I would have made up rules with regex.
Example.

 >>> import re

>>> s = "Richard Wayne Van Dyke"
>>> re.split(r"\s*(?:(?:[a-zA-Z]')|(Van \w.*))", s, re.I)[:-1]
['Richard Wayne', 'Van Dyke']
>>> s = 'Wayne Van Dyke'
>>> re.split(r"\s*(?:(?:[a-zA-Z]')|(Van \w.*))", s, re.I)[:-1]
['Wayne', 'Van Dyke']
>>> s = 'Edda Kathleen Van Heemstra Hepburn-Ruston'
>>> re.split(r"\s*(?:(?:[a-zA-Z]')|(Van \w.*))", s, re.I)[:-1]
['Edda Kathleen', 'Van Heemstra Hepburn-Ruston']

>>> s = "Gary Del Barco"
>>> re.split(r"\s*(?:(?:[a-zA-Z]')|(Del \w.*))", s, re.I)[:-1]
['Gary', 'Del Barco']

>>> s = 'Dave Allen Smith'
>>> re.split(r"\s*(?:(?:[a-zA-Z]')|(Del \w.*))", s, re.I)[:-1]
[]

So key word like Van and Del,in this regex will take key word and all word after as last name.
If need more rule than this,you have to make own make rule for problem names.
If pass in name that's not in regex,a empy list is returned.

mattrweaver commented: Thanks for the responses. I will be working with a limited set of data periodically, so I can easily write new rules for problem names. +0
snippsat 661 Master Poster

Is that what gets returned if the letter is not in the dictionary? So if it can't find the letter it adds 0?

Yes,and you can also return a more meaningful message.
Here in function and return value out.

def record(word):
    return {
        "t": 1, "f": 1, "c": 1,
        "b": 2, "h": 2, "y": 2,
        "q": 3, "w": 3, "z": 3
    }.get(word, "Not in record")

if __name__ == '__main__':
    word = input("Please enter a word: ")
    print(record(word))
snippsat 661 Master Poster

Beautiful Soup is for python . i am using windows and vb.net

You should find a parser for vb.net,like Html Agility Pack

i have been doing some research.
and found out about Regular expressions.....

Regex i bad tool for html,read this funny answer bye bobince .

gives me pratice coding.......

Yes and lot frustration if you gonne to this every time you want to parse stuff.
Beautiful Soup was mention so i can use some minutes and make a demo.

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
h1_tag = soup.find('h1')
table_tag = soup.find_all('table')
span_tag = soup.find_all('span', style=True)
span_tag = span_tag[0].find_all('div')

print(h1_tag.text)
for item in table_tag:
    print(item.text)
for item in span_tag:
    r = str(item).replace('<br/>', '\n')
    print(r.replace('<div>', '').replace('</div>', '').strip())

Output:

Friday 31 - 1 - 2014

Created:31/01/2014 2:32 PM
Updated:31/01/2014 7:03 PM
Location:37°35'13 S  145°7'41 E

Shift 143
Car 7008
Bus 280
564 / 9
Car 7008
Car 7011
Bus 361
572 / 20
snippsat 661 Master Poster

I just started to learn python few days ago. This is a small program I made to practise.

Ok,some points.

names = ['(1) Sphere','(2) Right Circular Cone','(3) Cylinder']
x=0
while x < 3:
    print(names[x])
    x +=1

This is not the way to loop in Python.
You just iterate over list like this.

names = ['(1) Sphere','(2) Right Circular Cone','(3) Cylinder']
for name in names:
    print(name)

Now all code is global space,in future think of stucture code better.
Eg using functions.

import math

def cylinder():
    '''Calculate volume of a cylinder'''
    R = int(input('\n'+"Enter value for r : "))
    H = int(input("Enter value for h : "))
    result = math.pi * (R*R) * H
    return result

Test.

>>> cylinder()
Enter value for r : 5
Enter value for h : 10
785.3981633974483

>>> help(cylinder)
Help on function cylinder in module __main__:

cylinder()
    Calculate volume of a cylinder

So you could had have 3 functions,this mean that code is isolatet in function.
As you see it help readability of code,and code reuse(you can now put this function in other code and call it).

snippsat 661 Master Poster

I've seen the Full stack python, it also gives you many options to choose & but not how do I choose them

Yes it can be confusing,Nginx + Gunicorn,Tornado,uWSGI?
Here is little info about Heroku and PythonAnywhere.

@Heroku
Do Python applications run behind Nginx?
So on Heroku you do not use Nginx,you just have to setup a server like Gunicorn.
You see how in Getting Started with Python on Heroku

PythonAnywhere is very easy,and do like all deploy stuff for you.
You use UI and upload files and do a coulpe of config choices.
Then you have website,and PythonAnywhere run that site with,
Nginx to do routing and uWSGI to run the apps.

snippsat 661 Master Poster

In the first question, ctually asking which directory on linux should I choose to place a project? Like /home/user/ or /var/www etc?

Where I should put my python scripts in Linux?.

In the 3rd question, you said you'd use something like Gunicorn,Tornado,uWSGI or Apache. The question how do you decide between so many options. When do you want to use Gunicorn & when do you prefer mod_wsgi on Apache like that?

I like Gunicorn easy to setup,and default options works good for most cases.
I you search eg: Gunicorn vs uWSGI you get a lot of opinions.

Look at Full Stack Python,there is a lot of info on deploy and run a Python web application.
For smaller personal projects you don't have to think to much about the deploy side.
For bigger commercial sites there is a lot of tought/work on the deploy side.

Gribouillis commented: awesome +0
snippsat 661 Master Poster

Where should I host a python project on linux? I'm sure there'd be multiple choices. So, Where would you host it & on what circumstances?

Github,Bitbucket...
If you mean web-host,pythonanywhere,Heroku,Webfaction,Digital ocean...

I understand that virtualenv creates a virtual environment separate from others. But, why should one need it? Do we use it in production too, if so, why?

You pip install stuff into virtualenv,
so you always get newest versions of modules/package.
It's isolatet,so it don't mess with your OS version of Python.
As you see in this Getting Started tutorial is normal to use virtualenv when using a web-host.

If I want to create a web application using python? What server should I choose & on what basis should I choose them for a given project.

Flask and Django has build in webserver,
this is good for working/testing local and building a web application.

When finish and want to deploy to web,
then think of(shall i use Gunicorn,Tornado,uWSGI or running mod_wsgi (Apache)?
Host like Pythonanywhere,Heroku make it easier to deploy Python code.

Gribouillis commented: great answer +14
snippsat 661 Master Poster

I am trying to convert a file to a dictionary here is the contents of the file,

You can data keep structure bye using serialization,
then you don't have to struggle to recreate structure from a string.
JSON is preferably over Pickle.

import json

record = {
'Name': 'DragonMastur',
'Hand': None,
'Inventory': {"Gold": 0, "Brush": 0, "Twig": 0, "Sapling": 0,
    "Metal Axe": 0, "Grass": 0, "Metal Pickaxe": 0, "Metal": 0,
    "Log": 0, "Diamond": 0, "Stick": 0, "Stone": 0, "Wheat": 0,
    "Stone Axe": 0, "Stone Pickaxe": 0},
'Health': 100
    }

with open("my_file.json", "w") as f_out:
    json.dump(record, f_out)
with open("my_file.json") as f_obj:
    saved_record = json.load(f_obj)

Test that saved_record still works as a dictionary.

>>> type(saved_record)
<class 'dict'>
>>> saved_record['Name']
'DragonMastur'
>>> saved_record['Inventory']
{'Brush': 0,
 'Diamond': 0,
 'Gold': 0,
 'Grass': 0,
 'Log': 0,
 'Metal': 0,
 'Metal Axe': 0,
 'Metal Pickaxe': 0,
 'Sapling': 0,
 'Stick': 0,
 'Stone': 0,
 'Stone Axe': 0,
 'Stone Pickaxe': 0,
 'Twig': 0,
 'Wheat': 0}
>>> saved_record['Inventory']['Gold']
0
snippsat 661 Master Poster

Maybe the sticky posts have, or could have a tag of their own.

Or just making a category like e.g Staring Python, Starting C++.
Then put sticky thread like in this picture in there.
The "Product Reviews" that i mark over has just 1 post,and could be changed.

snippsat 661 Master Poster

A must read

Or a better read
You should really look into and use Requests Shailang.

rproffitt commented: Nice. Something I didn't know, thanks. +5
snippsat 661 Master Poster

I have to say that i don't like this tagging system at all.
Maybe it's get better when i get used to it,but i am not sure.

In Python part of the old forum we had sticky thread,
do we really need to search for those threads now?
Or can post be sticky again?
Here is a picture.

snippsat 661 Master Poster

really don't even know which webpage language I should use HTML, PHP, SQL something else?.

You can of course use Python.
Micro-framework like Flask can be a good place to start.
Python has bigger Framework like Django, web2py or CMS like Django-cms.
These has a lot of tools,and can be a overwhelming when you shall learn basic web stuff.

Your question show that this is all new.
For web-development HTML,CSS,JavaScript(jQuery) is something that's has to be studied in some degree.
E.g you run Flask as server and Write HTML and CSS to show stuff in a webpage.

I'm assuming I can simply pipe the python code to an file of some sort, but is there a better approach to getting started for this type of application?

First you can test local and try to upload file to Flask server.
If you want this to be a webpage that is running public on internet,
you need a host like Pythonanywhere, Heroku.

snippsat 661 Master Poster

If you search for cola you see this url.
https://datacvr.virk.dk/data/visninger?soeg=cola&type=Alle
Generate own search url's.

>>> url = 'https://datacvr.virk.dk/data/visninger?soeg={}&type=Alle'
>>> search_lst = ['car', 'train']
>>> for item in search_lst:
...     print(url.format(item))
...     
https://datacvr.virk.dk/data/visninger?soeg=car&type=Alle
https://datacvr.virk.dk/data/visninger?soeg=train&type=Alle

E.g of take out some data,here all title text when search for cola.

import requests
from bs4 import BeautifulSoup

url = 'https://datacvr.virk.dk/data/visninger?soeg=cola&type=Alle'
page = requests.get(url)
soup = BeautifulSoup(page.content)
tile_tag = soup.find_all('h2', {'class': 'name'})
for name in tile_tag:
    print(name.text.strip())

"""Output-->
COCA-COLA NORDIC SERVICES ApS
Cola klubben
Coca-Cola Service S.A.
The Coca-Cola Company
CARLSBERG DANMARK A/S
Abby Thai Kropsmassage v/Ornanong Johansen
Karim Rahima
Coca-Cola Service S.A.
CARLSBERG DANMARK A/S Coca -Cola Tapperierne
COCA-COLA NORDIC SERVICES ApS
"""
Slavi commented: Thank you +6
snippsat 661 Master Poster
from bs4 import BeautifulSoup
import urllib2

html = '''
<img src="smiley.gif" alt="Smiley face" height="42" width="42">'''

soup = BeautifulSoup(html)
images = soup.find('img')
print(images['src']) #smiley.gif
snippsat 661 Master Poster

It work's for me when i do a little test,using Pyhon 3.4.2.

mytxt1.txt:

http://ascii.cl?parameter=%22Click+on+%27URL+Decode%27%21%22
login=bob%40%3CSCRipt%3Ealert%28Paros%29%3C%2FscrIPT%3E.parosproxy.org
http://ascii.cl?parameter=%22Click+on+%27URL+Decode%27%21%22
login=bob%40%3CSCRipt%3Ealert%28Paros%29%3C%2FscrIPT%3E.parosproxy.org

outtxt1.txt:

http://ascii.cl?parameter="Click+on+'URL+Decode'!"
login=bob@<SCRipt>alert(Paros)</scrIPT>.parosproxy.org
http://ascii.cl?parameter="Click+on+'URL+Decode'!"
login=bob@<SCRipt>alert(Paros)</scrIPT>.parosproxy.org
snippsat 661 Master Poster

Also, strings in Python 3 are unicode so enocde and decode are not necessary.

That's only true if text is already inside Python 3.
Here we are talking about taking text from outside into Python 3,
then we must define a encoding like utf-8,latin-1...,
or it will give an error or become a byte string.

Because we must read with correct encoding when taking text into Python 3,
with open() has new stuff like errors='ignore', errors='replace'

with open('some_file', 'r', encoding='utf-8', errors='ignore') as f:
    print(f.read())

So this statement.
In Python 3 are all strings are sequences of Unicode character
Yes this is true,
but then all text taken in from outside must have been correct encoded into Python 3.

snippsat 661 Master Poster

Python do have build in libraries that can generate key which hold cryptographic strength.
Her use SHA-256

>>> import hashlib
>>> hashlib.sha256(b"licence key").hexdigest()
'ad26f374a671d9add68a110b31769667691a54ed599e791b5c8eb065b16c9ddc'

Will also metion cryptography which is the future for cryptographic in Python.

snippsat 661 Master Poster

The most Pythonic [::-1]
There is also reversed used with join().

Python34 handels Unicode good if you get Persian language correct decoded into Python34.
In Python34 are all strings a sequences of Unicode characters.
Just so you know,there is a big difference between Unicode handling Python 2 and 3.

>>> s = 'ԈԇՄՋֆ'
>>> s
'ԈԇՄՋֆ'
>>> print(s)
ԈԇՄՋֆ
>>> s[::-1]
'ֆՋՄԇԈ'
>>> print(s[::-1])
ֆՋՄԇԈ
>>> print(''.join(reversed(s)))
ֆՋՄԇԈ

Hmm look like Persian character has a problem here.

ԈԇՄՋֆ

snippsat 661 Master Poster

Here is a hint.

>>> user_input = 'The quick brown fox jumps over a lazy dog'
>>> word_lst = user_input.split()
>>> word_lst
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'a', 'lazy', 'dog']
>>> len(word_lst)
9
>>> [len(c) for c in word_lst]
[3, 5, 5, 3, 5, 4, 1, 4, 3]
sum([len(c) for c in word_lst])
33

If you wonder about [len(c) for c in word_lst],so is this called list comprehensions.
list comprehensions is used very much in Python.
To write it in a ordinary loop, it looks like this.

>>> char_count = []
>>> for c in word_lst:
...     char_count.append(len(c))
...     
>>> char_count
[3, 5, 5, 3, 5, 4, 1, 4, 3]
snippsat 661 Master Poster

snippsat I understand the inputting it into a gui or >>> but I need it to take any user input and not just set filename. Unless I set filename to equal a list of file extensions.

from os.path import splitext

def parse_extension(filename): 
    if filename == splitext(filename)[-1]:
        print 'Please Enter a FileName: ' #Think of what you are doing here
    elif filename != splitext(filename)[-1]:
        print splitext(filename)[-1]

filename = raw_input('Please Enter a File Name: ')
parse_extension(filename)

I dont understand how the import os feature works

os is part of Python standard library,just import os and use it.
Doc Miscellaneous operating system interfaces
Tutorial OS Module

snippsat 661 Master Poster

wudie47 read your post,just 1 day old,
vegaseat did answer with the preferred way os.path.splitext().

>>> import os
>>> filename = 'python.exe'
>>> os.path.splitext(filename)
('python', '.exe')
>>> os.path.splitext(filename)[-1]
'.exe'
>>> name, extension = os.path.splitext(filename)
>>> name
'python'
>>> extension
'.exe'
snippsat 661 Master Poster

Need to see code to,and not just Traceback.
Do print(ser) and print(type(ser)),then i think you see that's ser is an integer and not a fileobject.
To create same Traceback.

>>> ser = 5
>>> ser.readline()
(most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'int' object has no attribute 'readline'
>>> print(type(ser))
<class 'int'>

UnicodeEncodeError: 'ascii' codec can't

This can be an decode/encode problem,maybe need to include utf-8.
Are you using Python 2 or 3 on raspberryPi?

snippsat 661 Master Poster

There is also a markdown2 module.

import markdown2

markdown = """\
# Hello, how are you
I'm fine, thank you

I know that it is not so **hard**
but for me it's not so *easy*

What is ##this?

How about `*this*`?

**it *wor`k`s!***

Let me put a bold link: [**stuff**](http://41.media.tumblr.com/49a58542fd70b8ca39b5bd0d9c9c53aa/tumblr_nob40mvTN41tb9nzio1_500.jpg)
## Okay, part two

But there's no part two!

###### So long!"""

print(markdown2.markdown(markdown))

"""Output-->
<h1>Hello, how are you</h1>

<p>I'm fine, thank you</p>

<p>I know that it is not so <strong>hard</strong>
but for me it's not so <em>easy</em></p>

<p>What is ##this?</p>

<p>How about <code>*this*</code>?</p>

<p><strong>it <em>wor<code>k</code>s!</em></strong></p>

<p>Let me put a bold link: <a href="http://41.media.tumblr.com/49a58542fd70b8ca39b5bd0d9c9c53aa/tumblr_nob40mvTN41tb9nzio1_500.jpg"><strong>stuff</strong></a></p>

<h2>Okay, part two</h2>

<p>But there's no part two!</p>

<h6>So long!</h6>
"""
snippsat 661 Master Poster

A good technique to understand code is to break it up in smaller parts.
For this is interactive interpreter great to us,
also us print() in code on places you wonder what's happends.
So lets say you wonder about deque(maxlen=history).

>>> from collections import deque
>>> lst = [1, 2, 3, 4, 5, 6, 7]
>>> d = deque(maxlen=3)
>>> for item in lst:
...     d.append(item)
...     print(d)
...     
deque([1], maxlen=3)
deque([1, 2], maxlen=3)
deque([1, 2, 3], maxlen=3)
deque([2, 3, 4], maxlen=3)
deque([3, 4, 5], maxlen=3)
deque([4, 5, 6], maxlen=3)
deque([5, 6, 7], maxlen=3)

So here it easy to see that it fill up a list,
up to 3 elements max and then it start to throw out the first vaules in.

snippsat 661 Master Poster

lxml need to be compiled,and for Python3.4 you most have Visual Studio C++ 2010(Windows).
But there is an easier way,go to Gohlke pre-compiled wheel.
Download lxml‑3.4.4‑cp34‑none‑win32.whl place it in C:\python34\Scripts folder.
Start cmd navigate to C:\python34\Scripts folder.
Then do pip install lxml‑3.4.4‑cp34‑none‑win32.whl.
As info so is pip pre-install(Scripts folder) on Python3.4.

Microsoft Windows [Versjon 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Med enerett.

C:\Users\Tom>cd\

C:\>cd python34\scripts

C:\Python34\Scripts>pip install lxml-3.4.4-cp34-none-win32.whl
Unpacking c:\python34\scripts\lxml-3.4.4-cp34-none-win32.whl
Installing collected packages: lxml
Successfully installed lxml
Cleaning up...

C:\Python34\Scripts>
snippsat 661 Master Poster

OK,... I know that my hired programmer does his development with Linux and/or Macos.
And apparently... those Parentheses are NOT need there, but they ARE needed in Windows?
Is that it?

He use Python 2,where print is a statement.
You use Python 3,where print is function(need Parentheses)
Dive into Python 3,difference 2 and 3.
key differences between Python 2 and 3

snippsat 661 Master Poster

I, and many others, desired a "switch" keyword in Python.

Do not speak for "others".
The swith/Case statement was finally rejected in 2006 PEP 3103

For me it was to a desire to make some of my code more compact and readable

The desired goal of readability don't show i your code(read PEP-8),
and the use of exec(),globals(),locals() doesn't make it better.

If need something more fancy than if/elif/else for this,
a dictionary is normal to use.

#Testet work in Python 2 and 3
from __future__ import print_function
try:
    input = raw_input
except NameError:
    pass

def red():
    return 'The apple is red'

def green():
    return 'The forest is green'

def blue():
    return 'The ocean is blue'

def switch_case(case):
    return {
    'red'   : red(),
    'green' : green(),
    'blue'  : blue()
    }.get(case, "Wrong input,need a RGB color")

if __name__ == '__main__':
    color = input("Enter a color: ").lower()
    print(switch_case(color))
snippsat 661 Master Poster

I installed Python v 3.4.3

pip comes pre-installed on Python 3.4.3,do not install pip.
First set up environment Variables Path,
Same as in video,but also point to script folder(pip placement),so for Python 3.4 you add ;C:\python34\;C:\python34\scripts to Path.

What "terminal" am I using, and what's with the "$" symbol? I dunno'.
I tried various lines in a CMD window, but nothing worked.

The "$" is for Linux,you use cmd.
Try again in cmd now that you have set environment Variables.
pip install requests

lxml-3.4.4.win32-py3.2.exe
I then started it, and it said...
"Python version 3.2 required, which was not found in the registry."

For lxml go to Gohlke
Download lxml‑3.4.4‑cp33‑none‑win32.whl to e.g python34/scripts folder.
Navigate in cmd to scripts folder,then do pip install lxml‑3.4.4‑cp33‑none‑win32.whl
Test that it work.

>>> from lxml import etree
>>> etree.__version__
u'3.3.0'
snippsat 661 Master Poster

It's a little old way of doing this,but it work if fixing as Girb posted.
You should not make a seperate line for count.
Do it like this.

my_dict = {}
s = 'hello world hello'
for word in s.split():
    if word in my_dict:
        my_dict[word] += 1
    else:
        my_dict[word] = 1

print(my_dict) #{'world': 1, 'hello': 2}

The next step in improving this,can be to use get() method.

my_dict = {}
s = 'hello world hello'
for word in s.split():
    my_dict[word] = my_dict.get(word, 0) + 1

print(my_dict) #{'world': 1, 'hello': 2}

Your code with full Python power,here i use colletions.Counter.
And regex to remove punctuation.
You should also look at PEP-8,e.g not use capitale letter in variable name.

from collections import Counter
import re    

with open('count_test.txt') as f:
    text = f.read().lower()
words = re.findall(r'\w+', text)

print(Counter(words))
print(Counter(words).most_common(2))
Slavi commented: love the get() +6
snippsat 661 Master Poster

Good effort,i give you a up vote:)
But have to mention your code style again,it's not so pretty.
I link to PEP-8 in your post,
just to show a doc that can help you in the future regarding code style.

Here a version i made,
Look a little at how code is formatet,
and names i use in code(No capitale letters,because that is used in class name).

#Testet work in Python 2 and 3
from __future__ import print_function
from random import randint
#Fix so input() work 2 and 3
try:
    input = raw_input
except NameError:
    pass

def random_hex_colors():
    return "#{:06x}".format(randint(0,0xFFFFFF)).upper()

def gen_html_tag(random_hex_colors, number_of_tags, width, filler_text):
    return \
    '\n'.join('<tr><td>{0}</td><td style ='
     '"background-color: {0};width:{1}px">{2}</td></tr>'
    .format(random_hex_colors(), html_width, text_filler)
    for i in range(number_of_tags))

def write_html(tag_gen, file_name):
    with open('{}.html'.format(file_name), 'w') as f_obj:
        f_obj.write('''\
<!DOCTYPE html>
<head>
<title>Random Color Chart</title>
</head>
<table border = "1">
<tr><th>Color Name</th><th>Color</th></tr>
{}
</table>'''.format(tag_gen))

if __name__ == '__main__':
    #Test without user input
    number_of_tags = 3
    html_width = 300
    text_filler = 'test'
    file_name = 'color_test'        
    #Call functions
    tag_gen = gen_html_tag(random_hex_colors,
    number_of_tags, html_width, text_filler)
    write_html(tag_gen, file_name)
snippsat 661 Master Poster

Done a little more testing.
Here from wheel doc

Many packages will be properly installed with only the “Unpack” step (simply extracting the file onto sys.path), and the unpacked archive preserves enough information to “Spread” (copy data and scripts to their final locations) at any later time.

Here test with lxml,i use virtualenv so i am sure OS is not affected.

from zipfile import ZipFile

#This get extractet to sys.path
with ZipFile('lxml-3.4.2-cp34-none-win32') as myzip:
    myzip.extractall()

Test:

(test) C:\Documents and Settings\Tom\Envs\test\Scripts
λ python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
>>> from lxml.html import parse,etree
>>> etree.__version__
u'3.4.4'

So with lxml it works fine.

The same with PyQt4 wheel dos not work,i got it almost to work.
I moved folder PyQt4 in purelib folder to sys.path.
Now get "ImportError: No module named sip" should be possible to fix.

snippsat 661 Master Poster

no, I've built an exe using GameMaker8 (has an icon and loading banner) which >boots Portable Python with python.exe loader.py

As usually i think you are doing some strange stuff:)
So you are talking about Portable Python 2.7.6.1
Which has PyQt4 installed,so why do you need to install PyQt4?
Maybe you should explain better,for i think not many will follow this stuff.

EDIT:
btw, the latest Portable Python is 2.7.6.1
would be nice if there was a more up-to-date build

oh it looks like I have installed 2.7.9... oops
lol

normally I install the non-portable python to match the portable python. :P

I have used portable python for many years on different computers,
Portable python closed environment,so i dont know why you want it to match the ordinary Python installation?
I would not use portable python to share code i have made,this it not what's it made for.

so ultimately (now that I know it's not using the wheel on linux, but a >locally installed pyqt4) it looks like this wheel is broken.

this question will be marked solved when I have a working portable >installation.
(I will note this if I find it myself)

I downloaded the current wheel from here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/

No it's not broken,i have tested that PyQt4 wheel in Virtualenv.
I have used a lot wheel(before all was exe)from Gohlke and stuff has …

snippsat 661 Master Poster

I got the wheel so I wouldn't have to install

Wheel has to installed,also same with older format egg.

(you don't need to install python to run my (not compiled) programs)

You are looking for module/package that can create standalone executables from Python scripts.
Py2exe, cx_Freeze(cross platform), Pynsist, Nuitka

I use Py2exe for my wx_nrk prosject,
has ca 2000 Windows users and ca 300-400 Linux users,
and Windows users do not have to install Python or wxPython,just click on a exe to get it to work.

so what exactly is the issue, and why do I need PyQt4 installed in this >program's directory?

It's not installing into script folder,it's installing like any other module/package you install in Python(into site-packages folder)
The wheel file from scripts folder can be deleted after installing.

I just said you should place it in scripts folder because pip is there in Python 2.7.9.
If you have set up environment variables Path to point to Python27 and Python27/Scripts folder.
Then you do pip install wheel from whatever place you choose.

snippsat 661 Master Poster

You have to install wheel with pip.
On Python 2.7.9 is pip pre-installed.
Put PyQt4-4.11.3-cp27-none-win32.whl in C:\Python27\scripts folder.
Start cmd navigate to C:\Python27\scripts folder,
then do: pip install PyQt4-4.11.3-cp27-none-win32.whl

snippsat 661 Master Poster

Also here:)

snippsat 661 Master Poster

Or a more modern click here :)

snippsat 661 Master Poster

You have been told before to before to watch your coding style.
Stop using global.

There is a also build module that solve this in Python 3.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

Test all computation are instantly.

>>> fib(100)
354224848179261915075
>>> fib(500)    139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125
>>> fib(700)    87470814955752846203978413017571327342367240967697381074230432592527501911290377655628227150878427331693193369109193672330777527943718169105124275

Maybe post it as question first before making a Code snippets,
to get advice about style and other way to solve it.

The author of lru_cache Raymond Hettinger,
had a whole talk about PEP-8 in this year PyCon.
Raymond Hettinger - Beyond PEP 8 -- Best practices for beautiful intelligible code -

Gribouillis commented: great +14
snippsat 661 Master Poster

You use subprocess module.

import subprocess

calc_program = "path_to_program"
subprocess.call([clac_program])