<commit_before>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os.path
import sys
import re
import traceback

from robottypes import is_str
from unic import unic
from robot.errors import DataError, TimeoutError, RemoteError

RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError)
if sys.platform.startswith('java'):
    from java.io import StringWriter, PrintWriter
    from java.lang import Throwable, OutOfMemoryError
    RERAISED_EXCEPTIONS += (OutOfMemoryError,)

_java_trace_re = re.compile('^\s+at (\w.+)')
_ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.',
                       'sun.reflect.', 'java.lang.reflect.')
_ignore_trace_until = (os.path.join('robot','running','handlers.py'), '_run_handler')
_generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception',
                       'Error', 'RuntimeError', 'RuntimeException',
                       'DataError', 'TimeoutError', 'ExecutionFailed', 'RemoteError')

def get_error_message():
    """Returns error message of the last occurred exception.

    This method handles also exceptions containing unicode messages. Thus it
    MUST be used to get messages from all exceptions originating outside the
    framework.
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if exc_type in (KeyboardInterrupt, SystemExit):
        raise exc_value
    if _is_java_exception(exc_value):
        return _get_java_message(exc_type, exc_value)
    return _get_python_message(exc_type, exc_value)

def get_error_details():
    """Returns error message and details of the last occurred exception.

    Error message contains exception's type and message and details contains
    stacktrace.

    This method handles also exceptions containing unicode messages. Thus it
    MUST be used to get messages from all exceptions originating outside the
    framework.
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if exc_type in (KeyboardInterrupt, SystemExit):
        raise exc_value
    if _is_java_exception(exc_value):
        message = _get_java_message(exc_type, exc_value)
        details = _get_java_details(exc_value)
    else:
        message = _get_python_message(exc_type, exc_value)
        details = _get_python_details(exc_value, exc_traceback)
    return message, details

def _is_java_exception(exc):
    return sys.platform.startswith('java') and isinstance(exc, Throwable)

def _get_name(exc_type):
    try:
        return exc_type.__name__
    except AttributeError:
        return unic(exc_type)

def _msg_to_str(msg):
    if msg is None:
        return ''
    if not is_str(msg):
        return unic(msg)
    return msg

def _get_java_message(exc_type, exc_value):
    exc_name = _get_name(exc_type)
    # OOME.getMessage and even toString seem to throw NullPointerException
    if exc_type is OutOfMemoryError:
        exc_msg = str(exc_value)
    else:
        exc_msg = exc_value.getMessage()
    return _format_message(exc_name, exc_msg, java=True)

def _get_java_details(exc_value):
    # OOME.printStackTrace seems to throw NullPointerException
    if isinstance(exc_value, OutOfMemoryError):
        return ''
    output = StringWriter()
    exc_value.printStackTrace(PrintWriter(output))
    lines = [ line for line in str(output).splitlines()
              if line and not _is_ignored_stacktrace_line(line) ]
    details = '\n'.join(lines)
    msg = _msg_to_str(exc_value.getMessage())
    if msg:
        details = details.replace(msg, '', 1)
    return details

def _is_ignored_stacktrace_line(line):
    res = _java_trace_re.match(line)
    if res is None:
        return False
    location = res.group(1)
    for entry in _ignored_java_trace:
        if location.startswith(entry):
            return True
    return False

def _get_python_message(exc_type, exc_value):
    # If exception is a "string exception" without a message exc_value is None
    if exc_value is None:
        return unic(exc_type)
    name = _get_name(exc_type)
    try:
        msg = unic(exc_value)
    except UnicodeError:   # Happens at least if exception message is unicode
        msg = unic(exc_value.args[0])
    return _format_message(name, msg)

def _get_python_details(exc_value, exc_tb):
    if isinstance(exc_value, (DataError, TimeoutError)):
        return ''
    if isinstance(exc_value, RemoteError):
        return exc_value.traceback
    tb = traceback.extract_tb(exc_tb)
    for row, (path, _, func, _) in enumerate(tb):
        if path.endswith(_ignore_trace_until[0]) and func == _ignore_trace_until[1]:
            tb = tb[row+1:]
            break
    details = 'Traceback (most recent call last):\n' \
            + ''.join(traceback.format_list(tb))
    return details.strip()

def _format_message(name, message, java=False):
    message = _msg_to_str(message)
    if java:
        message = _clean_up_java_message(message, name)
    name = name.split('.')[-1]  # Use only last part of the name
    if message == '':
        return name
    if name in _generic_exceptions:
        return message
    return '%s: %s' % (name, message)

def _clean_up_java_message(msg, name):
    # Remove possible stack trace from messages
    lines = msg.splitlines()
    while lines:
        if _java_trace_re.match(lines[-1]):
            lines.pop()
        else:
            break
    msg = '\n'.join(lines)
    # Remove possible exception name from the message
    tokens = msg.split(':', 1)
    if len(tokens) == 2 and tokens[0] == name:
        msg = tokens[1]
    return msg.strip()
<commit_msg>avoid using str<commit_after>#  Copyright 2008-2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os.path
import sys
import re
import traceback

from robottypes import is_str
from unic import unic
from robot.errors import DataError, TimeoutError, RemoteError

RERAISED_EXCEPTIONS = (KeyboardInterrupt, SystemExit, MemoryError)
if sys.platform.startswith('java'):
    from java.io import StringWriter, PrintWriter
    from java.lang import Throwable, OutOfMemoryError
    RERAISED_EXCEPTIONS += (OutOfMemoryError,)

_java_trace_re = re.compile('^\s+at (\w.+)')
_ignored_java_trace = ('org.python.', 'robot.running.', 'robot$py.',
                       'sun.reflect.', 'java.lang.reflect.')
_ignore_trace_until = (os.path.join('robot','running','handlers.py'), '_run_handler')
_generic_exceptions = ('AssertionError', 'AssertionFailedError', 'Exception',
                       'Error', 'RuntimeError', 'RuntimeException',
                       'DataError', 'TimeoutError', 'ExecutionFailed', 'RemoteError')

def get_error_message():
    """Returns error message of the last occurred exception.

    This method handles also exceptions containing unicode messages. Thus it
    MUST be used to get messages from all exceptions originating outside the
    framework.
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if exc_type in (KeyboardInterrupt, SystemExit):
        raise exc_value
    if _is_java_exception(exc_value):
        return _get_java_message(exc_type, exc_value)
    return _get_python_message(exc_type, exc_value)

def get_error_details():
    """Returns error message and details of the last occurred exception.

    Error message contains exception's type and message and details contains
    stacktrace.

    This method handles also exceptions containing unicode messages. Thus it
    MUST be used to get messages from all exceptions originating outside the
    framework.
    """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    if exc_type in (KeyboardInterrupt, SystemExit):
        raise exc_value
    if _is_java_exception(exc_value):
        message = _get_java_message(exc_type, exc_value)
        details = _get_java_details(exc_value)
    else:
        message = _get_python_message(exc_type, exc_value)
        details = _get_python_details(exc_value, exc_traceback)
    return message, details

def _is_java_exception(exc):
    return sys.platform.startswith('java') and isinstance(exc, Throwable)

def _get_name(exc_type):
    try:
        return exc_type.__name__
    except AttributeError:
        return unic(exc_type)

def _msg_to_str(msg):
    if msg is None:
        return ''
    if not is_str(msg):
        return unic(msg)
    return msg

def _get_java_message(exc_type, exc_value):
    exc_name = _get_name(exc_type)
    # OOME.getMessage and even toString seem to throw NullPointerException
    if exc_type is OutOfMemoryError:
        exc_msg = str(exc_value)
    else:
        exc_msg = exc_value.getMessage()
    return _format_message(exc_name, exc_msg, java=True)

def _get_java_details(exc_value):
    # OOME.printStackTrace seems to throw NullPointerException
    if isinstance(exc_value, OutOfMemoryError):
        return ''
    output = StringWriter()
    exc_value.printStackTrace(PrintWriter(output))
    lines = [ line for line in output.toString().splitlines()
              if line and not _is_ignored_stacktrace_line(line) ]
    details = '\n'.join(lines)
    msg = _msg_to_str(exc_value.getMessage())
    if msg:
        details = details.replace(msg, '', 1)
    return details

def _is_ignored_stacktrace_line(line):
    res = _java_trace_re.match(line)
    if res is None:
        return False
    location = res.group(1)
    for entry in _ignored_java_trace:
        if location.startswith(entry):
            return True
    return False

def _get_python_message(exc_type, exc_value):
    # If exception is a "string exception" without a message exc_value is None
    if exc_value is None:
        return unic(exc_type)
    name = _get_name(exc_type)
    try:
        msg = unic(exc_value)
    except UnicodeError:   # Happens at least if exception message is unicode
        msg = unic(exc_value.args[0])
    return _format_message(name, msg)

def _get_python_details(exc_value, exc_tb):
    if isinstance(exc_value, (DataError, TimeoutError)):
        return ''
    if isinstance(exc_value, RemoteError):
        return exc_value.traceback
    tb = traceback.extract_tb(exc_tb)
    for row, (path, _, func, _) in enumerate(tb):
        if path.endswith(_ignore_trace_until[0]) and func == _ignore_trace_until[1]:
            tb = tb[row+1:]
            break
    details = 'Traceback (most recent call last):\n' \
            + ''.join(traceback.format_list(tb))
    return details.strip()

def _format_message(name, message, java=False):
    message = _msg_to_str(message)
    if java:
        message = _clean_up_java_message(message, name)
    name = name.split('.')[-1]  # Use only last part of the name
    if message == '':
        return name
    if name in _generic_exceptions:
        return message
    return '%s: %s' % (name, message)

def _clean_up_java_message(msg, name):
    # Remove possible stack trace from messages
    lines = msg.splitlines()
    while lines:
        if _java_trace_re.match(lines[-1]):
            lines.pop()
        else:
            break
    msg = '\n'.join(lines)
    # Remove possible exception name from the message
    tokens = msg.split(':', 1)
    if len(tokens) == 2 and tokens[0] == name:
        msg = tokens[1]
    return msg.strip()
<|endoftext|>


<commit_before>from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.db.models import Count
from dwitter.models import Dweet
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils import timezone
from functools import wraps
import json

def ajax_login_required(view_func):
  @wraps(view_func)
  def wrapper(request, *args, **kwargs):
    if request.user.is_authenticated():
      return view_func(request, *args, **kwargs)
    json_resp = json.dumps({ 'not_authenticated': True })
    return HttpResponse(json_resp, content_type='application/json')
  return wrapper

def feed(request, page_nr, sort):
  page = int(page_nr)
  dweets_per_page = 10
  first = (page - 1) * dweets_per_page
  last = page * dweets_per_page
  dweet_count = Dweet.objects.count()

  if(first < 0 or first > dweet_count):
    raise Http404("No such page")
  if(last >= dweet_count ):
    last = dweet_count;

  if(sort == "top"):
      dweet_list = Dweet.objects.annotate(num_likes=Count('likes')).order_by('-num_likes')[first:last];
      next_url =  reverse('top_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('top_feed_page', kwargs={'page_nr': page - 1})
  elif (sort == "new"):
      dweet_list = Dweet.objects.order_by('-posted')[first:last];
      next_url =  reverse('new_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('new_feed_page', kwargs={'page_nr': page - 1})
  elif (sort == "hot"):
      dweet_list = Dweet.objects.annotate(num_likes=Count('likes')).order_by('-num_likes')[first:last];

      next_url =  reverse('hot_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('hot_feed_page', kwargs={'page_nr': page - 1})
  else:
    raise Http404("No such sorting method " + sort)

  context = {'dweet_list': dweet_list
            ,'header_title': 'Dwitter'
            ,'feed_type': 'all'
            ,'page_nr': page
            ,'next_url': next_url
            ,'prev_url': prev_url
            ,'sort': sort
            }
  return render(request, 'feed/feed.html', context );

@login_required
def dweet(request):
  d = Dweet(code = request.POST['code']
      , author = request.user
      , posted = timezone.now() )
  d.save()
  return HttpResponseRedirect(reverse('root'))

@login_required
def dweet_reply(request, dweet_id):
  reply_to = get_object_or_404(Dweet, id=dweet_id)
  d = Dweet(code = request.POST['code']
      , reply_to = reply_to
      , author = request.user
      , posted = timezone.now() )
  d.save()
  return HttpResponseRedirect(reverse('root'))

@login_required
def dweet_delete(request, dweet_id):
  dweet = get_object_or_404(Dweet, id=dweet_id)
  if(dweet.author == request.user):
      dweet.delete()
      return HttpResponseRedirect(reverse('root'))

  return HttpResponse("Not authorized to delete the dweet.")

@ajax_login_required
def like(request, post_id):
  dweet = get_object_or_404(Dweet, id=post_id)

  if(dweet.likes.filter(id=request.user.id).exists()):
    liked = False
    dweet.likes.remove(request.user)
  else:
    liked = True
    dweet.likes.add(request.user)
  dweet.save()
  json_resp = json.dumps({'likes': dweet.likes.count(), 'liked': liked})
  return HttpResponse(json_resp, content_type='application/json')
<commit_msg>Import Comment to views.py<commit_after>from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.db.models import Count
from dwitter.models import Dweet
from dwitter.models import Comment
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils import timezone
from functools import wraps
import json

def ajax_login_required(view_func):
  @wraps(view_func)
  def wrapper(request, *args, **kwargs):
    if request.user.is_authenticated():
      return view_func(request, *args, **kwargs)
    json_resp = json.dumps({ 'not_authenticated': True })
    return HttpResponse(json_resp, content_type='application/json')
  return wrapper

def feed(request, page_nr, sort):
  page = int(page_nr)
  dweets_per_page = 10
  first = (page - 1) * dweets_per_page
  last = page * dweets_per_page
  dweet_count = Dweet.objects.count()

  if(first < 0 or first > dweet_count):
    raise Http404("No such page")
  if(last >= dweet_count ):
    last = dweet_count;

  if(sort == "top"):
      dweet_list = Dweet.objects.annotate(num_likes=Count('likes')).order_by('-num_likes')[first:last];
      next_url =  reverse('top_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('top_feed_page', kwargs={'page_nr': page - 1})
  elif (sort == "new"):
      dweet_list = Dweet.objects.order_by('-posted')[first:last];
      next_url =  reverse('new_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('new_feed_page', kwargs={'page_nr': page - 1})
  elif (sort == "hot"):
      dweet_list = Dweet.objects.annotate(num_likes=Count('likes')).order_by('-num_likes')[first:last];

      next_url =  reverse('hot_feed_page', kwargs={'page_nr': page + 1})
      prev_url =  reverse('hot_feed_page', kwargs={'page_nr': page - 1})
  else:
    raise Http404("No such sorting method " + sort)

  context = {'dweet_list': dweet_list
            ,'header_title': 'Dwitter'
            ,'feed_type': 'all'
            ,'page_nr': page
            ,'next_url': next_url
            ,'prev_url': prev_url
            ,'sort': sort
            }
  return render(request, 'feed/feed.html', context );

@login_required
def dweet(request):
  d = Dweet(code = request.POST['code']
      , author = request.user
      , posted = timezone.now() )
  d.save()
  return HttpResponseRedirect(reverse('root'))

@login_required
def dweet_reply(request, dweet_id):
  reply_to = get_object_or_404(Dweet, id=dweet_id)
  d = Dweet(code = request.POST['code']
      , reply_to = reply_to
      , author = request.user
      , posted = timezone.now() )
  d.save()
  return HttpResponseRedirect(reverse('root'))

@login_required
def dweet_delete(request, dweet_id):
  dweet = get_object_or_404(Dweet, id=dweet_id)
  if(dweet.author == request.user):
      dweet.delete()
      return HttpResponseRedirect(reverse('root'))

  return HttpResponse("Not authorized to delete the dweet.")

@ajax_login_required
def like(request, post_id):
  dweet = get_object_or_404(Dweet, id=post_id)

  if(dweet.likes.filter(id=request.user.id).exists()):
    liked = False
    dweet.likes.remove(request.user)
  else:
    liked = True
    dweet.likes.add(request.user)
  dweet.save()
  json_resp = json.dumps({'likes': dweet.likes.count(), 'liked': liked})
  return HttpResponse(json_resp, content_type='application/json')
<|endoftext|>


<commit_before>from os.path import isdir,join,normpath
from os import listdir

from PIL import Image
from numpy import asfarray,dot,argmin,zeros, array, asarray, absolute
from numpy import average,sort,trace,copy
from numpy.linalg import svd,eigh,norm
from numpy import concatenate, reshape
from math import sqrt
import sys

import tkFileDialog
from patsy.util import wide_dtype_for

NUMFEATURES = 4
IMG_WIDTH = 150
IMG_HEIGHT = 220

def parseDirectory(directoryName,extension):
    '''This method returns a list of all filenames in the Directory directoryName.
    For each file the complete absolute path is given in a normalized manner (with
    double backslashes). Moreover only files with the specified extension are returned in
    the list.
    '''
    if not isdir(directoryName): return
    imagefilenameslist=sorted([
        normpath(join(directoryName, fname))
        for fname in listdir(directoryName)
        if fname.lower().endswith('.'+extension)
        ])
    return imagefilenameslist

#####################################################################################
# Implement required functions here
#
#
#

def generateListOfImgs(listOfTrainFiles):
    imgList = []
    for trainFile in listOfTrainFiles:
        imgList.append(Image.open(trainFile))
    return imgList

def convertImgListToNumpyData(imgList):
    imgArrays = []
    for img in imgList:
        imgArray = asfarray(img).reshape((1, -1))[0]
        normalizedImgArray = normalize(imgArray)
        imgArrays.append(normalizedImgArray)
    return asarray(imgArrays)

def normalize(array):
    max = array.max()
    return array / max

def calculateAverageImg(images):
    return average(images, axis=0)

def removeAverageImage(images, avgImage):
    for image in images:
        image -= avgImage
    return images

def calculateEigenfaces(faces, width, height):
    M = len(faces)
    w, v = eigh(faces.T.dot(faces))
    u = faces.dot(v)
    index = w.argsort()[::-1]
    w=w[index]
    u=u[:, index]
    return u

def transformToEigenfaceSpace(eigenfaces, face, numFeatures):
    pointToEigenspace = zeros(shape=(numFeatures))
    for i in range(numFeatures):
        pointToEigenspace[i] = dot((eigenfaces[:,i:i+1].T), face)
    return pointToEigenspace

def imageFromNormalizedArray(array, width=IMG_WIDTH, height=IMG_HEIGHT):
    return Image.fromarray(array.reshape((height, width))*250)

def mergeImage(rArray, gArray, bArray, width=IMG_WIDTH, height=IMG_HEIGHT):
    rChannel = imageFromNormalizedArray(rArray).convert('RGB').split()[0]
    gChannel = imageFromNormalizedArray(gArray).convert('RGB').split()[1]
    bChannel = imageFromNormalizedArray(bArray).convert('RGB').split()[2]
    return Image.merge('RGB', (rChannel, gChannel, bChannel))

####################################################################################
#Start of main programm

#Choose Directory which contains all training images
TrainDir=tkFileDialog.askdirectory(title="Choose Directory of training images")
#Choose the file extension of the image files
Extension='png'

images = convertImgListToNumpyData(generateListOfImgs(parseDirectory(TrainDir, Extension)))

avgImage = calculateAverageImg(copy(images))
normedArrayOfFaces = removeAverageImage(copy(images), avgImage)

#imageFromNormalizedArray(avgImage).show()

eigenfaces = calculateEigenfaces(normedArrayOfFaces.T, len(images[0]), len(images))
transposedFaces = []
for face in normedArrayOfFaces:
    transposedFaces.append(transformToEigenfaceSpace(eigenfaces, face, NUMFEATURES))

#Image.fromarray(avgImage.reshape((220, 150))*250).show()

#Choose the image which shall be recognized
testImageDirAndFilename=tkFileDialog.askopenfilename(title="Choose Image to detect")

testImage = Image.open(testImageDirAndFilename)
testface = convertImgListToNumpyData([testImage])[0]
testface -= avgImage

testface = transformToEigenfaceSpace(eigenfaces, testface, NUMFEATURES)

distance = sys.float_info.max
closestMatchIndex = 0
for index, face in enumerate(transposedFaces):
    newdistance = norm(testface - face)
    if distance > newdistance:
        closestMatchIndex = index
        distance = newdistance

#imageFromNormalizedArray(images[closestMatchIndex]).show()
#testImage.show()

testImageArray = normalize(convertImgListToNumpyData([testImage])[0])

#mergeImage(normalize(images[closestMatchIndex]), avgImage, normalize(testImageArray)).show()
imageFromNormalizedArray(absolute(normalize(images[closestMatchIndex] - testImageArray))).show()

####################################################################################
# Implement required functionality of the main programm here

<commit_msg>refactored imports and funcitons and added distance picture <commit_after>from os.path import isdir, join, normpath
from os import listdir

from PIL import Image
from numpy import asfarray, dot, zeros, asarray, absolute
from numpy import average, copy
from numpy.linalg import eigh, norm
import sys

import tkFileDialog

NUMFEATURES = 6
IMG_WIDTH = 150
IMG_HEIGHT = 220

def parseDirectory(directoryName,extension):
    '''This method returns a list of all filenames in the Directory directoryName.
    For each file the complete absolute path is given in a normalized manner (with
    double backslashes). Moreover only files with the specified extension are returned in
    the list.
    '''
    if not isdir(directoryName): return
    imagefilenameslist=sorted([
        normpath(join(directoryName, fname))
        for fname in listdir(directoryName)
        if fname.lower().endswith('.'+extension)
        ])
    return imagefilenameslist

#####################################################################################
# Implement required functions here
#
#
#

def generateListOfImgs(listOfTrainFiles):
    imgList = []
    for trainFile in listOfTrainFiles:
        imgList.append(Image.open(trainFile))
    return imgList

def convertImgListToNumpyData(imgList):
    imgArrays = []
    for img in imgList:
        imgArray = asfarray(img).reshape((1, -1))[0]
        normalizedImgArray = normalize(imgArray)
        imgArrays.append(normalizedImgArray)
    return asarray(imgArrays)

def normalize(array):
    max = array.max()
    return array / max

def calculateAverageImg(images):
    return average(images, axis=0)

def removeAverageImage(images, avgImage):
    for image in images:
        image -= avgImage
    return images

def calculateEigenfaces(faces, width, height):
    M = len(faces)
    w, v = eigh(faces.T.dot(faces))
    u = faces.dot(v)
    index = w.argsort()[::-1]
    w=w[index]
    u=u[:, index]
    return u

def transformToEigenfaceSpace(eigenfaces, face, numFeatures):
    pointToEigenspace = zeros(shape=(numFeatures))
    for i in range(numFeatures):
        pointToEigenspace[i] = dot((eigenfaces[:,i:i+1].T), face)
    return pointToEigenspace

def imageFromNormalizedArray(array, width=IMG_WIDTH, height=IMG_HEIGHT):
    return Image.fromarray(array.reshape((height, width))*250)

def mergeImage(rArray, gArray, bArray, width=IMG_WIDTH, height=IMG_HEIGHT):
    rChannel = imageFromNormalizedArray(rArray).convert('RGB').split()[0]
    gChannel = imageFromNormalizedArray(gArray).convert('RGB').split()[1]
    bChannel = imageFromNormalizedArray(bArray).convert('RGB').split()[2]
    return Image.merge('RGB', (rChannel, gChannel, bChannel))

def calculateDistance(transposedFaces, testface, imageFileNames):
    distance = sys.float_info.max
    closestMatchIndex = 0
    for index, face in enumerate(transposedFaces):
        newdistance = norm(testface - face)
        print str(newdistance) + " image: " + imageFileNames[index]
        if distance > newdistance:
            closestMatchIndex = index
            distance = newdistance
    return (closestMatchIndex, distance)

####################################################################################
#Start of main programm

#Choose Directory which contains all training images
TrainDir=tkFileDialog.askdirectory(title="Choose Directory of training images")
#Choose the file extension of the image files
Extension='png'

####################################################################################
# Implement required functionality of the main programm here
imageFileNames = parseDirectory(TrainDir, Extension)
images = convertImgListToNumpyData(generateListOfImgs(imageFileNames))

avgImage = calculateAverageImg(copy(images))
normedArrayOfFaces = removeAverageImage(copy(images), avgImage)

#imageFromNormalizedArray(avgImage).show()

eigenfaces = calculateEigenfaces(normedArrayOfFaces.T, len(images[0]), len(images))
transposedFaces = []
for face in normedArrayOfFaces:
    transposedFaces.append(transformToEigenfaceSpace(eigenfaces, face, NUMFEATURES))

#Image.fromarray(avgImage.reshape((220, 150))*250).show()

#Choose the image which shall be recognized
testImageDirAndFilename=tkFileDialog.askopenfilename(title="Choose Image to detect")

testImage = Image.open(testImageDirAndFilename)
testface = convertImgListToNumpyData([testImage])[0]
testface -= avgImage

testface = transformToEigenfaceSpace(eigenfaces, testface, NUMFEATURES)

closestMatchIndex, distance = calculateDistance(transposedFaces, testface, imageFileNames)
print "closest distance: " + str(distance) + " image: " + imageFileNames[closestMatchIndex]
#imageFromNormalizedArray(images[closestMatchIndex]).show()
#testImage.show()

testImageArray = normalize(convertImgListToNumpyData([testImage])[0])
closestMatchArray = normalize(images[closestMatchIndex])
diffToTestArray = absolute(normalize(closestMatchArray - testImageArray))
imageFromNormalizedArray(diffToTestArray).show()

#mergeImage(normalize(images[closestMatchIndex]), avgImage, normalize(testImageArray)).show()
mergeImage(closestMatchArray + diffToTestArray, normalize(closestMatchArray), normalize(closestMatchArray)).show()

<|endoftext|>


<commit_before># hack to return special attributes
from _sys import *

_getframe = Getframe
from javascript import JSObject
from browser import window

brython_debug_mode = __BRYTHON__.debug

base_exec_prefix = __BRYTHON__.brython_path

base_prefix = __BRYTHON__.brython_path

builtin_module_names=__BRYTHON__.builtin_module_names

byteorder='little'

def exc_info():
    exc = __BRYTHON__.current_exception
    if exc is None:
        return(None, None, None)
    return (exc.__class__,exc,exc.traceback)

exec_prefix = __BRYTHON__.brython_path

executable = __BRYTHON__.brython_path+'/brython.js'

def exit(i=None):
    raise SystemExit('')

class flag_class:
  def __init__(self):
      self.debug=0
      self.inspect=0
      self.interactive=0
      self.optimize=0
      self.dont_write_bytecode=0
      self.no_user_site=0
      self.no_site=0
      self.ignore_environment=0
      self.verbose=0
      self.bytes_warning=0
      self.quiet=0
      self.hash_randomization=1

flags = flag_class()

class float_info:
    mant_dig = 53
    max = window.Number.MAX_VALUE
    min = window.Number.MIN_VALUE
    radix = 2

def getfilesystemencoding(*args,**kw):
    """getfilesystemencoding() -> string
    Return the encoding used to convert Unicode filenames in
    operating system filenames."""
    return 'utf-8'

def getrecursionlimit():
    return 200

maxsize=2**63-1

maxunicode=1114111

# Imported from _sys
# path = __BRYTHON__.path
# #path_hooks = list(JSObject(__BRYTHON__.path_hooks))
# meta_path=__BRYTHON__.meta_path

platform = "brython"

prefix = __BRYTHON__.brython_path

version = '.'.join(str(x) for x in __BRYTHON__.version_info[:3])
version += " (default, %s) \n[Javascript 1.5] on Brython" % __BRYTHON__.compiled_date
hexversion = 0x03000000   # python 3.0

class __version_info(object):
    def __init__(self, version_info):
        self.version_info = version_info
        self.major = version_info[0]
        self.minor = version_info[1]
        self.micro = version_info[2]
        self.releaselevel = version_info[3]
        self.serial = version_info[4]

    def __getitem__(self, index):
        if isinstance(self.version_info[index], list):
           return tuple(self.version_info[index])
        return self.version_info[index]

    def hexversion(self):
        try:
          return '0%d0%d0%d' % (self.major, self.minor, self.micro)
        finally:  #probably some invalid char in minor (rc, etc)
          return '0%d0000' % (self.major)

    def __str__(self):
        _s="sys.version(major=%d, minor=%d, micro=%d, releaselevel='%s', serial=%d)"
        return _s % (self.major, self.minor, self.micro,
                     self.releaselevel, self.serial)
        #return str(self.version_info)

    def __eq__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) == other

        raise Error("Error! I don't know how to compare!")

    def __ge__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) >= other

        raise Error("Error! I don't know how to compare!")

    def __gt__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) > other

        raise Error("Error! I don't know how to compare!")

    def __le__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) <= other

        raise Error("Error! I don't know how to compare!")

    def __lt__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) < other

        raise Error("Error! I don't know how to compare!")

    def __ne__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) != other

        raise Error("Error! I don't know how to compare!")

#eventually this needs to be the real python version such as 3.0, 3.1, etc
version_info=__version_info(__BRYTHON__.version_info)

class _implementation:
  def __init__(self):
      self.name='brython'
      self.version = __version_info(__BRYTHON__.implementation)
      self.hexversion = self.version.hexversion()
      self.cache_tag=None

  def __repr__(self):
      return "namespace(name='%s' version=%s hexversion='%s')" % (self.name, self.version, self.hexversion)

  def __str__(self):
      return "namespace(name='%s' version=%s hexversion='%s')" % (self.name, self.version, self.hexversion)

implementation=_implementation()

class _hash_info:
  def __init__(self):
      self.width=32,
      self.modulus=2147483647
      self.inf=314159
      self.nan=0
      self.imag=1000003
      self.algorithm='siphash24'
      self.hash_bits=64
      self.seed_bits=128
      cutoff=0

  def __repr(self):
      #fix me
      return "sys.hash_info(width=32, modulus=2147483647, inf=314159, nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, seed_bits=128, cutoff=0)"

hash_info=_hash_info()

class _float_info:
    """
 |  A structseq holding information about the float type. It contains low level
 |  information about the precision and internal representation.
 |
 |  Brython's float is based on Javascript's Number type which is a
 |  double-precision 64-bit binary format IEEE 754 value
 |  (number between -(2**53 -1) and 2**53 -1). For more information see:
 |
 |     https://developer.mozilla.org/cs/docs/Web/JavaScript/Data_structures
 |     http://en.wikipedia.org/wiki/Double_precision_floating-point_format
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  dig
 |      DBL_DIG -- digits
 |
 |  epsilon
 |      DBL_EPSILON -- Difference between 1 and the next representable float
 |
 |  mant_dig
 |      DBL_MANT_DIG -- mantissa digits
 |
 |  max
 |      DBL_MAX -- maximum representable finite float
 |
 |  max_10_exp
 |      DBL_MAX_10_EXP -- maximum int e such that 10**e is representable
 |
 |  max_exp
 |      DBL_MAX_EXP -- maximum int e such that radix**(e-1) is representable
 |
 |  min
 |      DBL_MIN -- Minimum positive normalizer float
 |
 |  min_10_exp
 |      DBL_MIN_10_EXP -- minimum int e such that 10**e is a normalized
 |
 |  min_exp
 |      DBL_MIN_EXP -- minimum int e such that radix**(e-1) is a normalized float
 |
 |  radix
 |      FLT_RADIX -- radix of exponent
 |
 |  rounds
 |      FLT_ROUNDS -- integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT_ROUNDS macro at
 |                    interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings.
    """
    def __init__(self):
        self.dig = 15
        self.epsilon = 2**(-52)
        self.mant_dig = 53
        self.max = float(2**53-1)
        self.max_exp=2**10
        self.max_10_exp = 308
        self.min = 2**(-1022)
        self.radix=2
        self.rounds=1
        self._tuple = (self.max, self.max_exp, self.max_10_exp, self.min, self.min_exp, self.min_10_exp, self.dig, self.mant_dig, self.epsilon, self.radix, self.rounds)

    def __getitem__(self, k):
        return self._tuple[k]

    def __iter__(self):
        return iter(self._tuple)

warnoptions=[]

def getfilesystemencoding():
    return 'utf-8'

## __stdxxx__ contains the original values of sys.stdxxx
__stdout__ = __BRYTHON__.stdout
__stderr__ = __BRYTHON__.stderr
__stdin__ = __BRYTHON__.stdin

#delete objects not in python sys module namespace
del JSObject
del _implementation
<commit_msg>added some stuff to _float_info to make it work<commit_after># hack to return special attributes
from _sys import *

_getframe = Getframe
from javascript import JSObject
from browser import window

brython_debug_mode = __BRYTHON__.debug

base_exec_prefix = __BRYTHON__.brython_path

base_prefix = __BRYTHON__.brython_path

builtin_module_names=__BRYTHON__.builtin_module_names

byteorder='little'

def exc_info():
    exc = __BRYTHON__.current_exception
    if exc is None:
        return(None, None, None)
    return (exc.__class__,exc,exc.traceback)

exec_prefix = __BRYTHON__.brython_path

executable = __BRYTHON__.brython_path+'/brython.js'

def exit(i=None):
    raise SystemExit('')

class flag_class:
  def __init__(self):
      self.debug=0
      self.inspect=0
      self.interactive=0
      self.optimize=0
      self.dont_write_bytecode=0
      self.no_user_site=0
      self.no_site=0
      self.ignore_environment=0
      self.verbose=0
      self.bytes_warning=0
      self.quiet=0
      self.hash_randomization=1

flags = flag_class()

class float_info:
    mant_dig = 53
    max = window.Number.MAX_VALUE
    min = window.Number.MIN_VALUE
    radix = 2

def getfilesystemencoding(*args,**kw):
    """getfilesystemencoding() -> string
    Return the encoding used to convert Unicode filenames in
    operating system filenames."""
    return 'utf-8'

def getrecursionlimit():
    return 200

maxsize=2**63-1

maxunicode=1114111

# Imported from _sys
# path = __BRYTHON__.path
# #path_hooks = list(JSObject(__BRYTHON__.path_hooks))
# meta_path=__BRYTHON__.meta_path

platform = "brython"

prefix = __BRYTHON__.brython_path

version = '.'.join(str(x) for x in __BRYTHON__.version_info[:3])
version += " (default, %s) \n[Javascript 1.5] on Brython" % __BRYTHON__.compiled_date
hexversion = 0x03000000   # python 3.0

class __version_info(object):
    def __init__(self, version_info):
        self.version_info = version_info
        self.major = version_info[0]
        self.minor = version_info[1]
        self.micro = version_info[2]
        self.releaselevel = version_info[3]
        self.serial = version_info[4]

    def __getitem__(self, index):
        if isinstance(self.version_info[index], list):
           return tuple(self.version_info[index])
        return self.version_info[index]

    def hexversion(self):
        try:
          return '0%d0%d0%d' % (self.major, self.minor, self.micro)
        finally:  #probably some invalid char in minor (rc, etc)
          return '0%d0000' % (self.major)

    def __str__(self):
        _s="sys.version(major=%d, minor=%d, micro=%d, releaselevel='%s', serial=%d)"
        return _s % (self.major, self.minor, self.micro,
                     self.releaselevel, self.serial)
        #return str(self.version_info)

    def __eq__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) == other

        raise Error("Error! I don't know how to compare!")

    def __ge__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) >= other

        raise Error("Error! I don't know how to compare!")

    def __gt__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) > other

        raise Error("Error! I don't know how to compare!")

    def __le__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) <= other

        raise Error("Error! I don't know how to compare!")

    def __lt__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) < other

        raise Error("Error! I don't know how to compare!")

    def __ne__(self,other):
        if isinstance(other, tuple):
           return (self.major, self.minor, self.micro) != other

        raise Error("Error! I don't know how to compare!")

#eventually this needs to be the real python version such as 3.0, 3.1, etc
version_info=__version_info(__BRYTHON__.version_info)

class _implementation:
  def __init__(self):
      self.name='brython'
      self.version = __version_info(__BRYTHON__.implementation)
      self.hexversion = self.version.hexversion()
      self.cache_tag=None

  def __repr__(self):
      return "namespace(name='%s' version=%s hexversion='%s')" % (self.name, self.version, self.hexversion)

  def __str__(self):
      return "namespace(name='%s' version=%s hexversion='%s')" % (self.name, self.version, self.hexversion)

implementation=_implementation()

class _hash_info:
  def __init__(self):
      self.width=32,
      self.modulus=2147483647
      self.inf=314159
      self.nan=0
      self.imag=1000003
      self.algorithm='siphash24'
      self.hash_bits=64
      self.seed_bits=128
      cutoff=0

  def __repr(self):
      #fix me
      return "sys.hash_info(width=32, modulus=2147483647, inf=314159, nan=0, imag=1000003, algorithm='siphash24', hash_bits=64, seed_bits=128, cutoff=0)"

hash_info=_hash_info()

class _float_info:
    """
 |  A structseq holding information about the float type. It contains low level
 |  information about the precision and internal representation.
 |
 |  Brython's float is based on Javascript's Number type which is a
 |  double-precision 64-bit binary format IEEE 754 value
 |  (number between -(2**53 -1) and 2**53 -1). For more information see:
 |
 |     https://developer.mozilla.org/cs/docs/Web/JavaScript/Data_structures
 |     http://en.wikipedia.org/wiki/Double_precision_floating-point_format
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  dig
 |      DBL_DIG -- digits
 |
 |  epsilon
 |      DBL_EPSILON -- Difference between 1 and the next representable float
 |
 |  mant_dig
 |      DBL_MANT_DIG -- mantissa digits
 |
 |  max
 |      DBL_MAX -- maximum representable finite float
 |
 |  max_10_exp
 |      DBL_MAX_10_EXP -- maximum int e such that 10**e is representable
 |
 |  max_exp
 |      DBL_MAX_EXP -- maximum int e such that radix**(e-1) is representable
 |
 |  min
 |      DBL_MIN -- Minimum positive normalized float
 |
 |  min_10_exp
 |      DBL_MIN_10_EXP -- minimum int e such that 10**e is a normalized float
 |
 |  min_exp
 |      DBL_MIN_EXP -- minimum int e such that radix**(e-1) is a normalized float
 |
 |  radix
 |      FLT_RADIX -- radix of exponent
 |
 |  rounds
 |      FLT_ROUNDS -- integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT_ROUNDS macro at
 |                    interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings.
    """
    def __init__(self):
        _number = window.Number
        self.dig = 15
        self.epsilon = _number.EPSILON
        self.mant_dig = 53
        self.max = _number.MAX_VALUE
        self.max_exp=2**10
        self.max_10_exp = 308
        self.min = 2**(-1022)
        self.min_exp = -1021
        self.min_10_exp = -307
        self.radix=2
        self.rounds=1
        self._tuple = (self.max, self.max_exp, self.max_10_exp, self.min, self.min_exp, self.min_10_exp, self.dig, self.mant_dig, self.epsilon, self.radix, self.rounds)

    def __getitem__(self, k):
        return self._tuple[k]

    def __iter__(self):
        return iter(self._tuple)

float_info = _float_info()

warnoptions=[]

def getfilesystemencoding():
    return 'utf-8'

## __stdxxx__ contains the original values of sys.stdxxx
__stdout__ = __BRYTHON__.stdout
__stderr__ = __BRYTHON__.stderr
__stdin__ = __BRYTHON__.stdin

#delete objects not in python sys module namespace
del JSObject
del _implementation
<|endoftext|>


<commit_before>from django.conf import settings
from django.db.models import Count
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404, render, redirect

from mozilla_django_oidc.views import OIDCAuthenticationCallbackView

from moderator.moderate.models import Event, Question, Vote
from moderator.moderate.forms import EventForm, QuestionForm

class OIDCCallbackView(OIDCAuthenticationCallbackView):
    """Override OIDC callback view."""

    def login_failure(self, msg=''):
        """Returns a custom message in case of login failure."""

        if not msg:
            msg = ('Login failed. Make sure you are using a valid email '
                   'address and you are a vouched Mozillian.')
        messages.error(self.request, msg)
        return super(OIDCCallbackView, self).login_failure()

def main(request):
    """Render main page."""
    user = request.user
    if user.is_authenticated():

        events = Event.objects.filter(archived=False)
        if not user.userprofile.is_nda_member:
            events = events.exclude(is_nda=True)
        return render(request, 'index.jinja', {'events': events, 'user': user})
    return render(request, 'index.jinja', {'user': user})

@login_required(login_url='/')
def archive(request):
    """List of all archived events."""
    events_list = Event.objects.filter(archived=True)
    paginator = Paginator(events_list, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')

    try:
        events = paginator.page(page)
    except PageNotAnInteger:
        events = paginator.page(1)
    except EmptyPage:
        events = paginator.page(paginator.num_pages)

    return render(request, 'archive.jinja', {'events': events})

@login_required(login_url='/')
def edit_event(request, slug=None):
    """Creates a new event."""
    user = request.user
    query_args = {
        'created_by': user
    }
    if slug:
        query_args['slug'] = slug

    if user.is_superuser:
        del query_args['created_by']

    event = get_object_or_404(Event, **query_args) if slug else None
    event_form = EventForm(request.POST or None, instance=event, user=user)

    if event_form.is_valid():
        e = event_form.save(commit=False)
        if not event:
            e.created_by = user
        e.save()

        if slug:
            msg = 'Event successfully edited.'
        else:
            msg = 'Event successfully created.'
        messages.success(request, msg)
        return redirect(reverse('main'))

    ctx = {
        'slug': event.slug if event else None,
        'event_form': event_form,
        'event': event,
        'profile': user.userprofile
    }

    return render(request, 'create_event.jinja', ctx)

@login_required(login_url='/')
def delete_event(request, slug):
    """Delete an event."""
    user = request.user
    query_args = {
        'slug': slug,
        'created_by': user
    }
    # Allow superusers to edit all events
    if user.is_superuser:
        del query_args['created_by']

    event = get_object_or_404(Event, **query_args)
    event.delete()
    msg = 'Event successfully deleted.'
    messages.success(request, msg)
    return redirect(reverse('main'))

@login_required(login_url='/')
def show_event(request, e_slug, q_id=None):
    """Render event questions."""
    event = get_object_or_404(Event, slug=e_slug)
    question = None
    user = request.user

    # Do not display NDA events to non NDA members or non employees.
    if event.is_nda and not user.userprofile.is_nda_member:
        raise Http404

    if q_id:
        question = Question.objects.get(id=q_id)

    questions_q = Question.objects.filter(event=event).annotate(vote_count=Count('votes'))
    questions = questions_q.order_by('-vote_count')

    question_form = QuestionForm(request.POST or None, instance=question)

    is_replied = False
    if question_form.is_valid() and not event.archived:
        question_obj = question_form.save(commit=False)
        # Do not change the user if posting a reply
        if not question_obj.id:
            if not question_obj.is_anonymous:
                question_obj.asked_by = user
        elif not user.userprofile.is_admin:
            raise Http404
        else:
            is_replied = True
        question_obj.event = event
        question_obj.save()

        if not Vote.objects.filter(user=user, question=question_obj).exists() and not is_replied:
            Vote.objects.create(user=user, question=question_obj)

        return redirect(reverse('event', kwargs={'e_slug': event.slug}))

    return render(request, 'questions.jinja',
                  {'user': user,
                   'open': not event.archived,
                   'event': event,
                   'questions': questions,
                   'q_form': question_form})

@login_required
def upvote(request, q_id):
    """Upvote question"""

    question = Question.objects.get(pk=q_id)
    user_can_vote = True
    if question.event.is_nda and not request.user.userprofile.is_nda_member:
        user_can_vote = False

    if request.is_ajax() and not question.event.archived and user_can_vote:
        if not Vote.objects.filter(user=request.user, question=question).exists():
            Vote.objects.create(user=request.user, question=question)
        else:
            Vote.objects.filter(user=request.user, question=question).delete()

        response_dict = {
            'current_vote_count': question.votes.count()
        }

        return JsonResponse(response_dict)

    return show_event(request, question.event.slug)
<commit_msg>Do not list NDA event to non-NDA users.<commit_after>from django.conf import settings
from django.db.models import Count
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404, render, redirect

from mozilla_django_oidc.views import OIDCAuthenticationCallbackView

from moderator.moderate.models import Event, Question, Vote
from moderator.moderate.forms import EventForm, QuestionForm

class OIDCCallbackView(OIDCAuthenticationCallbackView):
    """Override OIDC callback view."""

    def login_failure(self, msg=''):
        """Returns a custom message in case of login failure."""

        if not msg:
            msg = ('Login failed. Make sure you are using a valid email '
                   'address and you are a vouched Mozillian.')
        messages.error(self.request, msg)
        return super(OIDCCallbackView, self).login_failure()

def main(request):
    """Render main page."""
    user = request.user
    if user.is_authenticated():

        events = Event.objects.filter(archived=False)
        if not user.userprofile.is_nda_member:
            events = events.exclude(is_nda=True)
        return render(request, 'index.jinja', {'events': events, 'user': user})
    return render(request, 'index.jinja', {'user': user})

@login_required(login_url='/')
def archive(request):
    """List of all archived events."""
    q_args = {
        'archived': True,
    }
    # Filter out NDA events for non-NDA users
    if not request.user.userprofile.is_nda_member and not request.user.is_superuser:
        q_args['is_nda'] = False
    events_list = Event.objects.filter(**q_args)
    paginator = Paginator(events_list, settings.ITEMS_PER_PAGE)
    page = request.GET.get('page')

    try:
        events = paginator.page(page)
    except PageNotAnInteger:
        events = paginator.page(1)
    except EmptyPage:
        events = paginator.page(paginator.num_pages)

    return render(request, 'archive.jinja', {'events': events})

@login_required(login_url='/')
def edit_event(request, slug=None):
    """Creates a new event."""
    user = request.user
    query_args = {
        'created_by': user
    }
    if slug:
        query_args['slug'] = slug

    if user.is_superuser:
        del query_args['created_by']

    event = get_object_or_404(Event, **query_args) if slug else None
    event_form = EventForm(request.POST or None, instance=event, user=user)

    if event_form.is_valid():
        e = event_form.save(commit=False)
        if not event:
            e.created_by = user
        e.save()

        if slug:
            msg = 'Event successfully edited.'
        else:
            msg = 'Event successfully created.'
        messages.success(request, msg)
        return redirect(reverse('main'))

    ctx = {
        'slug': event.slug if event else None,
        'event_form': event_form,
        'event': event,
        'profile': user.userprofile
    }

    return render(request, 'create_event.jinja', ctx)

@login_required(login_url='/')
def delete_event(request, slug):
    """Delete an event."""
    user = request.user
    query_args = {
        'slug': slug,
        'created_by': user
    }
    # Allow superusers to edit all events
    if user.is_superuser:
        del query_args['created_by']

    event = get_object_or_404(Event, **query_args)
    event.delete()
    msg = 'Event successfully deleted.'
    messages.success(request, msg)
    return redirect(reverse('main'))

@login_required(login_url='/')
def show_event(request, e_slug, q_id=None):
    """Render event questions."""
    event = get_object_or_404(Event, slug=e_slug)
    question = None
    user = request.user

    # Do not display NDA events to non NDA members or non employees.
    if event.is_nda and not user.userprofile.is_nda_member:
        raise Http404

    if q_id:
        question = Question.objects.get(id=q_id)

    questions_q = Question.objects.filter(event=event).annotate(vote_count=Count('votes'))
    questions = questions_q.order_by('-vote_count')

    question_form = QuestionForm(request.POST or None, instance=question)

    is_replied = False
    if question_form.is_valid() and not event.archived:
        question_obj = question_form.save(commit=False)
        # Do not change the user if posting a reply
        if not question_obj.id:
            if not question_obj.is_anonymous:
                question_obj.asked_by = user
        elif not user.userprofile.is_admin:
            raise Http404
        else:
            is_replied = True
        question_obj.event = event
        question_obj.save()

        if not Vote.objects.filter(user=user, question=question_obj).exists() and not is_replied:
            Vote.objects.create(user=user, question=question_obj)

        return redirect(reverse('event', kwargs={'e_slug': event.slug}))

    return render(request, 'questions.jinja',
                  {'user': user,
                   'open': not event.archived,
                   'event': event,
                   'questions': questions,
                   'q_form': question_form})

@login_required
def upvote(request, q_id):
    """Upvote question"""

    question = Question.objects.get(pk=q_id)
    user_can_vote = True
    if question.event.is_nda and not request.user.userprofile.is_nda_member:
        user_can_vote = False

    if request.is_ajax() and not question.event.archived and user_can_vote:
        if not Vote.objects.filter(user=request.user, question=question).exists():
            Vote.objects.create(user=request.user, question=question)
        else:
            Vote.objects.filter(user=request.user, question=question).delete()

        response_dict = {
            'current_vote_count': question.votes.count()
        }

        return JsonResponse(response_dict)

    return show_event(request, question.event.slug)
<|endoftext|>


<commit_before>from collections import OrderedDict
import numpy as np

import theano
import theano.tensor as T
#from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.tensor.shared_randomstreams import RandomStreams
import time

#theano.config.compute_test_value = 'warn'
#theano.config.exception_verbosity='high'
#theano.config.profile=True
theano.config.mode = "FAST_RUN"
#theano.config.mode = "FAST_COMPILE"
theano.config.scan.allow_gc =True
theano.config.scan.allow_output_prealloc =False
theano.optimizer_excluding="more_mem"

# initializing
rng = RandomStreams(seed=234)
photons = 10**6
SHELL_MAX = 101

i = T.iscalar('i')
i.tag.test_value = 3

mu_a = T.scalar('mu_a')
# provide Theano with a default test-value
mu_a.tag.test_value = 2.
mu_s = T.scalar('mu_s')
mu_s.tag.test_value = 20.
microns_per_shell = T.scalar('microns_per_shell')
microns_per_shell.tag.test_value = 50.

albedo = mu_s / (mu_s + mu_a)
shells_per_mfp = 1e4/microns_per_shell/(mu_a+mu_s)

x = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
y = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
z = theano.shared(np.zeros(photons, dtype=theano.config.floatX))

u = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
v = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
w = theano.shared(np.ones(photons, dtype=theano.config.floatX))

weight = theano.shared(np.ones(photons, dtype=theano.config.floatX))

heat = theano.shared(np.zeros(SHELL_MAX, dtype=theano.config.floatX))

x_i = x[i]
y_i = x[i]
z_i = z[i]

u_i = u[i]
v_i = v[i]
w_i = w[i]

weight_i = weight[i]

# move
random = rng.uniform(low=0.00003, high=1.)
t = -T.log(random)

x_moved = x_i + u_i*t
y_moved = y_i + v_i*t
z_moved = z_i + w_i*t

# absorb
shell = T.cast(T.sqrt(T.sqr(x_moved) + T.sqr(y_moved) + T.sqr(z_moved))
               * microns_per_shell, 'int32')
shell = T.clip(shell, 0, SHELL_MAX-1)

new_heat = (1.0 - albedo) * weight_i
new_weight = weight_i * albedo

# new direction
xi1 = rng.uniform(low=-1., high=1.)
xi2 = rng.uniform(low=-1., high=1.)
xi_norm = T.sqrt(T.sqr(xi1) + T.sqr(xi2))

t_xi = rng.uniform(low=0.000000001, high=1.)

# rescale xi12 to fit t_xi as norm
xi1 = xi1/xi_norm * T.sqr(t_xi)
xi2 = xi2/xi_norm * T.sqr(t_xi)

u_new_direction = 2. * t_xi - 1.
v_new_direction = xi1 * T.sqrt((1. - T.sqr(u_new_direction)) / t_xi)
w_new_direction = xi2 * T.sqrt((1. - T.sqr(u_new_direction)) / t_xi)

# roulette
weight_for_starting_roulette = 0.001
CHANCE = 0.1
partakes_roulette = T.switch(T.lt(new_weight, weight_for_starting_roulette),
                             1,
                             0)
roulette = rng.uniform(low=0., high=1.)
loses_roulette = T.gt(roulette, CHANCE)
# if roulette decides to terminate the photon: set weight to 0
weight_after_roulette = T.switch(T.and_(partakes_roulette, loses_roulette),
                                 0.,
                                 new_weight)
# if partakes in roulette but does not get terminated
weight_after_roulette = T.switch(T.and_(partakes_roulette, T.invert(loses_roulette)),
                                 weight_after_roulette / CHANCE,
                                 weight_after_roulette)
heat_subtensor = heat[shell]

def one_run(i, mu_a, mu_s, microns_per_shell,
            x, y, z, u, v, w, weight):
    return OrderedDict({heat: T.inc_subtensor(heat_subtensor, new_heat),
                        x: T.set_subtensor(x_i, x_moved),
                        y: T.set_subtensor(y_i, y_moved),
                        z: T.set_subtensor(z_i, z_moved),
                        u: T.set_subtensor(u_i, u_new_direction),
                        v: T.set_subtensor(v_i, v_new_direction),
                        w: T.set_subtensor(w_i, w_new_direction),
                        weight: T.set_subtensor(weight_i, weight_after_roulette)}), \
           theano.scan_module.until(T.isclose(weight_i, 0.))

one_photon_results, one_photon_updates = theano.scan(fn=one_run,
                                                     outputs_info=None,
                                                     non_sequences=[i, mu_a, mu_s, microns_per_shell,
                                                                    x, y, z, u, v, w, weight],
                                                     n_steps=10000,
                                                     strict=True)

final_heat_result = [one_photon_updates[weight], one_photon_updates[heat]]

initial_heat = np.zeros(SHELL_MAX, dtype=theano.config.floatX)

heat_for_one_photon = theano.function(inputs=[i, mu_a, mu_s, microns_per_shell],
                                      outputs=final_heat_result,
                                      updates=one_photon_updates)

start = time.time()

print("start simulation")

print(heat_for_one_photon(0, 2., 20., 50.))

end = time.time()
print("end simulation after: " + str(end - start) + " seconds")

<commit_msg>This version works. However, the (important) scan_module.unitl was removed due to a bug in theano (#3122)<commit_after>from collections import OrderedDict
import numpy as np

import theano
import theano.tensor as T
#from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from theano.tensor.shared_randomstreams import RandomStreams
import time

#theano.config.compute_test_value = 'warn'
#theano.config.exception_verbosity='high'
#theano.config.profile=True
#theano.config.mode = "FAST_RUN"
#theano.config.mode = "FAST_COMPILE"
#theano.config.scan.allow_gc =True
#theano.config.scan.allow_output_prealloc =False
#theano.optimizer_excluding="more_mem"

# initializing
rng = RandomStreams(seed=234)
photons = 10**6
SHELL_MAX = 101

i = T.iscalar('i')
i.tag.test_value = 3

mu_a = T.scalar('mu_a')
# provide Theano with a default test-value
mu_a.tag.test_value = 2.
mu_s = T.scalar('mu_s')
mu_s.tag.test_value = 20.
microns_per_shell = T.scalar('microns_per_shell')
microns_per_shell.tag.test_value = 50.

albedo = mu_s / (mu_s + mu_a)
shells_per_mfp = 1e4/microns_per_shell/(mu_a+mu_s)

x = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
y = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
z = theano.shared(np.zeros(photons, dtype=theano.config.floatX))

u = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
v = theano.shared(np.zeros(photons, dtype=theano.config.floatX))
w = theano.shared(np.ones(photons, dtype=theano.config.floatX))

weight = theano.shared(np.ones(photons, dtype=theano.config.floatX))

heat = theano.shared(np.zeros(SHELL_MAX, dtype=theano.config.floatX))

x_i = x[i]
y_i = x[i]
z_i = z[i]

u_i = u[i]
v_i = v[i]
w_i = w[i]

weight_i = weight[i]

# move
random = rng.uniform(low=0.00003, high=1.)
t = -T.log(random)

x_moved = x_i + u_i*t
y_moved = y_i + v_i*t
z_moved = z_i + w_i*t

# absorb
shell = T.cast(T.sqrt(T.sqr(x_moved) + T.sqr(y_moved) + T.sqr(z_moved))
               * microns_per_shell, 'int32')
shell = T.clip(shell, 0, SHELL_MAX-1)

new_weight = weight_i * albedo

# new direction
xi1 = rng.uniform(low=-1., high=1.)
xi2 = rng.uniform(low=-1., high=1.)
xi_norm = T.sqrt(T.sqr(xi1) + T.sqr(xi2))

t_xi = rng.uniform(low=0.000000001, high=1.)

# rescale xi12 to fit t_xi as norm
xi1 = xi1/xi_norm * T.sqr(t_xi)
xi2 = xi2/xi_norm * T.sqr(t_xi)

u_new_direction = 2. * t_xi - 1.
v_new_direction = xi1 * T.sqrt((1. - T.sqr(u_new_direction)) / t_xi)
w_new_direction = xi2 * T.sqrt((1. - T.sqr(u_new_direction)) / t_xi)

# roulette
weight_for_starting_roulette = 0.001
CHANCE = 0.1
partakes_roulette = T.switch(T.lt(new_weight, weight_for_starting_roulette),
                             1,
                             0)
roulette = rng.uniform(low=0., high=1.)
loses_roulette = T.gt(roulette, CHANCE)
# if roulette decides to terminate the photon: set weight to 0
weight_after_roulette = T.switch(T.and_(partakes_roulette, loses_roulette),
                                 0.,
                                 new_weight)
# if partakes in roulette but does not get terminated
weight_after_roulette = T.switch(T.and_(partakes_roulette, T.invert(loses_roulette)),
                                 weight_after_roulette / CHANCE,
                                 weight_after_roulette)

new_heat = (1.0 - albedo) * weight_i
heat_i = heat[shell]

def one_run(i, mu_a, mu_s, microns_per_shell,
            heat, x, y, z, u, v, w, weight):
    return OrderedDict({heat: T.set_subtensor(heat_i, new_heat),
                        x: T.set_subtensor(x_i, x_moved),
                        y: T.set_subtensor(y_i, y_moved),
                        z: T.set_subtensor(z_i, z_moved),
                        u: T.set_subtensor(u_i, u_new_direction),
                        v: T.set_subtensor(v_i, v_new_direction),
                        w: T.set_subtensor(w_i, w_new_direction),
                        weight: T.set_subtensor(weight_i, weight_after_roulette)})

one_photon_results, one_photon_updates = theano.scan(fn=one_run,
                                                     outputs_info=None,
                                                     non_sequences=[i, mu_a, mu_s, microns_per_shell,
                                                                    heat, x, y, z, u, v, w, weight],
                                                     n_steps=100,
                                                     strict=True)

final_heat_result = one_photon_updates[heat]

initial_heat = np.zeros(SHELL_MAX, dtype=theano.config.floatX)

heat_for_one_photon = theano.function(inputs=[i, mu_a, mu_s, microns_per_shell],
                                      outputs=final_heat_result,
                                      updates=one_photon_updates)

start = time.time()

print("start simulation")

print(heat_for_one_photon(0, 2., 20., 50.))

end = time.time()
print("end simulation after: " + str(end - start) + " seconds")

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from hashlib import md5
from urllib.parse import urlencode

from django.conf import settings
from allauth.socialaccount.models import SocialAccount

SECURE_BASE_URL = 'https://secure.gravatar.com/avatar/'
PROFILE_URL = 'http://www.gravatar.com/'
FACEBOOK_URL = 'http://graph.facebook.com/{}/picture?width=40&height=40'
RATINGS = ('g', 'pg', 'r', 'x')
MAX_SIZE = 512
MIN_SIZE = 1
DEFAULTS = ('404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro')

def email_hash(string):
    return md5(str(string.strip().lower()).encode('utf-8')).hexdigest()

def get_gravatar(email, rating='g', size=80, default='mm'):
    """Generate a link to the users' Gravatar."""
    assert rating.lower() in RATINGS
    assert MIN_SIZE <= size <= MAX_SIZE

    url = SECURE_BASE_URL

    options = (('s', size), ('r', rating), ('d', default))
    url += email_hash(email) + '?' + urlencode(options)
    return url

def get_profile_image(user):
    qset = user.socialaccount_set.all()

    if qset.filter(provider='facebook').exists():
        facebook = qset.filter(provider='facebook').first()
        return FACEBOOK_URL.format(facebook.uid)

    return get_gravatar(user.email)
<commit_msg>Remove unused imports<commit_after># -*- coding: utf-8 -*-
from hashlib import md5
from urllib.parse import urlencode

SECURE_BASE_URL = 'https://secure.gravatar.com/avatar/'
PROFILE_URL = 'http://www.gravatar.com/'
FACEBOOK_URL = 'http://graph.facebook.com/{}/picture?width=40&height=40'
RATINGS = ('g', 'pg', 'r', 'x')
MAX_SIZE = 512
MIN_SIZE = 1
DEFAULTS = ('404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro')

def email_hash(string):
    return md5(str(string.strip().lower()).encode('utf-8')).hexdigest()

def get_gravatar(email, rating='g', size=80, default='mm'):
    """Generate a link to the users' Gravatar."""
    assert rating.lower() in RATINGS
    assert MIN_SIZE <= size <= MAX_SIZE

    url = SECURE_BASE_URL

    options = (('s', size), ('r', rating), ('d', default))
    url += email_hash(email) + '?' + urlencode(options)
    return url

def get_profile_image(user):
    qset = user.socialaccount_set.all()

    if qset.filter(provider='facebook').exists():
        facebook = qset.filter(provider='facebook').first()
        return FACEBOOK_URL.format(facebook.uid)

    return get_gravatar(user.email)
<|endoftext|>


<commit_before>#
# Copyright (C) 2010-2013 by frePPLe bvba
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import jwt
import re
import threading

from django.contrib import auth
from django.contrib.auth import login
from django.contrib.auth.models import AnonymousUser
from django.middleware.locale import LocaleMiddleware as DjangoLocaleMiddleware
from django.utils import translation
from django.db import DEFAULT_DB_ALIAS
from django.http import Http404
from django.conf import settings

from freppledb.common.models import Scenario, User

# A local thread variable to make the current request visible everywhere
_thread_locals = threading.local()

class LocaleMiddleware(DjangoLocaleMiddleware):
  """
  This middleware extends the Django default locale middleware with the user
  preferences used in frePPLe:
    - language choice to override the browser default
    - user interface theme to be used
  """
  def process_request(self, request):
    # Make request information available throughout the application
    setattr(_thread_locals, 'request', request)

    # Authentication through a web token, specified as an URL parameter
    webtoken = request.GET.get('webtoken', None)
    if webtoken:
      # Decode the web token
      try:
        decoded = jwt.decode(
          webtoken,
          settings.DATABASES[request.database].get('SECRET_WEBTOKEN_KEY', settings.SECRET_KEY),
          algorithms=['HS256']
          )
        user = User.objects.get(username=decoded['user'])
        user.backend = settings.AUTHENTICATION_BACKENDS[0]
        login(request, user)
        request.session['navbar'] = decoded.get('navbar', True)
        request.session['xframe_options_exempt'] = True
      except:
        raise Exception('Invalid web token or user')
      language = request.user.language
      request.theme = request.user.theme or settings.DEFAULT_THEME
      request.pagesize = request.user.pagesize or settings.DEFAULT_PAGESIZE
    elif isinstance(request.user, AnonymousUser):
      # Anonymous users don't have preferences
      language = 'auto'
      request.theme = settings.DEFAULT_THEME
      request.pagesize = settings.DEFAULT_PAGESIZE
    else:
      language = request.user.language
      request.theme = request.user.theme or settings.DEFAULT_THEME
      request.pagesize = request.user.pagesize or settings.DEFAULT_PAGESIZE
    if language == 'auto':
      language = translation.get_language_from_request(request)
    if translation.get_language() != language:
      translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    request.charset = settings.DEFAULT_CHARSET

  def process_exception(self, request, exception):
    setattr(_thread_locals, 'request', None)
    return None

  def process_response(self, request, response):
    # Set a clickjacking protection x-frame-option header in the
    # response UNLESS one the following conditions applies:
    #  - a x-trame-options header is already populated
    #  - the view was marked xframe_options_exempt
    #  - a web token was used to authenticate the request
    # See https://docs.djangoproject.com/en/1.10/ref/clickjacking/#module-django.middleware.clickjacking
    # See https://en.wikipedia.org/wiki/Clickjacking
    if not response.get('X-Frame-Options', None) \
      and not getattr(response, 'xframe_options_exempt', False) \
      and not request.session.get('xframe_options_exempt', False):
        response['X-Frame-Options'] = getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper()

    if not response.streaming:
      setattr(_thread_locals, 'request', None)
    # Note: Streaming response get the request field cleared in the
    # request_finished signal handler
    return response

def resetRequest(**kwargs):
  """
  Used as a request_finished signal handler.
  """
  setattr(_thread_locals, 'request', None)

# Initialize the URL parsing middleware
for i in settings.DATABASES:
  settings.DATABASES[i]['regexp'] = re.compile("^/%s/" % i)

class MultiDBMiddleware(object):
  """
  This middleware examines the URL of the incoming request, and determines the
  name of database to use.
  URLs starting with the name of a configured database will be executed on that
  database. Extra fields are set on the request to set the selected database.
  This prefix is then stripped from the path while processing the view.

  If the request has a user, the database of that user is also updated to
  point to the selected database.
  We update the fields:
    - _state.db: a bit of a hack for the django internal stuff
    - is_active
    - is_superuser
  """
  def process_request(self, request):
    request.user = auth.get_user(request)
    if not request.user or request.user.is_anonymous():
      return
    default_scenario = None
    for i in request.user.scenarios:
      if i.name == DEFAULT_DB_ALIAS:
        default_scenario = i
      try:
        if settings.DATABASES[i.name]['regexp'].match(request.path):
          request.prefix = '/%s' % i.name
          request.path_info = request.path_info[len(request.prefix):]
          request.path = request.path[len(request.prefix):]
          request.database = i.name
          request.scenario = i
          request.user._state.db = i.name
          request.user.is_superuser = i.is_superuser
          return
      except:
        pass
    request.prefix = ''
    request.database = DEFAULT_DB_ALIAS
    if default_scenario:
      request.scenario = default_scenario
    else:
      request.scenario = Scenario(name=DEFAULT_DB_ALIAS)<commit_msg>Rest api fix<commit_after>#
# Copyright (C) 2010-2013 by frePPLe bvba
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import jwt
import re
import threading

from django.conf import settings
from django.contrib import auth
from django.contrib.auth import login
from django.contrib.auth.models import AnonymousUser
from django.middleware.locale import LocaleMiddleware as DjangoLocaleMiddleware
from django.utils import translation
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponseNotFound

from freppledb.common.models import Scenario, User

# A local thread variable to make the current request visible everywhere
_thread_locals = threading.local()

class LocaleMiddleware(DjangoLocaleMiddleware):
  """
  This middleware extends the Django default locale middleware with the user
  preferences used in frePPLe:
    - language choice to override the browser default
    - user interface theme to be used
  """
  def process_request(self, request):
    # Make request information available throughout the application
    setattr(_thread_locals, 'request', request)

    # Authentication through a web token, specified as an URL parameter
    webtoken = request.GET.get('webtoken', None)
    if webtoken:
      # Decode the web token
      try:
        decoded = jwt.decode(
          webtoken,
          settings.DATABASES[request.database].get('SECRET_WEBTOKEN_KEY', settings.SECRET_KEY),
          algorithms=['HS256']
          )
        user = User.objects.get(username=decoded['user'])
        user.backend = settings.AUTHENTICATION_BACKENDS[0]
        login(request, user)
        request.session['navbar'] = decoded.get('navbar', True)
        request.session['xframe_options_exempt'] = True
      except:
        raise Exception('Invalid web token or user')
      language = request.user.language
      request.theme = request.user.theme or settings.DEFAULT_THEME
      request.pagesize = request.user.pagesize or settings.DEFAULT_PAGESIZE
    elif isinstance(request.user, AnonymousUser):
      # Anonymous users don't have preferences
      language = 'auto'
      request.theme = settings.DEFAULT_THEME
      request.pagesize = settings.DEFAULT_PAGESIZE
    else:
      language = request.user.language
      request.theme = request.user.theme or settings.DEFAULT_THEME
      request.pagesize = request.user.pagesize or settings.DEFAULT_PAGESIZE
    if language == 'auto':
      language = translation.get_language_from_request(request)
    if translation.get_language() != language:
      translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    request.charset = settings.DEFAULT_CHARSET

  def process_exception(self, request, exception):
    setattr(_thread_locals, 'request', None)
    return None

  def process_response(self, request, response):
    # Set a clickjacking protection x-frame-option header in the
    # response UNLESS one the following conditions applies:
    #  - a x-trame-options header is already populated
    #  - the view was marked xframe_options_exempt
    #  - a web token was used to authenticate the request
    # See https://docs.djangoproject.com/en/1.10/ref/clickjacking/#module-django.middleware.clickjacking
    # See https://en.wikipedia.org/wiki/Clickjacking
    if not response.get('X-Frame-Options', None) \
      and not getattr(response, 'xframe_options_exempt', False) \
      and not request.session.get('xframe_options_exempt', False):
        response['X-Frame-Options'] = getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper()

    if not response.streaming:
      setattr(_thread_locals, 'request', None)
    # Note: Streaming response get the request field cleared in the
    # request_finished signal handler
    return response

def resetRequest(**kwargs):
  """
  Used as a request_finished signal handler.
  """
  setattr(_thread_locals, 'request', None)

# Initialize the URL parsing middleware
for i in settings.DATABASES:
  settings.DATABASES[i]['regexp'] = re.compile("^/%s/" % i)

class MultiDBMiddleware(object):
  """
  This middleware examines the URL of the incoming request, and determines the
  name of database to use.
  URLs starting with the name of a configured database will be executed on that
  database. Extra fields are set on the request to set the selected database.
  This prefix is then stripped from the path while processing the view.

  If the request has a user, the database of that user is also updated to
  point to the selected database.
  We update the fields:
    - _state.db: a bit of a hack for the django internal stuff
    - is_active
    - is_superuser
  """
  def process_request(self, request):
    request.user = auth.get_user(request)
    if not hasattr(request.user, 'scenarios'):
      # A scenario list is not available on the request
      for i in settings.DATABASES:
        try:
          if settings.DATABASES[i]['regexp'].match(request.path):
            scenario = Scenario.objects.get(name=i)
            if scenario.status != 'In use':
              print ('boom')
              return HttpResponseNotFound('Scenario not in use')
            request.prefix = '/%s' % i
            request.path_info = request.path_info[len(request.prefix):]
            request.path = request.path[len(request.prefix):]
            request.database = i
            return
        except Exception as e:
          print(e)
          pass
      request.prefix = ''
      request.database = DEFAULT_DB_ALIAS
    else:
      # A list of scenarios is already available
      if not request.user or request.user.is_anonymous():
        return
      default_scenario = None
      for i in request.user.scenarios:
        if i.name == DEFAULT_DB_ALIAS:
          default_scenario = i
        try:
          if settings.DATABASES[i.name]['regexp'].match(request.path):
            request.prefix = '/%s' % i.name
            request.path_info = request.path_info[len(request.prefix):]
            request.path = request.path[len(request.prefix):]
            request.database = i.name
            request.scenario = i
            request.user._state.db = i.name
            request.user.is_superuser = i.is_superuser
            return
        except:
          pass
      request.prefix = ''
      request.database = DEFAULT_DB_ALIAS
      if default_scenario:
        request.scenario = default_scenario
      else:
        request.scenario = Scenario(name=DEFAULT_DB_ALIAS)
<|endoftext|>


<commit_before>from negotiator_base import BaseNegotiator
from random import random, shuffle
from functools import reduce

# Example negotiator implementation, which randomly chooses to accept
# an offer or return with a randomized counteroffer.
# Important things to note: We always set self.offer to be equal to whatever
# we eventually pick as our offer. This is necessary for utility computation.
# Second, note that we ensure that we never accept an offer of "None".

class Negotiator(BaseNegotiator):
    # Override the make_offer method from BaseNegotiator to accept a given offer 5%
    # of the time, and return a random permutation the rest of the time.

    def __init__(self):
        super().__init__()
        self.current_iter = 0
        self.round_number = 0
        self.utility_history = {}  # keeps track of past opponent utilities
        self.offer_history = {}  # keeps track of past opponent offers
        self.past_offers = []  # keeps track of our past offers

    def make_offer(self, offer):
        #set up history data structure for current round
        if self.round_number not in self.utility_history.keys():
            self.utility_history[self.round_number] = {}
        if self.round_number not in self.offer_history.keys():
            self.offer_history[self.round_number] = {}
        if offer is None:
            # Need to make a first offer to start negotiations
            # This offer does not count towards the number of negotiations
            offer = self.make_first_offer()
            self.past_offers.append(offer)
        elif self.current_iter == self.iter_limit:
            # Last round - update variables, make a last offer
            self.offer_history[self.round_number][self.current_iter] = offer  # record current offer in history
            self.current_iter = 0
            self.round_number += 1
            offer = self.make_final_offer(offer)
        elif offer is not None:
            # In the middle of negotiations, make an offer
            self.current_iter += 1
            self.offer_history[self.round_number][self.current_iter] = offer  # record current offer in history
            offer = self.make_intermediate_offer(offer)
            self.past_offers.append(offer)
        return offer

    def make_first_offer(self):
        print('first offer')
        return self.preferences

    def make_intermediate_offer(self, offer):
        print('in middle of negotiations')
        if offer in self.past_offers:
            self.past_offers = []  # this round of our negotiation is over, we can clear our offer history
            return offer
        return self.preferences

    def make_final_offer(self, offer):
        print('in final inter')
        self.past_offers = []  # this round of our negotiation is over, we can clear our offer history
        if offer in self.past_offers:
            return offer
        return self.preferences

    def receive_utility(self, utility):
        # recieves the utility from the previous negotiation and puts it into the right place in history
        round_hist = self.utility_history[self.round_number]
        round_hist[self.current_iter] = utility
        pass

    def calc_utility(self, offer):
        total = len(self.preferences)
        util = reduce(lambda points, item: points + ((total / (offer.index(item) + 1)) - abs(offer.index(item) - self.preferences.index(item))), offer, 0)
        return util<commit_msg>Merging my AI w/ Monty's Code to be in line w/ floryian<commit_after>from negotiator_base import BaseNegotiator
from random import random, shuffle
from functools import reduce

# Example negotiator implementation, which randomly chooses to accept
# an offer or return with a randomized counteroffer.
# Important things to note: We always set self.offer to be equal to whatever
# we eventually pick as our offer. This is necessary for utility computation.
# Second, note that we ensure that we never accept an offer of "None".

class Negotiator(BaseNegotiator):
    # Override the make_offer method from BaseNegotiator to accept a given offer 5%
    # of the time, and return a random permutation the rest of the time.

    def __init__(self):
        super().__init__()
        self.current_iter = 0
        self.round_number = 0
        self.utility_history = {}  # keeps track of past opponent utilities
        self.offer_history = {}  # keeps track of past opponent offers
        self.past_offers = []  # keeps track of our past offers
        self.goes_last = True

    def make_offer(self, offer):
        #set up history data structure for current round
        if self.round_number not in self.utility_history.keys():
            self.utility_history[self.round_number] = {}
        if self.round_number not in self.offer_history.keys():
            self.offer_history[self.round_number] = {}
        if offer is None:
            # Need to make a first offer to start negotiations, does not go last
            # This offer does not count towards the number of negotiations
            self.goes_last = False
            offer = self.make_first_offer()
            self.past_offers.append(offer)
        elif self.current_iter == self.iter_limit:
            # Last round - update variables, make a last offer
            self.offer_history[self.round_number][self.current_iter] = offer  # record current offer in history
            self.current_iter = 0
            self.round_number += 1
            offer = self.make_final_offer(offer)
        elif offer is not None:
            # In the middle of negotiations, make an offer
            self.current_iter += 1
            self.offer_history[self.round_number][self.current_iter] = offer  # record current offer in history
            offer = self.make_intermediate_offer(offer)
            self.past_offers.append(offer)
        return offer

    def make_first_offer(self):
        # print('first offer')
        return self.preferences

    def make_intermediate_offer(self, offer):
        # print('in middle of negotiations')
        if offer in self.past_offers:
            self.past_offers = []  # this round of our negotiation is over, we can clear our offer history
            return offer
        else:
            self.offer = self.one_up(offer)
            return self.offer

    def make_final_offer(self, offer):
        # print('in final inter')
        self.past_offers = []  # this round of our negotiation is over, we can clear our offer history
        if offer in self.past_offers:
            return offer
        else:
            self.offer = self.one_up(offer)
            return self.offer

    def one_up(self, opponent_offer):
        if opponent_offer is None:
            return self.offer
        if self.offer == opponent_offer:
            return self.offer
        starting_index = 0
        while self.offer[starting_index] == opponent_offer[starting_index]:
            if starting_index == len(self.offer) - 1:
                break
            starting_index += 1
        swap_index = starting_index
        while True:
            if self.offer[swap_index] == opponent_offer[starting_index]:
                break
            else:
                swap_index += 1
        self.offer[starting_index], self.offer[swap_index] = self.offer[swap_index], self.offer[starting_index]
        return self.offer

    def receive_utility(self, utility):
        # recieves the utility from the previous negotiation and puts it into the right place in history
        round_hist = self.utility_history[self.round_number]
        round_hist[self.current_iter] = utility
        pass

    def calc_utility(self, offer):
        # This is the way florian said to do it in class on 4/7
        old_offer = self.offer
        self.offer = offer
        util = self.utility()
        self.offer = old_offer
        return util<|endoftext|>