Django-page-cms gets official inline page editing support
http://django-page-cms.readthedocs.io/en/latest/edit-content.html
/r/django
https://redd.it/5jl3ej
http://django-page-cms.readthedocs.io/en/latest/edit-content.html
/r/django
https://redd.it/5jl3ej
Cracking The BBC'S GCHQ Puzzlebook Challenge With Python
https://stiobhart.net/2016-12-03-gchqpuzzlebook/
/r/Python
https://redd.it/5k2ox3
https://stiobhart.net/2016-12-03-gchqpuzzlebook/
/r/Python
https://redd.it/5k2ox3
stiobhart.net
Cracking the BBC's GCHQ Puzzlebook Challenge With Python
image credit: BBC NOTE: There’s now a follow-up to this post, wherein I recreate this bumbling incompetency in Go /Golang
TOC The Challenge 1st Attempt: Pencil and Paper Enter Python Python: Failed Attempt 01 Python: Failed Attempt 02 Python: Success!…
TOC The Challenge 1st Attempt: Pencil and Paper Enter Python Python: Failed Attempt 01 Python: Failed Attempt 02 Python: Success!…
[AF] Flask Admin not displaying Foreign Key column
I'm building a blog with Flask. I use Flask-Admin for setting up an administrative interface. Everything is fine, but I cannot see the "tags" field in the Post form. This is defined as a relationship/FK in my Post model.
Please see below my model file and admin configuration. Appreciate any idea.
Thanks!
##### MODELS.PY
tags = db.Table('post_tag',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, default=datetime.utcnow)
title = db.Column(db.String(140))
slug = db.Column(db.String(200))
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
_tags = db.relationship('Tag', secondary=tags,
backref=db.backref('posts', lazy='dynamic'))
@observes('title')
def compute_slug(self, title):
self.slug = re.sub('[^\w]+', '-', title.lower())
@staticmethod
def newest(num):
return Post.query.order_by(desc(Post.date)).limit(num)
@property
def tags(self):
return ",".join([t.name for t in self._tags])
@tags.setter
def tags(self, string):
if string:
self._tags = [Tag.get_or_create(name) for name in string.split(',')]
def __repr__(self):
return "<Post '{}': '{}'>".format(self.title,self.date)
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(25), nullable=False, unique=True, index=True)
@staticmethod
def get_or_create(name):
try:
return Tag.query.filter_by(name=name).one()
except:
return Tag(name=name)
@staticmethod
def all():
return Tag.query.all()
def __str__(self):
return self.name
def __repr__(self):
return self.name
##ADMIN.PY
admin = Admin(app, name='Admin', template_mode='bootstrap3')
class CKTextAreaWidget(TextArea):
def __call__(self, field, **kwargs):
if kwargs.get('class'):
kwargs['class'] += ' ckeditor'
else:
kwargs.setdefault('class', 'ckeditor')
return super(CKTextAreaWidget, self).__call__(field, **kwargs)
class CKTextAreaField(TextAreaField):
widget = CKTextAreaWidget()
class PostAdmin(sqla.ModelView):
form_overrides = dict(content=CKTextAreaField)
create_template = 'blog/ckeditor.html'
edit_template = 'blog/ckeditor.html'
form_excluded_columns = ('slug')
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(PostAdmin(Post, db.session))
class TagAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(TagAdmin(Tag, db.session))
class UserAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(UserAdmin(User, db.session))
/r/flask
https://redd.it/5dbvbi
I'm building a blog with Flask. I use Flask-Admin for setting up an administrative interface. Everything is fine, but I cannot see the "tags" field in the Post form. This is defined as a relationship/FK in my Post model.
Please see below my model file and admin configuration. Appreciate any idea.
Thanks!
##### MODELS.PY
tags = db.Table('post_tag',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, default=datetime.utcnow)
title = db.Column(db.String(140))
slug = db.Column(db.String(200))
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
_tags = db.relationship('Tag', secondary=tags,
backref=db.backref('posts', lazy='dynamic'))
@observes('title')
def compute_slug(self, title):
self.slug = re.sub('[^\w]+', '-', title.lower())
@staticmethod
def newest(num):
return Post.query.order_by(desc(Post.date)).limit(num)
@property
def tags(self):
return ",".join([t.name for t in self._tags])
@tags.setter
def tags(self, string):
if string:
self._tags = [Tag.get_or_create(name) for name in string.split(',')]
def __repr__(self):
return "<Post '{}': '{}'>".format(self.title,self.date)
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(25), nullable=False, unique=True, index=True)
@staticmethod
def get_or_create(name):
try:
return Tag.query.filter_by(name=name).one()
except:
return Tag(name=name)
@staticmethod
def all():
return Tag.query.all()
def __str__(self):
return self.name
def __repr__(self):
return self.name
##ADMIN.PY
admin = Admin(app, name='Admin', template_mode='bootstrap3')
class CKTextAreaWidget(TextArea):
def __call__(self, field, **kwargs):
if kwargs.get('class'):
kwargs['class'] += ' ckeditor'
else:
kwargs.setdefault('class', 'ckeditor')
return super(CKTextAreaWidget, self).__call__(field, **kwargs)
class CKTextAreaField(TextAreaField):
widget = CKTextAreaWidget()
class PostAdmin(sqla.ModelView):
form_overrides = dict(content=CKTextAreaField)
create_template = 'blog/ckeditor.html'
edit_template = 'blog/ckeditor.html'
form_excluded_columns = ('slug')
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(PostAdmin(Post, db.session))
class TagAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(TagAdmin(Tag, db.session))
class UserAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(UserAdmin(User, db.session))
/r/flask
https://redd.it/5dbvbi
reddit
[AF] Flask Admin not displaying Foreign Key column • /r/flask
I'm building a blog with Flask. I use Flask-Admin for setting up an administrative interface. Everything is fine, but I cannot see the "tags"...
How to authenticate IMAP using oauth tokens?
I'm building a flask app that authenticates a user using Google's OAuth and then connects to gmail using IMAP for further email processing, however, i'm having trouble with the whole process.
My current code is as follows. I'm able to sign the user into google and access their user information, such as their email, and obtain an access token, however, i'm not sure where to go from there. Any/all help is greatly appreciated.
from flask import Flask, request, url_for, session, redirect, jsonify
from flask_oauth import OAuth
import json
import imaplib
import email
from bs4 import BeautifulSoup
GOOGLE_CLIENT_ID = 'MY ID'
GOOGLE_CLIENT_SECRET = 'MY SECRET'
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console
SECRET_KEY = 'Uber'
DEBUG = True
app = Flask(__name__)
app.secret_key = 'Uber'
oauth = OAuth()
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
@app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))
access_token = access_token[0]
from urllib2 import Request, urlopen, URLError
headers = {'Authorization': 'OAuth '+access_token}
req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
None, headers)
try:
res = urlopen(req)
except URLError, e:
if e.code == 401:
# Unauthorized - bad token
session.pop('access_token', None)
return redirect(url_for('login'))
return res.read()
j = json.loads(res.read())
email_address = j['email']
print email_address, access_token
return "Hello World"
@app.route('/login')
def login():
callback=url_for('authorized', _external=True)
return google.authorize(callback=callback)
@app.route(REDIRECT_URI)
@google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('index'))
@google.tokengetter
def get_access_token():
return session.get('access_token')
def Uber_Cost(email_address, access_token):
# this function is completed, i'm just not sure how to authenticate IMAP using the oauth from above
/r/flask
https://redd.it/5dc81w
I'm building a flask app that authenticates a user using Google's OAuth and then connects to gmail using IMAP for further email processing, however, i'm having trouble with the whole process.
My current code is as follows. I'm able to sign the user into google and access their user information, such as their email, and obtain an access token, however, i'm not sure where to go from there. Any/all help is greatly appreciated.
from flask import Flask, request, url_for, session, redirect, jsonify
from flask_oauth import OAuth
import json
import imaplib
import email
from bs4 import BeautifulSoup
GOOGLE_CLIENT_ID = 'MY ID'
GOOGLE_CLIENT_SECRET = 'MY SECRET'
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console
SECRET_KEY = 'Uber'
DEBUG = True
app = Flask(__name__)
app.secret_key = 'Uber'
oauth = OAuth()
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
@app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))
access_token = access_token[0]
from urllib2 import Request, urlopen, URLError
headers = {'Authorization': 'OAuth '+access_token}
req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
None, headers)
try:
res = urlopen(req)
except URLError, e:
if e.code == 401:
# Unauthorized - bad token
session.pop('access_token', None)
return redirect(url_for('login'))
return res.read()
j = json.loads(res.read())
email_address = j['email']
print email_address, access_token
return "Hello World"
@app.route('/login')
def login():
callback=url_for('authorized', _external=True)
return google.authorize(callback=callback)
@app.route(REDIRECT_URI)
@google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('index'))
@google.tokengetter
def get_access_token():
return session.get('access_token')
def Uber_Cost(email_address, access_token):
# this function is completed, i'm just not sure how to authenticate IMAP using the oauth from above
/r/flask
https://redd.it/5dc81w
A collection of the not-so-obvious Python stuff
http://nbviewer.jupyter.org/github/rasbt/python_reference/blob/master/tutorials/not_so_obvious_python_stuff.ipynb?create=1
/r/JupyterNotebooks
https://redd.it/48q8a5
http://nbviewer.jupyter.org/github/rasbt/python_reference/blob/master/tutorials/not_so_obvious_python_stuff.ipynb?create=1
/r/JupyterNotebooks
https://redd.it/48q8a5
nbviewer.jupyter.org
Notebook on nbviewer
Check out this Jupyter notebook!
The new f-strings in Python 3.6
https://cito.github.io/blog/f-strings/
/r/Python
https://redd.it/5k3p10
https://cito.github.io/blog/f-strings/
/r/Python
https://redd.it/5k3p10
cito.github.io
The new f-strings in Python 3.6 | Seasoned & Agile
[python, f-strings]
[P] A framework to build object detectors easily in Python
https://github.com/EvgenyNekrasov/gpod
/r/MachineLearning
https://redd.it/5k32dl
https://github.com/EvgenyNekrasov/gpod
/r/MachineLearning
https://redd.it/5k32dl
GitHub
EvgenyNekrasov/gpod
gpod - GPOD - General Purpose Object Detector in Python
Mining Twitter: a chapter from "Mining the Social Web"
http://nbviewer.jupyter.org/github/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/ipynb/Chapter%201%20-%20Mining%20Twitter.ipynb
/r/JupyterNotebooks
https://redd.it/48cm4r
http://nbviewer.jupyter.org/github/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/ipynb/Chapter%201%20-%20Mining%20Twitter.ipynb
/r/JupyterNotebooks
https://redd.it/48cm4r
nbviewer.jupyter.org
Notebook on nbviewer
Check out this Jupyter notebook!
YuleLog - A terminal based Yule Log Fireplace for the Christmas Season. Made with Asciimatics!
I had the idea this morning to make a terminal based fireplace like the ones you see on youtube around this time of year. I looked around and didn't really see anything like it so I figured I'd go ahead with it.
I have always loved Asciimatics and remembered there's an awesome fire effect built in. There was a Christmas example, but it only had floating text.
I then found a photo of a log and converted it with https://picascii.com/ and spent some time tweaking the position a bit till it looked good on different console sizes.
It's up on Pypi so you can
`$ pip install YuleLog`
Not a lot of work at all but I'm pretty happy with the outcome and I hope you all are too :D
tl;dr - YuleLog -
Screenshot: https://github.com/Duroktar/YuleLog/blob/master/yule_log/screenshot.png
Github - https://github.com/Duroktar/YuleLog
Pypi - https://pypi.python.org/pypi
Release page - https://github.com/Duroktar/YuleLog/releases/tag/0.0.1
Love, Peace and Happiness to you all. Merry Christmas!!
edit: WORKS BEST IN FULLSCREEN!
/r/Python
https://redd.it/5k5o9l
I had the idea this morning to make a terminal based fireplace like the ones you see on youtube around this time of year. I looked around and didn't really see anything like it so I figured I'd go ahead with it.
I have always loved Asciimatics and remembered there's an awesome fire effect built in. There was a Christmas example, but it only had floating text.
I then found a photo of a log and converted it with https://picascii.com/ and spent some time tweaking the position a bit till it looked good on different console sizes.
It's up on Pypi so you can
`$ pip install YuleLog`
Not a lot of work at all but I'm pretty happy with the outcome and I hope you all are too :D
tl;dr - YuleLog -
Screenshot: https://github.com/Duroktar/YuleLog/blob/master/yule_log/screenshot.png
Github - https://github.com/Duroktar/YuleLog
Pypi - https://pypi.python.org/pypi
Release page - https://github.com/Duroktar/YuleLog/releases/tag/0.0.1
Love, Peace and Happiness to you all. Merry Christmas!!
edit: WORKS BEST IN FULLSCREEN!
/r/Python
https://redd.it/5k5o9l
Basic Model concept but I can't wrap my head around how to do it... Help, please.
Spending part of the Christmas holiday working on my first big Django project and I've hit a wall. I just can't wrap my head around how to do this so any help would be appreciated.
Custom user account (already made and set up) has a field which is used to reference an external API. Information related to the user (transaction list with details) is pulled from the external API (JSON) and saved to my database. Each user will have multiple transactions and each transaction will have multiple pieces of data associated with it that needs to be saved (to be later presented as a graph).
I can't wrap my head around how to set up the model to get the JSON data into my database. This includes creating the model and saving it.
I realize it's probably an elementary problem but if anyone can just list what I need to do to get this done I'd appreciate it. Most tutorials use data from forms (or blog entries) to illustrate how to save data to a database so I guess I need to know how to process and save data from a non-form outside source.
/r/django
https://redd.it/5k45xh
Spending part of the Christmas holiday working on my first big Django project and I've hit a wall. I just can't wrap my head around how to do this so any help would be appreciated.
Custom user account (already made and set up) has a field which is used to reference an external API. Information related to the user (transaction list with details) is pulled from the external API (JSON) and saved to my database. Each user will have multiple transactions and each transaction will have multiple pieces of data associated with it that needs to be saved (to be later presented as a graph).
I can't wrap my head around how to set up the model to get the JSON data into my database. This includes creating the model and saving it.
I realize it's probably an elementary problem but if anyone can just list what I need to do to get this done I'd appreciate it. Most tutorials use data from forms (or blog entries) to illustrate how to save data to a database so I guess I need to know how to process and save data from a non-form outside source.
/r/django
https://redd.it/5k45xh
reddit
Basic Model concept but I can't wrap my head around... • /r/django
Spending part of the Christmas holiday working on my first big Django project and I've hit a wall. I just can't wrap my head around how to do...
I implemented a module in python for oversampling skewed datasets. Would love to hear your thoughts on it!
It is an implementation of the ADASYN algorithm (link to paper: bit.ly/22KgAnP) and is designed to work along the scikit-learn API. I ran into the need of an oversampling module that focuses more on examples that are harder to classify, and I said, what the heck... I will implement it on my own. Feel free to use it in your projects and if you find any bugs just open an issue
https://github.com/stavskal/ADASYN
Don't forget to star if you find it useful ;)
/r/pystats
https://redd.it/44r9ye
It is an implementation of the ADASYN algorithm (link to paper: bit.ly/22KgAnP) and is designed to work along the scikit-learn API. I ran into the need of an oversampling module that focuses more on examples that are harder to classify, and I said, what the heck... I will implement it on my own. Feel free to use it in your projects and if you find any bugs just open an issue
https://github.com/stavskal/ADASYN
Don't forget to star if you find it useful ;)
/r/pystats
https://redd.it/44r9ye
ieeexplore.ieee.org
ADASYN: Adaptive synthetic sampling approach for imbalanced learning - IEEE Xplore Document
This paper presents a novel adaptive synthetic (ADASYN) sampling approach for learning from imbalanced data sets. The essential idea of ADASYN is to use a
[OC] Single and Multiple Regression using Python
https://cheekynomics.wordpress.com/2016/01/30/indicators-of-deprivation-2-2/
/r/pystats
https://redd.it/43djn7
https://cheekynomics.wordpress.com/2016/01/30/indicators-of-deprivation-2-2/
/r/pystats
https://redd.it/43djn7
cheekynomics
Indicators of Deprivation (2)
Indicators of Deprivation Part 2 Part 1 of this analysis can be found here. By the end of the last part, I had loaded and cleaned all of the different data and collected them together into a single…
Supervisord project: Python 2 to 3 porting help needed
Supervisor is a process supervisor used by hundreds of thousands (millions?) of production systems. It is used by people who don't even use Python as their application language.
supervisord is one of the most useful tools to run production systems.. and is more relevant when we look at the Docker world..Where is it is usually run as "init 1".
For us (and a crazy ton of systems people who dont even use python for application code), the "supervisor" incompatibility is a blocker to move to py3.
Unfortunately, I think the maintainers are handicapped by py3 expertise - https://github.com/Supervisor/supervisor/labels/python%203
>Supervisor has some major issues on Python 3. Many of these issues are encoding related as well so merging this one patch doesn't move the needle much. We need someone who has strong experience in Python 2/3 porting and is willing to spend a non-trivial amount of time looking at these bytes/strings issues together.
https://github.com/Supervisor/supervisor/pull/471#issuecomment-267793117
/r/Python
https://redd.it/5k1875
Supervisor is a process supervisor used by hundreds of thousands (millions?) of production systems. It is used by people who don't even use Python as their application language.
supervisord is one of the most useful tools to run production systems.. and is more relevant when we look at the Docker world..Where is it is usually run as "init 1".
For us (and a crazy ton of systems people who dont even use python for application code), the "supervisor" incompatibility is a blocker to move to py3.
Unfortunately, I think the maintainers are handicapped by py3 expertise - https://github.com/Supervisor/supervisor/labels/python%203
>Supervisor has some major issues on Python 3. Many of these issues are encoding related as well so merging this one patch doesn't move the needle much. We need someone who has strong experience in Python 2/3 porting and is willing to spend a non-trivial amount of time looking at these bytes/strings issues together.
https://github.com/Supervisor/supervisor/pull/471#issuecomment-267793117
/r/Python
https://redd.it/5k1875
GitHub
Supervisor/supervisor
supervisor - Supervisor process control system for UNIX
a Py3.6 fizzBuzz oneliner with f-strings
print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')
/r/Python
https://redd.it/5k7lnb
print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')
/r/Python
https://redd.it/5k7lnb
reddit
a Py3.6 fizzBuzz oneliner with f-strings • /r/Python
print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')
What do Tim O'Reilly, Lady Gaga, and Marissa Mayer all have in common? (from: Mining the Social Web)
http://nbviewer.jupyter.org/github/ptwobrussell/mining-the-social-web-2nd-edition/blob/master/ipynb/__What%20do%20Tim%20O'Reilly,%20Lady%20Gaga,%20and%20Marissa%20Mayer%20all%20have%20in%20common.ipynb
/r/JupyterNotebooks
https://redd.it/48cnh1
http://nbviewer.jupyter.org/github/ptwobrussell/mining-the-social-web-2nd-edition/blob/master/ipynb/__What%20do%20Tim%20O'Reilly,%20Lady%20Gaga,%20and%20Marissa%20Mayer%20all%20have%20in%20common.ipynb
/r/JupyterNotebooks
https://redd.it/48cnh1
nbviewer.jupyter.org
Notebook on nbviewer
Check out this Jupyter notebook!
How to build an interactive dashboard?
Do any packages exist allowing a dashboard with greater layout flexibility than the notebook allows?
/r/IPython
https://redd.it/4ogcgg
Do any packages exist allowing a dashboard with greater layout flexibility than the notebook allows?
/r/IPython
https://redd.it/4ogcgg
reddit
How to build an interactive dashboard? • /r/IPython
Do any packages exist allowing a dashboard with greater layout flexibility than the notebook allows?
My YouTube channel on Python programming (specialized in Data Science)
https://www.youtube.com/c/Pyrevolution/sub_confirmation=1
/r/pystats
https://redd.it/430gaf
https://www.youtube.com/c/Pyrevolution/sub_confirmation=1
/r/pystats
https://redd.it/430gaf
YouTube
PyRevolution
Free Python Programming tutorials for all!!! Come and Join the Python Revolution to learn about GUI Development, APIs, Data Science and much much more... Aut...
Awesome O: The really big list of really interesting open source projects in Python.
https://github.com/lk-geimfari/awesomeo/blob/master/languages/PYTHON.md
/r/Python
https://redd.it/5k8ocx
https://github.com/lk-geimfari/awesomeo/blob/master/languages/PYTHON.md
/r/Python
https://redd.it/5k8ocx
GitHub
lk-geimfari/awesomeo
awesomeo - The really big list of really interesting open source projects in all languages.
pandas-profiling: Create beautiful HTML profiling reports from pandas DataFrame objects
https://github.com/JosPolfliet/pandas-profiling
/r/pystats
https://redd.it/42upfp
https://github.com/JosPolfliet/pandas-profiling
/r/pystats
https://redd.it/42upfp
GitHub
JosPolfliet/pandas-profiling
pandas-profiling - Create HTML profiling reports from pandas DataFrame objects