text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{% block title %}{{ SITENAME }}{% endblock title %}</title>
    <link rel="stylesheet" type="text/css" href="{{ SITEURL }}/theme/css/screen.min.css">
    <link rel="stylesheet" type="text/css" href="{{ SITEURL }}/theme/css/highlight.min.css">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="publisher" href="{{ PUBLISHER }}">
    <link rel="apple-touch-startup-image" href="{{ SITEURL }}/theme/images/logo.png">
    <link type="text/plain" rel="socialmedia" href="{{ SITEURL }}/socialmedia.txt">
    <link rel="dns-prefetch" href="{{ SITEURL }}"/>
    <link rel="dns-prefetch" href="//www.gstatic.com"/>
    <link rel="dns-prefetch" href="//fonts.gstatic.com"/>
    <link rel="dns-prefetch" href="//fonts.googleapis.com"/>
    <link rel="dns-prefetch" href="//accounts.google.com"/>
    <link rel="dns-prefetch" href="//ssl.google-analytics.com"/>
    <link rel="dns-prefetch" href="//www.google-analytics.com"/>
    <link rel="dns-prefetch" href="//googleads.g.doubleclick.net"/>
    <link rel="dns-prefetch" href="//pagead2.googlesyndication.com"/>
    <link rel="dns-prefetch" href="//twemoji.maxcdn.com"/>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="application-name" content="{{ SITENAME }}"/>
    <meta name="msapplication-starturl" content="http:{{ SITEURL }}"/>
    <meta name="msapplication-tooltip" content="{{ TAG_LINE }}"/>
    <meta name="msapplication-window" content="width=1024;height=768"/>
    <meta name="msapplication-task" content="name={{ SITENAME }};action-uri=http:{{ SITEURL }};icon-uri={{ SITEURL }}/theme/images/favicon.ico"/>
    <meta name="msapplication-TileImage" content="{{ SITEURL }}/theme/images/apple-touch-icon-144x144.png"/>
    <meta name="msapplication-TileColor" content="#1F1F21"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="imagetoolbar" content="no">
    <meta http-equiv="pragma" content="cache">
    <meta http-equiv="cache-control" content="cache">
    <meta http-equiv="vary" content="content-language">
    <meta http-equiv="Cache-control" content="max-age=2592000, public">
    <meta http-equiv="content-style-type" content="text/css">
    <meta name="application-name" content="{{ SITENAME }}">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="google-site-verification" content="{{ GOOGLE_SV }}">
    <meta name="alexaVerifyID" content="{{ ALEXA }}"/>
    <meta name="wot-verification" content="{{ MY_WOT }}"/>
    <meta name="msvalidate.01" content="{{ MSVALIDATE }}" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="medium" content="mult">
    <meta name="adblock" content="disable">
    <meta name="rating" content="General">
    <meta name="resource-type" content="document">
    <meta name="revisit-after" content="1 days">
    <meta name="revisit" content="1">
    <meta name="robots" content="index,follow">
    <meta name="no-email-collection" content="http://www.unspam.com/noemailcollection/">
{# Open Graph tags #}
    {% if USE_OPEN_GRAPH is not defined %}
        {% set USE_OPEN_GRAPH = False %}
    {% endif %}
{% if USE_OPEN_GRAPH %}
{% if OPEN_GRAPH_FB_APP_ID %}
    <meta property="fb:app_id" content="{{ OPEN_GRAPH_FB_APP_ID }}">
{% endif %}
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@{{ TWITTER_USERNAME }}">
    <meta property="og:site_name" content="{{ SITENAME }}">
    <meta property="og:locale" content="{{ SITE_LANG }}">
    <meta property="og:locale:alternate" content="{{ SITE_LANG_ALTERNATE }}">
    {% if article %}
    <link rel="canonical" href="{{ article.url }}">
    <link rel="dns-prefetch" href="//disqus.com"/>
    <link rel="dns-prefetch" href="//a.disquscdn.com"/>
    <link rel="dns-prefetch" href="//{{ DISQUS_SITENAME }}.disqus.com"/>
    <link rel="dns-prefetch" href="//glitter-services.disqus.com"/>
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="300">
    <meta property="og:image:height" content="300">
    <meta property="og:type" content="article">
    <meta property="og:title" content="{{ article.title|striptags }}">
    <meta property="og:url" content="{{ article.url }}">
    <meta property="og:description" content="{{ article.summary|striptags|escape }}">
    <meta property="article:published_time" content="{{ article.date|strftime('%A, %B %d, %Y') }}">
    <meta name="twitter:title" content="{{ article.title|striptags }}">
    <meta name="twitter:description" content="{{ article.summary|striptags|escape }}">
    <meta name="description" content="{{ article.summary|striptags|escape }}">
    <meta name="twitter:creator" content="@{{ article.twitter }}">
    <meta name="twitter:image" content="{{ article.image }}">
    <meta property="og:image" content="{{ article.image }}">
    <meta name="dcterms.title" content="{{ article.title|striptags }}">
    <meta name="dcterms.description" content="{{ article.summary|striptags|escape }}">
    <meta name="dcterms.language" content="es">
    <meta name="dcterms.type" content="post">
    <meta name="dcterms.source" content="{{ article.url }}">
    <meta name="dcterms.publisher" content="{{ article.twitter }}">
    {% if article.category %}
    <meta property="article:section" content="{{ article.category }}">
    {% endif %}
    {% for tag in article.tags %}
    <meta property="article:tag" content="{{ tag }}">
    {% endfor %}
    {% if article.author %}
    <meta property="article:author" content="{{ article.author }}">
    {% endif %}
    {% elif page %}
    <link rel="canonical" href="{{ page.url }}">
    <meta property="og:type" content="article">
    <meta property="og:title" content="{{ page.title }}">
    <meta property="og:url" content="{{ page.url }}">
    <meta property="og:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta name="twitter:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="300">
    <meta property="og:image:height" content="300">
    <meta name="dcterms.title" content="{{ page.title }}">
    <meta name="dcterms.description" content="{{ SITE_DESCRIPTION }}">
    <meta name="dcterms.language" content="es">
    <meta name="dcterms.type" content="page">
    <meta name="dcterms.source" content="{{ page.url }}">
    <meta name="dcterms.publisher" content="{{ AUTHOR }}">
    {% else %}
    <meta property="og:type" content="website">
    <meta property="og:title" content="{{ SITENAME }}">
    <meta property="og:url" content="{{ SITEURL }}">
    <meta property="og:description" content="{{ SITE_DESCRIPTION }}">
    <link rel="canonical" href="{{ SITEURL }}">
    <meta property="og:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta name="twitter:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="300">
    <meta property="og:image:height" content="300">
    <meta name="description" content="{{ SITE_DESCRIPTION }}">
    <meta name="dcterms.title" content="{{ SITENAME }}">
    <meta name="dcterms.description" content="{{ SITE_DESCRIPTION }}">
    <meta name="dcterms.language" content="es">
    <meta name="dcterms.type" content="frontpage">
    <meta name="dcterms.identifier" content="0">
    <meta name="dcterms.source" content="{{ SITEURL }}">
    <meta name="dcterms.publisher" content="{{ AUTHOR }}">
    {% if OPEN_GRAPH_IMAGE %}
    <meta property="og:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta name="twitter:image" content="{{ SITEURL }}/theme/images/logo.png">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="300">
    <meta property="og:image:height" content="300">
    {% endif %}
    {% endif %}
{% endif %}
{% if FEED_RSS %}
    <link href="{{ FEED_RSS }}" type="application/atom+xml" rel="alternate" title="{{ SITENAME }} RSS Feed">
{% endif %}
    <link rel="apple-touch-icon" sizes="152x152" href="{{ SITEURL }}/theme/images/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="144x144" href="{{ SITEURL }}/theme/images/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="114x114" href="{{ SITEURL }}/theme/images/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="{{ SITEURL }}/theme/images/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="76x76" href="{{ SITEURL }}/theme/images/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="72x72" href="{{ SITEURL }}/theme/images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="60x60" href="{{ SITEURL }}/theme/images/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="57x57" href="{{ SITEURL }}/theme/images/apple-touch-icon-57x57.png">
    <link rel="icon" type="image/png" href="{{ SITEURL }}/theme/images/favicon-196x196.png" sizes="196x196">
    <link rel="icon" type="image/png" href="{{ SITEURL }}/theme/images/favicon-160x160.png" sizes="160x160">
    <link rel="icon" type="image/png" href="{{ SITEURL }}/theme/images/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="{{ SITEURL }}/theme/images/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="{{ SITEURL }}/theme/images/favicon-16x16.png" sizes="16x16">
    <link rel="shortcut icon" href="{{ SITEURL }}/theme/images/favicon.ico">

    <meta itemprop="name" content="{{ SITENAME }}">
    <meta itemprop="url" content="{{ SITEURL }}">
    <meta itemprop="headline" content="{{ SITENAME }} || {{ TAG_LINE }}">
    <meta itemprop="description about" content="{{ SITE_DESCRIPTION }}">
    <meta itemprop="keywords" content="gnu, linux, software libre, código abierto, tecnología">
    <meta itemprop="primaryImageOfPage" content="{{ SITEURL }}/theme/images/logo.png">
    <meta itemprop="inLanguage" content="es">
    {% include 'navigation.html' %}

                    ☰
                    Menu

{{ SITENAME }}

{{TAG_LINE}}

                Scroll Down

    {% block content %}
    {% endblock %}

                CC Attribution-NonCommercial-ShareAlike 4.0 International License.

Proudly published with Pelican


text:
package com.github.mauricio.async.db.postgresql.codec

import com.github.mauricio.async.db.postgresql.exceptions.{MessageTooLongException}
import com.github.mauricio.async.db.postgresql.messages.backend.{ServerMessage, SSLResponseMessage}
import com.github.mauricio.async.db.postgresql.parsers.{AuthenticationStartupParser, MessageParsersRegistry}
import com.github.mauricio.async.db.util.{BufferDumper, Log}
import java.nio.charset.Charset
import com.github.mauricio.async.db.exceptions.NegativeMessageSizeException
import io.netty.handler.codec.ByteToMessageDecoder
import io.netty.channel.ChannelHandlerContext
import io.netty.buffer.ByteBuf

object MessageDecoder {
  val log = Log.get[MessageDecoder]
  val DefaultMaximumSize = 16777216
}

class MessageDecoder(sslEnabled: Boolean, charset: Charset, maximumMessageSize : Int = MessageDecoder.DefaultMaximumSize) extends ByteToMessageDecoder {

  import MessageDecoder.log

  private val parser = new MessageParsersRegistry(charset)

  private var sslChecked = false

  override def decode(ctx: ChannelHandlerContext,  b: ByteBuf, out: java.util.List[Object]): Unit = {

    if (sslEnabled & !sslChecked)  {
      val code = b.readByte()
      sslChecked = true
      out.add(new SSLResponseMessage(code == 'S'))
    } else if (b.readableBytes() >= 5) {

      b.markReaderIndex()

      val code = b.readByte()
      val lengthWithSelf = b.readInt()
      val length = lengthWithSelf - 4

      if ( length < 0 ) {
        throw new NegativeMessageSizeException(code, length)
      }

      if ( length > maximumMessageSize ) {
        throw new MessageTooLongException(code, length, maximumMessageSize)
      }

      if (b.readableBytes() >= length) {

        if ( log.isTraceEnabled ) {
          log.trace(s"Received buffer ${code}\n${BufferDumper.dumpAsHex(b)}")
        }

        val result = code match {
          case ServerMessage.Authentication => {
            AuthenticationStartupParser.parseMessage(b)
          }
          case _ => {
            parser.parse(code, b.readSlice(length))
          }
        }

        out.add(result)

      } else {
        b.resetReaderIndex()
        return
      }

    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

################################################################################
#                                                                              #
#		Filename:	process_order.php			       #
#		Author:		Martin Settle				       #
#               Created:	2 Sept 2006				       #
#		Description:	order processing			       #
#		Calls:		config.php				       #
#		Called by:	productlist.php				       #
#									       #
#   Copyright 2010 Trellis Ltd
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
################################################################################

/*
MODIFICATION HISTORY
	- 2006.09.02 file created
	- 2008.03.12 modified to use temp_orders

*/

if(empty($CoopName))
{
	session_start();

	if(empty($_SESSION['member_id']))
	{
		header ("Location:index.php");
		exit();
		}

	header ("Cache-control: private");

	$Secure = 1;
	include 'config.php';
	}

if($_POST['process'] == 'Update my Order') {
	// process the orders

	foreach($_POST['quantity'] as $product_id => $new_request) {
		$new_request = trim($new_request);
		//echo $product_id . " => " .  $new_request . "
";
		if($new_request != '') {
			//submission logic goes here
			$new_request = quote_smart($new_request);
			$existinglookup = mysql_query("SELECT * FROM temp_orders WHERE order_product_id = $product_id AND order_member_id = $_SESSION[member_id] AND order_date = '$_SESSION[order_date]'");
			if (mysql_num_rows($existinglookup) == 1) {
				$existing_id = mysql_result($existinglookup,0,'temp_order_id');
				if ($new_request == 0) {
					//echo "DEL: " . $product_id . " => " .  $new_request . "
";
					mysql_query("DELETE FROM temp_orders WHERE temp_order_id = $existing_id");
				}
				elseif ($new_request > 0) {
					//echo "UPD: " . $product_id . " => " .  $new_request . "
";
					mysql_query("UPDATE temp_orders SET order_quantity_requested = $new_request WHERE temp_order_id = $existing_id");
				}
			}
			else if ($new_request > 0) {
				//echo "INS: " . $product_id . " => " .  $new_request . "
";
				$fetch_price = mysql_query("SELECT current_price FROM product_calendar WHERE product_id = $product_id and order_date = '{$_SESSION['order_date']}'");
				$current_price = mysql_result($fetch_price,0);
				mysql_query("INSERT INTO temp_orders SET order_product_id = $product_id, order_member_id = $_SESSION[member_id], order_date = '" . $_SESSION['order_date'] . "', order_quantity_requested = $new_request, order_current_price = $current_price");
			}
		}
	}

	header("Location: my_order.php");
	exit();
}
header("Location: productlist.php");

?>


text:
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaPreCompiled.h"
#include "Node/Action/Timeline/RenderingObjectTimeline.h"
#include "Node/INode.h"
#include "Resource/Timeline/RenderingObjectTimelineModel.h"
#include "Resource/Model/Mesh/Fixed/TextureQuadMesh.h"

MEDUSA_BEGIN;

RenderingObjectTimeline::RenderingObjectTimeline(const Share<RenderingObjectTimelineModel>& model, bool isRepeatForever, float beforeDelay /*= 0.f*/, float repeatDuration /*= 0.f*/, float afterDelay /*= 0.f*/, const StringRef& name /*= StringRef::Empty*/)
	: ITimeline(model, isRepeatForever, beforeDelay, repeatDuration, afterDelay, name)
{

}

RenderingObjectTimeline::RenderingObjectTimeline(const Share<RenderingObjectTimelineModel>& model, intp repeatCount, float beforeDelay /*= 0.f*/, float repeatDuration /*= 0.f*/, float afterDelay /*= 0.f*/, const StringRef& name /*= StringRef::Empty*/)
	: ITimeline(model, repeatCount, beforeDelay, repeatDuration, afterDelay, name)
{

}

RenderingObjectTimeline::RenderingObjectTimeline(const Share<RenderingObjectTimelineModel>& model, intp currentCount, intp repeatCount, float beforeDelay /*= 0.f*/, float repeatDuration /*= 0.f*/, float afterDelay /*= 0.f*/, const StringRef& name /*= StringRef::Empty*/)
	: ITimeline(model, currentCount, repeatCount, beforeDelay, repeatDuration, afterDelay, name)
{

}

RenderingObjectTimeline::~RenderingObjectTimeline()
{
}

RenderingObjectTimeline* RenderingObjectTimeline::Clone() const
{
	Share<RenderingObjectTimelineModel> model = mModel.CastPtr<RenderingObjectTimelineModel>();
	return new RenderingObjectTimeline(model, mCurrentCount, mRepeatCount, mBeforeDelay, mRepeatDuration, mAfterDelay, mName);
}

bool RenderingObjectTimeline::OnUpdate(float prevElapsed, float dt, float blend /*= 1.f*/)
{
	uint frame = UpdateFrameIndex();
	auto model = mModel.CastPtr<RenderingObjectTimelineModel>();
	auto* obj = model->GetItemByIndex(frame);
	INode* node = (INode*)mTarget;
	node->SetRenderingObject(*obj);

	return true;
}

MEDUSA_END;


text:
require "test_helper"

class Admin::ConsultationsControllerTest < ActionController::TestCase
  include TaxonomyHelper

  setup do
    login_as :writer
    @current_user.permissions << "Preview design system"
    ConsultationResponseForm.any_instance.stubs(:consultation_participation).returns(stub(consultation: stub(auth_bypass_id: "auth bypass id")))
  end

  should_be_an_admin_controller

  should_allow_creating_of :consultation
  should_allow_editing_of :consultation

  should_allow_organisations_for :consultation
  should_allow_attached_images_for :consultation
  should_prevent_modification_of_unmodifiable :consultation
  should_allow_alternative_format_provider_for :consultation
  should_allow_scheduled_publication_of :consultation
  should_allow_access_limiting_of :consultation

  view_test "new displays consultation fields" do
    get :new

    assert_select "form#new_edition" do
      assert_select "textarea[name='edition[summary]']"
      assert_select "select[name*='edition[opening_at']", count: 5
      assert_select "select[name*='edition[closing_at']", count: 5
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][link_url]']"
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][email]']"
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][title]']"
      assert_select "input[type='file'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][consultation_response_form_data_attributes][file]']"
    end
  end

  test "create should create a new consultation" do
    attributes = controller_attributes_for(
      :consultation,
      consultation_participation_attributes: {
        link_url: "http://participation.com",
        email: "countmein@participation.com",
        consultation_response_form_attributes: {
          title: "the title of the response form",
          consultation_response_form_data_attributes: {
            file: upload_fixture("two-pages.pdf"),
          },
        },
      },
    )

    post :create, params: { edition: attributes }

    consultation = Consultation.last
    response_form = consultation.consultation_participation.consultation_response_form
    assert_equal attributes[:summary], consultation.summary
    assert_equal attributes[:opening_at], consultation.opening_at
    assert_equal attributes[:closing_at], consultation.closing_at
    assert_equal "http://participation.com", consultation.consultation_participation.link_url
    assert_equal "countmein@participation.com", consultation.consultation_participation.email
    assert_equal "the title of the response form", response_form.title
    assert response_form.consultation_response_form_data.file.present?
  end

  test "create should not persist external_url if the external checkbox is not checked" do
    attributes = controller_attributes_for(
      :consultation,
      external: "0",
      external_url: "http://participation.com",
      consultation_participation_attributes: {
        link_url: "http://participation.com",
        email: "countmein@participation.com",
        consultation_response_form_attributes: {
          title: "the title of the response form",
          consultation_response_form_data_attributes: {
            file: upload_fixture("two-pages.pdf"),
          },
        },
      },
    )

    post :create, params: { edition: attributes }

    consultation = Consultation.last
    assert consultation.external_url.blank?
  end

  test "create should create a new consultation without consultation participation if participation fields are all blank" do
    attributes = controller_attributes_for(
      :consultation,
      consultation_participation_attributes: {
        link_url: nil,
        email: nil,
        consultation_response_form_attributes: {
          title: nil,
          consultation_response_form_data_attributes: {
            file: nil,
          },
        },
      },
    )

    post :create, params: { edition: attributes }

    consultation = Consultation.last
    assert_nil consultation.consultation_participation
  end

  view_test "creating a consultation with invalid data but valid form file should still display the cached form file" do
    attributes = controller_attributes_for(
      :consultation,
      consultation_participation_attributes: {
        link_url: nil,
        email: nil,
        consultation_response_form_attributes: {
          title: nil,
          consultation_response_form_data_attributes: {
            file: upload_fixture("two-pages.pdf"),
          },
        },
      },
    )

    post :create, params: { edition: attributes }

    assert_select "form#new_edition" do
      assert_select "input[name='edition[consultation_participation_attributes][consultation_response_form_attributes][consultation_response_form_data_attributes][file_cache]'][value$='two-pages.pdf']"
      assert_select ".govuk-body.already-uploaded", text: "two-pages.pdf already uploaded"
    end
  end

  view_test "show renders the summary" do
    draft_consultation = create(:draft_consultation, summary: "a-simple-summary")
    stub_publishing_api_expanded_links_with_taxons(draft_consultation.content_id, [])

    get :show, params: { id: draft_consultation }
    assert_select ".page-header .lead", text: "a-simple-summary"
  end

  view_test "edit displays consultation fields" do
    response_form = create(:consultation_response_form)
    participation = create(:consultation_participation, consultation_response_form: response_form)
    consultation = create(:consultation, consultation_participation: participation)

    get :edit, params: { id: consultation }

    assert_select "form#edit_edition" do
      assert_select "textarea[name='edition[summary]']"
      assert_select "select[name*='edition[opening_at']", count: 5
      assert_select "select[name*='edition[closing_at']", count: 5
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][link_url]']"
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][email]']"
      assert_select "textarea[name='edition[consultation_participation_attributes][postal_address]']"
      assert_select "input[type='hidden'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][id]'][value='#{response_form.id}']"
      assert_select "input[type='text'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][title]']"
      assert_select "input[type='hidden'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][consultation_response_form_data_attributes][id]'][value='#{response_form.consultation_response_form_data.id}']"
      assert_select "input[type='file'][name='edition[consultation_participation_attributes][consultation_response_form_attributes][consultation_response_form_data_attributes][file]']"
    end
  end

  test "update should save modified consultation attributes" do
    consultation = create(:consultation)

    put :update,
        params: { id: consultation,
                  edition: {
                    summary: "new-summary",
                    opening_at: 1.day.ago,
                    closing_at: 50.days.from_now,
                    consultation_participation_attributes: {
                      link_url: "http://consult.com",
                      email: "tell-us-what-you-think@gov.uk",
                    },
                  } }

    consultation.reload
    assert_equal "new-summary", consultation.summary
    assert_equal 1.day.ago, consultation.opening_at
    assert_equal 50.days.from_now, consultation.closing_at
    assert_equal "http://consult.com", consultation.consultation_participation.link_url
    assert_equal "tell-us-what-you-think@gov.uk", consultation.consultation_participation.email
  end

  test "update should save consultation without consultation participation if participation fields are all blank" do
    consultation = create(:consultation)

    put :update,
        params: { id: consultation,
                  edition: {
                    consultation_participation_attributes: {
                      link_url: nil,
                      email: nil,
                    },
                  } }

    consultation.reload
    assert_nil consultation.consultation_participation
  end

  view_test "updating should not allow removal of response form without explicit action" do
    response_form = create(:consultation_response_form)
    participation = create(:consultation_participation, consultation_response_form: response_form)
    consultation = create(:consultation, consultation_participation: participation)

    put :update,
        params: { id: consultation,
                  edition: {
                    consultation_participation_attributes: {
                      id: participation.id,
                      consultation_response_form_attributes: {
                        id: response_form.id,
                        _destroy: "1",
                      },
                    },
                  } }

    refute_select ".errors"
    consultation.reload
    assert_not_nil consultation.consultation_participation.consultation_response_form
  end

  view_test "updating should respect the attachment_action for response forms to keep it" do
    two_pages_pdf = upload_fixture("two-pages.pdf")
    greenpaper_pdf = upload_fixture("greenpaper.pdf")

    response_form = create(:consultation_response_form, file: two_pages_pdf)
    participation = create(:consultation_participation, consultation_response_form: response_form)
    consultation = create(:consultation, consultation_participation: participation)

    put :update,
        params: { id: consultation,
                  edition: {
                    consultation_participation_attributes: {
                      id: participation.id,
                      consultation_response_form_attributes: {
                        id: response_form.id,
                        attachment_action: "keep",
                        _destroy: "1",
                        consultation_response_form_data_attributes: {
                          id: response_form.consultation_response_form_data.id,
                          file: greenpaper_pdf,
                        },
                      },
                    },
                  } }

    refute_select ".errors"
    consultation.reload
    assert_not_nil consultation.consultation_participation.consultation_response_form
    assert_equal "two-pages.pdf", consultation.consultation_participation.consultation_response_form.consultation_response_form_data.carrierwave_file
  end

  view_test "updating should respect the attachment_action for response forms to remove it" do
    AssetManagerDeleteAssetWorker.stubs(:perform_async)

    response_form = create(:consultation_response_form)
    participation = create(:consultation_participation, consultation_response_form: response_form)
    consultation = create(:consultation, consultation_participation: participation)

    put :update,
        params: { id: consultation,
                  edition: {
                    consultation_participation_attributes: {
                      id: participation.id,
                      consultation_response_form_attributes: {
                        id: response_form.id,
                        attachment_action: "remove",
                      },
                    },
                  } }

    refute_select ".errors"
    consultation.reload
    assert_nil consultation.consultation_participation.consultation_response_form
    assert_raise(ActiveRecord::RecordNotFound) do
      response_form.consultation_response_form_data.reload
    end
    assert_raise(ActiveRecord::RecordNotFound) do
      response_form.reload
    end
  end

  view_test "updating should respect the attachment_action for response forms to replace it" do
    Services.asset_manager.stubs(:whitehall_asset).returns("id" => "http://asset-manager/assets/asset-id")
    Services.asset_manager.stubs(:delete_asset)

    two_pages_pdf = upload_fixture("two-pages.pdf")
    greenpaper_pdf = upload_fixture("greenpaper.pdf")

    response_form = create(:consultation_response_form, file: two_pages_pdf)
    participation = create(:consultation_participation, consultation_response_form: response_form)
    consultation = create(:consultation, consultation_participation: participation)

    put :update,
        params: { id: consultation,
                  edition: {
                    consultation_participation_attributes: {
                      id: participation.id,
                      consultation_response_form_attributes: {
                        id: response_form.id,
                        attachment_action: "replace",
                        _destroy: "1",
                        consultation_response_form_data_attributes: {
                          id: response_form.consultation_response_form_data.id,
                          file: greenpaper_pdf,
                        },
                      },
                    },
                  } }

    refute_select ".errors"
    consultation.reload
    assert_not_nil consultation.consultation_participation.consultation_response_form
    assert_equal "greenpaper.pdf", consultation.consultation_participation.consultation_response_form.consultation_response_form_data.carrierwave_file
  end

private

  def controller_attributes_for(edition_type, attributes = {})
    super.except(:alternative_format_provider).reverse_merge(
      alternative_format_provider_id: create(:alternative_format_provider).id,
    )
  end
end


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

'use strict';

angular.module('todos').controller('CreateCtrl', ['$scope', '$location', 'storage',
        /**
         * Controller for creating new documents
         *
         * @param {angular.Scope} $scope
         * @param {angular.$location} $location
         * @param {!object} storage
         * @constructor
         */
            function ($scope, $location, storage) {
            $scope.message = 'Please wait';
            storage.requireAuth().then(function () {
                storage.createDocument('Grace project').then(function (file) {
                    $location.url('/todos/' + file.id + '/');
                });
            }, function () {
                $location.url('/install?target=' + encodeURIComponent($location.url()));
            });
        }]
);


text:
import sys

MAX_INT = sys.maxint
'''
Heap data structure
-------------------
Maintains a balanced binary tree, where the value of each node is never larger than the values of its children.
The tree is represented using an array, since it is easy to calculate the index of the parent/child of a given
element (see __find_parent_index/__find_child_indexes)
'''
class Heap:
    def __init__(self):
        self.l = []

    def insert(self, value):
        self.l.append(value)
        index_of_value = len(self.l) - 1

        while index_of_value:
            index_of_parent = self.__find_parent_index(index_of_value)
            value_of_parent = self.l[index_of_parent]
            if value_of_parent > value:
                self.__swap(index_of_value, index_of_parent)
                index_of_value = index_of_parent
            else:
                break

    def extract_min(self):
        count = len(self.l)
        if count == 0:
            return None

        min_value = self.l.pop(0)
        count -= 1
        if count == 0:
            return min_value

        last_value = self.l.pop(count - 1)
        self.l.insert(0, last_value)

        i = 0
        value = last_value

        while True:
            i1, i2 = self.__find_child_indexes(i)

            v1 = MAX_INT if i1 is None else self.l[i1]
            v2 = MAX_INT if i2 is None else self.l[i2]

            if value <= min(v1, v2):
                break

            elif v1 <= v2:
                self.__swap(i1, i)
                i = i1
            else:
                self.__swap(i2, i)
                i = i2

        return min_value

    def __swap(self, i1, i2):
        self.l[i1], self.l[i2] = self.l[i2], self.l[i1]

    def __find_parent_index(self, i):
        return i / 2 # Python discards remainders for integer division, which is what we need here

    def __find_child_indexes(self, i):
        max_index = len(self.l) - 1
        i1 = i*2
        i2 = i1 + 1

        if i1 > max_index:
            return None, None
        else:
            return i1, None if i2 > max_index else i2


text:
import ShareYourSystem as SYS

#define and command with one get key str
MyCommander=SYS.CommanderClass(
	).command(
		#CommandingGetVariable
		'/',
		#CommandingSetVariable
		{
			'MyStr':"hello"
		}
	)

#print
print('MyCommander.GettedValueVariable is ')
print(MyCommander.GettedValueVariable)

#command with just one variable
SYS.CommanderClass.printHello=lambda _SelfVariable:SYS._print(
	_SelfVariable.MyStr
)
MyCommander.command('/','#call:printHello')


text:
/**
 * @ignore
 * singleTouchStart event
 * @author yiminghe@gmail.com
 */
KISSY.add('event/dom/touch/single-touch-start', function (S, eventHandleMap, DomEvent, SingleTouch) {

    var event = 'singleTouchStart';

    function SingleTouchStart() {
    }

    S.extend(SingleTouchStart, SingleTouch, {

        onTouchStart: function (e) {
            if (SingleTouchStart.superclass.onTouchStart.apply(this, arguments) !== false) {
                var touch= e.touches[0];
                DomEvent.fire(e.target, event, {
                    touch: touch[0],
                    pageX:touch.pageX,
                    pageY:touch.pageY,
                    which: 1,
                    touches: e.touches
                });
                return undefined;
            }
            return false;
        }

    });

    eventHandleMap[event] = {
        handle: new SingleTouchStart()
    };

    return SingleTouchStart;

}, {
    requires: ['./handle-map', 'event/dom/base', './single-touch']
});

/**
 * for draggable:
 * listen singleTouchStart insteadof native touchstart in case inner element call stopPropagation
 */


text:
/**
 * Java Interface example.
 * This Java Interface example describes how interface is defined and
 * being used in Java language.
 *
 * Syntax of defining java interface is,
 * <modifier> interface <interface-name>{
 *  //members and methods()
 * }
 *
 * @author Keeyana Jones <keeyanajones@yahoo.com>
 *
 **/

package javaproject;

//declare an interface
interface IntExample {
  /**
   * Syntax to declare method in java interface is,
   * <modifier> <return-type> methodName(<optional-parameters>);
   * IMPORTANT : Methods declared in the interface are implicitly public and
   * abstract.
   **/

  public void sayHello();
}

/**
 * Classes are extended while interfaces are implemented.
 * To implement an interface use implements keyword.
 * IMPORTANT : A class can extend only one other class, while it
 * can implement n number of interfaces.
 **/
public class JavaInterface implements IntExample {
    /**
     * We have to define the method declared in implemented interface,
     * or else we have to declare the implementing class as abstract class.
     **/

    public void sayHello() {
        System.out.println("Hello Visitor!");
    }

    public static void main(String args[]) {
        //create object of the class
        JavaInterface javaInterface = new JavaInterface();
        //invoke sayHello(), declared in IntExample interface.
        javaInterface.sayHello();
    }
}


text:
@interface SettingsViewController : UIViewController <FeedDelegate> {
//    NSString *feedId;
//    NSString *apiKey;

    Feed *myFeed;

    IBOutlet UITextField *feedIdField;
    IBOutlet UILabel *infoField;
    IBOutlet UIButton *saveButton;
    IBOutlet UIButton *loginButton;

    IBOutlet UISlider *updateFrequency;
    IBOutlet UILabel *updateFrequencyValue;
}
@property (nonatomic, retain) NSString *accessToken;

- (IBAction)saveSettings:(id)sender;
- (IBAction)backgroundClick:(id)sender;
- (IBAction)beginAuthorisation:(id)sender;
- (IBAction)frequencyChanged:(id)sender;

- (void)loadSettings;
@end


text:
package org.sakaiproject.tool.assessment.ui.bean.authz;

import org.sakaiproject.tool.assessment.facade.AgentFacade;
import org.sakaiproject.tool.assessment.services.PersistenceService;
import org.sakaiproject.tool.assessment.ui.listener.author.AuthorActionListener;
import org.sakaiproject.tool.assessment.ui.listener.select.SelectActionListener;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.tool.assessment.data.dao.authz.AuthorizationData;
import org.sakaiproject.tool.cover.ToolManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthorizationBean implements Serializable {
  /**
	 *
	 */
	private static final long serialVersionUID = -2782949557257727817L;

private static Log log = LogFactory.getLog(AuthorizationBean.class);

  private HashMap<String, Boolean> map = new HashMap<String, Boolean>();
  private boolean adminPrivilege = false;
  private boolean adminNewAssessmentPrivilege = false;
  private boolean adminCoreAssessmentPrivilege = false;
  private boolean adminPublishedAssessmentPrivilege = false;
  private boolean adminAssessmentPrivilege = false;
  private boolean adminTemplatePrivilege = false;
  private boolean adminQuestionPoolPrivilege = false;
  private Boolean superUser = null;

  public AuthorizationBean(){
  }

  public HashMap<String, Boolean> getAuthzMap(){
    return map;
  }
  public boolean getAdminPrivilege(){
	  if(!this.initializedPerm){
		  initializePermission();
		  this.initializedPerm=true;
	  }
    return getPrivilege("admin.privilege");
  }

  public boolean getAdminNewAssessment(){
    return getPrivilege("admin.new.assessment");
  }

  public boolean getAdminCoreAssessment(){
    return getPrivilege("admin.core.assessment");
  }

  public boolean getAdminPublishedAssessment(){
    return getPrivilege("admin.published.assessment");
  }

  public boolean getAdminAssessment(){
    return getPrivilege("admin.assessment");
  }

  public boolean getAdminTemplate(){
    return getPrivilege("admin.template");
  }

  public boolean getAdminQuestionPool(){
    return getPrivilege("admin.questionpool");
  }

  // This method is called (via jsf/security/roleCheckStaticInclude.jsp)
  // when user first enter samigo in a site.
  // This is the time when we determine his permission in the site.
  // This info is stored in the AuthorizationService HashMap for the entire session.
  public void addAllPrivilege(String siteId){
    // admin functions
    boolean p1 = canCreateAssessment(siteId);
    boolean p2 = canEditAnyAssessment(siteId);
    boolean p3 = canEditOwnAssessment(siteId);
    boolean p4 = canDeleteAnyAssessment(siteId);
    boolean p5 = canDeleteOwnAssessment(siteId);
    boolean p6 = canPublishAnyAssessment(siteId);
    boolean p7 = canPublishOwnAssessment(siteId);
    boolean p8 = canGradeAnyAssessment(siteId);
    boolean p9 = canGradeOwnAssessment(siteId);
    boolean p10 = canCreateQuestionPool(siteId);
    boolean p11 = canEditOwnQuestionPool(siteId);
    boolean p12 = canDeleteOwnQuestionPool(siteId);
    boolean p13 = canCopyOwnQuestionPool(siteId);
    boolean p14 = canCreateTemplate(siteId);
    boolean p15 = canEditOwnTemplate(siteId);
    boolean p16 = canDeleteOwnTemplate(siteId);

    // non admin functions
    canTakeAssessment(siteId);
    canSubmitAssessmentForGrade(siteId);

    // set adminPrivilege
    adminNewAssessmentPrivilege = p1;
    addAdminPrivilege(adminNewAssessmentPrivilege, "admin.new.assessment", siteId);

    adminCoreAssessmentPrivilege = p2 || p3 || p4 || p5 || p6 || p7;
    addAdminPrivilege(adminCoreAssessmentPrivilege, "admin.core.assessment", siteId);

    adminPublishedAssessmentPrivilege = p8 || p9;
    addAdminPrivilege(adminPublishedAssessmentPrivilege, "admin.published.assessment", siteId);

    adminAssessmentPrivilege = p1 || p2 || p3 || p4 || p5 || p6 || p7 || p8 || p9;
    addAdminPrivilege(adminAssessmentPrivilege, "admin.assessment", siteId);

    adminQuestionPoolPrivilege = p10 || p11 || p12 || p13;
    addAdminPrivilege(adminQuestionPoolPrivilege, "admin.questionpool", siteId);

    adminTemplatePrivilege = p14 ||p15 || p16;
    addAdminPrivilege(adminTemplatePrivilege, "admin.template", siteId);

    adminPrivilege = adminAssessmentPrivilege || adminQuestionPoolPrivilege || adminTemplatePrivilege;
    addAdminPrivilege(adminPrivilege, "admin.privilege", siteId);
  }

  public boolean canTakeAssessment(String siteId)
  {
    return addPrivilege("assessment.takeAssessment", siteId);
  }

  public boolean canSubmitAssessmentForGrade(String siteId)
  {
    return addPrivilege("assessment.submitAssessmentForGrade", siteId);
  }

  public boolean canCreateAssessment(String siteId)
  {
    return addPrivilege("assessment.createAssessment", siteId);
  }

  public boolean canEditAnyAssessment(String siteId)
  {
    return addPrivilege("assessment.editAssessment.any", siteId);
  }

  public boolean canEditOwnAssessment(String siteId)
  {
    return addPrivilege("assessment.editAssessment.own", siteId);
  }

  public boolean canDeleteAnyAssessment(String siteId)
  {
    return addPrivilege("assessment.deleteAssessment.any", siteId);
  }

  public boolean canDeleteOwnAssessment(String siteId)
  {
    return addPrivilege("assessment.deleteAssessment.own", siteId);
  }

  public boolean canPublishAnyAssessment(String siteId)
  {
    return addPrivilege("assessment.publishAssessment.any", siteId);
  }

  public boolean canPublishOwnAssessment(String siteId)
  {
    return addPrivilege("assessment.publishAssessment.own", siteId);
  }

  public boolean canGradeAnyAssessment(String siteId)
  {
    return addPrivilege("assessment.gradeAssessment.any", siteId);
  }

  public boolean canGradeOwnAssessment(String siteId)
  {
    return addPrivilege("assessment.gradeAssessment.own", siteId);
  }

  public boolean canCreateQuestionPool(String siteId)
  {
    return addPrivilege("assessment.questionpool.create", siteId);
  }

  public boolean canEditOwnQuestionPool(String siteId)
  {
    return addPrivilege("assessment.questionpool.edit.own", siteId);
  }

  public boolean canDeleteOwnQuestionPool(String siteId)
  {
    return addPrivilege("assessment.questionpool.delete.own", siteId);
  }

  public boolean canCopyOwnQuestionPool(String siteId)
  {
    return addPrivilege("assessment.questionpool.copy.own", siteId);
  }

  public boolean canCreateTemplate(String siteId)
  {
    return addPrivilege("assessment.template.create", siteId);
  }

  public boolean canEditOwnTemplate(String siteId)
  {
    return addPrivilege("assessment.template.edit.own", siteId);
  }

  public boolean canDeleteOwnTemplate(String siteId)
  {
    return addPrivilege("assessment.template.delete.own", siteId);
  }

  public boolean addPrivilege(String functionName, String siteId){
     boolean privilege = PersistenceService.getInstance().getAuthzQueriesFacade().hasPrivilege(functionName);
     map.put(functionName+"_"+siteId, Boolean.valueOf(privilege));
     return privilege;
  }

  private boolean initializedPerm =  false;
  /**
   * This will initialize the user permissions and related assessment's list
   */
  private void initializePermission(){
	  //this is moved from original roleCheckStaticInclude.jsp page, which is not working for JSF 1.2 up.
	  addAllPrivilege(ToolManager.getCurrentPlacement().getContext());
	  if (!adminPrivilege)
	  {
	          SelectActionListener listener = new SelectActionListener();
	          listener.processAction(null);
	  }
	  else
	  {
	     AuthorActionListener authorlistener = new AuthorActionListener();
	     authorlistener.processAction(null);
	  }
  }

  public void addAdminPrivilege(boolean privilege, String functionName, String siteId){
     map.put(functionName+"_"+siteId, Boolean.valueOf(privilege));
  }

  public boolean getTakeAssessment(){
    return getPrivilege("assessment.takeAssessment");
  }

  public boolean getSubmitAssessmentForGrade(){
    return getPrivilege("assessment.submitAssessmentForGrade");
  }
  public boolean getCreateAssessment(){
    return getPrivilege("assessment.createAssessment");
  }

  public boolean getEditAnyAssessment() {
    return getPrivilege("assessment.editAssessment.any");
  }

  public boolean getEditOwnAssessment() {
    return getPrivilege("assessment.editAssessment.own");
  }

  public boolean getDeleteAnyAssessment() {
    return getPrivilege("assessment.deleteAssessment.any");
  }

  public boolean getDeleteOwnAssessment() {
    return getPrivilege("assessment.deleteAssessment.own");
  }

  public boolean getPublishAnyAssessment() {
    return getPrivilege("assessment.publishAssessment.any");
  }

  public boolean getPublishOwnAssessment() {
    return getPrivilege("assessment.publishAssessment.own");
  }

  public boolean getGradeAnyAssessment() {
    boolean priv = getPrivilege("assessment.gradeAssessment.any");
    return priv;
  }

  public boolean getGradeOwnAssessment() {
    boolean priv = getPrivilege("assessment.gradeAssessment.own");
    return priv;
  }

  public boolean getCreateQuestionPool() {
    return getPrivilege("assessment.questionpool.create");
  }

  public boolean getEditOwnQuestionPool() {
    return getPrivilege("assessment.questionpool.edit.own");
  }

  public boolean getDeleteOwnQuestionPool() {
    return getPrivilege("assessment.questionpool.delete.own");
  }

  public boolean getCopyOwnQuestionPool() {
    return getPrivilege("assessment.questionpool.copy.own");
  }

  public boolean getCreateTemplate() {
    return getPrivilege("assessment.template.create");
  }

  public boolean getEditOwnTemplate() {
    return getPrivilege("assessment.template.edit.own");
  }

  public boolean getDeleteOwnTemplate() {
    return getPrivilege("assessment.template.delete.own");
  }

  public boolean getPrivilege(String functionName){
    return getPrivilege(functionName,null);
  }

  public boolean getPrivilege(final String functionName, String siteId){
	if (siteId == null) {
		siteId  = AgentFacade.getCurrentSiteId();
	}

    boolean privilege = false;
    Object o = map.get(functionName+"_"+siteId);
    if (o != null) privilege = ((Boolean)o).booleanValue();
    return privilege;
  }

  // added the follwoing for ShowMediaServlet
  public boolean getGradeAnyAssessment(String siteId) {
    return getPrivilege("assessment.gradeAssessment.any", siteId);
  }

  public boolean getGradeOwnAssessment(String siteId) {
    return getPrivilege("assessment.gradeAssessment.own", siteId);
  }

  public boolean isUserAllowedToPublishAssessment(final String assessmentId, final String assessmentOwnerId, final boolean published) {
    if (!isAssessmentInSite(assessmentId, published)) {
      return false;
    }

    if (getPublishAnyAssessment()) {
      return true;
    }
    else if (getPublishOwnAssessment()) {
      final String loggedInUser = AgentFacade.getAgentString();
      return StringUtils.equals(loggedInUser, assessmentOwnerId);
    }
    return false;
  }

  public boolean isUserAllowedToGradeAssessment(final String assessmentId, final String assessmentOwnerId, final boolean published) {
	 return isUserAllowedToGradeAssessment(assessmentId,assessmentOwnerId,published,null);
  }

  public boolean isUserAllowedToGradeAssessment(final String assessmentId, final String assessmentOwnerId, final boolean published, String currentSiteId) {
    if (!isAssessmentInSite(assessmentId,currentSiteId,published)) {
      return false;
    }

    // Second check on the realm permissions
    if (getGradeAnyAssessment(currentSiteId)) {
      return true;
    }
    else if (getGradeOwnAssessment(currentSiteId)) {
      final String loggedInUser = AgentFacade.getAgentString();
      return StringUtils.equals(loggedInUser, assessmentOwnerId);
    }
    return false;
  }

  public boolean isUserAllowedToEditAssessment(final String assessmentId, final String assessmentOwnerId, final boolean published) {
    if (!isAssessmentInSite(assessmentId, published)) {
      return false;
    }

    // Second check on the realm permissions
    if (getEditAnyAssessment()) {
      return true;
    }
    else if (getEditOwnAssessment()) {
      final String loggedInUser = AgentFacade.getAgentString();
      return StringUtils.equals(loggedInUser, assessmentOwnerId);
    }
    return false;
  }

  public boolean isUserAllowedToDeleteAssessment(final String assessmentId, final String assessmentOwnerId, final boolean published) {
    if (!isAssessmentInSite(assessmentId, published)) {
      return false;
    }

    // Second check on the realm permissions
    if (getDeleteAnyAssessment()) {
      return true;
    }
    else if (getDeleteOwnAssessment()) {
      final String loggedInUser = AgentFacade.getAgentString();
      return StringUtils.equals(loggedInUser, assessmentOwnerId);
    }
    return false;
  }

  public boolean isUserAllowedToTakeAssessment(final String assessmentId) {
    if (!isAssessmentInSite(assessmentId, true)) {
      return false;
    }

    // Second check on the realm permissions
    return getTakeAssessment();
  }

  public boolean isUserAllowedToCreateAssessment() {
    return getCreateAssessment();
  }

  // Check whether the assessment belongs to the given site
  public static boolean isAssessmentInSite(final String assessmentId, String siteId, final boolean published) {
	//Try to get the site Id
	if (siteId == null) {
		siteId = AgentFacade.getCurrentSiteId();
	}
    // get list of site that this published assessment has been released to
    List<AuthorizationData> l = PersistenceService.getInstance().getAuthzQueriesFacade().getAuthorizationByFunctionAndQualifier(published ? "OWN_PUBLISHED_ASSESSMENT" : "EDIT_ASSESSMENT", assessmentId);

    for (int i=0; i < l.size(); i++) {
      String assessmentSiteId = (l.get(i)).getAgentIdString();
      if (siteId.equals(assessmentSiteId)) {
        return true;
      }
    }

    return false;
  }

  public static boolean isAssessmentInSite(final String assessmentId, final boolean published) {
    return isAssessmentInSite(assessmentId, AgentFacade.getCurrentSiteId(), published);
  }

  public boolean isSuperUser() {
	  if (superUser == null) {
		  superUser = SecurityService.isSuperUser();
	  }
	  return superUser;
  }

}


text:
<?php
include('config.php');
include('header.php');

?>

<?php include('menu.php'); ?>

Search

			<form name="frm" method="POST" action="">

Name	<input type="text" id="name" class="pendek">

Codec
				<select id="codec">
					<option value ="" selected>-- codec --</option>
					<option value="XViD" >XViD</option>
                    <option value="x264" >x264</option>
                    <option value="MPEG2" >MPEG2</option>
                    <option value="DiVX" >DiVX</option>
                    <option value="DVDR" >DVDR</option>
                    <option value="VC-1" >VC-1</option>
                    <option value="h.264" >h.264</option>
                    <option value="WMV" >WMV</option>
                    <option value="BD" >BD</option>
                    <option value="x264-Hi10P" >x264-Hi10P</option>
				</select>

Resolution
				<select id="resolution">
					<option value ="" selected>-- resolution --</option>
                    <option value="SD" >SD</option>
                    <option value="720p" >720p</option>
                    <option value="1080p" >1080p</option>
                    <option value="1080i" >1080i</option>
                    <option value="Portable Device" >Portable Device</option>
				</select>

Source
				<select id="source">
					<option value ="" selected>-- source --</option>
                    <option value="HDTV" >HDTV</option>
                    <option value="PDTV" >PDTV</option>
                    <option value="DSR" >DSR</option>
                    <option value="DVDRip" >DVDRip</option>
                    <option value="TVRip" >TVRip</option>
                    <option value="VHSRip" >VHSRip</option>
                    <option value="Bluray" >Bluray</option>
                    <option value="BDRip" >BDRip</option>
                    <option value="BRRip" >BRRip</option>
                    <option value="DVD5" >DVD5</option>
                    <option value="DVD9" >DVD9</option>
                    <option value="HDDVD" >HDDVD</option>
                    <option value="WEB-DL" >WEB-DL</option>
                    <option value="WEBRip" >WEBRip</option>
                    <option value="BD5" >BD5</option>
                    <option value="BD9" >BD9</option>
                    <option value="BD25" >BD25</option>
                    <option value="BD50" >BD50</option>
                    <option value="Mixed" >Mixed</option>
                    <option value="Unknown" >Unknown</option>
				</select>

Container
				<select id="container">
					<option value ="" selected>-- container --</option>
                    <option value="AVI" >AVI</option>
                    <option value="MKV" >MKV</option>
                    <option value="VOB" >VOB</option>
                    <option value="MPEG" >MPEG</option>
                    <option value="MP4" >MP4</option>
                    <option value="ISO" >ISO</option>
                    <option value="WMV" >WMV</option>
                    <option value="TS" >TS</option>
                    <option value="M4V" >M4V</option>
                    <option value="M2TS" >M2TS</option>
				</select>

Origin
				<select id="origin">
					<option value ="" selected>-- origin --</option>
                    <option value="None" >None</option>
                    <option value="Scene" >Scene</option>
                    <option value="P2P" >P2P</option>
                    <option value="User" >User</option>
                    <option value="Mixed" >Mixed</option>
                    <option value="Internal" >Internal</option>
				</select>

Category
				<select id="category">
					<option value ="" selected>-- category --</option>
                    <option value="Episode" >Episode</option>
                    <option value="Season" >Season</option>
				</select>

			<input type="submit" class="button" id="Search" value="Submit">
			<input type="reset" class="button" value="Reset">

		</form>

<?php include('footer.php'); ?>


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PresenterType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Presenter',
            'allow_extra_fields' => true,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_presenter';
    }
}


text:
{% extends "kishore/admin/base.html" %}
{% load kishore_tags %}
{% load kishore_admin_tags %}

{% block artist_nav %}active{% endblock %}

{% block content %}

Add an Artist

<form method="post" action="." class="artist-form image-picker-form">
  {% csrf_token %}
  {% include 'kishore/admin/admin_form.html' %}
  <button type="submit" class="btn btn-primary">Create</button>
</form>
{% endblock %}


text:
import ctypes
import gobject
import signal
import sys
import thread

from statement import Statement

#
# The primary means we use to interrupt a running thread is a Python facility
# to set an exception asynchronously on another thread. To keep it out of
# unsuspecting hands, it's not bound in Python, so we need to accesss it
# through pthreads.
#
_PyThreadState_SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc

#
# _PyThreadState_SetAsyncExc won't immediately wake up a thread that is blocking
# in a syscall, so we also send a Unix signal to hopefully wake such a thread
# up. (This can be foiled if the syscall is called within C code that catches
# EINTR and restarts. In that case, we have no way of killing the thread without
# breaking Python internal state so we don't try.)
#
# To make sending a signal wake the thread up out of the syscall without killing
# the thread, we need a non-default no-op handler for the signal. The slightly
# tricky thing about what we do is that signal.signal() is defined to affect only
# the main thread, but the way it does it is set up a handler for all threads and
# then ignore the signal in all but the main thread. So, our ignore_handler is
# never called, but Python's handler does what we wanted to do (ignore the signal)
# anyways.
#
if sys.platform == 'win32':
    _pthread_kill = None
else:
    if sys.platform == 'darwin':
        # pthread_kill is in the C library on OS/X
        # ctypes.util.find_library("c") should work in theory, but doesn't
        _pthreads_dll = ctypes.CDLL("/usr/lib/libc.dylib")
    else:
        # Assume Linux. We intentionally don't guard this against failure
        # so that we get bug reports when we don't find libpthread
        _pthreads_dll = ctypes.CDLL("libpthread.so.0")

    _pthread_kill = _pthreads_dll.pthread_kill

if _pthread_kill is not None:
    def _ignore_handler(signum, frame):
        pass

    signal.signal(signal.SIGUSR1, _ignore_handler)

class ThreadExecutor(gobject.GObject):
    """Class to execute Python statements asynchronously in a thread

    Signals
    =======
     -  B{statement-executing}(executor, statement) emitted when the executor starts processing a statement. There is no guarantee that this signal will be emitted for each processed statement.
     -  B{statement-complete}(executor, statement) emitted when the executor is done with all processing it will do on a statement
     -  B{complete}(executor): emitted when the executor is done with all processing

    """

    __gsignals__ = {
        'statement-executing' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
        'statement-complete' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,)),
        'complete' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
    }

    def __init__(self, parent_statement=None):
        """Initialize the ThreadExecutor object

        @param parent_statement: prievous statement defining the execution environment for the first statement

        """
        gobject.GObject.__init__(self)

        self.parent_statement = parent_statement
        self.statements = []
        self.lock = thread.allocate_lock()

        self.idle_id = 0
        self.last_complete = -1
        self.last_signalled = -1
        self.complete = False
        self.interrupted = False

    def __run_idle(self):
        self.lock.acquire()
        complete = self.complete
        last_complete = self.last_complete
        self.idle_id = 0
        self.lock.release()

        for i in xrange(self.last_signalled + 1, last_complete + 1):
            self.emit('statement-complete', self.statements[i])

        self.last_signalled = last_complete

        if self.complete:
            self.emit('complete')
        elif last_complete < len(self.statements) - 1:
            self.emit('statement-executing', self.statements[last_complete + 1])

        return False

    def __queue_idle(self):
        # Must be called with the lock held
        if not self.idle_id:
            self.idle_id = gobject.idle_add(self.__run_idle)

    def __run_thread(self):
        # The patten used twice here of:
        #
        #  try:
        #      # do something with lock not held
        #      self.lock.acquire()
        #   except:
        #      self.lock.acquire()
        #   finally:
        #      # do finishing steps
        #
        # Counts on two things: a) we can receive an unexpected exception like
        # KeyboardInterrupt only once b) that exception can't occur with the lock
        # held. Given those assumptions, we can be sure that the finishing steps
        # will be run and they won't be interrupted.
        #
        statement = None
        try:
            for i, statement in enumerate(self.statements):
                self.lock.acquire()
                statement.before_execute()
                self.__queue_idle()
                try:
                    self.lock.release()
                    statement.execute()
                    self.lock.acquire()
                except:
                    self.lock.acquire()
                finally:
                    statement.after_execute()
                    result_state = statement.state
                    self.last_complete = i;
                    self.__queue_idle()
                    self.lock.release()

                    if result_state != Statement.EXECUTE_SUCCESS:
                        break

            self.lock.acquire()
        except KeyboardInterrupt, e:
            self.lock.acquire()
        except BaseException, e:
            self.lock.acquire()
            raise
        finally:
            self.complete = True
            self.last_complete = len(self.statements) - 1
            self.__queue_idle()
            self.lock.release()

    def add_statement(self, statement):
        """Add a statement to the list of statements that the executor will execute."""

        self.statements.append(statement)

    def compile(self):
        """Compile all statements.

        If compilation failed, then all processing for the executor is complete, so
        ::statement-complete is emitted for each statement, then ::complete is emitted.
        Otherwise no signals are emitted, until the executor is run using execute()

        @returns: True if all statements compiled successfully

        """

        success = True
        parent = self.parent_statement
        for statement in self.statements:
            statement.set_parent(parent)
            if not statement.compile():
                success = False
            parent = statement

        if not success:
            for statement in self.statements:
                self.emit('statement-complete', statement)
            self.emit('complete')

        return success

    def execute(self):
        """Execute the statements of the executor asynchronously in a thread."""
        self.tid = thread.start_new_thread(self.__run_thread, ())

    def interrupt(self):
        """Interrupts the execution of the executor if possible.

        Makes a best-effort attempt to interrupt the execution of the executor.
        An attempt is made to interrupt any blocking system calls, however if
        the execution is inside native code this may not be succesful.
        Long-running native code-computations will also not be interrupted.

        Once the thread is succesfully interrupted, execution finishes as per normal
        by emitting the ::statement-complete and ::complete signals, except that
        the state of the interrupted statement will be Statement.INTERRUPTED,
        and subsequence statements will have a state of Statement.COMPILE_SUCCESS.

        Calling interrupt() more than once will have no effect.

        """

        # See note in __run_thread() as to why we need to lock and why we need to
        # protect against sending the KeyboardInterrupt exception more than once
        self.lock.acquire()
        if not self.complete and not self.interrupted:
            self.interrupted = True
            _PyThreadState_SetAsyncExc(self.tid, ctypes.py_object(KeyboardInterrupt))
            if _pthread_kill is not None:
                _pthread_kill(self.tid, signal.SIGUSR1)
        self.lock.release()

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

if __name__ == '__main__': #pragma: no cover
    gobject.threads_init()

    import stdout_capture
    stdout_capture.init()

    import time

    from notebook import Notebook
    from statement import Statement
    from test_utils import assert_equals
    from worksheet import Worksheet

    failed = False

    notebook = Notebook()
    worksheet = Worksheet(notebook)

    def test_execute(statements):
        executor = ThreadExecutor()

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            statement._got_executing = False
            executor.add_statement(statement)

        loop = gobject.MainLoop()

        def on_statement_executing(executor, statement):
            if hasattr(statement, '_got_state'):
                statement._out_of_order = True
            statement._got_executing = True

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results
            statement._out_of_order = False

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.connect('statement-executing', on_statement_executing)
        executor.connect('statement-complete', on_statement_complete)
        executor.connect('complete', on_complete)

        if executor.compile():
            executor.execute()
            interrupt_source = gobject.timeout_add(500, interrupt)
            timeout_source = gobject.timeout_add(1000, timeout)
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")
            gobject.source_remove(interrupt_source)
            gobject.source_remove(timeout_source)

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
            if s._out_of_order:
                raise AssertionError("ThreadExecutor sent 'statement-executing' after 'statement-complete'")
            if s._expected_state == Statement.INTERRUPTED and not s._got_executing:
                raise AssertionError("ThreadExecutor did not send 'statement-executing' within timeout")

    test_execute(
        [
            ("a = 1", Statement.COMPILE_SUCCESS, None),
            ("a =", Statement.COMPILE_ERROR, None)
        ])

    test_execute(
        [
            ("a = 1", Statement.EXECUTE_SUCCESS, []),
            ("a", Statement.EXECUTE_SUCCESS, ['1'])
        ])

    test_execute(
        [
            ("a = 1", Statement.EXECUTE_SUCCESS, []),
            ("b", Statement.EXECUTE_ERROR, None),
            ("c = 2", Statement.COMPILE_SUCCESS, None)
        ])

    # Test interrupting straight python code
    test_execute(
        [
            ("y = 1", Statement.EXECUTE_SUCCESS, []),
            ("for x in xrange(0,100000000): y = y* 2", Statement.INTERRUPTED, None),
            ("z = 1", Statement.COMPILE_SUCCESS, None)
        ])

    # Test interrupting a blocking syscall, if support on this platform
    if _pthread_kill is not None:
        test_execute(
            [
                ("import sys", Statement.EXECUTE_SUCCESS, []),
                ("sys.stdin.readline()", Statement.INTERRUPTED, None),
                ("z = 1", Statement.COMPILE_SUCCESS, None)
            ])


text:
namespace blink {

WorkerNavigatorServices::~WorkerNavigatorServices()
{
}

WorkerNavigatorServices& WorkerNavigatorServices::from(WorkerNavigator& navigator)
{
    WorkerNavigatorServices* supplement = static_cast<WorkerNavigatorServices*>(HeapSupplement<WorkerNavigator>::from(navigator, supplementName()));
    if (!supplement) {
        supplement = new WorkerNavigatorServices();
        provideTo(navigator, supplementName(), supplement);
    }
    return *supplement;
}

ServicePortCollection* WorkerNavigatorServices::services(ExecutionContext* context, WorkerNavigator& navigator)
{
    return WorkerNavigatorServices::from(navigator).services(context);
}

ServicePortCollection* WorkerNavigatorServices::services(ExecutionContext* context)
{
    if (!m_services)
        m_services = ServicePortCollection::create(context);
    return m_services.get();
}

DEFINE_TRACE(WorkerNavigatorServices)
{
    visitor->trace(m_services);
    HeapSupplement<WorkerNavigator>::trace(visitor);
}

WorkerNavigatorServices::WorkerNavigatorServices()
{
}

const char* WorkerNavigatorServices::supplementName()
{
    return "WorkerNavigatorServices";
}

} // namespace blink


text:
/*
 *  Util.cpp
 *  mert - Minimum Error Rate Training
 *
 *  Created by Nicola Bertoldi on 13/05/08.
 *
 */

#include "Util.h"
#include "Timer.h"

using namespace std;

namespace
{

MosesTuning::Timer g_timer;
int g_verbose = 0;

bool FindDelimiter(const std::string &str, const std::string &delim, size_t *pos)
{
  *pos = str.find(delim);
  return *pos != std::string::npos ? true : false;
}

} // namespace

namespace MosesTuning
{

int verboselevel()
{
  return g_verbose;
}

int setverboselevel(int v)
{
  g_verbose = v;
  return g_verbose;
}

size_t getNextPound(std::string &str, std::string &substr,
                    const std::string &delimiter)
{
  size_t pos = 0;

  // skip all occurrences of delimiter
  while (pos == 0) {
    if (FindDelimiter(str, delimiter, &pos)) {
      substr.assign(str, 0, pos);
      str.erase(0, pos + delimiter.size());
    } else {
      substr.assign(str);
      str.assign("");
    }
  }
  return pos;
}

void split(const std::string &s, char delim, std::vector<std::string> &elems)
{
  std::stringstream ss(s);
  std::string item;
  while(std::getline(ss, item, delim)) {
    elems.push_back(item);
  }
}

void Tokenize(const char *str, const char delim,
              std::vector<std::string> *res)
{
  while (1) {
    const char *begin = str;
    while (*str != delim && *str) str++;
    if (begin != str)            // Don't create empty string objects.
      res->push_back(std::string(begin, str));
    if (*str++ == 0) break;
  }
}

void ResetUserTime()
{
  g_timer.start();
}

void PrintUserTime(const std::string &message)
{
  g_timer.check(message.c_str());
}

double GetUserTime()
{
  return g_timer.get_elapsed_cpu_time();
}

}