text:
import re, hashlib, random, json, csv, sys
from datetime import datetime, timedelta, tzinfo
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import caches
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.files.uploadhandler import MemoryFileUploadHandler
from django.core.validators import validate_email
from django.db.models import ProtectedError
from django.forms import ValidationError
from django.forms.models import modelformset_factory, inlineformset_factory
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.template import RequestContext
from django.utils.datastructures import MultiValueDictKeyError
from django.views.defaults import page_not_found, permission_denied, bad_request
from itertools import chain
from polls import models
from polls.includes import forms, email_messages
from pprint import pprint

#################################################
#### PASO DE MENSAJES Y PARAMETROS POR CACHE ####
#################################################

# Crea un mensaje que se mostrara en la siguiente pagina
def set_cache_message(user, msg_type, msg):

	if not user.is_authenticated():
		return

	cache = caches['default']

	if (msg_type == 'error'):
		key = 'error_msg'
	elif (msg_type == 'warning'):
		key = 'warning_msg'
	elif (msg_type == 'success'):
		key = 'success_msg'
	else:
		key = 'info_msg'

	key = hashlib.sha256(('%d_%s' % (user.pk, key)).encode('utf-8')).hexdigest()
	cache.set(key, msg)

# Lee el contenido de las variables de mensaje si existen.
def caches_messages(user):

	if not user.is_authenticated():
		return

	cache = caches['default']

	# Construyo las claves
	error_key = hashlib.sha256(("%d_error_msg" % user.pk).encode('utf-8')).hexdigest()
	warning_key = hashlib.sha256(("%d_warning_msg" % user.pk).encode('utf-8')).hexdigest()
	success_key = hashlib.sha256(("%d_success_msg" % user.pk).encode('utf-8')).hexdigest()
	info_key = hashlib.sha256(("%d_info_msg" % user.pk).encode('utf-8')).hexdigest()

	# Recojo los mensajes
	error_msg = cache.get(error_key, None);
	warning_msg = cache.get(warning_key, None);
	success_msg = cache.get(success_key, None);
	info_msg = cache.get(info_key, None);

	# Limpio las variables
	cache.set(error_key, None);
	cache.set(warning_key, None);
	cache.set(success_key, None);
	cache.set(info_key, None);

	return error_msg, warning_msg, success_msg, info_msg

def set_cache_param(user, name, value):

	if not user.is_authenticated():
		return

	cache = caches['default']

	key = hashlib.sha256(('%d_%s' % (user.pk, name)).encode('utf-8')).hexdigest()
	cache.set(key, value)

def caches_param(user, name):

	if not user.is_authenticated():
		return

	cache = caches['default']

	key = hashlib.sha256(('%d_%s' % (user.pk, name)).encode('utf-8')).hexdigest()
	param = cache.get(key, None)
	cache.set(key, None)

	return param

#################################################
#################################################

def login_view(request):
	login_active = "active"
	login_form = forms.LoginForm()
	reg_form = forms.RegisterForm()
	js_actions = "$('#registerForm').modal('hide')"
	error_msg = ''
	register_error = ''
	info_msg = ''

	if request.user is not None and request.user.is_active:
		try:
			redir = request.GET['next'];
		except 	MultiValueDictKeyError:
			redir = '/polls/home/';

		return HttpResponseRedirect(redir)

	if (request.method == 'POST'):
		if (request.POST['wichform'] == 'registration'):
			reg_form = forms.RegisterForm(request.POST)
			if reg_form.is_valid():
				password = request.POST['password']
				first_name = request.POST['first_name']
				last_name = request.POST['last_name']
				email = request.POST['email']

				new_user = User.objects.create_user(username=email, password=password, first_name=first_name, last_name=last_name, email=email)
				new_user.is_active = False
				new_user.save()

				# Send activation email
				salt = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()[:5]
				activation_key = hashlib.sha256((salt+email).encode('utf-8')).hexdigest()
				key_expires = datetime.now() + timedelta(2)

				new_user_profile = models.UserProfile(user=new_user, activation_key=activation_key, key_expires=key_expires)
				new_user_profile.save()
				new_user_profile.send_activation_email()

				reg_form = forms.RegisterForm()
				info_msg = "Thank you for your registration. You will now receive an activation email. Please activate your account within the next 48 hours."
			else:
				js_actions = "$('#registerForm').modal('show')"
		else:
			login_form = forms.LoginForm(request.POST)
			email = request.POST['email']
			password = request.POST['password']
			user = authenticate(username=email, password=password)
			if user is not None:
				if user.is_active:
					login(request, user)
					try:
						redir = request.GET['next'];
					except 	MultiValueDictKeyError:
						redir = '/polls/home/';

					return HttpResponseRedirect(redir)
				else:
					info_msg = 'Your user has not been activated yet. If the problem persist, please contact us.'
			else:
				error_msg = 'Wrong username or password. Please try again.'

	return render(
					request,
					'polls/login.html',
					context={
						'login_form': login_form,
						'reg_form': reg_form,
						'error_msg': error_msg,
						'info_msg': info_msg,
						'js_actions': js_actions,
						'login_active': login_active,
						'register_error': register_error
					}
				)

def logout_view(request):
	logout(request)
	return HttpResponseRedirect('/polls/login/')

def activate_account(request, activation_key):
	msg = ''
	user_profile = None
	status = False
	try:
		user_profile = models.UserProfile.objects.get(activation_key=activation_key)
		status = user_profile.activate_account(activation_key)
		if not status:
			msg = 'Sorry, your activation link has expired. Please register again.'
		else:
			msg = 'Congratulatins! You have activated your account succesfully. You can now login into BBPolls.'

	except ObjectDoesNotExist:
		msg = "Sorry, your account could not be found or you have already activated your account."

	return render(request, 'polls/activate_account.html',
				{'user_profile':user_profile, 'msg':msg, 'status':status});

@login_required(login_url='/polls/login')
def polls_index(request):
	mypolls_active = 'active'
	js_file = "polls_index.js"

	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True
	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	published_polls = models.Poll.objects.filter(user=request.user, poll_status=models.Poll.ST_PUBLISHED).order_by("publish_date")
	draft_polls = models.Poll.objects.filter(user=request.user, poll_status=models.Poll.ST_DRAFT).order_by("-last_modified")
	archived_polls = models.Poll.objects.filter(user=request.user, poll_status=models.Poll.ST_ARCHIVED).order_by("-archive_date")

	# send_poll_form = forms.SendPollForm()

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/polls_index.html',
							{'published_polls':published_polls,
								'username':request.user.username,
								'draft_polls':draft_polls,
								'archived_polls':archived_polls,
								'error_msg':error_msg,
								'warning_msg':warning_msg,
								'success_msg':success_msg,
								'info_msg':info_msg,
								'js_file':js_file,
								'send_poll_form':forms.SendPollForm(),
								'is_pollster':is_pollster,
								'mypolls_active':mypolls_active});

@login_required(login_url='/polls/login')
def send_poll(request, poll_id):
	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True
	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id)
	except ObjectDoesNotExist:
		set_cache_message(request.user, "error", "Sorry! Poll not found")
		return HttpResponseRedirect("/polls/my-polls/")

	# send_poll_form = forms.SendPollForm(request.POST)

	if (request.method == 'POST'):

		emails_text = request.POST["emails"]
		emails = []

		for line_emails in emails_text.splitlines():
			line_emails = line_emails.strip()
			if (',' in line_emails):
				splited_line = line_emails.split(",")
				for e in splited_line:
					e = e.strip()
					if e != "":
						try:
							validate_email(e)
							emails.append(e.strip())
						except ValidationError:
							continue

			elif (';' in line_emails):
				splited_line = line_emails.split(";")
				for e in splited_line:
					e = e.strip()
					if e != "":
						try:
							validate_email(e)
							emails.append(e.strip())
						except ValidationError:
							continue

			elif (' ' in line_emails):
				splited_line = line_emails.split(" ")
				for e in splited_line:
					e = e.strip()
					if e != "":
						try:
							validate_email(e)
							emails.append(e.strip())
						except ValidationError:
							continue

			elif(line_emails != ""):
				try:
					validate_email(line_emails)
					emails.append(line_emails.strip())
				except ValidationError:
					continue

		emails = list(set(emails))

		if not emails:
			set_cache_message(request.user, "warning", "No emails were found")
		else:
			poll.send_poll(emails)
			set_cache_message(request.user, "success", "Invitations sent!")

	return HttpResponseRedirect("/polls/my-polls/")

@login_required(login_url='/polls/login')
def publish_poll(request, poll_id):
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id)

		if (poll.poll_status == models.Poll.ST_ARCHIVED):
			set_cache_message(request.user, "error", "Sorry! An archived poll cannot be unarchived")
			return HttpResponseRedirect("/polls/my-polls/")
		elif (not poll.is_doable):
			set_cache_message(request.user, "error", "Sorry! Is not possible to publish this poll. At least one question in this poll that cannot be proeprly answered")
			return HttpResponseRedirect("/polls/my-polls/")

	except ObjectDoesNotExist:
		set_cache_message(request.user, "error", "Sorry! Poll not found")
		return HttpResponseRedirect("/polls/my-polls/")

	pprint("PUBLISH Current status: %s" % poll.poll_status, sys.stdout)
	poll.poll_status = models.Poll.ST_PUBLISHED
	poll.publish_date = datetime.now()
	poll.save()
	pprint("PUBLISH Current status: %s" % poll.poll_status, sys.stdout)

	return HttpResponseRedirect('/polls/my-polls/')

@login_required(login_url='/polls/login')
def archive_poll(request, poll_id):
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True
	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id)

		if (poll.poll_status == models.Poll.ST_DRAFT):
			set_cache_message(request.user, "error", "Sorry! Only published polls may be archived")
			return HttpResponseRedirect("/polls/my-polls/")

	except ObjectDoesNotExist:
		set_cache_message(request.user, "error", "Sorry! Poll not found")
		return HttpResponseRedirect("/polls/my-polls/")

	models.Response.objects.filter(poll=poll, is_completed=False).delete()
	pprint("ARCHIVE Current status: %s" % poll.poll_status, sys.stdout)
	poll.poll_status = models.Poll.ST_ARCHIVED
	poll.archive_date = datetime.now()
	poll.save()
	pprint("ARCHIVE Current status: %s" % poll.poll_status, sys.stdout)

	return HttpResponseRedirect('/polls/my-polls/')

@login_required(login_url='/polls/login')
def unpublish_poll(request, poll_id):
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id)

		if (poll.poll_status == models.Poll.ST_ARCHIVED):
			set_cache_message(request.user, "error", "Sorry! An archived poll cannot be unarchived")
			return HttpResponseRedirect("/polls/my-polls/")

	except ObjectDoesNotExist:
		set_cache_message(request.user, "error", "Sorry! Poll not found")
		return HttpResponseRedirect("/polls/my-polls/")

	if (models.Response.objects.filter(poll=poll, is_completed=True)):
		set_cache_message(request.user, "error", "Sorry! This poll has already been answered and cannot be unpublish.")
		return HttpResponseRedirect("/polls/my-polls/")

	models.Response.objects.filter(poll=poll, is_completed=False).delete()
	pprint("UNPUBLISH Current status: %s" % poll.poll_status, sys.stdout)
	poll.poll_status = models.Poll.ST_DRAFT
	poll.save()
	pprint("UNPUBLISH New status: %s" % poll.poll_status, sys.stdout)

	return HttpResponseRedirect('/polls/my-polls/')

@login_required(login_url='/polls/login')
def create_poll(request):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	mypolls_active = 'active'
	js_actions = "$('[data-toggle=\"tooltip\"]').tooltip({html: true})"

	create_form = forms.PollCreateForm(request.POST or None, prefix="create");
	import_form = forms.PollImportForm(request.POST or None, request.FILES or None, prefix="import")

	if(request.method == 'POST'): # Create
		if ('create' in request.POST):
			if create_form.is_valid():
				poll_name = request.POST['create-name'];
				p = models.Poll(name=poll_name, user=request.user)
				p.save();
				return HttpResponseRedirect('/polls/manage-poll/%d/' % p.pk)

		elif ('import' in request.POST): # Import
			if (import_form.is_valid()):
				# Check size
				data = b''
				for chunk in request.FILES['import-import_file'].chunks():
					data+=chunk

				json_data = json.loads(data)
				try:
					poll = models.Poll.import_poll(json_data, request.user)
					return HttpResponseRedirect('/polls/manage-poll/%d/' % poll.pk)
				except ValidationError as ve:
					import_form.errors["import_file"] = [ve.messages[0]]

	return render(request, 'polls/create-poll.html',
								{'create_form':create_form,
									'username':request.user.username,
									'import_form':import_form,
									'js_actions':js_actions,
									'is_pollster':is_pollster,
									'mypolls_active':mypolls_active});

@login_required(login_url='/polls/login')
def manage_poll(request, poll_id):

	mypolls_active = 'active'
	js_file = "manage-poll.js"

	js_actions = "$('[data-toggle=\"tooltip\"]').tooltip({html: true});"

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	scroll = caches_param(request.user, "scroll")
	pprint(scroll, sys.stderr)
	if scroll:
		js_actions += "$('body').scrollTop(%s)" % scroll

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		poll_form = forms.PollForm(instance = poll)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The poll you are trying to access does not exist anymore.");
		return HttpResponseRedirect("/polls/my-polls/")

	can_edit = poll.poll_status == models.Poll.ST_DRAFT;

	if not can_edit:
		poll_form.disable()

	question_queryset = models.Question.objects.filter(poll=poll).order_by('order');

	if (request.method == 'POST' and can_edit):
		poll_form = forms.PollForm(request.POST, instance=poll)
		if poll_form.is_valid():
			poll_form.save()
			return HttpResponseRedirect('/polls/my-polls/')

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/manage-poll.html',
								{'poll_form':poll_form,
									'username':request.user.username,
									'question_queryset':question_queryset,
									'poll':poll,
									'js_file':js_file,
									'js_actions':js_actions,
									'error_msg':error_msg,
									'warning_msg':warning_msg,
									'success_msg':success_msg,
									'info_msg':info_msg,
									'mypolls_active':mypolls_active,
									'is_pollster':is_pollster,
									'can_edit':can_edit});

@login_required(login_url='/polls/login')
def add_question(request, poll_id):
	mypolls_active = 'active'
	js_actions = "$('[data-toggle=\"tooltip\"]').tooltip({html: true})"

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "The poll you are trying to create a question within, does not exist anymore.");
		return HttpResponseRedirect("/polls/my-polls/")

	try:
		response = models.Response.objects.get(poll=poll, is_completed=True)
		set_cache_message(request.user, 'error', "Sorry! The poll has been already answered and cannot be edited.");
		return HttpResponseRedirect("/polls/my-polls/")

	except ObjectDoesNotExist:
		pass

	question_form = forms.AddQuestionForm(request.POST or None)
	BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=3, can_delete=False)
	choice_formset = BaseChoiceFormset()

	if (request.method == 'POST'):
		if (request.POST['submit'] == 'Save'):
			if question_form.is_valid():
				new_question = question_form.save(commit=False)
				new_question.poll = poll
				new_question.save()
				choice_formset = BaseChoiceFormset(request.POST, instance=new_question)
				if choice_formset.is_valid():
					choice_formset.save()
					set_cache_message(request.user, 'success', 'New question created')
					return HttpResponseRedirect('/polls/manage-poll/%s/' % poll_id)

		elif(request.POST['submit'] == 'Save and add new'):
			if question_form.is_valid():
				new_question = question_form.save(commit=False)
				new_question.poll = poll
				new_question.save()
				choice_formset = BaseChoiceFormset(request.POST, instance=new_question)
				if choice_formset.is_valid():
					choice_formset.save()
					question_form = forms.QuestionForm(None)
					set_cache_message(request.user, 'success', 'New question created')
					return HttpResponseRedirect('/polls/manage-poll/%s/add-question/' % poll_id)

		else:
			more_choices = request.POST['number-choices']
			if not more_choices:
				more_choices=0

			try:
				more_choices = int(more_choices)
				if more_choices < 0:
					more_choices = 0

				BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=more_choices+3, can_delete=False)

			except ValueError:
				BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=3, can_delete=False)
			choice_formset = BaseChoiceFormset()

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/manage-question.html',
								{'question_form':question_form,
									'username':request.user.username,
									'poll':poll, 'choice_formset':choice_formset,
									'question_index':poll.number_questions+1,
									'create_question':True,
									'js_actions':js_actions,
									'error_msg':error_msg,
									'warning_msg':warning_msg,
									'success_msg':success_msg,
									'info_msg':info_msg,
									'is_pollster':is_pollster,
									'mypolls_active':mypolls_active});

@login_required(login_url='/polls/login')
def increase_question_order(request, poll_id, question_id, scroll):
	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	mypolls_active = 'active'
	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The question you are trying to increase order to does not exist anymore");
		return HttpResponseRedirect("/polls/manage-poll/%s/" % poll_id)

	pprint(scroll, sys.stderr)
	if scroll:
		set_cache_param(request.user, "scroll", scroll)

	question.increase_order();
	return HttpResponseRedirect("/polls/manage-poll/%s/" % poll_id);

@login_required(login_url='/polls/login')
def decrease_question_order(request, poll_id, question_id, scroll):
	mypolls_active = 'active'

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The question you are trying to decrease order to does not exist anymore");
		return HttpResponseRedirect("/polls/manage-poll/%s/" % poll_id)

	pprint(scroll, sys.stderr)
	if scroll:
		set_cache_param(request.user, "scroll", scroll)

	question.decrease_order();
	return HttpResponseRedirect('/polls/manage-poll/%s/'% poll_id);

@login_required(login_url='/polls/login')
def manage_question(request, poll_id, question_id):
	mypolls_active = 'active'
	manage_only = 'manage-only'
	js_file = "manage-question.js"
	js_actions = "$('[data-toggle=\"tooltip\"]').tooltip({html: true})"

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "The question you are trying to delete does not exist anymore.")
		return HttpResponseRedirect("/polls/manage-poll/%s/" % poll_id)

	can_edit = poll.poll_status == models.Poll.ST_DRAFT;

	i = 0;
	for q in models.Question.objects.filter(poll=poll):
		i +=1;
		if (q.pk == question.pk):
			break;

	BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=0)
	multimedia_sources = models.MultimediaSource.objects.filter(question=question).order_by('media_type')
	choice_formset = BaseChoiceFormset(request.POST or None, instance=question)

	if (request.method == 'POST' and can_edit):
		if (request.POST['submit'] == 'Save'):
			question_form = forms.QuestionForm(request.POST, instance=question)
			if question_form.is_valid():
				question = question_form.save()
				if choice_formset.is_valid():
					choice_formset.save();
					return HttpResponseRedirect('/polls/manage-poll/%s/' % poll_id)
		else:
			more_choices = request.POST['number-choices']
			if not more_choices:
				more_choices=0
			try:
				BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=int(more_choices))
			except ValueError:
				BaseChoiceFormset = inlineformset_factory(models.Question, models.Choice, form=forms.ChoiceForm, extra=0)

	question_form = forms.QuestionForm(instance=question)
	choice_formset = BaseChoiceFormset(instance=question)

	if not can_edit:
		question_form.disable()
		for choice_form in choice_formset:
			choice_form.disable()

	video_message = "You have %d video sources available" % question.number_video_srcs
	if (question.number_video_srcs > 0):
		video_class = "alert-success"
	else:
		video_class = "alert-danger"

	audio_message = "You have %d audio sources available" % question.number_audio_srcs
	if (question.number_audio_srcs > 0):
		audio_class = "alert-success"
	else:
		audio_class = "alert-danger"

	image_message = "You have %d image sources available" % question.number_image_srcs
	if (question.number_image_srcs > 0):
		image_class = "alert-success"
	else:
		image_class = "alert-danger"

	iframe_message = "You have %d iframe sources available" % question.number_iframe_srcs
	if (question.number_iframe_srcs > 0):
		iframe_class = "alert-success"
	else:
		iframe_class = "alert-danger"

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/manage-question.html',
								{'question_form':question_form,
									'username':request.user.username,
									'poll':poll,
									'question_index':i,
									'question_pk':question_id,
									'choice_formset':choice_formset,
									'multimedia_sources':multimedia_sources,
									'manage_only':manage_only,
									'mypolls_active':mypolls_active,
									'create_question':False,
									'error_msg':error_msg,
									'warning_msg':warning_msg,
									'success_msg':success_msg,
									'info_msg':info_msg,
									'image_message': image_message,
									'image_class': image_class,
									'audio_message': audio_message,
									'audio_class': audio_class,
									'video_message': video_message,
									'video_class': video_class,
									'iframe_message': iframe_message,
									'iframe_class': iframe_class,
									'js_file': js_file,
									'js_actions' : js_actions,
									'is_pollster':is_pollster,
									'can_edit':can_edit});

@login_required(login_url='/polls/login')
def clone_poll(request, poll_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		poll.clone()
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The poll you are trying to clone does not exist anymore.")

	return HttpResponseRedirect('/polls/my-polls/')

@login_required(login_url='/polls/login')
def remove_poll(request, poll_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		poll.delete()
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The poll you are trying to clone does not exist anymore.")

	except ProtectedError:
		set_cache_message(request.user, 'error', "Sorry! The poll has been already answered and cannot be removed.")

	return HttpResponseRedirect('/polls/my-polls/')

@login_required(login_url='/polls/login')
def remove_question(request, poll_id, question_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
		question.delete()
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "The question you are trying to delete does not exist anymore.")
		return HttpResponseRedirect('/polls/manage-poll/%s/' % poll_id)

	try:
		response = models.Response.objects.get(poll=poll, is_completed=True)
		set_cache_message(request.user, 'error', "Sorry! The poll have been already answered and cannot be edited.")
		return HttpResponseRedirect('/polls/my-polls/')
	except ObjectDoesNotExist:
		pass

	set_cache_message(request.user, 'success', "Question successfully removed")
	return HttpResponseRedirect('/polls/manage-poll/%s/' % poll.pk)

@login_required(login_url='/polls/login')
def add_multimedia_source(request, poll_id, question_id, source='url'):
	mypolls_active = "active"

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "The question you are trying to delete does not exist anymore.")
		return HttpResponseRedirect('/polls/manage-poll/%s/' % poll_id)

	try:
		response = models.Response.objects.get(poll=poll, is_completed=True)
		set_cache_message(request.user, 'error', "Sorry! The poll has been already answered and cannot be edited.");
		return HttpResponseRedirect("/polls/my-polls/")

	except ObjectDoesNotExist:
		pass

	i = 0;
	for q in models.Question.objects.filter(poll=poll):
		i +=1;
		if (q.pk == question.pk):
			break;

	if (source == 'url'):
		if (request.method  == 'POST'):
			multimedia_form = forms.MultimediaSourceFormURL(request.POST)

			if multimedia_form.is_valid():
				try:
					mmsrc = multimedia_form.save(commit=False)
					mmsrc.question = question
					mmsrc.validate_mime_type()
					mmsrc.save()

					set_cache_message(request.user, 'success', "Multimedia source successfully created")
					return HttpResponseRedirect('/polls/manage-poll/%s/manage-question/%s/' % (poll.pk, question.pk))
				except ValidationError as ve:
					multimedia_form = forms.MultimediaSourceFormURL(request.POST)
					multimedia_form.errors["url_source"] = [ve.messages[0]]
		else:
			multimedia_form = forms.MultimediaSourceFormURL()

	elif (source == 'file'):
		pass
	else:
		pass

	return render(request, 'polls/add-multimedia-source.html',
								{'multimedia_form':multimedia_form,
									'username':request.user.username,
									'poll':poll,
									'question':question,
									'question_index':i,
									'mypolls_active':mypolls_active})

@login_required(login_url='/polls/login')
def remove_multimedia_source(request, poll_id, question_id, mmsrc_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		question = models.Question.objects.get(pk=question_id, poll=poll)
		mmsrc = models.MultimediaSource.objects.get(pk=mmsrc_id, question=question)
		mmsrc.delete()
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "The source you are trying to delete does not exist anymore.")
		return HttpResponseRedirect("/polls/manage-poll/%s/manage-question/%s/" % (poll.pk, question.pk))

	set_cache_message(request.user, 'success', "Multimedia source successfully removed")
	return HttpResponseRedirect("/polls/manage-poll/%s/manage-question/%s/" % (poll.pk, question.pk))

def do_survey(request, poll_id, try_poll=False, invitation_key=None):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False

	try:
		poll = models.Poll.objects.get(pk=poll_id)
	except ObjectDoesNotExist:
		if try_poll:
			set_cache_message(request.user, 'error', "Poll not found.")
			return HttpResponseRedirect('/polls/my-polls/')
		else:
			set_cache_message(request.user, 'error', "Poll not found.")
			return HttpResponseRedirect('/polls/home/')

	# Comprobamos que el usuario tenga permisos parar acceder
	if (invitation_key is not None):
		try:
			poll_invitation = models.AnonymousInvitation.objects.get(poll=poll, key=invitation_key)
			anonymous_poll = True

			if (poll_invitation.response is not None and poll_invitation.response.is_completed):
				return HttpResponseRedirect('/polls/login/')

		except ObjectDoesNotExist:
			return HttpResponseRedirect('/polls/login/?next=/polls/do-poll/%d/' % poll.pk)

	elif (request.user.is_authenticated()):
		print("auth user")
		if (poll.access_type != models.Poll.AT_PUBLIC):
			if ((request.user not in poll.allowed_users.all()
			and request.user.groups not in poll.allowed_groups.all())
			and (request.user != poll.user and not try_poll)):

				print("not allowed user")
				set_cache_message(request.user, 'error', "Sorry! You don't have permission to access this poll.")
				return HttpResponseRedirect('/polls/home/')

		anonymous_poll = False;
	else:
		print("neither invitation_key, neither allowed_user")
		return HttpResponseRedirect('/polls/login/?next=%s' % request.path)

	if (poll.randomize_questions):
		questions = models.Question.objects.filter(poll=poll).order_by('?')
	else:
		questions = models.Question.objects.filter(poll=poll).order_by('order')

	choices = models.Choice.objects.filter(question__in=questions)

	if (not anonymous_poll):
		try:
			response = models.Response.objects.get(poll=poll, user=request.user)
		except ObjectDoesNotExist:
			response = None
	else:
		response = poll_invitation.response

	error_msg = None;
	if (request.method == 'POST') and not try_poll:

		if response is not None:
			response.choices.clear()
			models.Verbatim.objects.filter(response=response).delete()
		else:
			try:
				response = models.Response(poll=poll, user=request.user)
			except ValueError:
				if anonymous_poll:
					response = models.Response(poll=poll, user=None)
					poll_invitation.response = response
					poll_invitation.save()
				else:
					set_cache_message(request.user, 'error', "Unexpected error occurred when attempting to save your response. Please contact the administrator.")
					return HttpResponseRedirect(request.path)

			response.save()

		for field, value in request.POST.items():
			if re.match('^q\d*_choice\d*$', field) == None:
				continue
			try:
				choice = models.Choice.objects.get(pk=int(value), question__poll=poll)
				response.choices.add(choice)

				if not choice.is_fixed:
					v = models.Verbatim(response=response, choice=choice, verbatim=request.POST['%s_verbatim' % choice.pk])
					v.save()

			except (ObjectDoesNotExist, ValueError):
				error_msg = "Corrupted data, please try again."
				break

		if error_msg:
			set_cache_message(request.user, "error", error_msg)
			response.delete();

		else:
			if request.user.is_authenticated():
				error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
			cs = response.choices.all()
			completed = True
			for q in models.Question.objects.filter(poll=poll):
				if not cs.exists():
					completed = False
					break
				cs = cs.exclude(question=q)

			if completed: # Complete also saves the Response
				set_cache_message(request.user, "success", "You have successfully completed the poll. Thank you!")
				response.set_complete()
			else:
				set_cache_message(request.user, "info", "The poll has not been completed. You may finish it in the \"Ongoing Polls\" section at the home page.")

			return HttpResponseRedirect('/polls/home/')

	elif request.user.is_authenticated():
			error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)

	if anonymous_poll:
		template = "non-auth-do_survey.html"
		username = None
	else:
		template = "do_survey.html"
		username = request.user.username

	return render(request, 'polls/%s' % template,
								{'poll':poll,
									'username':username,
									'questions':questions,
									'choices':choices,
									'response':response,
									'try_poll':try_poll,
									'error_msg':error_msg,
									'anonymous_poll':anonymous_poll,
									'is_pollster':is_pollster});

@login_required(login_url='/polls/login')
def review_survey(request, poll_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False

	try:
		poll = models.Poll.objects.get(pk=poll_id)
		response = models.Response.objects.get(poll=poll, user=request.user)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "You have not completed this poll yet.")
		return HttpResponseRedirect('/polls/home/')

	if (not response.is_completed):
		set_cache_message(request.user, 'error', "You have not completed this poll yet.")
		return HttpResponseRedirect('/polls/home/')

	questions = models.Question.objects.filter(poll=poll)
	choices = models.Choice.objects.filter(question__in=questions)

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/review_survey.html',
								{'response':response,
									'username':request.user.username,
									'choices':choices,
									'questions':questions,
									'poll':poll,
									'error_msg':error_msg,
									'is_pollster':is_pollster});

@login_required(login_url='/polls/login')
def remove_response(request, poll_id):
	try:
		response = models.Response.objects.get(poll__pk=poll_id, user=request.user)
		response.delete()
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "You have not completed this poll yet.")

	return HttpResponseRedirect('/polls/home/')

@login_required(login_url='/polls/login')
def home(request):
	home_active = 'active'

	# Checking pollster permission
	try:
		g = request.user.groups.get(name='sys_pollsters')
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False

	public_polls = models.Poll.objects.filter(poll_status=models.Poll.ST_PUBLISHED, access_type=models.Poll.AT_PUBLIC, is_finished=False).exclude(user=request.user)
	restricted_polls = models.Poll.objects.filter(poll_status=models.Poll.ST_PUBLISHED, access_type=models.Poll.AT_RESTRICTED, allowed_groups__in=request.user.groups.all(), is_finished=False).exclude(user=request.user)
	private_polls = models.Poll.objects.filter(poll_status=models.Poll.ST_PUBLISHED, access_type=models.Poll.AT_PRIVATE, allowed_users=request.user, is_finished=False).exclude(user=request.user)

	if (public_polls or restricted_polls or private_polls):

		available_polls = list(chain(public_polls, private_polls, restricted_polls))
	else:
		available_polls = None

	responses = models.Response.objects.filter(user=request.user)
	completed_polls = responses.exclude(is_completed=False)
	ongoing_polls = responses.exclude(is_completed=True, poll__is_finished=False)

	pprint("available_polls before: ", stream=sys.stderr)
	pprint(available_polls, stream=sys.stderr)

	if responses.exists() and available_polls is not None:
		for response in responses:
			if response.poll in available_polls:
				available_polls.remove(response.poll)

	pprint("available_polls after: ", stream=sys.stderr)
	pprint(available_polls, stream=sys.stderr)

	error_msg, warning_msg, success_msg, info_msg = caches_messages(request.user)
	return render(request, 'polls/home.html',
								{'available_polls':available_polls,
									'username':request.user.username,
									'completed_polls':completed_polls,
									'ongoing_polls':ongoing_polls,
									'error_msg':error_msg,
									'warning_msg':warning_msg,
									'success_msg':success_msg,
									'info_msg':info_msg,
									'home_active':home_active,
									'is_pollster':is_pollster});

@login_required(login_url='/polls/login')
def view_stats(request, poll_id):
	mypolls_active = "active"
	css_file = "view_stats.css"
	js_file = "view_stats.js"

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The poll you are trying to see the statistics from, does not exists anymore.")
		return HttpResponseRedirect("/polls/manage-poll/%s/" % poll_id)

	questions = models.Question.objects.filter(poll=poll)
	choices = models.Choice.objects.filter(question__in=questions)
	verbatims = models.Verbatim.objects.filter(choice__in=choices)

	print("Preguntas: %d" % questions.count())
	print("Opciones: %d" % choices.count())
	print("Verbatims: %d" % verbatims.count())

	return render(request, 'polls/view_stats.html',
								{'poll':poll,
									'username':request.user.username,
									'questions':questions,
									'choices':choices,
									'verbatims':verbatims,
									'css_file':css_file,
									'mypolls_active':mypolls_active,
									'is_pollster':is_pollster,
									'js_file':js_file});

@login_required(login_url='/polls/login')
def account(request):
	account_active = 'active'
	password_error = None
	user_error = None
	user_form = forms.UserProfileForm(instance=request.user)
	password_form = forms.PasswordChangeForm()

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False

	if (request.method == 'POST'):

		if (request.POST['submit'] == 'Save'):
			user_form = forms.UserProfileForm(request.POST, instance=request.user)
			if user_form.is_valid():
				user_form.save()

		else:
			password_form = forms.PasswordChangeForm(request.POST)
			if password_form.is_valid():
				old_password = password_form.cleaned_data['old_password']
				password = password_form.cleaned_data['password']
				cpassword = password_form.cleaned_data['confirm_password']

				if not (request.user.check_password(old_password)):
					password_error = 'Wrong password. Please try again.'

				elif (password != cpassword):
					password_error = "New passwords don't match. Please try again."

				else:
					request.user.set_password(password)
					request.user.save()

	return render(request, 'polls/account.html',
								{'user_form':user_form,
									'password_form': password_form,
									'account_active':account_active,
									'username':request.user.username,
									'password_error':password_error,
									'user_error':user_error,
									'is_pollster':is_pollster});

def about(request):
	about_active = 'active'
	is_pollster = False

	if request.user.is_authenticated():
		template = 'polls/about.html'
		username = request.user.username
		# Checking pollster permission
		try:
			g = request.user.groups.get(name="sys_pollsters")
			is_pollster = True

		except ObjectDoesNotExist:
			is_pollster = False

	else:
		username = ''
		template = 'polls/non-auth-about.html'

	return render(request, template, {'about_active':about_active, 'is_pollster':is_pollster, 'username':username});

def contact(request):
	contact_active = 'active'
	is_pollster = False

	if request.user.is_authenticated():
		template = 'polls/contact.html'
		username = request.user.username
		# Checking pollster permission
		try:
			g = request.user.groups.get(name="sys_pollsters")
			is_pollster = True

		except ObjectDoesNotExist:
			pass
	else:
		template = 'polls/non-auth-contact.html'
		username = ''

	return render(request, template, {'contact_active':contact_active, 'is_pollster':is_pollster, 'username':username});

@login_required(login_url='/polls/login')
def export_poll(request, poll_id):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
	except ObjectDoesNotExist:
		set_cache_message(request.user, 'error', "Sorry! The poll you are trying to export does not exist anymore.")
		return HttpResponseRedirect("/polls/my-polls/%s/" % poll_id)

	poll_json =  poll.get_json()
	json_response = JsonResponse(poll_json, safe=False)
	json_response['Content-Disposition'] = 'attachment; filename=%s.json' % poll.name
	return json_response

@login_required(login_url='/polls/login')
def get_csv_stats(request, poll_id, delimiter=','):

	# Checking pollster permission
	try:
		g = request.user.groups.get(name="sys_pollsters")
		is_pollster = True

	except ObjectDoesNotExist:
		is_pollster = False
		set_cache_message(request.user, "error", "Sorry, you don't have permission to access this area. Redirecting to home page...")
		return HttpResponseRedirect('/polls/home/')

	try:
		poll = models.Poll.objects.get(pk=poll_id, user=request.user)
		poll_csv = poll.get_responses_csv()

		csv_response = HttpResponse(content_type='text/csv')
		csv_response['Content-Disposition'] = 'attachment; filename=%s_stats.csv' % poll.name

		writer = csv.writer(csv_response, delimiter=delimiter)
		writer.writerows(poll_csv)

		return csv_response

	except ObjectDoesNotExist:
		 return page_not_found(request)


text:
import React, { PropTypes } from 'react';
import styles from './BannerImage.css';

const BannerImage = ({ url }) => (
  <div
    className={styles.container}
    style={{ backgroundImage: `url('${url}')` }}
  />
);

BannerImage.propTypes = {
  url: PropTypes.string.isRequired,
};

export default BannerImage;

redpajama_set_name: RedPajamaGithub


text:
//Write a program that reads the coefficents a, b and c of a quadratic equation: ax2+bx+c=0 and solves it
//(prints its real roots);

using System;

class QudraticEquation
{
    static void Main()
    {
        double a, b, c;
        bool isValid;
        do
        {
            Console.WriteLine("Please input the coefficent a:");
            isValid = double.TryParse(Console.ReadLine(), out a);
        }
        while (!isValid);
        do
        {
            Console.WriteLine("Please input the coefficent b:");
            isValid = double.TryParse(Console.ReadLine(), out b);
        }
        while (!isValid);
        do
        {
            Console.WriteLine("Please input the coefficent c:");
            isValid = double.TryParse(Console.ReadLine(), out c);
        }
        while (!isValid);
        double d = b * b - 4 * a * c;
        if (d < 0)
            Console.WriteLine("The equation has no real roots.");
        else if (d == 0)
            Console.WriteLine("The equation has one root: {0}", -b / 2 * a);
        else
            Console.WriteLine("The equation has two real roots: {0}, {1}", -(b + Math.Sqrt(d)) / 2 * a, -(b - Math.Sqrt(d)) / 2 * a);
    }
}


text:
var insert = require('./insert')

insert('bulk to string', [{
  name: 'Squirtle', type: 'water'
}, {
  name: 'Starmie', type: 'water'
}, {
  name: 'Lapras', type: 'water'
}, {
  name: 'Charmander', type: 'fire'
}], function (db, t, done) {
  db.runCommand('serverStatus', function (err, resp) {
    t.error(err)
    if (parseFloat(resp.version) < 2.6) return t.end()

    var bulk = db.a.initializeOrderedBulkOp()
    bulk.insert({ item: 'abc123', status: 'A', defaultQty: 500, points: 5 })
    bulk.insert({ item: 'ijk123', status: 'A', defaultQty: 100, points: 10 })
    bulk.find({ item: null }).update({ $set: { item: 'TBD' } })
    bulk.find({ status: 'D' }).removeOne()

    var result = bulk.toString()
    t.equals(typeof result, 'string', 'bulk.toString() should return a string')
    result = JSON.parse(result)
    t.equals(result.nInsertOps, 2, 'Should result in nInsertOps field set to 2')
    t.equals(result.nUpdateOps, 1, 'Should result in nUpdateOps field set to 1')
    t.equals(result.nRemoveOps, 1, 'Should result in nRemoveOps field set to 1')
    t.equals(result.nBatches, 3, 'Should result in nBatches field set to 3')

    done()
  })
})


text:
<?php

class PagesCache extends CacheManager
{

	public function getCachedFilePathForPath($path)
	{
		if (!$path) return false;
		$path_md5 = md5($path);
		return $this->getCacheDir() . '/' . $path_md5 . '.php';
	}

	public function isCachedPageAtPathExists($path)
	{
		if (!$path) return false;
		return file_exists($this->getCachedFilePathForPath($path));
	}

	public function getCachedHTMLAtPath($path)
	{
		if (!$path) return false;
		if ($this->isCachedPageAtPathExists($path)){
			$expiration = $this->getCacheTimeStampTime();
			if (!$expiration) $expiration = 0;
			$cachedPage = include($this->getCachedFilePathForPath($path));
			if (!($cachedPage instanceof PageCache)) return false;
			if (!$cachedPage->isValid($expiration)) return false;
			return $cachedPage;
		} else
			return false;
	}

	public function createCachedPageForPathWithTemplate($path, $template)
	{
		if (!$path) return false;
		$str = '<?php $template = <<<EOTMUESLI' . "\n" . (string)$template . "\nEOTMUESLI;\n" . 'return new PageCache('.time().', $template);';
		return $this->save($this->getCachedFilePathForPath($path), $str);
	}

	public function resetCache()
	{
		$this->saveCacheTimeStampFile();
	}

	protected function saveCacheTimeStampFile()
	{
		$str = time();
		$this->save($this->getCacheTimeStampFilename(), $str);
	}
	protected function getCacheTimeStampFilename()
	{
		return $this->getCacheDir() . '/expired.php';
	}
	public function getCacheTimeStampTime()
	{
		$filename = $this->getCacheTimeStampFilename();
		if (!file_exists($filename)) return false;
		$timestamp = file_get_contents($filename);
		return $timestamp;
	}
}


text:
/*
 *
 * JAProcessInfo.h
 *
 * Author: http://jongampark.wordpress.com/2008/01/26/a-simple-objectie-c-class-for-checking-if-a-specific-process-is-running/
 *
 */
#import "JAProcessInfo.h"

#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <sys/sysctl.h>

typedef struct kinfo_proc kinfo_proc;

@implementation JAProcessInfo
- (id) init
{
    self = [super init];

    if (self != nil)
    {
        numberOfProcesses = -1; // means "not initialized"
        processList = NULL;
    }

    return self;
}

- (int)numberOfProcesses
{
    return numberOfProcesses;
}

- (void)setNumberOfProcesses:(int)num
{
    numberOfProcesses = num;
}

- (int)getBSDProcessList:(kinfo_proc **)procList
   withNumberOfProcesses:(size_t *)procCount
{
    int             err;
    kinfo_proc *    result;
    bool            done;
    static const int    name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
    size_t          length;

    // a valid pointer procList holder should be passed
    assert( procList != NULL );
    // But it should not be pre-allocated
    assert( *procList == NULL );
    // a valid pointer to procCount should be passed
    assert( procCount != NULL );

    *procCount = 0;

    result = NULL;
    done = false;

    do
    {
        assert( result == NULL );

        // Call sysctl with a NULL buffer to get proper length
        length = 0;
        err = sysctl((int *)name,(sizeof(name)/sizeof(*name))-1,NULL,&length,NULL,0);
        if( err == -1 )
            err = errno;

        // Now, proper length is optained
        if( err == 0 )
        {
            result = malloc(length);
            if( result == NULL )
                err = ENOMEM;   // not allocated
        }

        if( err == 0 )
        {
            err = sysctl( (int *)name, (sizeof(name)/sizeof(*name))-1, result, &length, NULL, 0);
            if( err == -1 )
                err = errno;

            if( err == 0 )
                done = true;
            else if( err == ENOMEM )
            {
                assert( result != NULL );
                free( result );
                result = NULL;
                err = 0;
            }
        }
    }while ( err == 0 && !done );

    // Clean up and establish post condition
    if( err != 0 && result != NULL )
    {
        free(result);
        result = NULL;
    }

    *procList = result; // will return the result as procList
    if( err == 0 )
        *procCount = length / sizeof( kinfo_proc );

    assert( (err == 0) == (*procList != NULL ) );

    return err;
}

- (void)obtainFreshProcessList
{
    int i;
    kinfo_proc *allProcs = 0;
    size_t numProcs;
    NSString *procName;

    int err =  [self getBSDProcessList:&allProcs withNumberOfProcesses:&numProcs];
    if( err )
    {
        numberOfProcesses = -1;
        processList = NULL;

        return;
    }

    // Construct an array for ( process name )
    processList = [NSMutableArray arrayWithCapacity:numProcs];
    for( i = 0; i < numProcs; i++ )
    {
        procName = [NSString stringWithFormat:@"%s", allProcs[i].kp_proc.p_comm];
        [processList addObject:procName];
    }

    [self setNumberOfProcesses:numProcs];

    // NSLog(@"# of elements = %d total # of process = %d\n",
    //         [processArray count], numProcs );

    free( allProcs );

}

- (BOOL)findProcessWithName:(NSString *)procNameToSearch
{
    int index;

    index = [processList indexOfObject:procNameToSearch];

    if( index == -1 )
        return NO;
    else
        return YES;
}
@end


text:
namespace password_manager {

TestPasswordStore::TestPasswordStore()
    : PasswordStore(base::MessageLoopProxy::current(),
                    base::MessageLoopProxy::current()) {
}

TestPasswordStore::~TestPasswordStore() {
}

const TestPasswordStore::PasswordMap& TestPasswordStore::stored_passwords()
    const {
  return stored_passwords_;
}

void TestPasswordStore::Clear() {
  stored_passwords_.clear();
}

bool TestPasswordStore::IsEmpty() const {
  // The store is empty, if the sum of all stored passwords across all entries
  // in |stored_passwords_| is 0.
  size_t number_of_passwords = 0u;
  for (PasswordMap::const_iterator it = stored_passwords_.begin();
       !number_of_passwords && it != stored_passwords_.end(); ++it) {
    number_of_passwords += it->second.size();
  }
  return number_of_passwords == 0u;
}

bool TestPasswordStore::FormsAreEquivalent(const autofill::PasswordForm& lhs,
                                           const autofill::PasswordForm& rhs) {
  return lhs.origin == rhs.origin &&
      lhs.username_element == rhs.username_element &&
      lhs.username_value == rhs.username_value &&
      lhs.password_element == rhs.password_element &&
      lhs.signon_realm == rhs.signon_realm;
}

void TestPasswordStore::GetAutofillableLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
  ScopedVector<autofill::PasswordForm> results;
  for (const auto& forms_for_realm : stored_passwords_) {
    for (const autofill::PasswordForm& form : forms_for_realm.second)
      results.push_back(new autofill::PasswordForm(form));
  }
  request->NotifyConsumerWithResults(results.Pass());
}

PasswordStoreChangeList TestPasswordStore::AddLoginImpl(
    const autofill::PasswordForm& form) {
  PasswordStoreChangeList changes;
  stored_passwords_[form.signon_realm].push_back(form);
  changes.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form));
  return changes;
}

PasswordStoreChangeList TestPasswordStore::UpdateLoginImpl(
    const autofill::PasswordForm& form) {
  PasswordStoreChangeList changes;
  std::vector<autofill::PasswordForm>& forms =
      stored_passwords_[form.signon_realm];
  for (std::vector<autofill::PasswordForm>::iterator it = forms.begin();
       it != forms.end(); ++it) {
    if (FormsAreEquivalent(form, *it)) {
      *it = form;
      changes.push_back(PasswordStoreChange(PasswordStoreChange::UPDATE, form));
    }
  }
  return changes;
}

PasswordStoreChangeList TestPasswordStore::RemoveLoginImpl(
    const autofill::PasswordForm& form) {
  PasswordStoreChangeList changes;
  std::vector<autofill::PasswordForm>& forms =
      stored_passwords_[form.signon_realm];
  std::vector<autofill::PasswordForm>::iterator it = forms.begin();
  while (it != forms.end()) {
    if (FormsAreEquivalent(form, *it)) {
      it = forms.erase(it);
      changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
    } else {
      ++it;
    }
  }
  return changes;
}

ScopedVector<autofill::PasswordForm> TestPasswordStore::FillMatchingLogins(
    const autofill::PasswordForm& form,
    PasswordStore::AuthorizationPromptPolicy prompt_policy) {
  ScopedVector<autofill::PasswordForm> matched_forms;
  std::vector<autofill::PasswordForm> forms =
      stored_passwords_[form.signon_realm];
  for (const auto& stored_form : forms) {
    matched_forms.push_back(new autofill::PasswordForm(stored_form));
  }
  return matched_forms.Pass();
}

void TestPasswordStore::ReportMetricsImpl(const std::string& sync_username,
                                          bool custom_passphrase_sync_enabled) {
}

PasswordStoreChangeList TestPasswordStore::RemoveLoginsCreatedBetweenImpl(
    base::Time begin,
    base::Time end) {
  PasswordStoreChangeList changes;
  return changes;
}

PasswordStoreChangeList TestPasswordStore::RemoveLoginsSyncedBetweenImpl(
    base::Time begin,
    base::Time end) {
  PasswordStoreChangeList changes;
  return changes;
}

void TestPasswordStore::GetBlacklistLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
}

bool TestPasswordStore::FillAutofillableLogins(
    ScopedVector<autofill::PasswordForm>* forms) {
  return true;
}

bool TestPasswordStore::FillBlacklistLogins(
    ScopedVector<autofill::PasswordForm>* forms) {
  return true;
}

void TestPasswordStore::AddSiteStatsImpl(const InteractionsStats& stats) {
}

void TestPasswordStore::RemoveSiteStatsImpl(const GURL& origin_domain) {
}

scoped_ptr<InteractionsStats> TestPasswordStore::GetSiteStatsImpl(
    const GURL& origin_domain) {
  return scoped_ptr<InteractionsStats>();
}

}  // namespace password_manager


text:
author: slowe
comments: true
date: 2013-04-17 19:06:44+00:00
layout: post
slug: openstack-summit-2013-openstack-high-availability-in-grizzly-and-beyond
title: 'OpenStack Summit 2013: OpenStack High Availability in Grizzly and Beyond'
wordpress_id: 3153
categories: Liveblog
tags:
- OpenStack
- Storage
- Networking
---

This is a session titled "More Reliable, More Resilient, More Redundant: OpenStack High Availability in Grizzly and Beyond." The presenter is Florian Haas from Hastexo (@hastexo). Florian is one of the founders of Hastexo, which is a services firm that provides OpenStack services, among other things.

There are four things that need to be addressed when discussing high availability:

* Infrastructure

* Storage

* Compute

* Networking

The presentation starts with a discussion of the infrastructure layer. Changes from Folsom to Grizzly are relatively few. Examples of infrastructure services like the databases (typically MySQL, sometimes PostgreSQL), AMQP (message queue; could be using RabbitMQ, ZeroMQ, etc.), and API services. With regard to infrastructure HA, there are 5 types of infrastructure nodes:

1. Cloud controller

2. API node

3. Network node

4. Compute node

5. Storage controller

The cloud controller runs services that underpin OpenStack. It runs a relational database, an AMQP server, registry services, etc. The ability for an implementation to use active/passive or active/active depends largely on the specific back-end applications in use. Largely, cloud controllers will be deployed active/passive (this is due, in part at least, to the persistent data storage found in the relational databases).

API nodes are fundamentally stateless (locally); it interacts with the AMQP message bus. For most API services, we can use active/active scale-out approaches for API services.

The network node is, according to the presenter, "interesting." This node takes care of routing between tenant networks, provider networks, and upstream networks. The network node typically also runs the DHCP agent to provide IP addresses to tenant systems. We'll come back to the network node shortly.

The compute node is the hypervisor itself, where guest VMs/instances actually execute.

The storage controller depends greatly on what kind of back-end block storage. The block storage server (Cinder server) might have no local storage (which might be the case if you were running with Ceph, for example) or it might have lots of local storage.

All five of these infrastructure node types can use the same high availability stack, but with a few minor differences. The "recommended" high availability stack is Pacemaker. Hastexo has reference configurations for using Pacemaker with all OpenStack infrastructure services. According to the presenter, "it's not rocket science---you can do it."

The presenter next shows a diagram of an architecture using Pacemaker and Corosync for high availability of the cloud controller. From there he shows an example of using Pacemaker/Corosync for high availability of the stateless API services.

From here, he moves on to discuss HA for compute in a bit more detail. Grizzly addresses guest HA. He shows a hack where you "override" a couple of parameters to "trick" Nova into restarting VMs on another host after the first host fails. Unfortunately, this hack breaks live migration and is unsafe with Cinder volumes (although the Cinder issue is fixable).

In Grizzly, Nova has a `nova evacuate` command, but this command actually only works _after_ a host has failed. This evacuation functionality isn't present in Horizon (the Dashboard).

Another interesting feature is VM Ensembles. This feature allows you to group guests in a resilient fashion. The presenter provides an example of 6 VMs (2 each of three tiers), and the desire to make sure that the redundant nodes aren't running on the same compute node. (For VMware users, this would be analogous to anti-affinity rules.) Unfortunately, this feature did not make it into the Grizzly release (it should be in Havana). A workaround would be to use a scheduler filter.

Looking in more detail at Networking, the same HA architecture (Pacemaker/Corosync) worked reasonably well in Folsom for Quantum-server and L3 agent. It didn't work so well for the DHCP agent. However, this active/passive approach didn't scale well. Grizzly helps address this by running multiple DHCP agents and multiple L3 agents to provide better scale-out support (via the Quantum scheduler).

Finally, the presenter moves on to discuss storage. Grizzly has dramatically expanded the amount of support within Cinder for block storage options; the presenter highly recommends upgrading to Grizzly if you need expanded Cinder support. He briefly mentions new Cinder drivers for NFS, GlusterFS, 3Par, LeftHand, EMC, and others. Pacemaker/Corosync is needed for the Cinder volume server. There is a hack required (need to override a host value in the database) in order to provide high availability for the Cinder volume server. It's possible that this hack will be fixed in Havana (a bug has already been filed to fix it).

A few other tidbits:

* Libvirt watchdog support in Nova and Glance is coming

* Heat will bring some additional high availability features (Heat is now an integrated project and will be fully supported with Havana, as will Ceilometer)

* The RabbitMQ library (Kombu) has gained the ability to have a list of queue hosts to which to connect (instead of just a single host)

* ZeroMQ (peer-to-peer messaging) is another interesting option

* MySQL/Galera is firming up to provide write-set replication (which will enable synchronous replication)

* Some changes are occurring within RBD when you use it for both Glance and Cinder (the presenter did not elaborate)

At this point, the presenter wrapped up the session by opening up for questions and answers.


text:
{% assign contact = site.data.contact %}
{% capture index_url %}{{ site.baseurl }}/{% endcapture %}

        Copyright © 2015 – {{ site.time | date: "%Y" }} Daniel Limberger{% comment %}, Privacy Policy{% endcomment %}

<data hidden value="{{ site.data.gitrev.revision }}">revision</data>

#

#

  ‹
  ›
  ×


text:
from time import time
from copy import copy
from threading import Lock
from rospy import Publisher, SubscribeListener
from rospy import logwarn
from rostopic import get_topic_type
from rosbridge_library.internal import ros_loader, message_conversion
from rosbridge_library.internal.topics import TopicNotEstablishedException, TypeConflictException

class PublisherConsistencyListener(SubscribeListener):
    """ This class is used to solve the problem that sometimes we create a
    publisher and then immediately publish a message, before the subscribers
    have set up their connections.

    Call attach() to attach the listener to a publisher.  It sets up a buffer
    of outgoing messages, then when a new connection occurs, sends the messages
    in the buffer.

    Call detach() to detach the listener from the publisher and restore the
    original publish methods.

    After some particular timeout (default to 1 second), the listener stops
    buffering messages as it is assumed by this point all subscribers will have
    successfully set up their connections."""

    timeout = 1  # Timeout in seconds to wait for new subscribers
    attached = False

    def attach(self, publisher):
        """ Overrides the publisher's publish method, and attaches a subscribe
        listener to the publisher, effectively routing incoming connections
        and outgoing publish requests through this class instance """
        # Do the attaching
        self.publisher = publisher
        publisher.impl.add_subscriber_listener(self)
        self.publish = publisher.publish
        publisher.publish = self.publish_override

        # Set state variables
        self.lock = Lock()
        self.established_time = time()
        self.msg_buffer = []
        self.attached = True

    def detach(self):
        """ Restores the publisher's original publish method and unhooks the
        subscribe listeners, effectively finishing with this object """
        self.publisher.publish = self.publish
        if self in self.publisher.impl.subscriber_listeners:
            self.publisher.impl.subscriber_listeners.remove(self)
        self.attached = False

    def peer_subscribe(self, topic_name, topic_publish, peer_publish):
        """ Called whenever there's a new subscription.

        If we're still inside the subscription setup window, then we publish
        any buffered messages to the peer.

        We also check if we're timed out, but if we are we don't detach (due
        to threading complications), we just don't propagate buffered messages
        """
        if not self.timed_out():
            self.lock.acquire()
            msgs = copy(self.msg_buffer)
            self.lock.release()
            for msg in msgs:
                peer_publish(msg)

    def timed_out(self):
        """ Checks to see how much time has elapsed since the publisher was
        created """
        return time() - self.established_time > self.timeout

    def publish_override(self, message):
        """ The publisher's publish method is replaced with this publish method
        which checks for timeout and if we haven't timed out, buffers outgoing
        messages in preparation for new subscriptions """
        if not self.timed_out():
            self.lock.acquire()
            self.msg_buffer.append(message)
            self.lock.release()
        self.publish(message)

class MultiPublisher():
    """ Keeps track of the clients that are using a particular publisher.

    Provides an API to publish messages and register clients that are using
    this publisher """

    def __init__(self, topic, msg_type=None, latched_client_id=None, queue_size=100):
        """ Register a publisher on the specified topic.

        Keyword arguments:
        topic    -- the name of the topic to register the publisher to
        msg_type -- (optional) the type to register the publisher as.  If not
        provided, an attempt will be made to infer the topic type
        latch    -- (optional) if a client requested this publisher to be latched,
                    provide the client_id of that client here

        Throws:
        TopicNotEstablishedException -- if no msg_type was specified by the
        caller and the topic is not yet established, so a topic type cannot
        be inferred
        TypeConflictException        -- if the msg_type was specified by the
        caller and the topic is established, and the established type is
        different to the user-specified msg_type

        """
        # First check to see if the topic is already established
        topic_type = get_topic_type(topic)[0]

        # If it's not established and no type was specified, exception
        if msg_type is None and topic_type is None:
            raise TopicNotEstablishedException(topic)

        # Use the established topic type if none was specified
        if msg_type is None:
            msg_type = topic_type

        # Load the message class, propagating any exceptions from bad msg types
        msg_class = ros_loader.get_message_class(msg_type)

        # Make sure the specified msg type and established msg type are same
        if topic_type is not None and topic_type != msg_class._type:
            raise TypeConflictException(topic, topic_type, msg_class._type)

        # Create the publisher and associated member variables
        self.clients = {}
        self.latched_client_id = latched_client_id
        self.topic = topic
        self.msg_class = msg_class
        self.publisher = Publisher(topic, msg_class, latch=(latched_client_id!=None), queue_size=queue_size)
        self.listener = PublisherConsistencyListener()
        self.listener.attach(self.publisher)

    def unregister(self):
        """ Unregisters the publisher and clears the clients """
        self.publisher.unregister()
        self.clients.clear()

    def verify_type(self, msg_type):
        """ Verify that the publisher publishes messages of the specified type.

        Keyword arguments:
        msg_type -- the type to check this publisher against

        Throws:
        Exception -- if ros_loader cannot load the specified msg type
        TypeConflictException -- if the msg_type is different than the type of
        this publisher

        """
        if not ros_loader.get_message_class(msg_type) is self.msg_class:
            raise TypeConflictException(self.topic,
                                        self.msg_class._type, msg_type)
        return

    def publish(self, msg):
        """ Publish a message using this publisher.

        Keyword arguments:
        msg -- the dict (json) message to publish

        Throws:
        Exception -- propagates exceptions from message conversion if the
        provided msg does not properly conform to the message type of this
        publisher

        """
        # First, check the publisher consistency listener to see if it's done
        if self.listener.attached and self.listener.timed_out():
            self.listener.detach()

        # Create a message instance
        inst = self.msg_class()

        # Populate the instance, propagating any exceptions that may be thrown
        message_conversion.populate_instance(msg, inst)

        # Publish the message
        self.publisher.publish(inst)

    def register_client(self, client_id):
        """ Register the specified client as a client of this publisher.

        Keyword arguments:
        client_id -- the ID of the client using the publisher

        """
        self.clients[client_id] = True

    def unregister_client(self, client_id):
        """ Unregister the specified client from this publisher.

        If the specified client_id is not a client of this publisher, nothing
        happens.

        Keyword arguments:
        client_id -- the ID of the client to remove

        """
        if client_id in self.clients:
            del self.clients[client_id]

    def has_clients(self):
        """ Return true if there are clients to this publisher. """
        return len(self.clients) != 0

class PublisherManager():
    """ The PublisherManager keeps track of ROS publishers

    It maintains a MultiPublisher instance for each registered topic

    When unregistering a client, if there are no more clients for a publisher,
    then that publisher is unregistered from the ROS Master
    """

    def __init__(self):
        self._publishers = {}

    def register(self, client_id, topic, msg_type=None, latch=False, queue_size=100):
        """ Register a publisher on the specified topic.

        Publishers are shared between clients, so a single MultiPublisher
        instance is created per topic, even if multiple clients register.

        Keyword arguments:
        client_id  -- the ID of the client making this request
        topic      -- the name of the topic to publish on
        msg_type   -- (optional) the type to publish
        latch      -- (optional) whether to make this publisher latched
        queue_size -- (optional) rospy publisher queue_size to use

        Throws:
        Exception -- exceptions are propagated from the MultiPublisher if
        there is a problem loading the specified msg class or establishing
        the publisher

        """
        latched_client_id = client_id if latch else None
        if not topic in self._publishers:
            self._publishers[topic] = MultiPublisher(topic, msg_type, latched_client_id,
             queue_size=queue_size)
        elif latch and self._publishers[topic].latched_client_id != client_id:
            logwarn("Client ID %s attempted to register topic [%s] as latched " +
                    "but this topic was previously registered." % (client_id, topic))
            logwarn("Only a single registered latched publisher is supported at the time")
        elif not latch and self._publishers[topic].latched_client_id:
            logwarn("New non-latched publisher registration for topic [%s] which is " +
                    "already registered as latched. but this topic was previously " +
                    "registered." % topic)
            logwarn("Only a single registered latched publisher is supported at the time")

        if msg_type is not None:
            self._publishers[topic].verify_type(msg_type)

        self._publishers[topic].register_client(client_id)

    def unregister(self, client_id, topic):
        """ Unregister a client from the publisher for the given topic.

        If there are no clients remaining for that publisher, then the
        publisher is unregistered from the ROS Master

        Keyword arguments:
        client_id -- the ID of the client making this request
        topic     -- the topic to unregister the publisher for

        """
        if not topic in self._publishers:
            return

        self._publishers[topic].unregister_client(client_id)

        if not self._publishers[topic].has_clients():
            self._publishers[topic].unregister()
            del self._publishers[topic]

    def unregister_all(self, client_id):
        """ Unregisters a client from all publishers that they are registered
        to.

        Keyword arguments:
        client_id -- the ID of the client making this request """
        for topic in self._publishers.keys():
            self.unregister(client_id, topic)

    def publish(self, client_id, topic, msg, latch=False, queue_size=100):
        """ Publish a message on the given topic.

        Tries to create a publisher on the topic if one does not already exist.

        Keyword arguments:
        client_id -- the ID of the client making this request
        topic     -- the topic to publish the message on
        msg       -- a JSON-like dict of fields and values
        latch     -- (optional) whether to make this publisher latched
        queue_size -- (optional) rospy publisher queue_size to use

        Throws:
        Exception -- a variety of exceptions are propagated.  They can be
        thrown if there is a problem setting up or getting the publisher,
        or if the provided msg does not map to the msg class of the publisher.

        """
        self.register(client_id, topic, latch=latch, queue_size=queue_size)

        self._publishers[topic].publish(msg)

manager = PublisherManager()


text:
var application = require("application"),
    authenticationService = require("./components/authentication/authentication-service");

if (authenticationService.isAuthenticated()) {
    authenticationService.setAuthorization();
    application.mainModule = "app/components/home/home";
} else {
    application.mainModule = "app/components/authentication/authentication";
}

application.cssFile = "app/app.css";
application.start();


text:
package leetcode;

/**
 * Created by wangxiaoyi on 15/9/27.
 */
 public class ListNode {
         public int val;
         public ListNode next;
         public ListNode(int x) { val = x; }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:flowable="http://flowable.org/bpmn"
  targetNamespace="Examples">

  <process id="process">

    <startEvent id="theStart" />
    <sequenceFlow sourceRef="theStart" targetRef="service1" />

    <serviceTask id="service1" flowable:delegateExpression="${triggerableServiceTask}" flowable:triggerable="true"/>
    <sequenceFlow sourceRef="service1" targetRef="usertask1" />

    <userTask id="usertask1" name="Task A"/>
    <sequenceFlow sourceRef="usertask1" targetRef="theEnd" />

    <endEvent id="theEnd" />

    <subProcess id="eventSubProcess" triggeredByEvent="true">
      <startEvent id="catchError">
        <errorEventDefinition /> <!-- no errorCode: catch any error -->
      </startEvent>
      <sequenceFlow id="flow3" sourceRef="catchError" targetRef="taskAfterErrorCatch" />
      <userTask id="taskAfterErrorCatch" name="Escalated Task" />
    </subProcess>
  </process>

</definitions>


text:
/**
 * Launch configurations and other definitions specific to
 * kernels which are linear, i.e. should be scheduled with
 * a uni-dimensional grid
 */
#ifndef CUDA_LINEAR_GRID_H_
#define CUDA_LINEAR_GRID_H_

#include "cuda/api/kernel_launch.cuh"

namespace cuda {
namespace linear_grid {

enum : grid_dimension_t	{ single_block = 1 };
enum : grid_block_dimension_t { single_thread_per_block = 1 };

class launch_configuration_t {
public:
	grid_dimension_t	    grid_length; // in threads
	grid_block_dimension_t  block_length; // in threads
	shared_memory_size_t    dynamic_shared_memory_size; // in bytes

	launch_configuration_t()
	 : grid_length(single_block), block_length(single_thread_per_block),
	   dynamic_shared_memory_size(no_shared_memory) { }
	launch_configuration_t(
		grid_dimension_t grid_length_,
	    grid_block_dimension_t block_length_,
	    shared_memory_size_t dynamic_shared_memory_size = no_shared_memory)
	: grid_length(grid_length_), block_length(block_length_),
	  dynamic_shared_memory_size(dynamic_shared_memory_size) { }

	// Allows linear launch configs to be passed
	// to the launcher function
	operator cuda::launch_configuration_t()
	{
		 return { grid_length, block_length, dynamic_shared_memory_size };
	}
};

} // linear_grid
} // namespace cuda

#endif /* CUDA_LINEAR_GRID_H_ */


text:
q=../../../question_library/eop/chapter7/

rm -rf $q/*

# ***** structure and value of an expression
code_activator_generate.py abcd_io.py $q
code_activator_generate.py uvwx_io.py $q

code_activator_generate.py inc_dec_easy_io.py $q
code_activator_generate.py inc_dec_harder_io.py $q

code_activator_generate.py conditional_expression_io.py $q

multiple_choice_generate.py multiple_choice.py $q


text:
<?php

namespace Pterodactyl\Services\Servers;

use Pterodactyl\Models\User;
use Illuminate\Support\Collection;
use Pterodactyl\Models\EggVariable;
use Illuminate\Validation\ValidationException;
use Pterodactyl\Traits\Services\HasUserLevels;
use Illuminate\Contracts\Validation\Factory as ValidationFactory;

class VariableValidatorService
{
    use HasUserLevels;

    /**
     * @var \Illuminate\Contracts\Validation\Factory
     */
    private $validator;

    /**
     * VariableValidatorService constructor.
     */
    public function __construct(ValidationFactory $validator)
    {
        $this->validator = $validator;
    }

    /**
     * Validate all of the passed data against the given service option variables.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function handle(int $egg, array $fields = []): Collection
    {
        $query = EggVariable::query()->where('egg_id', $egg);
        if (!$this->isUserLevel(User::USER_LEVEL_ADMIN)) {
            // Don't attempt to validate variables if they aren't user editable
            // and we're not running this at an admin level.
            $query = $query->where('user_editable', true)->where('user_viewable', true);
        }

        /** @var \Pterodactyl\Models\EggVariable[] $variables */
        $variables = $query->get();

        $data = $rules = $customAttributes = [];
        foreach ($variables as $variable) {
            $data['environment'][$variable->env_variable] = array_get($fields, $variable->env_variable);
            $rules['environment.' . $variable->env_variable] = $variable->rules;
            $customAttributes['environment.' . $variable->env_variable] = trans('validation.internal.variable_value', ['env' => $variable->name]);
        }

        $validator = $this->validator->make($data, $rules, [], $customAttributes);
        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        return Collection::make($variables)->map(function ($item) use ($fields) {
            return (object) [
                'id' => $item->id,
                'key' => $item->env_variable,
                'value' => $fields[$item->env_variable] ?? null,
            ];
        });
    }
}


text:
describe('MetadataService', function() {
    beforeEach(module("cheese"));

    it('should initialize properly', function(){
        expect(true).toBe(true);
    });
});


text:
package com.jorgecastilloprz.pagedheadlistview.utils;

/**
 * Created by jorge on 7/08/14.
 */
public enum IndicatorTypes {
    NONE, TOPALIGNED, BOTTOMALIGNED;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenNLP.Tools.Trees.TRegex.Tsurgeon
{
    public class CoindexNodes : TsurgeonPattern
    {
        private const string CoindexationIntroductionString = "-";

        public CoindexNodes(TsurgeonPattern[] children) :
            base("coindex", children)
        {
        }

        public override void SetRoot(TsurgeonPatternRoot root)
        {
            base.SetRoot(root);
            root.SetCoindexes();
        }

        public override TsurgeonMatcher GetMatcher(Dictionary<string, Tree> newNodeNames, CoindexationGenerator coindexer)
        {
            return new Matcher(newNodeNames, coindexer, this);
        }

        private class Matcher : TsurgeonMatcher
        {
            private CoindexNodes node;

            public Matcher(Dictionary<string, Tree> newNodeNames, CoindexationGenerator coindexer, CoindexNodes node) :
                base(node, newNodeNames, coindexer)
            {
                this.node = node;
            }

            public override Tree Evaluate(Tree tree, TregexMatcher tregex)
            {
                int newIndex = Coindexer.GenerateIndex();
                foreach (TsurgeonMatcher child in ChildMatcher)
                {
                    Tree node = child.Evaluate(tree, tregex);
                    node.Label().SetValue(node.Label().Value() + CoindexationIntroductionString + newIndex);
                }
                return tree;
            }
        }
    }
}


text:
namespace blink {

// Used to get whether message loop is ready for current thread, to help
// blink::initialize() determining whether can initialize mojo stuff or not.
// TODO(leonhsl): http://crbug.com/660274 Remove this API by ensuring
// a message loop before calling blink::initialize().
inline bool CanInitializeMojo() {
  return base::MessageLoopCurrent::IsSet();
}

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_MOJO_HELPER_H_


text:
        <oppia-search-results></oppia-search-results>

            {{ 'I18N_LIBRARY_NO_EXPLORATIONS' | translate }}

 0"
             class="oppia-exploration-summary-header">

            <oppia-exploration-summary-tile *ngIf="tile.activity_type == 'exploration'"
                                            [explorationId]="tile.id"
                                            [explorationTitle]="tile.title"
                                            [lastUpdatedMsec]="tile.last_updated_msec"
                                            [objective]="tile.objective"
                                            [category]="tile.category"
                                            [ratings]="tile.ratings"
                                            [numViews]="tile.num_views"
                                            [thumbnailIconUrl]="tile.thumbnail_icon_url"
                                            [thumbnailBgColor]="tile.thumbnail_bg_color"
                                            class="protractor-test-exp-summary-tile">
            </oppia-exploration-summary-tile>

{{ 'I18N_LIBRARY_MAIN_HEADER' | translate }}

{{ 'I18N_LIBRARY_SUB_HEADER' | translate }}

          <oppia-search-bar [enableDropup]="false"></oppia-search-bar>

{{ 'I18N_CLASSROOM_CALLOUT_HEADING_2' | translate }}

{{ 'I18N_CLASSROOM_CALLOUT_HEADING_1' | translate }}

{{ 'I18N_CLASSROOM_CALLOUT_PARAGRAPH_1' | translate }}

               {{ 'I18N_CLASSROOM_CALLOUT_BUTTON' | translate }}

          <picture class="classroom-promo-image">
            <source type="image/webp"
                    [srcset]="getStaticImageUrl('/landing/math/fractions/matthew_paper.webp')">
            <source type="image/png"
                    [srcset]="getStaticImageUrl('/landing/math/fractions/matthew_paper.png')">

          </picture>

             {{ 'I18N_LIBRARY_NO_EXPLORATION_GROUPS' | translate }}

                

            <button mat-button class="md-no-ink oppia-library-carousel-scroller"
                    (click)="scroll(idx, true)"
                    *ngIf="leftmostCardIndices[idx] != 0">
              
            </button>

                  <oppia-collection-summary-tile *ngIf="tile.activity_type == 'collection'"
                                                 [getCollectionId]="tile.id"
                                                 [getCollectionTitle]="tile.title"
                                                 [getLastUpdatedMsec]="tile.last_updated_msec"
                                                 [getObjective]="tile.objective"
                                                 [getNodeCount]="tile.node_count"
                                                 [getCategory]="tile.category"
                                                 [getThumbnailIconUrl]="tile.thumbnail_icon_url"
                                                 [getThumbnailBgColor]="tile.thumbnail_bg_color"
                                                 [isOwnedByCurrentUser]="activitiesOwned.collections[tile.id]"
                                                 [showLearnerDashboardIconsIfPossible]="true">
                  </oppia-collection-summary-tile>
                  <oppia-exploration-summary-tile *ngIf="tile.activity_type == 'exploration'"
                                                  [explorationId]="tile.id"
                                                  [explorationTitle]="tile.title"
                                                  [lastUpdatedMsec]="tile.last_updated_msec"
                                                  [objective]="tile.objective"
                                                  [category]="tile.category"
                                                  [ratings]="tile.ratings"
                                                  [numViews]="tile.num_views"
                                                  [thumbnailIconUrl]="tile.thumbnail_icon_url"
                                                  [thumbnailBgColor]="tile.thumbnail_bg_color"
                                                  class="protractor-test-exp-summary-tile"
                                                  [isOwnedByCurrentUser]="activitiesOwned.explorations[tile.id]"
                                                  [showLearnerDashboardIconsIfPossible]="true">
                  </oppia-exploration-summary-tile>

            <button mat-button class="md-no-ink oppia-library-carousel-scroller"
                    (click)="scroll(idx, false)"
                    [hidden]="(group.activity_summary_dicts.length - tileDisplayCount) <= leftmostCardIndices[idx]"
                    aria-hidden="true">
              
            </button>
            <div class="oppia-library-carousel-scroller"
                 *ngIf="(group.activity_summary_dicts?.length - tileDisplayCount) <= leftmostCardIndices[idx]">

            <button mat-button class="md-no-ink oppia-library-carousel-scroller"
                    (click)="decrementLeftmostCardIndex(idx)"
                    [hidden]="leftmostCardIndices[idx] == 0"
                    aria-hidden="true">
              
            </button>

                <oppia-collection-summary-tile *ngIf="group.activity_summary_dicts[leftmostCardIndices[idx]].activity_type == 'collection'"
                                               [getCollectionId]="group.activity_summary_dicts[leftmostCardIndices[idx]].id"
                                               [getCollectionTitle]="group.activity_summary_dicts[leftmostCardIndices[idx]].title"
                                               [getLastUpdatedMsec]="group.activity_summary_dicts[leftmostCardIndices[idx]].last_updated_msec"
                                               [getObjective]="group.activity_summary_dicts[leftmostCardIndices[idx]].objective"
                                               [getNodeCount]="group.activity_summary_dicts[leftmostCardIndices[idx]].node_count"
                                               [getCategory]="group.activity_summary_dicts[leftmostCardIndices[idx]].category"
                                               [getThumbnailIconUrl]="group.activity_summary_dicts[leftmostCardIndices[idx]].thumbnail_icon_url"
                                               [getThumbnailBgColor]="group.activity_summary_dicts[leftmostCardIndices[idx]].thumbnail_bg_color"
                                               [showLearnerDashboardIconsIfPossible]="true"
                                               [isContainerNarrow]="true">
                </oppia-collection-summary-tile>
                <oppia-exploration-summary-tile *ngIf="group.activity_summary_dicts[leftmostCardIndices[idx]].activity_type == 'exploration'"
                                                [explorationId]="group.activity_summary_dicts[leftmostCardIndices[idx]].id"
                                                [explorationTitle]="group.activity_summary_dicts[leftmostCardIndices[idx]].title"
                                                [lastUpdatedMsec]="group.activity_summary_dicts[leftmostCardIndices[idx]].last_updated_msec"
                                                [objective]="group.activity_summary_dicts[leftmostCardIndices[idx]].objective"
                                                [category]="group.activity_summary_dicts[leftmostCardIndices[idx]].category"
                                                [ratings]="group.activity_summary_dicts[leftmostCardIndices[idx]].ratings"
                                                [numViews]="group.activity_summary_dicts[leftmostCardIndices[idx]].num_views"
                                                [thumbnailIconUrl]="group.activity_summary_dicts[leftmostCardIndices[idx]].thumbnail_icon_url"
                                                [thumbnailBgColor]="group.activity_summary_dicts[leftmostCardIndices[idx]].thumbnail_bg_color"
                                                class="protractor-test-exp-summary-tile"
                                                [showLearnerDashboardIconsIfPossible]="true"
                                                [isContainerNarrow]="true">
                </oppia-exploration-summary-tile>

            <button mat-button class="md-no-ink oppia-library-carousel-scroller"
                    (click)="incrementLeftmostCardIndex(idx)"
                    [hidden]="(group.activity_summary_dicts?.length - tileDisplayCount) <= leftmostCardIndices[idx]">
              
            </button>
            <div class="oppia-library-carousel-scroller"
                 *ngIf="(group.activity_summary_dicts?.length - tileDisplayCount) <= leftmostCardIndices[idx]">


text:
Responsive View
==============

develop & explorer responsive webdesign

## Get the chrome extension

<https://chrome.google.com/webstore/detail/responsive-view-chrome-he/hfkchhgoijlonlhpmgefgolgbipellmg>

## Examles

<http://rv.k94n.com/#http://www.google.com/nexus/7/>

<http://rv.k94n.com/#http://mashable.com/>

<http://rv.k94n.com/#http://getbootstrap.com/examples/jumbotron/>

<http://rv.k94n.com/#http://thenextweb.com/>

<http://rv.k94n.com/#http://skinnyties.com/>

<http://rv.k94n.com/#http://aneventapart.com/>

## ViennaJs Slides 2013-08-28

<https://speakerdeck.com/k9ordon/responsive-view-viennajs-2013-08>

## Upcoming

- user agents
- more + custom device sets
- rotateable devices
- share/explore responsive sites
- create sharable screenshots

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/k9ordon/responsiveview/trend.png)](https://bitdeli.com/free "Bitdeli Badge")