Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.8K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Is it useful to install Anaconda on linux, when python and most packages can be installed via package managers ?

My main usage of python for the moment are scripting, and machine learning (using frameworks as tensorflow and keras)

/r/Python
https://redd.it/7dls42
Own decorator getting arguments from another line after - @app.route(rule, *args) - is it possible?

I want to store all functions from my flask app, so I made my own decorator inside Blog class and calling it as follows. It works well, but I also want to store these arguments (rule and methods) from @app.route inside my Blog class. Code as follows:

@Blog.register() # my own generator
@app.route(rule="/api/login", methods=["POST"])
def login():
if request.method == "POST":
data = my_logging_func()
return jsonify(data)

Is there a way to get @app.route params in @Blog.register() as it wraps over it?


/r/flask
https://redd.it/7d3wbt
Inlineformset with Multiple Parents and One Child

Is there a way to have in a template multiple parent forms with one child form for each parent? I can easily create one parent with multiple children using inlineformset but I'm not sure how to make multiple parents with one child.

Code below is setup to handle one parent with one child.

**models.py**

class Parent(models.Model):
parent_name = models.CharField(max_length=30)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name="parent")
child_name = models.CharField(max_length=30)

**view.py**

def myview(request):
ChildFormSet = inlineformset_factory(Parent, Child,
form=ChildForm,
can_delete=False,
max_num=1)
parent_form = ParentForm()
formset = ChildFormSet(instance=Parent())
if request.POST:
parent_form = ParentForm(request.POST)
if parent_form.is_valid():
try:
parent = Parent.objects.get(parent_name=parent_form.cleaned_data['parent_name'])
except ObjectDoesNotExist:
parent = parent_form.save(commit=False)
formset = ChildFormSet(request.POST, instance=parent)
if formset.is_valid():
parent.save()
formset.save()
messages.success(request, 'Saved.')
return HttpResponseRedirect('')
return render(request, "pcform.html", {
'parent_form': parent_form,
'formset': formset,
})

**pcform.html**

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}
<form method="POST" class="" autocomplate="off">
{% crispy parent_form %}
{% crispy formset formset.form.helper %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}


/r/django
https://redd.it/7dm0ft
[N] A user friendly editor based on Tensorflow: AI Blocks

Hi everyone!

AI Blocs is a *WYSIWYG* interface making it easier for developers to implement models quickly, I wanted to share my tool with you, hopefully this might help someone, It has proven itself to be very useful to me.

[Screenshot](https://raw.githubusercontent.com/MrNothing/AI-Blocks/master/sc5.png)

The interface is inspired from Unity, you can attach scripts to objects in the scene, run graphs and view the output in real time.

I would love to get some feedback if you have time to check it out.

**Github**: https://github.com/MrNothing/AI-Blocks

**Releases**: https://github.com/MrNothing/AI-Blocks/releases

Thank you!

/r/MachineLearning
https://redd.it/7dk945
I made a crappy game that you might like.

**Edit:** **[GITHUB LINK] (https://github.com/brumafriend/BrumaGame)** TO CODE.

Made with python3, also it's a "console game" AKA all text.

**NOTE: I AM NOT GOOD AT CODING. So don't expect this to be good. At all.**

How the game works:
You have an army and a population, which number 5000 and 25000 respectively. Your population does not include soldiers. The aim is to conquer all 5 of the other countries there are right now: _UK, USA, France, Germany and Russia_.

You can lose in two ways. Firstly, if your population & army is so small that you can't win any war or explore to find more soldiers. Secondly, and most importantly, through **tension**:

Tension starts at 10%.
Winning a war decreases tension.
Losing a war increases tension.
If tension is > 50% there is a chance there may be a civil war which can defeat you or severely damage your army and population numbers.

The mechanics:

**Conscription**: Conscription can allow you to add to an army's numbers by recruiting civilians. Your army can only get to 10,000 members through conscription and for each 1000 people conscripted, **tension** rises by 10%.

**Exploring**: You need 400 civs and 100 soldiers to explore. Exploring can result in gaining civilians and soldiers, this also decreases tension. It can also result in disaster - making you lose the people sent out and causing an increase in tension of 20%.

**War**: The most important aspect of the game is war. Waging war against another country is simple; winning is not. Your chance to win is (x/y)*50 with x being your troops and y being the enemy's. So, if you have equal numbers then there's a 50% chance you win. Upon winning, tension is decreased and you gain troops. You can't defeat the same country twice. Upon losing, tension increases and you lose half of your troops. You can try to attack the country again at a later date.

**Money**: (as of 22:00, 17/11/2017) Money can be used to purchase soldiers. In a desperate situation? Buy your way out of it! You start with $50,000. Winning wars earns you money, losing wars loses you money. Money can also be earned by exploring.



^_edit_: ^Wow. ^Thanks ^for ^the ^support ^guys. ^I'll ^try ^to ^update ^the ^game ^and ^update ^the ^github ^with ^it. ^The ^advice ^has ^been ^helpful ^and ^if ^any ^of ^you ^want ^to ^help ^me ^with ^the ^creation ^of ^the ^game ^in ^any ^way, ^feel ^free ^to ^send ^me ^a ^message.

/r/Python
https://redd.it/7dm6sm
Frustrated Newbie with some newbie questions.

I've been trying to understand python and once i feel im getting a grasp of it, i try to type in the code from an example online and i cant even get to the second line. I use "IDLE" and i type "total_secs = int(input("How many seconds, in total?"))" and i want to go to the second line to continue the code and all it does is print "How many seconds, in total?" The next part of the code is "hours = total_secs // 3600" but...like i said..it just prints the first line. Am I missing something? I appreciate any help. Thanks in advance.

/r/Python
https://redd.it/7dp9rk
How does the upvote/downvote number on Reddit/Steck Uberflow change instantly? Is it fake clientside code?

If you upvote/downvote any post on Steck Uberflow or Reddit, you'll see the number change instantly. This doesn't seem feasible or sensible. Is it just frontend code that add or minus 1 automatically when you click the upvote/downvote button?

EDIT: I just realized this isn't a Django-related question. Sorry about that.

/r/django
https://redd.it/7dpuub
Paying for help with a Django issue?

Hey all,

I'm a Django novice/intermediate user - I have already launched a web app and I'm working on a second, slightly more complex one.

I've hit a bit of a snag with a particular issue and can't seem to find any solutions on the internet as it's very specific. I'm trying to juggle the functionality of three different django plugins and I fear the scope of what I'm trying to do is slightly above my current competencies.

Because this particular feature I want to implement is something I care for quite dearly I'm prepared to use some of my personal savings to pay someone to help me implement it, or at least to explain how I could go about implementing it myself.

Does anyone know of any good places where I could search for such a person and how much an hour or two of their time would cost?

Thanks

**EDIT** ###More details below

So basically I've got [django-filter](https://github.com/carltongibson/django-filter) set up and working correctly to filter my Product model based on various fields. The user ticks a checkbox or selects something from a dropdown and hits "Submit" on the form and everything filters/sorts correctly.

The issue I'm having is that I'd like to use AJAX so that there is no need to submit the form. The actual filtering/sorting logic is handled by `django-filter` and apparently I'd need to create an API endpoint with `django-rest-framework` so that AJAX can interact with that data.

To make matters more complicated, I'm using `django-wagtail` as a CMS which means I don't have any `views.py` or `urls.py` to work with. The only way to submit data other than HTML is by [overriding the serve() method on the actual page model](http://docs.wagtail.io/en/v1.13.1/reference/pages/model_recipes.html#overriding-the-serve-method).

I more or less know *what* needs to be done but I'm definitely lacking the skills/knowledge/experience to know exactly how to get this to work, and I can't afford to waste a week tinkering around to get it to work...

/r/django
https://redd.it/7dntaj
Will neural network work as articles classification on my website?

I have jobs aggregator which parses offers.
Jobs come from different sources and sometimes there are not relevant posts which I moderate by myself.
Right now I have more than 1000 moderated posts in the database. Can I somehow add automatic filter with neural networks or machine learning? Is there any tutorial on that topic?

I found what I need, here is a nltk guide. https://www.youtube.com/watch?v=FLZvOKSCkxY&list=PLQVvvaa0QuDf2JswnfiGkliBInZnIC4HL&index=1

/r/django
https://redd.it/7dns4f
[D] Low entry barrier is destroying deep learning reputation

For a long time now, I notice many self-proclaimed deep learning experts, wizards, and what-not. With no educational or research background in either machine or deep learning, they think they have obtained expert knowledge in deep learning just by installing tensorflow or keras and running some code from github. Then, they immediately add "deep learning expert" to their name and write tutorial blog posts or even have the nerve to offer courses and write books. Not long ago, I reviewed a book proposal about deep reinforcement learning by some two "hackers", who had no education and no work experience in either machine, deep or deep reinforcement learning, yet they felt they are already experts in it that they just had to write a book about it...

Why this bothers me?

It destroys the reputation of deep learning. Most companies have no clue how to recognize these so called "experts". The job interviewers don't have the required deep learning expertise to properly evaluate candidates and NIPS, ICML, et al. mean nothing to them. So they end up hiring the "experts". Then when inevitably their "deep learning" solutions fail, they conclude that deep learning is not working and it's nothing but a hype. As more and more companies experience this, more and more companies become skeptical about deep learning.
Already, people from the industry half-jokingly refer to AI as artificially inflated.

What do you think? Do you agree or not?
If you agree, what should we do?
Start, a deep learning hiring agency? :)


Update: When I say low entry barrier I don't mean access to education. I mean the accessibility of the material, i.e. you don't need to know much about machine or deep learning to apply it with success to well known problems. However, you do need the knowledge and the research experience to apply it on novel problems.

/r/MachineLearning
https://redd.it/7dqtby
Flask-Login issues.

I am using the Flask-Login extension( https://github.com/maxcountryman/flask-login)

I've followed the documentation pretty closely but each time I try to go to a 'login required' route it returns me to my login page even after a successful login.

I've printed my "next" variable and it always returns "login". Any suggestions?

I'm not using a DB just a list of faux users for the time being.
Hoping to eventually authenticate with Active directory, but need to get some basics of Flask-Login down first.

/r/flask
https://redd.it/7dsuxy
[AF] Generating and exporting a CSV for client side download

I’ve built a simple Flask application with number of screens for adding & editing data stored in a SQLite database. Additionally, I have a basic reporting page that pulls data from the database and displays the results in a table.

I’d like to allow the client to hit a button above the report table that downloads a CSV file containing the same data stored in the table.

I have successfully been able to create a csv file containing the correct data, but the csv file is saved to a local server directory making it inaccessible to anyone without sever access.

Are there any modules or configurations in Flask (or in python3 generally) that can allow me to achieve this goal of getting the data from the database, to a csv, to the client browser? If possible, I do not want to have to store the generated csv server side at all.

/r/flask
https://redd.it/7cz8eb
Safety precautions when running flask locally?

I have the following code running on my Raspberry Pi which I'm using as to WOL my PC, from my phone.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
'WOL Code here'
return 'not a post request'

if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)

Basically I just open up the webpage from my phone when I'm on my home network and it runs, super simple. Since this is running on my local network (so technically any device which is connected to my wifi could trigger this) are there any security precautions I need to take? I know the docs say that **"Flask's built-in server is not suitable for production"** but would that include such a simple app like this? Am I better off deploying/running it a different way? I've no plans to use this outside of my local network at the moment, if that makes any difference.

/r/flask
https://redd.it/7dvbea
Open-sourced a library that converts a Shapefile, GeoJSON, or CSV to an equal-area hexgrid cartogram. Suggestions and criticism appreciated.

I just open-source a library that outputs an equal area hexgrid SVG, given a shapefile/GeoJSON/CSV - https://github.com/LokiTechnologies/equalareacartogram. [As shown in this image](https://i.imgur.com/Da6colB.jpg), it outputs the map on the right given the map on the left as an input.

This is my first attempt at open-sourcing something, and this library is likely to contain several errors and bad practices. Would appreciate critiques and suggestions for improvement!

/r/Python
https://redd.it/7ds41t
[AF] How to render a template from a helper function?

Quick question, I need to check the existence of an object in the database in a lot of app routes, so I figured I'd just call a function which checks the said existence and returns an error template if it isn't found. However, when going to my site, 'error.html' is not rendered at all even though the bool is True. What am I missing?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
foo()
render_template('succes.html')

def foo():
if some_bool_resulting_from_a_check:
return render_template('error.html')


/r/flask
https://redd.it/7cyion
What would be a standard modern python workflow?

I am working on linux, mainly using python for scripting and machine learning.

I am wondering if there is a standard workflow for python developers as of 2017.

Among others are these considered standard/widely used, why, and how?

* Virtual Environments / Virtual Environments Wrappers
* Alternative Interpreters / Notebooks (like ipython/jupyter)
* conda package manager and environments
* Version control
* Others...

What are you guys using ?

PS: Just found [this example](http://tdhopper.com.s3-website-us-east-1.amazonaws.com/conda/). Wondering if it is still up to date..

/r/Python
https://redd.it/7dqqu0