Skip to content
This repository has been archived by the owner on Jan 13, 2024. It is now read-only.

Commit

Permalink
applies flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
sdpython committed Mar 21, 2015
1 parent 6c832aa commit 6d6d310
Show file tree
Hide file tree
Showing 21 changed files with 137 additions and 64 deletions.
9 changes: 9 additions & 0 deletions README.rst
Expand Up @@ -4,6 +4,15 @@
README / Changes
================


.. image:: https://badge.fury.io/py/ensae_teaching_cs.svg
:target: http://badge.fury.io/py/ensae_teaching_cs

.. image:: http://img.shields.io/pypi/dm/ensae_teaching_cs.png
:alt: PYPI Package
:target: https://pypi.python.org/pypi/ensae_teaching_cs


This page gives access to the content of practical sessions I give at the
`ENSAE <http://www.ensae.fr/>`_. They are based on Python. The project
is hosted on GitHub can be modified by sending me pull requests:
Expand Down
9 changes: 9 additions & 0 deletions _doc/sphinxdoc/source/index.rst
Expand Up @@ -3,6 +3,15 @@
ENSAE - Programmation - Xavier Dupré
====================================


.. image:: https://badge.fury.io/py/ensae_teaching_cs.svg
:target: http://badge.fury.io/py/ensae_teaching_cs

.. image:: http://img.shields.io/pypi/dm/ensae_teaching_cs.png
:alt: PYPI Package
:target: https://pypi.python.org/pypi/ensae_teaching_cs


Cette page donne accès au contenu des séances de travaux pratiques en programmation
que je dispense à l'`ENSAE <http://www.ensae.fr/>`_. Ils s'appuient principalement sur
le langage Python. Le contenu est librement disponible sur `GitHub/ensae_teaching_cs <https://github.com/sdpython/ensae_teaching_cs>`_
Expand Down
78 changes: 78 additions & 0 deletions _unittests/ut_module/test_flake8.py
@@ -0,0 +1,78 @@
"""
@brief test log(time=0s)
"""

import sys
import os
import unittest
import re
import flake8


try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..")))
if path not in sys.path:
sys.path.append(path)
import src

try:
import pyquickhelper
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
"..",
"..",
"..",
"pyquickhelper",
"src")))
if path not in sys.path:
sys.path.append(path)
import pyquickhelper


from pyquickhelper import fLOG, run_cmd


class TestFlake8(unittest.TestCase):

def test_flake8(self):
fLOG(
__file__,
self._testMethodName,
OutputPrint=__name__ == "__main__")

thi = os.path.abspath(os.path.dirname(__file__))
src = os.path.normpath(os.path.join(thi, "..", "..", "src"))
exe = os.path.dirname(sys.executable)
scr = os.path.join(exe, "Scripts")
fla = os.path.join(scr, "flake8")
cmd = fla + " " + src
out, err = run_cmd(cmd, fLOG=fLOG, wait=True)

lines = out.split("\n")
lines = [_ for _ in lines if "E501" not in _ and "__init__.py" not in _ and "E265" not in _
and "W291" not in _ and "W293" not in _]
lines = [_ for _ in lines if len(_) > 1]
if __name__ == "__main__":
for l in lines:
spl = l.split(":")
if len(spl[0]) == 1:
spl[1] = ":".join(spl[0:2])
del spl[0]
print(
' File "{0}", line {1}, {2}'.format(spl[0], spl[1], spl[-1]))
if len(lines) > 1:
raise Exception(
"{0} lines\n{1}".format(len(lines), "\n".join(lines)))

if __name__ == "__main__":
unittest.main()
1 change: 0 additions & 1 deletion src/ensae_teaching_cs/automation/notebook_test_helper.py
Expand Up @@ -4,7 +4,6 @@
@brief Some automation helpers to test notebooks and check they are still working fine.
"""
import os
import sys
from pyquickhelper import noLOG
from pyquickhelper.ipythonhelper.notebook_helper import run_notebook

Expand Down
3 changes: 1 addition & 2 deletions src/ensae_teaching_cs/automation/project_helper.py
Expand Up @@ -4,7 +4,6 @@
"""
import re
import os
import pymmails
from pyquickhelper import noLOG, run_cmd, remove_diacritics

_email_regex = re.compile("[*] *e?mails? *: *([^*+]+)")
Expand Down Expand Up @@ -533,7 +532,7 @@ def ul(last):
str(name) +
"\n" +
str(s))
subject = s[0]
# subject = s[0]
eleves = list(group[col_student])
names = [(_,) + split_name(_) for _ in eleves]
eleves.sort()
Expand Down
12 changes: 6 additions & 6 deletions src/ensae_teaching_cs/coding_party/coding_party1_velib.py
Expand Up @@ -129,10 +129,10 @@ def vitesse(c, d, params):
Il reste un cas pour lequel, je ne sais pas encore quelle valeur donner :
il s'agit des demi-appariements : un vélo rétiré mais jamais reposé et réciproquement.
"""
if c[0] == None or d[0] == None:
if c[0] is None or d[0] is None:
# cas des vélos perdus
if c[0] == None:
if d[0] == None:
if c[0] is None:
if d[0] is None:
return None
else:
return 0.0, 0.0 # je ne sais pas trop quoi mettre
Expand Down Expand Up @@ -180,11 +180,11 @@ def distance(positif, negatif, appariement, params):
val.append(v)

mean = sum(val) / len(val)
cor = [v for v in val if v < 1e8] # on enlève les appariements négatifs
cor = [v_ for v_ in val if v < 1e8] # on enlève les appariements négatifs
mean_cor = sum(cor) / len(cor)
dev = sum((x - mean)**2 for x in val) / len(val)
return mean_cor, \
cost + dev**0.5 * (1 + len(nb_max)), \
return mean_cor, \
cost + dev**0.5 * (1 + len(nb_max)), \
mean, \
len(val) - len(cor)

Expand Down
24 changes: 13 additions & 11 deletions src/ensae_teaching_cs/faq/faq_ipython.py
Expand Up @@ -8,6 +8,7 @@
import os
import sys


def notebook_path():
"""
change matplotlib style
Expand Down Expand Up @@ -146,42 +147,43 @@ def custom_cmd(self, line):
if name not in magic_command_instance.shell.user_ns:
raise KeyError("variable {0} not found".format(name))
return magic_command_instance.shell.user_ns[name]



def ipython_cython_extension():
"""
The function raises an exception if cython has a good chance not
to work because Python does not find any suitable compiler
(not `MinGW <http://www.mingw.org/>`_ or
`Visual Studio Express <https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx>`_
or any expected version).
In that case, the function displays a message with some indications
on how to fix it.
@FAQ(ipython___Cython ne fonctionne pas sous Windows)
.. index:: vcvarsall, cython
Cela se caractérise par le message ::
Unable to find vcvarsall.bat
Le blog post
`Build a Python 64 bit extension on Windows <http://www.xavierdupre.fr/blog/2013-07-07_nojs.html>`_
répond à cette question.
Le fichier à modifier est le suivant ::
C:\Python34_x64\lib\distutils\msvc9compiler.py
@endFAQ
"""
if not sys.platform.startswith("win"):
return True

import distutils.msvc9compiler as mod
fc = os.path.abspath(mod.__file__)
with open(fc, "r") as f : code = f.read()

with open(fc, "r") as f:
code = f.read()

find = "'win-amd64' : 'x86_amd64'"
if find not in code:
url = "http://www.xavierdupre.fr/blog/2013-07-07_nojs.html"
Expand Down
6 changes: 2 additions & 4 deletions src/ensae_teaching_cs/faq/faq_pandas.py
Expand Up @@ -4,8 +4,6 @@
@brief Quelques problèmes récurrents avec `pandas <http://pandas.pydata.org/>`_.
"""

import os


def read_csv(filepath_or_buffer, encoding="utf8", sep="\t", **args):
"""
Expand Down Expand Up @@ -57,14 +55,14 @@ def read_csv(filepath_or_buffer, encoding="utf8", sep="\t", **args):
raise UnicodeError(
"'charmap' codec can't encode characters in position 0-1325: character maps to <undefined>")
return df
except UnicodeError as e:
except UnicodeError:
df = pandas.read_csv(
filepath_or_buffer,
encoding="utf-8-sig",
sep=sep,
**args)
return df
except UnicodeDecodeError as e:
except UnicodeDecodeError:
df = pandas.read_csv(
filepath_or_buffer,
encoding="utf-8-sig",
Expand Down
4 changes: 2 additions & 2 deletions src/ensae_teaching_cs/faq/faq_python.py
Expand Up @@ -80,7 +80,7 @@ def difference_div():
div2 = 4 / 2
div3 = 1 // 2
div4 = 1.0 // 2.0
return div1, div2, div3, div3
return div1, div2, div3, div4


def python_path():
Expand Down Expand Up @@ -421,7 +421,7 @@ def enumerate_regex_search(exp, text):
@endFAQ
"""
found = exp.search(text)
# found = exp.search(text)
for m in exp.finditer(text):
yield m

Expand Down
6 changes: 2 additions & 4 deletions src/ensae_teaching_cs/ml/sklearn_example_classifier.py
Expand Up @@ -4,8 +4,7 @@
"""

from .sklearn_base_classifier import SkBaseClassifier

from numpy import argsort, sqrt
from .sklearn_parameters import SkException
import numpy
import pandas

Expand Down Expand Up @@ -65,7 +64,7 @@ def predict(self, X):
"""
scores = self.decision_function(X)
if len(scores.shape) == 1:
indices = (scores > 0).astype(np.int)
indices = (scores > 0).astype(numpy.int)
else:
indices = scores.argmax(axis=1)
return indices
Expand Down Expand Up @@ -109,7 +108,6 @@ def knn_search(self, x):
@param x vector
@return k-nearest neighbors list( (distance**2, index) )
"""
K = self.P.k
X = self._TrainingX
ones = numpy.ones((len(X), len(x)))
po = x * ones
Expand Down
2 changes: 1 addition & 1 deletion src/ensae_teaching_cs/ml/sklearn_parameters.py
Expand Up @@ -55,7 +55,7 @@ def fmt(v):
return "'{0}'".format(v)
else:
return str(v)
return ", ".join("{0}={1}".format(k, fmt(getattr(self, v)))
return ", ".join("{0}={1}".format(k, fmt(getattr(self, k)))
for k in sorted(self.Keys))

def to_dict(self):
Expand Down
1 change: 1 addition & 0 deletions src/ensae_teaching_cs/mypython/custom_magics.py
Expand Up @@ -149,5 +149,6 @@ def register_magics():
"""
register magics function, can be called from a notebook
"""
from IPython import get_ipython
ip = get_ipython()
ip.register_magics(CustomMagics)
2 changes: 0 additions & 2 deletions src/ensae_teaching_cs/special/einstein_prolog.py
Expand Up @@ -5,8 +5,6 @@
Français `Intégramme <http://fr.wikipedia.org/wiki/Int%C3%A9gramme>`_. The algorithm is based
on logic and its `clause <http://en.wikipedia.org/wiki/Clause_(logic)>`_.
"""
import os
import sys
import copy


Expand Down
7 changes: 2 additions & 5 deletions src/ensae_teaching_cs/special/rues_paris.py
Expand Up @@ -3,9 +3,6 @@
@file
@brief Code implémentant la première solution proposée à `Parcourir les rues de Paris <http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/notebooks/rue_paris_parcours.html>`_.
"""
import os
import sys
import copy
import random
import math
import pyensae
Expand Down Expand Up @@ -139,7 +136,7 @@ def possible_edges(edges, threshold, fLOG=None, distance=distance_haversine):

possibles = {(e[0], e[1]): e[-1] for e in edges}
possibles.update({(e[1], e[0]): e[-1] for e in edges})
initial = possibles.copy()
# initial = possibles.copy()
for i1, v1 in vertices.items():
for i2, v2 in vertices.items():
if i1 >= i2:
Expand Down Expand Up @@ -426,7 +423,7 @@ def euler_path(edges, added_edges):
path = _explore_path(edges_from, begin)
for p in path:
if len(p) == 0:
stop
raise Exception("this exception should not happen")
while len(edges_from) > 0:
start = None
for i, p in enumerate(path):
Expand Down
6 changes: 0 additions & 6 deletions src/ensae_teaching_cs/td_1a/classiques.py
Expand Up @@ -251,9 +251,3 @@ def str2date(s, format="%d/%m/%Y"):
"""
return datetime.datetime.strptime(s, format)

if __name__ == "__main__":
l, d = liste_modifie_dans_la_boucle()
print(l, d)
r = repetition_a_eviter(l)
print(r)
11 changes: 6 additions & 5 deletions src/ensae_teaching_cs/td_1a/discours_politique.py
Expand Up @@ -6,11 +6,12 @@
"""

import re
import os
import json
import io
import html.parser
from pyquickhelper import noLOG, get_url_content
import html.entities as htmlentitydefs
from pyquickhelper import get_url_content


endLine = "\r\n"

Expand Down Expand Up @@ -101,9 +102,9 @@ def fixup(m):
if text[:2] == "&#":
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
return chr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
return chr(int(text[2:-1]))
except ValueError:
pass
else:
Expand All @@ -116,7 +117,7 @@ def fixup(m):
elif text[1:-1] == "lt":
text = "&amp;lt;"
else:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
text = chr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
Expand Down

0 comments on commit 6d6d310

Please sign in to comment.