text:
require "test_helper"

class Admin::EditionFilterTest < ActiveSupport::TestCase
  setup do
    @current_user = build(:gds_editor)
  end

  test "can preload unpublishing data if asked to" do
    news_article = create(:news_article)
    create(:unpublishing, edition: news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user, include_unpublishing: true).editions
    assert_equal news_article, editions.first
    assert editions.first.association(:unpublishing).loaded?
  end

  test "does not preload unpublishing data unless asked to" do
    news_article = create(:news_article)
    create(:unpublishing, edition: news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user).editions
    assert_equal news_article, editions.first
    assert_not editions.first.association(:unpublishing).loaded?
  end

  test "can preload last author data if asked to" do
    news_article = create(:news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user, include_last_author: true).editions
    assert_equal news_article, editions.first
    assert editions.first.association(:last_author).loaded?
  end

  test "does not preload last author data unless asked to" do
    news_article = create(:news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user).editions
    assert_equal news_article, editions.first
    assert_not editions.first.association(:last_author).loaded?
  end

  test "can preload link check report data if asked to" do
    news_article = create(:news_article)
    create(:link_checker_api_report, link_reportable: news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user, include_link_check_reports: true).editions
    assert_equal news_article, editions.first
    assert editions.first.association(:link_check_reports).loaded?
  end

  test "does not preload link check report data unless asked to" do
    news_article = create(:news_article)
    create(:link_checker_api_report, link_reportable: news_article)

    editions = Admin::EditionFilter.new(Edition, @current_user).editions
    assert_equal news_article, editions.first
    assert_not editions.first.association(:last_author).loaded?
  end

  test "ignores invalid state scopes" do
    news_article = create(:draft_news_article)

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, state: "delete_all").editions
    assert_equal [news_article], Edition.all
  end

  test "should filter by edition type" do
    news_article = create(:news_article)
    _another_edition = create(:publication)

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, type: "news_article").editions
  end

  test "should filter by edition state" do
    draft_edition = create(:draft_publication)
    _edition_in_other_state = create(:published_publication)

    assert_equal [draft_edition], Admin::EditionFilter.new(Edition, @current_user, state: "draft").editions
  end

  test "should filter by edition author" do
    author = create(:user)
    edition = create(:publication, authors: [author])
    _edition_by_another_author = create(:publication)

    assert_equal [edition], Admin::EditionFilter.new(Edition, @current_user, author: author.to_param).editions
  end

  test "should filter by organisation" do
    organisation = create(:organisation)
    edition = create(:publication, organisations: [organisation])
    _edition_in_no_organisation = create(:publication)
    _edition_in_another_organisation = create(:publication, organisations: [create(:organisation)])

    assert_equal [edition], Admin::EditionFilter.new(Edition, @current_user, organisation: organisation.to_param).editions
  end

  test "should filter by edition type, state and author" do
    author = create(:user)
    news_article = create(:draft_news_article, authors: [author])
    _another_edition = create(:published_publication, authors: [author])

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, type: "news_article", state: "draft", author: author.to_param).editions
  end

  test "should filter by edition type, state and organisation" do
    organisation = create(:organisation)
    news_article = create(:draft_news_article, organisations: [organisation])
    _another_edition = create(:published_news_article, organisations: [organisation])

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, type: "news_article", state: "draft", organisation: organisation.to_param).editions
  end

  test "should filter by edition type, state and world location" do
    location = create(:world_location)
    news_article = create(:draft_news_article, world_locations: [location])
    _another_edition = create(:published_news_article, world_locations: [location])

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, type: "news_article", state: "draft", world_location: location.id).editions
  end

  test "should filter by world location" do
    location = create(:world_location)
    _consultation = create(:consultation)
    news_article = create(:news_article, world_locations: [location])

    assert_equal [news_article], Admin::EditionFilter.new(Edition, @current_user, world_location: location.id).editions
  end

  test "should filter by user's world locations" do
    location = create(:world_location)
    user = create(:user, world_locations: [location])
    _consultation = create(:consultation)
    news_article = create(:news_article, world_locations: [location])

    assert_equal [news_article], Admin::EditionFilter.new(Edition, user, world_location: "user").editions
  end

  test "should filter by news article sub-type" do
    _news_story   = create(:news_article, news_article_type: NewsArticleType::NewsStory)
    press_release = create(:news_article, news_article_type: NewsArticleType::PressRelease)
    assert_equal [press_release], Admin::EditionFilter.new(Edition, @current_user, type: "news_article_2").editions
  end

  test "should filter by speech sub-type" do
    _transcript    = create(:speech, speech_type: SpeechType::Transcript)
    speaking_notes = create(:speech, speech_type: SpeechType::SpeakingNotes)
    assert_equal [speaking_notes], Admin::EditionFilter.new(Edition, @current_user, type: "speech_3").editions
  end

  test "should filter by publication sub-type" do
    guidance = create(:publication, publication_type: PublicationType::Guidance)
    _form    = create(:publication, publication_type: PublicationType::Form)
    assert_equal [guidance], Admin::EditionFilter.new(Edition, @current_user, type: "publication_#{PublicationType::Guidance.id}").editions
  end

  test "should filter by multiple publication sub-types" do
    guidance     = create(:publication, publication_type: PublicationType::Guidance)
    form         = create(:publication, publication_type: PublicationType::Form)
    policy_paper = create(:publication, publication_type: PublicationType::PolicyPaper)

    assert_same_elements [form, policy_paper],
                         Admin::EditionFilter.new(
                           Edition,
                           @current_user,
                           type: "publication",
                           subtypes: [PublicationType::PolicyPaper.id, PublicationType::Form.id],
                         ).editions

    assert_equal [guidance],
                 Admin::EditionFilter.new(
                   Edition,
                   @current_user,
                   type: "publication",
                   subtypes: [PublicationType::Guidance.id],
                 ).editions
  end

  test "should filter by title" do
    detailed = create(:news_article, title: "Test mcTest")
    _news_article = create(:news_article, title: "A news_article")

    assert_equal [detailed], Admin::EditionFilter.new(Edition, @current_user, title: "test").editions
  end

  test "should filter by date" do
    _older_news_article = create(:draft_news_article, updated_at: 3.days.ago)
    newer_news_article = create(:draft_news_article, updated_at: 1.minute.ago)

    assert_equal [newer_news_article], Admin::EditionFilter.new(Edition, @current_user, from_date: 2.days.ago.to_date.to_fs(:short)).editions
  end

  test "can filter by topical_events" do
    topical_event = create(:topical_event)
    tagged_news   = create(:published_news_article, topical_events: [topical_event])
    _not_tagged   = create(:published_news_article)
    filter        = Admin::EditionFilter.new(Edition, @current_user, topical_event: topical_event.to_param)

    assert_equal [tagged_news], filter.editions
  end

  test "should filter by broken links" do
    edition_with_broken_links = create(
      :published_publication,
      body: "[A broken page](https://www.gov.uk/another-bad-link)\n[A bad link](https://www.gov.uk/bad-link)",
    )
    edition = create(
      :published_publication,
      body: "[Good](https://www.gov.uk/good-link)",
    )
    good_link = create(:link_checker_api_report_link, uri: "https://www.gov.uk/good-link", status: "ok")
    bad_link = create(:link_checker_api_report_link, uri: "https://www.gov.uk/bad-link", status: "broken")
    another_bad_link = create(:link_checker_api_report_link, uri: "https://www.gov.uk/another-bad-link", status: "broken")
    create(:link_checker_api_report, batch_id: 1, link_reportable: edition_with_broken_links, links: [bad_link, another_bad_link])
    create(:link_checker_api_report, batch_id: 2, link_reportable: edition, links: [good_link])

    assert_equal [edition_with_broken_links], Admin::EditionFilter.new(Edition, @current_user, only_broken_links: true).editions
  end

  test "should return the editions ordered by most recent first" do
    older_news_article = create(:draft_news_article, updated_at: 3.days.ago)
    newer_news_article = create(:draft_news_article, updated_at: 1.minute.ago)

    assert_equal [newer_news_article, older_news_article], Admin::EditionFilter.new(Edition, @current_user, {}).editions
  end

  test "should be invalid if author can't be found" do
    filter = Admin::EditionFilter.new(Edition, @current_user, author: "invalid")
    assert_not filter.valid?
  end

  test "should be invalid if organisation can't be found" do
    filter = Admin::EditionFilter.new(Edition, @current_user, organisation: "invalid")
    assert_not filter.valid?
  end

  test "should generate page title when there are no filter options" do
    filter = Admin::EditionFilter.new(Edition, build(:user))
    assert_equal "Everyone's documents", filter.page_title
  end

  test "should generate page title when we're displaying active documents" do
    filter = Admin::EditionFilter.new(Edition, build(:user), state: "active")
    assert_equal "Everyone's documents", filter.page_title
  end

  test "should generate page title when filtering by document state" do
    filter = Admin::EditionFilter.new(Edition, build(:user), state: "draft")
    assert_equal "Everyone's draft documents", filter.page_title
  end

  test "should generate page title when filtering by document type" do
    filter = Admin::EditionFilter.new(Edition, build(:user), type: "news_article")
    assert_equal "Everyone's news articles", filter.page_title
  end

  test "should generate page title when filtering by document sub-type" do
    filter = Admin::EditionFilter.new(Edition, build(:user), type: "news_article_1")
    assert_equal "Everyone's news stories", filter.page_title
  end

  test "should generate page title when filtering by any organisation" do
    organisation = create(:organisation, name: "Cabinet Office")
    filter = Admin::EditionFilter.new(Edition, build(:user), organisation: organisation.to_param)
    assert_equal "Cabinet Office's documents", filter.page_title
  end

  test "should generate page title when filtering by my organisation" do
    organisation = create(:organisation)
    user = create(:user, organisation:)
    filter = Admin::EditionFilter.new(Edition, user, organisation: organisation.to_param)
    assert_equal "My department's documents", filter.page_title
  end

  test "should generate page title when filtering by any author" do
    user = create(:user, name: "John Doe")
    filter = Admin::EditionFilter.new(Edition, build(:user), author: user.to_param)
    assert_equal "John Doe's documents", filter.page_title
  end

  test "should generate page title when filtering by my documents" do
    user = create(:user)
    filter = Admin::EditionFilter.new(Edition, user, author: user.to_param)
    assert_equal "My documents", filter.page_title
  end

  test "should generate page title when filtering by document state, document type and organisation" do
    organisation = create(:organisation, name: "Cabinet Office")
    filter = Admin::EditionFilter.new(Edition, build(:user), state: "published", type: "consultation", organisation: organisation.to_param)
    assert_equal "Cabinet Office's published consultations", filter.page_title
  end

  test "should generate page title when filtering by document state, document type and author" do
    user = create(:user, name: "John Doe")
    filter = Admin::EditionFilter.new(Edition, build(:user), state: "rejected", type: "speech", author: user.to_param)
    assert_equal "John Doe's rejected speeches", filter.page_title
  end

  test "should generate page title when filtering by title" do
    filter = Admin::EditionFilter.new(Edition, build(:user), title: "test")
    assert_equal "Everyone's documents that match 'test'", filter.page_title
  end

  test "should generate page title when filtering by world location" do
    location = create(:world_location, name: "Spain")
    filter = Admin::EditionFilter.new(Edition, build(:user), world_location: location.to_param)
    assert_equal "Everyone's documents about Spain", filter.page_title
  end

  test "should generate page title for from date" do
    filter = Admin::EditionFilter.new(Edition, build(:user), from_date: "09/11/2011")
    assert_equal "Everyone's documents from 09/11/2011", filter.page_title
  end

  test "should generate page title for to date" do
    filter = Admin::EditionFilter.new(Edition, build(:user), to_date: "09/11/2011")
    assert_equal "Everyone's documents before 09/11/2011", filter.page_title
  end

  test "should paginate editions" do
    3.times { create(:news_article) }
    filter = Admin::EditionFilter.new(Edition, build(:user), per_page: 2)
    assert_equal 2, filter.editions.count
  end

  test "editions_for_csv should not be paginated" do
    3.times { create(:news_article) }
    filter = Admin::EditionFilter.new(Edition, build(:user), per_page: 2)
    count = 0
    filter.each_edition_for_csv { |_unused| count += 1 }
    assert_equal 3, count
  end

  test "exportable? if number of editions is below threshold" do
    filter = Admin::EditionFilter.new(Edition, build(:user), per_page: 2)
    filter.stubs(:unpaginated_editions).returns(stub(count: 8000))
    assert filter.exportable?
    filter.stubs(:unpaginated_editions).returns(stub(count: 8001))
    assert_not filter.exportable?
  end
end


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

namespace Framework.Ioc.Benchmark.Domain
{
	public interface IAuthenticator
	{
		ILogger Logger { get; }
		IErrorHandler ErrorHandler { get; }
		IDatabase Database { get; }
	}
}

redpajama_set_name: RedPajamaGithub


text:
		Shop :
		Orders

<a href="<?= site_url('admin/shop'); ?>"> Shop

Orders <?php if ($trackingStatus) echo '('.$statusArray[$trackingStatus].')'?>

Orders

							<?php
								foreach ($statusArray as $key => $status):
									$options[$key] = $status;
								endforeach;

								echo form_dropdown('filter',$options,$trackingStatus,'id="filter" style="right:165px;"');
							?>

							<a href="<?= site_url('/admin/shop/export_orders'); ?>" class="mb-xs mt-xs mr-xs btn btn-blue">Export Orders as CSV

							<form method="post" action="<?= site_url('/admin/shop/orders'); ?>" class="default" id="search">
								<input type="text" name="searchbox" id="searchbox" class="formelement inactive" title="Search Products..." />
								<input type="image" src="<?= base_url($this->config->item('staticPath')); ?>/images/btn_search.gif" id="searchbutton" />
							</form>

						<?php if ($orders): ?>

						<?php echo $this->pagination->create_links(); ?>

								Order ID
								Date Ordered
								Full Name
								Number of Items
								Total (<?php echo currency_symbol(); ?>)
								Status

						<?php foreach ($orders as $order):
							if (!$order['viewed']) $class = 'style="font-weight: bold;"'; else $class='';
						?>
							<tr <?php echo $class ?>>
								<?php echo anchor('/admin/shop/view_order/'.$order['transactionID'], $order['transactionCode']); ?>
								<?php echo dateFmt($order['dateCreated'], '', '', TRUE); ?>
								<?php echo $order['firstName']; ?> <?php echo $order['lastName']; ?>
								<?php echo $order['numItems']; ?>
								<?php echo currency_symbol().number_format($order['amount'],2); ?>

									<?php
										if ($order['trackingStatus'] == 'U' && $order['paid']) echo 'Unprocessed';
										elseif ($order['trackingStatus'] == 'L') echo 'Allocated';
										elseif ($order['trackingStatus'] == 'A') echo 'Awaiting Goods';
										elseif ($order['trackingStatus'] == 'O') echo 'Out of Stock';
										elseif ($order['trackingStatus'] == 'D') echo 'Dispatched';
										else echo 'Unpaid Checkout';
									?>

								<?php echo anchor('/admin/shop/view_order/'.$order['transactionID'], 'View'); ?>
								<?php echo anchor('/admin/shop/delete_order/'.$order['transactionID'], 'Delete', 'onclick="return confirm(\'Are you absolutely sure you want to delete this order? There is no undo.\')"'); ?>

						<?php endforeach; ?>

						<?php echo $this->pagination->create_links(); ?>

Back to top

						<?php else: ?>

There were no orders found.

						<?php endif; ?>


text:
package org.mutabilitydetector.checkers;

import java.util.ArrayList;
import java.util.List;

import org.mutabilitydetector.asmoverride.AsmCompatibility;
import org.mutabilitydetector.asmoverride.AsmVerifierFactory;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.AnalyzerException;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;

public abstract class FieldAssignmentVisitor extends MethodNode {

    protected List<FieldInsnNode> fieldAssignments = new ArrayList<FieldInsnNode>();
    protected final String owner;
    private final AsmVerifierFactory verifierFactory;

    public FieldAssignmentVisitor(String owner,
            int access,
            String name,
            String desc,
            String signature,
            String[] exceptions,
            AsmVerifierFactory verifierFactory) {
        super(AsmCompatibility.AsmApiVersion, access, name, desc, signature, exceptions);
        this.owner = owner;
        this.verifierFactory = verifierFactory;
    }

    @Override
    public void visitFieldInsn(int opcode, String fieldsOwner, String fieldName, String fieldDesc) {
        super.visitFieldInsn(opcode, fieldsOwner, fieldName, fieldDesc);
        if (opcode == Opcodes.PUTFIELD) {
            fieldAssignments.add((FieldInsnNode) instructions.getLast());
        }

    }

    /**
     *
     * At the end of a method, the frames are analysed to be able to inspect
     * the state of the stack when the field is assigned. This method is
     * called, giving the frame at the time of the assignment, as well as
     * the instruction node.
     *
     * @param assignmentFrame
     * @param fieldInsnNode
     */
    abstract protected void visitFieldAssignmentFrame(Frame<BasicValue> assignmentFrame, FieldInsnNode fieldInsnNode, BasicValue stackValue);

    @Override
    public void visitEnd() {
        super.visitEnd();

        if (fieldAssignments.isEmpty()) { return; }

        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifierFactory.interpreter());
        Frame<BasicValue>[] frames;
        try {
            frames = a.analyze(owner, this);

            for (FieldInsnNode fieldInsnNode : fieldAssignments) {
                Frame<BasicValue> assignmentFrame = frames[instructions.indexOf(fieldInsnNode)];
                int stackSlot = assignmentFrame.getStackSize() - 1;
                BasicValue stackValue = assignmentFrame.getStack(stackSlot);
                visitFieldAssignmentFrame(assignmentFrame, fieldInsnNode, stackValue);
            }
        } catch (AnalyzerException forwarded) {
            throw new RuntimeException(forwarded);
        }
    }

    protected boolean isInvalidStackValue(BasicValue stackValue) {
        return stackValue == null || "Lnull;".equals(stackValue.getType().toString());
    }

    protected BasicValue getStackValue(Frame<BasicValue> assignmentFrame) {
        int stackSlot = assignmentFrame.getStackSize() - 1;
        return assignmentFrame.getStack(stackSlot);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>run</actionName>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-classpath %classpath echode.EchodeStarter</exec.args>
                <exec.executable>java</exec.executable>
            </properties>
        </action>
    </actions>


text:
jQuery(document).ready(function() {
    var yafCKEditor = jQuery('textarea.YafTextEditor').ckeditor({
        extraPlugins: 'autosave,bbcode,syntaxhighlight,bbcodeselector,codemirror',
        autosave_saveDetectionSelectors: "a[id*='_PostReply'],a[id*='Cancel']",
        toolbar: [
            ['Source'],
            ['Undo', 'Redo'],
            ['-', 'NumberedList', 'BulletedList'],
            ['-', 'Link', 'Unlink', 'Image'],
            ['Blockquote', 'syntaxhighlight', 'bbcodeselector'],
            ['SelectAll', 'RemoveFormat'],
            ['About'],
            '/',
            ['Bold', 'Italic', 'Underline', '-', 'TextColor', 'Font', 'FontSize'],
            ['JustifyLeft', 'JustifyCenter', 'JustifyRight'],
            ['Outdent', 'Indent']
        ],
        entities_greek: false,
        entities_latin: false,
        language: editorLanguage,
        disableObjectResizing: true,
        forcePasteAsPlainText: true,
        contentsCss: 'Scripts/ckeditor/yaf_contents.css',
        codemirror:
        {
            mode: 'bbcode'
        }
    });

    jQuery("a[id*='_PostReply'],a[id*='_Save']").click(function() {
        yafCKEditor.editor.updateElement();
    });

    yafCKEditor.editor.addCommand('highlight', {
        modes: { wysiwyg: 1, source: 1 },
        exec: function(editor) {
            var selection = editor.getSelection();
            if (!selection) {
                editor.insertHtml('[h]' + '[/h]');
            }
            var text = selection.getSelectedText();

            editor.insertHtml('[h]' + text + '[/h]');
        }
    });

    yafCKEditor.editor.addCommand('postmessage', {
        modes: { wysiwyg: 1, source: 1 },
        exec: function () {
            yafCKEditor.editor.updateElement();
            if (jQuery("a[id*='_PostReply']").length) {
                __doPostBack(jQuery("a[id*='_PostReply']").attr('id').replace('_', '$').replace('_', '$'), '');
            } else if (jQuery("a[id*='_Save']").length) {
                __doPostBack(jQuery("a[id*='_Save']").attr('id').replace('_', '$').replace('_', '$'), '');
            }
        }
    });
});

CKEDITOR.on( 'dialogDefinition', function(ev) {
    var tab,
        name = ev.data.name,
        definition = ev.data.definition;

    if (name == 'link') {
        definition.removeContents('target');
        definition.removeContents('upload');
        definition.removeContents('advanced');
        tab = definition.getContents('info');
        tab.remove('emailSubject');
        tab.remove('emailBody');
    } else if (name == 'image') {
        definition.removeContents('advanced');
        tab = definition.getContents('Link');
        tab.remove('cmbTarget');
        tab = definition.getContents('info');
        tab.remove('txtAlt');
        tab.remove('basic');
    }
});


text:
const testFixtureMaker = require('../src/testing/test-fixture-maker');
const errorFormatter = require('../src/testing/validation-error-formatter');

describe('Skip validation for strict unchanged value constraint:', () => {
  const testFixture =
    testFixtureMaker.initFromSyncFunction('build/sync-functions/test-skip-validation-when-value-unchanged-strict-sync-function.js');

  afterEach(() => {
    testFixture.resetTestEnvironment();
  });

  describe('with static validation', () => {
    it('allows document creation with valid values', () => {
      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: 49,
        floatProp: -153.9,
        stringProp: 'a-string',
        booleanProp: true,
        dateProp: '1953-01-14',
        datetimeProp: '2018-06-13T16:33-07:00',
        timeProp: '17:45:53.912',
        timezoneProp: '+15:15',
        enumProp: 3,
        uuidProp: '0d852732-81f0-4501-bb13-2c1ebc98d8f6',
        attachmentReferenceProp: 'foobar.txt',
        arrayProp: [ 'a', 'b', 'c' ],
        objectProp: { nestedProp: 'foo' },
        hashtableProp: { bar: -7 }
      };

      testFixture.verifyDocumentCreated(doc);
    });

    it('allows document replacement with invalid values that strictly equal the original values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      const doc = Object.assign({ }, oldDoc);

      testFixture.verifyDocumentReplaced(doc, oldDoc);
    });

    it('allows document replacement of invalid values with valid values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: 0,
        floatProp: 0,
        stringProp: 'foobar',
        booleanProp: true,
        dateProp: '1952-12-31',
        datetimeProp: '2018-06-13T16:03-07:30',
        timeProp: '18:21:35',
        timezoneProp: 'Z',
        enumProp: 1,
        uuidProp: '094b0d17-f266-4a10-af04-8b6ae0312131',
        attachmentReferenceProp: 'barbaz.txt',
        arrayProp: [ ],
        objectProp: { },
        hashtableProp: { foo: 5564 }
      };

      testFixture.verifyDocumentReplaced(doc, oldDoc);
    });

    it('allows document replacement of invalid values with null values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: null,
        floatProp: null,
        stringProp: null,
        booleanProp: null,
        dateProp: null,
        datetimeProp: null,
        timeProp: null,
        timezoneProp: null,
        enumProp: null,
        uuidProp: null,
        attachmentReferenceProp: null,
        arrayProp: null,
        objectProp: null,
        hashtableProp: null
      };

      testFixture.verifyDocumentReplaced(doc, oldDoc);
    });

    it('allows document replacement of invalid values with undefined values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc'
      };

      testFixture.verifyDocumentReplaced(doc, oldDoc);
    });

    it('rejects document creation with invalid values', () => {
      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      testFixture.verifyDocumentNotCreated(
        doc,
        'staticSkipValidationWhenValueUnchangedStrictDoc',
        [
          errorFormatter.minimumValueViolation('integerProp', 0),
          errorFormatter.maximumValueViolation('floatProp', 0),
          errorFormatter.minimumLengthViolation('stringProp', 4),
          'booleanProp must be true',
          errorFormatter.maximumValueViolation('dateProp', '1953-01-14'),
          errorFormatter.maximumValueViolation('datetimeProp', '2018-06-13T23:33Z'),
          errorFormatter.minimumValueExclusiveViolation('timeProp', '17:45:53.911'),
          errorFormatter.maximumValueExclusiveViolation('timezoneProp', '+15:30'),
          errorFormatter.enumPredefinedValueViolation('enumProp', [ 1, 2, 3 ]),
          errorFormatter.maximumValueExclusiveViolation('uuidProp', '10000000-0000-0000-0000-000000000000'),
          errorFormatter.attachmentReferenceRegexPatternViolation('attachmentReferenceProp', /^[a-z]+\.txt$/),
          errorFormatter.maximumLengthViolation('arrayProp', 3),
          errorFormatter.unsupportedProperty('objectProp.foo'),
          errorFormatter.typeConstraintViolation('hashtableProp[bar]', 'integer')
        ]);
    });

    it('rejects document replacement with invalid values that semantically equal the original values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1.0,
        floatProp: 14.360,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-14T01:33:00+01:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34F0D4A2-BC77-4AEA-B3FD-D579B66EE4BC',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      testFixture.verifyDocumentNotReplaced(
        doc,
        oldDoc,
        'staticSkipValidationWhenValueUnchangedStrictDoc',
        [
          errorFormatter.maximumValueViolation('datetimeProp', '2018-06-13T23:33Z'),
          errorFormatter.maximumValueExclusiveViolation('uuidProp', '10000000-0000-0000-0000-000000000000')
        ]);
    });

    it('rejects document replacement with invalid values', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: 49,
        floatProp: -153.9,
        stringProp: 'a-string',
        booleanProp: true,
        dateProp: '1953-01-14',
        datetimeProp: '2018-06-13T16:33-07:00',
        timeProp: '17:45:53.912',
        timezoneProp: '+15:15',
        enumProp: 3,
        uuidProp: '0d852732-81f0-4501-bb13-2c1ebc98d8f6',
        attachmentReferenceProp: 'foobar.txt',
        arrayProp: [ 'a', 'b', 'c' ],
        objectProp: { nestedProp: 'foo' },
        hashtableProp: { bar: -7 }
      };

      const doc = {
        _id: 'my-doc',
        type: 'staticSkipValidationWhenValueUnchangedStrictDoc',
        integerProp: -1,
        floatProp: 14.36,
        stringProp: 'foo',
        booleanProp: false,
        dateProp: '1953-01-15',
        datetimeProp: '2018-06-13T16:33-08:00',
        timeProp: '17:45:53.911',
        timezoneProp: '+15:30',
        enumProp: 'a',
        uuidProp: '34f0d4a2-bc77-4aea-b3fd-d579b66ee4bc',
        attachmentReferenceProp: 'foobar.baz',
        arrayProp: [ 'a', 'b', 'c', 'd' ],
        objectProp: { foo: 'bar' },
        hashtableProp: { bar: 'baz' }
      };

      testFixture.verifyDocumentNotReplaced(
        doc,
        oldDoc,
        'staticSkipValidationWhenValueUnchangedStrictDoc',
        [
          errorFormatter.minimumValueViolation('integerProp', 0),
          errorFormatter.maximumValueViolation('floatProp', 0),
          errorFormatter.minimumLengthViolation('stringProp', 4),
          'booleanProp must be true',
          errorFormatter.maximumValueViolation('dateProp', '1953-01-14'),
          errorFormatter.maximumValueViolation('datetimeProp', '2018-06-13T23:33Z'),
          errorFormatter.minimumValueExclusiveViolation('timeProp', '17:45:53.911'),
          errorFormatter.maximumValueExclusiveViolation('timezoneProp', '+15:30'),
          errorFormatter.enumPredefinedValueViolation('enumProp', [ 1, 2, 3 ]),
          errorFormatter.maximumValueExclusiveViolation('uuidProp', '10000000-0000-0000-0000-000000000000'),
          errorFormatter.attachmentReferenceRegexPatternViolation('attachmentReferenceProp', /^[a-z]+\.txt$/),
          errorFormatter.maximumLengthViolation('arrayProp', 3),
          errorFormatter.unsupportedProperty('objectProp.foo'),
          errorFormatter.typeConstraintViolation('hashtableProp[bar]', 'integer')
        ]);
    });
  });

  describe('with dynamic validation', () => {
    it('allows document creation with valid values', () => {
      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: true,
        uuidProp: '7ed6ad77-b18f-4a1a-bf72-6e74a22b88c1',
        minimumUuidValue: '70000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentCreated(doc);
    });

    it('allows document replacement with strictly equal invalid values when validation is allowed to be skipped', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: true,
        uuidProp: '189331f4-62dd-4036-90e5-291648b05e38'
      };

      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        uuidProp: '189331f4-62dd-4036-90e5-291648b05e38',
        minimumUuidValue: '20000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentReplaced(doc, oldDoc);
    });

    it('rejects document creation with invalid values', () => {
      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: true,
        uuidProp: '0b352e9b-1c1f-433a-9c98-dd0242127185',
        minimumUuidValue: '10000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentNotCreated(
        doc,
        'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        [ errorFormatter.minimumValueViolation('uuidProp', '10000000-0000-0000-0000-000000000000') ]);
    });

    it('rejects document replacement with unequal invalid values when validation is allowed to be skipped', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: true,
        uuidProp: '4b424579-81c9-4740-9511-eca9c8a89f95'
      };

      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        uuidProp: '1d9d9668-249e-47fe-95e0-06cdac93f0f1',
        minimumUuidValue: '50000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentNotReplaced(
        doc,
        oldDoc,
        'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        [ errorFormatter.minimumValueViolation('uuidProp', '50000000-0000-0000-0000-000000000000') ]);
    });

    it('rejects document replacement with semantically equal invalid values when validation is allowed to be skipped', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: true,
        uuidProp: 'EC8EE255-CF77-46C6-B935-12A0DC5E8942'
      };

      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        uuidProp: 'ec8ee255-cf77-46c6-b935-12a0dc5e8942',
        minimumUuidValue: 'F0000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentNotReplaced(
        doc,
        oldDoc,
        'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        [ errorFormatter.minimumValueViolation('uuidProp', 'F0000000-0000-0000-0000-000000000000') ]);
    });

    it('rejects document replacement with equal invalid values when validation is NOT allowed to be skipped', () => {
      const oldDoc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        allowValidationSkip: false,
        uuidProp: '22632a18-4045-4dfc-a5f0-23d2aa6af894'
      };

      const doc = {
        _id: 'my-doc',
        type: 'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        uuidProp: '22632a18-4045-4dfc-a5f0-23d2aa6af894',
        minimumUuidValue: 'd0000000-0000-0000-0000-000000000000'
      };

      testFixture.verifyDocumentNotReplaced(
        doc,
        oldDoc,
        'dynamicSkipValidationWhenValueUnchangedStrictDoc',
        [ errorFormatter.minimumValueViolation('uuidProp', 'd0000000-0000-0000-0000-000000000000') ]);
    });
  });
});


text:
package joshie.lib.base;

import joshie.lib.util.Text;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public abstract class ItemBaseArmor extends ItemArmor {
    protected String mod;
    protected String path;

    public ItemBaseArmor(String mod, CreativeTabs tab, ArmorMaterial material, int j, int k) {
        super(material, j, k);
        setCreativeTab(tab);
        this.mod = mod;
    }

    public void setTextureFolder(String thePath) {
        this.path = thePath;
    }

    @Override
    public Item setUnlocalizedName(String name) {
        super.setUnlocalizedName(name);
        GameRegistry.registerItem(this, name.replace(".", "_"));
        return this;
    }

    @Override
    public String getUnlocalizedName() {
        return mod + "." + super.getUnlocalizedName().replace("item.", "").replace("_", ".");
    }

    @Override
    public String getItemStackDisplayName(ItemStack stack) {
        return Text.localize(getUnlocalizedName());
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void registerIcons(IIconRegister iconRegister) {
        String path = this.path != null ? this.path : mod + ":";
        String name = super.getUnlocalizedName().replace("item.", "").toLowerCase();
        itemIcon = iconRegister.registerIcon(path + Text.removeDecimals(name));
    }
}


text:
from urllib.parse import urlencode
# for processing search results
import json

class ConfigurationError(Exception):
    pass

class SearchResultItem:
    """For search result encapsulation"""

    def __init__(self, title, url, description):
        self.title = title
        self.url = url
        self.description = description

class SearchEngine:
    """Search engine abstraction"""

    @staticmethod
    def get_alias():
        """Must return search engine alias"""
        pass

    def try_configure(self, settings):
        """ Allows to configure search engine"""
        pass

    def search(self, query):
        """Allows to search throught the Internet"""
        pass

    def set_transport(self, transport):
        """Sets transport for making HTTPS requests"""

        self.transport = transport

class GoogleCustomSearchEngine(SearchEngine):
    """Search engine that uses Google Custom Search Engine API"""

    @staticmethod
    def get_alias():
        return "google_cse"

    def try_configure(self, settings):
        settings = settings.get(self.get_alias())
        if not ('developer_key' in settings and 'engine_id' in settings):
            raise ConfigurationError('Google CSE API requires developer key and engine id')

        self.settings = settings

    def search(self, query):
        """Allows to search throught the Internet"""

        url = 'https://www.googleapis.com/customsearch/v1?' + urlencode({
            'alt' : 'json',
            'key': self.settings.get('developer_key'),
            'cx': self.settings.get('engine_id'),
            'q': query
        })

        result = json.loads(self.transport.get(url))

        items = []
        for item in result['items']:
            items.append(SearchResultItem(item['title'], item['link'], item['snippet']))

        return items

class DuckDuckGoSearchEngine(SearchEngine):
    """Search engine that uses DuckDuckGo API"""

    def get_alias():
        return "duck_duck_go"

    def search(self, query):
        """Allows to search throught the Internet"""

        url = 'https://api.duckduckgo.com/?' + urlencode({
            'format' : 'json',
            'q': query,
            'no_html': 1
        })

        result = json.loads(self.transport.get(url))

        items = []
        for item in result['RelatedTopics']:
            if 'Topics' in item:
                for nestedItem in item['Topics']:
                    items.append(SearchResultItem(nestedItem['Text'], nestedItem['FirstURL'], nestedItem['Text']))
            else:
                items.append(SearchResultItem(item['Text'], item['FirstURL'], item['Text']))

        return items


text:
from __future__ import print_function, division
import sys
if (sys.version_info > (3, 0) ):
    import queue
else:
    import Queue as queue

import os
import torch
#import pandas as pd
#from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
#from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils

# Ignore warnings
import warnings
warnings.filterwarnings("ignore")

#plt.ion()   # interactive mode

import cv2
#import argparse

import threading
import time

# https://pymotw.com/3/queue/

class CV2videoloader(threading.Thread):
    def __init__(self,name,videosrc,video_buffer,pulse=0.5,camera_config=None):
        self.videosrc= videosrc if videosrc != None else 0
        self.camera = cv2.VideoCapture(self.videosrc)
        self.buffer = video_buffer if isinstance( video_buffer , queue.Queue) else None
        self.stop = False
        self.pulse = pulse
        self.debug = False
        threading.Thread.__init__(self)

    def run(self):
        while not self.stop:
            time.sleep(self.pulse)
            if self.debug: print("----get one----")
            (grabbed, frame) = self.camera.read()
            if grabbed == False:
                warnings.warn("the camera {} is grabing air".format(self.videosrc) )
            else:
                self.buffer.put(frame)

class torchStream():
    def __init__(self,name,video_buffer,batchsize=1,transform=None):

        self.name =name
        self.video_buffer= video_buffer if isinstance( video_buffer , queue.Queue) else None

        if transform!= None:
            self.transform = transform
        else:
             self.transform=transforms.ToTensor()
             warnings.warn("at least do a ToTensor operation to the raw image")

        self.batchsize = batchsize
        self.batchbuffer = list()

    def __len__(self):
        return self.video_buffer.qsize()

    def batchpop(self):
        self.batchbuffer = [ self.transform( self.video_buffer.get() ) for i in range(self.batchsize) ]
        return torch.stack( self.batchbuffer,0 )

    def pop(self):
        return self.transform( self.video_buffer.get() )

class tfstream():
    def __init__(self,name,video_buffer):
        pass

    def __call__(self):
        return 0

    def stop():
        return 0

    def isstop():
        return 0

if __name__ == '__main__':

    data_transform = transforms.Compose([
            transforms.ToPILImage(),
            transforms.Scale(256),
            transforms.ToTensor(),
                                ])

    def show_stream_batch(sample_batched):
        images_batch = sample_batched
        batch_size = len(images_batch)
        grid = utils.make_grid(images_batch)
        t=transforms.ToPILImage()
        plt.imshow( t(grid) )

    video_buffer = queue.Queue( maxsize = 30 )
    CV2L= CV2videoloader( name='test',
            videosrc=0,video_buffer=video_buffer,
            camera_config=None )

    torS = torchStream(name='test',video_buffer=video_buffer,batchsize=5,transform=data_transform )

    CV2L.start()
    time.sleep(3)
    show_stream_batch( torS.batchpop() )
    CV2L.stop = True
    CV2L.join()
    plt.show()


text:
package eu.uqasar.web.pages.reporting;

import eu.uqasar.util.reporting.Util;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 *
 */
class QueryPage extends WebPage {

    private QueryPage(final PageParameters parameters) {
        super(parameters);
        try {
            HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest();
            HttpServletResponse response = (HttpServletResponse) getResponse().getContainerResponse();
            //generate cube output

            JSONObject objToReturn = new JSONObject();
            response.setContentType("text/html;charset=UTF-8");

            String cubeurl = request.getParameter("data[cube]");
            String urlToLoad = Util.constructCubeRetrieverURL(request.getParameter("data[rules]"), cubeurl);
            String urlToLoadAsLink = "" + urlToLoad + "";

            JSONObject cuberesponse = Util.readJsonFromUrl(urlToLoad);
            JSONObject donutchartJSON = new JSONObject();

            if (cuberesponse.has("error")) {
                System.out.println("Exception during retrieval !");
                objToReturn.put("error", cuberesponse.get("error"));
            } else {

                JSONArray cuberesponse_arr = cuberesponse.getJSONArray("cells");

                if (cuberesponse_arr.length() > 0) {

                    System.out.println("cuberesponse_arr");
                    System.out.println(cuberesponse_arr);

                    List<String> facts = Util.retrieveDimensions(cubeurl + "/model");

                    String cube_table = "
";

                    cube_table += "
";
                    for (String fact : facts) {

                        if (cuberesponse_arr.optJSONObject(0).has(fact)) {
                            cube_table += "" + fact + "	";
                        }

                    }
                    cube_table += "count	";
                    cube_table += "
";

                    int[] barchartvalues = new int[cuberesponse_arr.length()];

                    for (int i = 0; i < cuberesponse_arr.length(); i++) {

                        String factsDescription = "";
                        cube_table += "
";
                        for (String fact : facts) {

                            if (cuberesponse_arr.optJSONObject(i).has(fact)) {

                                String factid = cuberesponse_arr.getJSONObject(i).get(fact).toString();
                                System.out.println(fact + " : " + factid + "\n\n");
                                cube_table += "" + factid + "	";
                                factsDescription += fact + ":" + factid + " ";
                            }

                        }

                        if (cuberesponse_arr.getJSONObject(i).has("count")) {
                            int countID = cuberesponse_arr.getJSONObject(i).getInt("count");
                            System.out.println("count : " + countID + "\n\n");
                            cube_table += "" + countID + "	";
                            barchartvalues[i] = countID;
                            donutchartJSON.put(factsDescription, countID);
                        }

                        cube_table += "
";

                    }

                    cube_table += "
";

                    objToReturn.put("cubetable", cube_table);
                    objToReturn.put("donutchart", donutchartJSON.toString());

                }
                objToReturn.put("totalcuberesponse", cuberesponse);
                objToReturn.put("cubeurl", urlToLoadAsLink);
                objToReturn.put("summary", Util.createSummaryTable(cuberesponse));
            }

            response.setContentType("text/x-json;charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            response.setStatus(HttpServletResponse.SC_OK);
            System.out.println("objToReturn" + objToReturn);
            response.getWriter().print(objToReturn.toString());
            response.getWriter().flush();
            response.getWriter().close();

        } catch (IOException ex) {
            Logger.getLogger(QueryPage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//QueryPage

}//EoC


text:
<?php

namespace Oro\Bundle\FormBundle\Tests\Unit\Form\Type;

use Doctrine\ORM\EntityManager;

use Symfony\Component\Form\Test\FormIntegrationTestCase;

use Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider;
use Oro\Bundle\FormBundle\Autocomplete\ConverterInterface;
use Oro\Bundle\FormBundle\Autocomplete\SearchHandlerInterface;
use Oro\Bundle\FormBundle\Autocomplete\SearchRegistry;
use Oro\Bundle\FormBundle\Form\DataTransformer\EntityToIdTransformer;
use Oro\Bundle\FormBundle\Form\Type\OroJquerySelect2HiddenType;
use Oro\Bundle\FormBundle\Tests\Unit\MockHelper;

class OroJquerySelect2HiddenTypeTest extends FormIntegrationTestCase
{
    /**
     * @var \Symfony\Component\Form\FormFactory
     */
    protected $factory;

    /**
     * @var OroJquerySelect2HiddenType
     */
    private $type;

    /**
     * @var SearchRegistry|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $searchRegistry;

    /**
     * @var SearchHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $searchHandler;

    /**
     * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $converter;

    /**
     * @var EntityManager|\PHPUnit_Framework_MockObject_MockObject
     */
    private $entityManager;

    /**
     * @var EntityToIdTransformer|\PHPUnit_Framework_MockObject_MockObject
     */
    private $entityToIdTransformer;

    /**
     * @var ConfigProvider|\PHPUnit_Framework_MockObject_MockObject
     */
    private $configProvider;

    protected function setUp()
    {
        parent::setUp();
        $this->type = $this->getMockBuilder('Oro\Bundle\FormBundle\Form\Type\OroJquerySelect2HiddenType')
            ->setMethods(['createDefaultTransformer'])
            ->setConstructorArgs(
                [
                    $this->getMockEntityManager(),
                    $this->getMockSearchRegistry(),
                    $this->getConfigProvider()
                ]
            )
            ->getMock();
    }

    protected function getExtensions()
    {
        return array_merge(parent::getExtensions(), [new TestFormExtension()]);
    }

    /**
     * @dataProvider bindDataProvider
     *
     * @param mixed $bindData
     * @param mixed $formData
     * @param mixed $viewData
     * @param array $options
     * @param array $expectedCalls
     * @param array $expectedVars
     */
    public function testBindData(
        $bindData,
        $formData,
        $viewData,
        array $options,
        array $expectedCalls,
        array $expectedVars
    ) {
        if (isset($options['converter'])
            && is_string($options['converter'])
            && method_exists($this, $options['converter'])
        ) {
            $options['converter'] = $this->$options['converter']();
        }

        foreach ($expectedCalls as $key => $calls) {
            $mock = $this->{'getMock' . ucfirst($key)}();
            MockHelper::addMockExpectedCalls($mock, $calls, $this);
        }

        $form = $this->factory->create($this->type, null, $options);

        $form->submit($bindData);

        $this->assertTrue($form->isSynchronized());
        $this->assertEquals($formData, $form->getData());

        $view = $form->createView();
        $this->assertEquals($viewData, $view->vars['value']);

        foreach ($expectedVars as $name => $expectedValue) {
            $this->assertEquals($expectedValue, $view->vars[$name]);
        }
    }

    /**
     * Data provider for testBindData
     *
     * @return array
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function bindDataProvider()
    {
        $entityId1 = $this->createMockEntity('id', 1);

        return [
            'use autocomplete_alias'     => [
                '1',
                $entityId1,
                '1',
                ['autocomplete_alias' => 'foo'],
                'expectedCalls' => [
                    'searchRegistry'        => [
                        ['getSearchHandler', ['foo'], 'getMockSearchHandler'],
                        ['getSearchHandler', ['foo'], 'getMockSearchHandler'],
                        ['getSearchHandler', ['foo'], 'getMockSearchHandler']
                    ],
                    'searchHandler'         => [
                        ['getProperties', [], ['bar', 'baz']],
                        ['getEntityName', [], 'TestEntityClass'],
                        [
                            'convertItem',
                            [$entityId1],
                            ['id' => 1, 'bar' => 'Bar value', 'baz' => 'Baz value']
                        ],
                    ],
                    'formType'              => [
                        ['createDefaultTransformer', ['TestEntityClass'], 'getMockEntityToIdTransformer']
                    ],
                    'entityToIdTransformer' => [
                        ['transform', [null], null],
                        ['reverseTransform', ['1'], $entityId1]
                    ]
                ],
                'expectedVars'  => [
                    'configs' => [
                        'placeholder'        => 'oro.form.choose_value',
                        'allowClear'         => 1,
                        'minimumInputLength' => 0,
                        'autocomplete_alias' => 'foo',
                        'properties'         => ['bar', 'baz'],
                        'route_name'         => 'oro_form_autocomplete_search',
                        'route_parameters'   => [],
                        'component'       => 'autocomplete'
                    ],
                    'attr'    => [
                        'data-selected-data' => json_encode(
                            [
                                ['id' => 1, 'bar' => 'Bar value', 'baz' => 'Baz value']
                            ]
                        )
                    ]
                ]
            ],
            'without autocomplete_alias' => [
                '1',
                $entityId1,
                '1',
                [
                    'configs'      => [
                        'route_name'       => 'custom_route',
                        'route_parameters' => ['test' => 'hello']
                    ],
                    'converter'    => 'getMockConverter',
                    'entity_class' => 'TestEntityClass'
                ],
                'expectedCalls' => [
                    'converter'             => [
                        [
                            'convertItem',
                            [$entityId1],
                            ['id' => 1, 'bar' => 'Bar value', 'baz' => 'Baz value']
                        ],
                    ],
                    'formType'              => [
                        ['createDefaultTransformer', ['TestEntityClass'], 'getMockEntityToIdTransformer']
                    ],
                    'entityToIdTransformer' => [
                        ['transform', [null], null],
                        ['reverseTransform', ['1'], $entityId1]
                    ]
                ],
                'expectedVars'  => [
                    'configs' => [
                        'placeholder'        => 'oro.form.choose_value',
                        'allowClear'         => 1,
                        'minimumInputLength' => 0,
                        'route_name'         => 'custom_route',
                        'route_parameters'   => ['test' => 'hello'],
                    ],
                    'attr'    => [
                        'data-selected-data' => json_encode(
                            [
                                ['id' => 1, 'bar' => 'Bar value', 'baz' => 'Baz value']
                            ]
                        )
                    ]
                ]
            ]
        ];
    }

    /**
     * @dataProvider createErrorsDataProvider
     *
     * @param array  $options
     * @param array  $expectedCalls
     * @param string $expectedException
     * @param string $expectedExceptionMessage
     */
    public function testCreateErrors(
        array $options,
        array $expectedCalls,
        $expectedException,
        $expectedExceptionMessage
    ) {
        if (isset($options['converter'])
            && is_string($options['converter'])
            && method_exists($this, $options['converter'])
        ) {
            $options['converter'] = $this->$options['converter']();
        }

        foreach ($expectedCalls as $key => $calls) {
            $mock = $this->{'getMock' . ucfirst($key)}();
            MockHelper::addMockExpectedCalls($mock, $calls, $this);
        }

        $this->setExpectedException($expectedException, $expectedExceptionMessage);
        $this->factory->create($this->type, null, $options);
    }

    /**
     * Data provider for testBindData
     *
     * @return array
     */
    public function createErrorsDataProvider()
    {
        return [
            'configs.route_name must be set' => [
                [
                    'entity_class' => '\stdClass'
                ],
                'expectedCalls'            => [],
                'expectedException'        => 'Symfony\Component\Form\Exception\InvalidConfigurationException',
                'expectedExceptionMessage' => 'Option "configs[route_name]" must be set.'
            ],
            'converter must be set'          => [
                [
                    'entity_class' => '\stdClass',
                    'configs'      => [
                        'route_name' => 'foo'
                    ]
                ],
                'expectedCalls'            => [
                    'formType' => [
                        ['createDefaultTransformer', ['\stdClass'], 'getMockEntityToIdTransformer']
                    ],
                ],
                'expectedException'        => 'Symfony\Component\Form\Exception\InvalidConfigurationException',
                'expectedExceptionMessage' => 'The option "converter" must be set.'
            ],
            'converter invalid'              => [
                [
                    'entity_class' => '\stdClass',
                    'converter'    => 'bar',
                    'configs'      => [
                        'route_name' => 'foo'
                    ]
                ],
                'expectedCalls'            => [
                    'formType' => [
                        ['createDefaultTransformer', ['\stdClass'], 'getMockEntityToIdTransformer']
                    ],
                ],
                'expectedException'        => 'Symfony\Component\Form\Exception\UnexpectedTypeException',
                'expectedExceptionMessage' =>
                    'Expected argument of type "Oro\Bundle\FormBundle\Autocomplete\ConverterInterface", "string" given'
            ],
            'entity_class must be set'       => [
                [
                    'autocomplete_alias' => null,
                    'converter'          => 'getMockConverter',
                    'configs'            => [
                        'route_name' => 'foo'
                    ]
                ],
                'expectedCalls'            => [],
                'expectedException'        => 'Symfony\Component\Form\Exception\InvalidConfigurationException',
                'expectedExceptionMessage' => 'The option "entity_class" must be set.'
            ],
            'entity_class must be set2'      => [
                [
                    'converter'    => 'getMockConverter',
                    'entity_class' => 'bar',
                    'configs'      => [
                        'route_name' => 'foo'
                    ],
                    'transformer'  => 'invalid'
                ],
                'expectedCalls'            => [],
                'expectedException'        => 'Symfony\Component\Form\Exception\TransformationFailedException',
                'expectedExceptionMessage' =>
                    sprintf(
                        'The option "transformer" must be an instance of "%s".',
                        'Symfony\Component\Form\DataTransformerInterface'
                    )
            ]
        ];
    }

    public function testDefaultFormOptions()
    {
        $options = [
            'converter'    => $this->getMockConverter(),
            'entity_class' => '\stdClass',
            'configs'      => ['route_name' => 'custom']
        ];
        $this->type->expects($this->once())->method('createDefaultTransformer')
            ->will($this->returnValue($this->getMockEntityToIdTransformer()));

        $form = $this->factory->create($this->type, null, $options);

        $expectedOptions = [
            'error_bubbling' => false
        ];
        foreach ($expectedOptions as $optionName => $optionValue) {
            $this->assertSame($optionValue, $form->getConfig()->getOption($optionName));
        }
    }

    /**
     * Create mock entity by id property name and value
     *
     * @param string $property
     * @param mixed  $value
     *
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function createMockEntity($property, $value)
    {
        $getter = 'get' . ucfirst($property);
        $result = $this->getMock('MockEntity', [$getter]);
        $result->expects($this->any())->method($getter)->will($this->returnValue($value));

        return $result;
    }

    /**
     * @return EntityManager|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockEntityManager()
    {
        if (!$this->entityManager) {
            $this->entityManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
                ->disableOriginalConstructor()
                ->setMethods(['getClassMetadata', 'getRepository'])
                ->getMockForAbstractClass();
        }

        return $this->entityManager;
    }

    /**
     * @return SearchRegistry|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockSearchRegistry()
    {
        if (!$this->searchRegistry) {
            $this->searchRegistry = $this->getMockBuilder('Oro\Bundle\FormBundle\Autocomplete\SearchRegistry')
                ->disableOriginalConstructor()
                ->setMethods(['hasSearchHandler', 'getSearchHandler'])
                ->getMock();
        }

        return $this->searchRegistry;
    }

    /**
     * @return ConfigProvider|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getConfigProvider()
    {
        if (!$this->configProvider) {
            $this->configProvider = $this
                ->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
                ->disableOriginalConstructor()
                ->getMock();

            $config = $this->getMock('Oro\Bundle\EntityConfigBundle\Config\ConfigInterface');

            $this->configProvider
                ->expects($this->any())
                ->method('getConfig')
                ->will($this->returnValue($config));
        }

        return $this->configProvider;
    }

    /**
     * @return ConverterInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockConverter()
    {
        if (!$this->converter) {
            $this->converter = $this->getMock('Oro\Bundle\FormBundle\Autocomplete\ConverterInterface');
        }

        return $this->converter;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockFormType()
    {
        return $this->type;
    }

    /**
     * @return SearchHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockSearchHandler()
    {
        if (!$this->searchHandler) {
            $this->searchHandler = $this->getMock('Oro\Bundle\FormBundle\Autocomplete\SearchHandlerInterface');
        }

        return $this->searchHandler;
    }

    /**
     * @return EntityToIdTransformer|\PHPUnit_Framework_MockObject_MockObject
     */
    public function getMockEntityToIdTransformer()
    {
        if (!$this->entityToIdTransformer) {
            $this->entityToIdTransformer =
                $this->getMockBuilder('Oro\Bundle\FormBundle\Form\DataTransformer\EntityToIdTransformer')
                    ->disableOriginalConstructor()
                    ->setMethods(['transform', 'reverseTransform'])
                    ->getMockForAbstractClass();
        }

        return $this->entityToIdTransformer;
    }
}


text:
package application.Errors;

import static application.View.myResources;
import application.Constants.ExceptionConstants;

public class FXMLException extends SLogoException {
	public FXMLException(){
		myMessage = myResources.getString(ExceptionConstants.FXML_EXCEPTION);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agathas.Storefront.Infrastructure.Domain;
using Agathas.Storefront.Infrastructure.UnitOfWork;
using Agathas.Storefront.Model.Basket;
using Agathas.Storefront.Model.Products;
using Agathas.Storefront.Model.Shipping;
using Agathas.Storefront.Services.Interfaces;
using Agathas.Storefront.Services.Mapping;
using Agathas.Storefront.Services.Messaging.ProductCatalogService;
using Agathas.Storefront.Services.ViewModels;

namespace Agathas.Storefront.Services.Implementations
{
    public class BasketService : IBasketService
    {
        private readonly IBasketRepository _basketRepository;
        private readonly IProductRepository _productRepository;
        private readonly IDeliveryOptionRepository _deliveryOptionRepository;
        private readonly IUnitOfWork _uow;

        public BasketService(IBasketRepository basketRepository,
                             IProductRepository productRepository,
                             IDeliveryOptionRepository deliveryOptionRepository,
                             IUnitOfWork uow)
        {
            _basketRepository = basketRepository;
            _productRepository = productRepository;
            _deliveryOptionRepository = deliveryOptionRepository;
            _uow = uow;
        }

        public GetBasketResponse GetBasket(GetBasketRequest request)
        {
            GetBasketResponse response = new GetBasketResponse();

            Basket basket = _basketRepository.FindBy(request.BasketId);
            BasketView basketView;

            if (basket != null)
                basketView = basket.ConvertToBasketView();
            else
                basketView = new BasketView();

            response.Basket = basketView;

            return response;
        }

        public CreateBasketResponse CreateBasket(CreateBasketRequest request)
        {
            CreateBasketResponse response = new CreateBasketResponse();

            Basket basket = new Basket();

            basket.SetDeliveryOption(GetCheapestDeliveryOption());

            AddProductsToBasket(request.ProductsToAdd, basket);

            ThrowExceptionIfBasketIsInvalid(basket);

            _basketRepository.Save(basket);
            _uow.Commit();

            response.Basket = basket.ConvertToBasketView();

            return response;
        }

        private DeliveryOption GetCheapestDeliveryOption()
        {
            return _deliveryOptionRepository.FindAll()
                            .OrderBy(d => d.Cost).FirstOrDefault();
        }

        private void ThrowExceptionIfBasketIsInvalid(Basket basket)
        {
            if (basket.GetBrokenRules().Count() > 0)
            {
                StringBuilder brokenRules = new StringBuilder();
                brokenRules.AppendLine("There were problems saving the Basket:");
                foreach (BusinessRule businessRule in basket.GetBrokenRules())
                {
                    brokenRules.AppendLine(businessRule.Rule);
                }

                throw new ApplicationException(brokenRules.ToString());

            }
        }

        public ModifyBasketResponse ModifyBasket(ModifyBasketRequest request)
        {
            ModifyBasketResponse response = new ModifyBasketResponse();
            Basket basket = _basketRepository.FindBy(request.BasketId);

            if (basket == null)
                throw new BasketDoesNotExistException();

            AddProductsToBasket(request.ProductsToAdd, basket);

            UpdateLineQtys(request.ItemsToUpdate, basket);

            RemoveItemsFromBasket(request.ItemsToRemove, basket);

            if (request.SetShippingServiceIdTo != 0)
            {
                DeliveryOption deliveryOption =
                     _deliveryOptionRepository.FindBy(request.SetShippingServiceIdTo);
                basket.SetDeliveryOption(deliveryOption);
            }

            ThrowExceptionIfBasketIsInvalid(basket);

            _basketRepository.Save(basket);
            _uow.Commit();

            response.Basket = basket.ConvertToBasketView();

            return response;
        }

        private void RemoveItemsFromBasket(IList<int> productsToRemove, Basket basket)
        {
            foreach (int productId in productsToRemove)
            {
                Product product = _productRepository.FindBy(productId);
                if (product != null)
                    basket.Remove(product);
            }
        }

        private void UpdateLineQtys(
               IList<ProductQtyUpdateRequest> productQtyUpdateRequests, Basket basket)
        {
            foreach (ProductQtyUpdateRequest productQtyUpdateRequest in
                                                             productQtyUpdateRequests)
            {
                Product product = _productRepository
                                         .FindBy(productQtyUpdateRequest.ProductId);

                if (product != null)
                    basket.ChangeQtyOfProduct(productQtyUpdateRequest.NewQty, product);
            }
        }

        private void AddProductsToBasket(IList<int> productsToAdd, Basket basket)
        {
            Product product;

            if (productsToAdd.Count() > 0)
                foreach (int productId in productsToAdd)
                {
                    product = _productRepository.FindBy(productId);
                    basket.Add(product);
                }
        }

        public GetAllDispatchOptionsResponse GetAllDispatchOptions()
        {
            GetAllDispatchOptionsResponse response = new GetAllDispatchOptionsResponse();
            response.DeliveryOptions = _deliveryOptionRepository.FindAll()
                                    .OrderBy(d => d.Cost).ConvertToDeliveryOptionViews();

            return response;
        }
    }

}


text:
package org.mini2Dx.android.di;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.mini2Dx.core.di.ComponentScanner;
import org.mini2Dx.core.di.DependencyInjection;
import org.mini2Dx.core.di.annotation.Prototype;
import org.mini2Dx.core.di.annotation.Singleton;

import android.content.Context;
import android.util.Log;
import dalvik.system.DexFile;

/**
 * Android implementation of {@link ComponentScanner}
 */
public class AndroidComponentScanner implements ComponentScanner {
	private static final String TAG = AndroidComponentScanner.class
			.getSimpleName();

	private Context applicationContext;
	private List<Class<?>> singletonClasses;
	private List<Class<?>> prototypeClasses;

	public AndroidComponentScanner(Context applicationContext) {
		this.applicationContext = applicationContext;

		singletonClasses = new ArrayList<Class<?>>();
		prototypeClasses = new ArrayList<Class<?>>();
	}

	@Override
	public void scan(String[] packageNames) throws IOException {
		if (applicationContext == null) {
			throw new NullPointerException(
					AndroidComponentScanner.class.getSimpleName()
							+ ".APPLICATION_CONTEXT needs to be set before initialising "
							+ DependencyInjection.class.getSimpleName());
		}

		DexFile dex = new DexFile(
				applicationContext.getApplicationInfo().sourceDir);
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		Enumeration<String> entries = dex.entries();
		while (entries.hasMoreElements()) {
			String className = entries.nextElement();
			if (classNameContainsPackage(packageNames, className)) {
				try {
					checkClassForAnnotations(classLoader.loadClass(className));
				} catch (Exception e) {
					Log.wtf(TAG, e);
				}
			}
		}
	}

	private void checkClassForAnnotations(Class<?> clazz) {
		try {
			Annotation annotation = clazz.getAnnotation(Singleton.class);
			if (annotation != null) {
				singletonClasses.add(clazz);
				return;
			}

			annotation = clazz.getAnnotation(Prototype.class);
			if (annotation != null) {
				prototypeClasses.add(clazz);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean classNameContainsPackage(String[] packageNames,
			String className) {
		for (String packageName : packageNames) {
			if (className.toLowerCase().startsWith(packageName.toLowerCase())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<Class<?>> getSingletonClasses() {
		return singletonClasses;
	}

	@Override
	public List<Class<?>> getPrototypeClasses() {
		return prototypeClasses;
	}

}


text:
$(function () {

    $(".item-rating span.plus, .item-rating span.minus").on("click", function (e) {
        e.preventDefault();
        $(this).toggleClass("active");
    });
});


text:
namespace System.IO
{
    public partial class FileSystemWatcher
    {
        /// <summary>Called when FileSystemWatcher is finalized.</summary>
        private void FinalizeDispose()
        {
        }

        private void StartRaisingEvents()
        {
            throw new PlatformNotSupportedException();
        }

        private void StopRaisingEvents()
        {
            throw new PlatformNotSupportedException();
        }
    }
}


text:
(function() {
  'use strict';

  //--------------------------------------
  //MAIN CALLBACK FUNCTIONS
  //--------------------------------------
  function config($stateProvider) {
    $stateProvider
    .state('home', {
      parent: 'root',
      url: '/home',
      views: {
        'container@': {
          templateUrl: '/partials/home',
          controller: 'mainCtrl',
          controllerAs: 'main'
        }
      },
      resolve: {
        postPromise: ['postService', function(postService){
          return postService.getAll();
        }]
      }
    });
  } //config callback

  function mainCtrl(postService, authService) {
    var vm = this;

    if (postService.message === '') {
      vm.addMessage = false;
    } else {
      vm.addMessage = true;
      vm.message = postService.message;
    }

    //used to display all posts
    vm.posts = postService.posts;

    vm.isLoggedIn = authService.isLoggedIn;

    vm.addPost = function() {
      if (!vm.title || vm.title === '') {
        return;
      }

      postService.create({
        title: vm.title,
        link: vm.link
      });
      vm.title = '';
      vm.link = '';
      vm.addMessage = false;
    };

    vm.incrementUpvotes = function(post) {
      postService.upvote(post);
    };

    vm.getUpvotedColor = function(post) {
      if (isUpvotedByCurrentUser(post)) {
        return 'text-primary';
      } else {
        return 'text-muted';
      }
    };

    function isUpvotedByCurrentUser(post) {
      return post.usersWhoUpvoted.indexOf(authService.currentUserId()) != -1;
    };

    // vm.colors = ['pink', 'yellow', 'beige'];
    // vm.change = function() {
    //   return vm.colors[Math.floor((Math.random()*3))];
    // };
    //
    // // vm.modalShown = false;
    // // vm.toggleModal = function() {
    // //   vm.modalShown = !vm.modalShown;
    // // };
    //
    // vm.likeFunction = function() {
    //   alert('I like the post');
    // };
    //
    // vm.message = 'Post Created!';
  } //mainCtrl callback

  //--------------------------------------
  //ANGULAR
  //--------------------------------------
  angular.module('flapperNews')

  .config(['$stateProvider', config])

  .controller('mainCtrl', ['postService', 'authService', mainCtrl]);

})();


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title></title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://unay-cilamega.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//unay-cilamega.github.io/themes/casper/assets/css/screen.css?v=1508479041355" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="" href="https://unay-cilamega.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

    Scroll Down

        Page 0 of 0

        Page 0 of 0

 © 2017

Proudly published with HubPress


text:
/*
 * echoアプリのフォーム
 */
package org.seasar.sastruts.hoge.form;

public class RestTrialForm {

	public String id;
	public String jsonBody;

}


text:
/* Generated By:JJTree: Do not edit this line. SimpleNode.java */

package org.python.ReL.WDB.parser.generated.wdb.parser;

import org.python.ReL.WDB.database.wdb.metadata.ParserAdapter;
import org.python.ReL.WDB.database.wdb.metadata.IndexSelectResult;
import org.python.ReL.WDB.database.wdb.metadata.WDBObject;

import java.io.*;
import java.util.ArrayList;

public class SimpleNode implements Node, Serializable {
  protected Node parent;
  protected Node[] children;
  protected int id;
  protected QueryParser parser;

  public SimpleNode(int i) {
    id = i;
  }

  public SimpleNode(QueryParser p, int i) {
    this(i);
    parser = p;
  }

  public void jjtOpen() {
  }

  public void jjtClose() {
  }

  public void jjtSetParent(Node n) { parent = n; }
  public Node jjtGetParent() { return parent; }

  public void jjtAddChild(Node n, int i) {
    if (children == null) {
      children = new Node[i + 1];
    } else if (i >= children.length) {
      Node c[] = new Node[i + 1];
      System.arraycopy(children, 0, c, 0, children.length);
      children = c;
    }
    children[i] = n;
  }

  public Node jjtGetChild(int i) {
    return children[i];
  }

  public int jjtGetNumChildren() {
    return (children == null) ? 0 : children.length;
  }

  /* You can override these two methods in subclasses of SimpleNode to
     customize the way the node appears when the tree is dumped.  If
     your output uses more than one line you should override
     toString(String), otherwise overriding toString() is probably all
     you need to do. */

  public String toString() { return QueryParserTreeConstants.jjtNodeName[id]; }
  public String toString(String prefix) { return prefix + toString(); }

  /* Override this method if you want to customize how the node dumps
     out its children. */

  public void dump(String prefix) {
    System.out.println(toString(prefix));
    if (children != null) {
      for (int i = 0; i < children.length; ++i) {
	SimpleNode n = (SimpleNode)children[i];
	if (n != null) {
	  n.dump(prefix + " ");
	}
      }
    }
  }
  public IndexSelectResult filterObjectsWithIndexes(ParserAdapter da, ArrayList indexes) throws Exception
  {
	  IndexSelectResult isr = new IndexSelectResult();
	  //These conditions are not supported so return a "scan" or "can't help" result
	  return isr;
  }
  public boolean eval(ParserAdapter da, WDBObject wdbO) throws Exception
  {
  	return false;
  }
}


text:
namespace {

// A helper function to touch all pages in the range
// [base_addr, base_addr + length).
void TouchPagesInRange(const void* base_addr, uint32_t length) {
  DCHECK(base_addr);
  DCHECK_GT(length, static_cast<uint32_t>(0));

  // Get the system info so we know the page size. Also, make sure we use a
  // non-zero value for the page size; GetSystemInfo() is hookable/patchable,
  // and you never know what shenanigans someone could get up to.
  SYSTEM_INFO system_info = {};
  ::GetSystemInfo(&system_info);
  if (system_info.dwPageSize == 0)
    system_info.dwPageSize = 4096;

  // We don't want to read outside the byte range (which could trigger an
  // access violation), so let's figure out the exact locations of the first
  // and final bytes we want to read.
  volatile uint8_t const* touch_ptr =
      reinterpret_cast<uint8_t const*>(base_addr);
  volatile uint8_t const* final_touch_ptr = touch_ptr + length - 1;

  // Read the memory in the range [touch_ptr, final_touch_ptr] with a stride
  // of the system page size, to ensure that it's been paged in.
  uint8_t dummy;
  for (; touch_ptr < final_touch_ptr; touch_ptr += system_info.dwPageSize)
    dummy = *touch_ptr;
  dummy = *final_touch_ptr;
}

}  // namespace

void PreReadFile(const base::FilePath& file_path) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (base::win::GetVersion() > base::win::VERSION_XP) {
    // Vista+ branch. On these OSes, the forced reads through the file actually
    // slows warm starts. The solution is to sequentially read file contents.
    base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
                                   base::File::FLAG_SEQUENTIAL_SCAN);
    if (!file.IsValid())
      return;

    const DWORD kStepSize = 1024 * 1024;
    char* buffer = reinterpret_cast<char*>(
        ::VirtualAlloc(nullptr, kStepSize, MEM_COMMIT, PAGE_READWRITE));
    if (!buffer)
      return;

    while (file.ReadAtCurrentPos(buffer, kStepSize) > 0) {}

    ::VirtualFree(buffer, 0, MEM_RELEASE);
  } else {
    // WinXP branch. Here, reading the DLL from disk doesn't do what we want so
    // instead we pull the pages into memory and touch pages at a stride. We use
    // the system's page size as the stride, to make sure each page in the range
    // is touched.

    // Don't show an error popup when |file_path| is not a valid PE file.
    UINT previous_error_mode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
    ::SetErrorMode(previous_error_mode | SEM_FAILCRITICALERRORS);

    base::ScopedNativeLibrary dll_module(::LoadLibraryExW(
        file_path.value().c_str(), NULL,
        LOAD_WITH_ALTERED_SEARCH_PATH | DONT_RESOLVE_DLL_REFERENCES));

    ::SetErrorMode(previous_error_mode);

    // Pre-reading non-PE files is not supported on XP.
    if (!dll_module.is_valid())
      return;

    base::win::PEImage pe_image(dll_module.get());
    if (!pe_image.VerifyMagic())
      return;

    // We don't want to read past the end of the module (which could trigger
    // an access violation), so make sure to check the image size.
    PIMAGE_NT_HEADERS nt_headers = pe_image.GetNTHeaders();
    const uint32_t dll_module_length = nt_headers->OptionalHeader.SizeOfImage;

    // Page in the module.
    TouchPagesInRange(dll_module.get(), dll_module_length);
  }
}

void PreReadMemoryMappedFile(const base::MemoryMappedFile& memory_mapped_file,
                             const base::FilePath& file_path) {
  base::ThreadRestrictions::AssertIOAllowed();
  if (!memory_mapped_file.IsValid())
    return;

  // Load ::PrefetchVirtualMemory dynamically, because it is only available on
  // Win8+.
  using PrefetchVirtualMemoryPtr = decltype(::PrefetchVirtualMemory)*;
  PrefetchVirtualMemoryPtr prefetch_virtual_memory =
      reinterpret_cast<PrefetchVirtualMemoryPtr>(::GetProcAddress(
          ::GetModuleHandle(L"kernel32.dll"), "PrefetchVirtualMemory"));
  if (!prefetch_virtual_memory) {
    // If ::PrefetchVirtualMemory is not available, fall back to PreReadFile.
    PreReadFile(file_path);
    return;
  }

  WIN32_MEMORY_RANGE_ENTRY memory_range;
  memory_range.VirtualAddress = const_cast<void*>(
      reinterpret_cast<const void*>(memory_mapped_file.data()));
  memory_range.NumberOfBytes = memory_mapped_file.length();
  prefetch_virtual_memory(::GetCurrentProcess(), 1U, &memory_range, 0);
}


text:
<?php
/**
 * The Action class
 */
abstract class LtAction
{
	/**
	 * The context object
	 *
	 * @var object
	 */
	public $context;

	public $viewDir;
	public $viewTplDir;
	public $viewTplAutoCompile;

	/**
	 * The dtd config for validator
	 *
	 * @var array
	 */
	protected $dtds = array();

	/**
	 * The Access Control List
	 *
	 * @var array
	 */
	protected $acl;

	/**
	 * The current user's roles
	 *
	 * @var array
	 */
	protected $roles = array();

	/**
	 * A flag to indicate if subclass call LtAction::__construct()
	 *
	 * @var boolean
	 */
	protected $constructed = false;

	/**
	 * The response type
	 *
	 * @var string
	 */
	protected $responseType = "html";

	/**
	 * Result properties
	 */
	protected $code;

	protected $message;

	public $data;

	protected $view;

	protected $layout;

	/**
	 * The constructor function, initialize the URI property
	 */
	public function __construct()
	{
		$this->constructed = true;
	}

	public function executeChain()
	{
		if (!$this->constructed)
		{
			//DebugHelper::debug('SUBCLASS_NOT_CALL_PARENT_CONSTRUCTOR', array('class' => $actionClassName));
			trigger_error('SUBCLASS_NOT_CALL_PARENT_CONSTRUCTOR');
		}
		$this->afterConstruct();
		$validateResult = $this->validateInput();
		if (0 == $validateResult["error_total"])
		{
			if ($this->checkPrivilege())
			{
				$this->beforeExecute();
				$this->execute();
			}
			else
			{
				$this->code = 403;
				$this->message = "Access denied";
			}
		}
		else
		{
			$this->code = 407;
			$this->message = "Invalid input";
			$this->data['error_messages'] = $validateResult["error_messages"];
		}
		$this->writeResponse();
	}

	/**
	 * Do something after subClass::__construct().
	 */
	protected function afterConstruct()
	{

	}

	/**
	 * Validate the data from client
	 *
	 * @return array
	 */
	protected function validateInput()
	{
		$validateResult = array("error_total" => 0, "error_messages" => array());
		if (!empty($this->dtds) && class_exists('LtValidator'))
		{
			$validator = new LtValidator;
			$validator->init();
			foreach ($this->dtds as $variable => $dtd)
			{
				$from = isset($dtd->from) ? $dtd->from : 'request';

				foreach ($dtd->rules as $ruleKey => $ruleValue)
				{
					if ($ruleValue instanceof ConfigExpression)
					{
						eval('$_ruleValue = ' . $ruleValue->__toString());
						$dtd->rules[$ruleKey] = $_ruleValue;
					}
				}
				$error_messages = $validator->validate($this->context->$from($variable), $dtd);
				if (!empty($error_messages))
				{
					$validateResult['error_total'] ++;
					$validateResult['error_messages'][$variable] = $error_messages;
				}
			}
		}
		return $validateResult;
	}

	/**
	 * Check if current user have privilege to do this
	 *
	 * @return boolen
	 */
	protected function checkPrivilege()
	{
		$allow = true;
		if (!empty($this->roles) && class_exists('LtRbac'))
		{
			$module = $this->context->uri["module"];
			$action = $this->context->uri["action"];
			$roles = array_merge(array("*"), $this->roles);
			$rbac = new LtRbac();
			$rbac->init();
			$allow = $rbac->checkAcl($roles, "$module/$action");
		}
		return $allow;
	}

	/**
	 * Do something before subClass::execute().
	 */
	protected function beforeExecute()
	{
	}

	protected function execute()
	{
	}

	protected function writeResponse()
	{
		switch ($this->responseType)
		{
			case 'json':
				echo json_encode(array("code" => $this->code,
						"message" => $this->message,
						"data" => $this->data
						));
				exit; //
				break;
			case 'tpl':
				if (null === $this->view)
				{
					$this->view = new LtTemplateView;
				}
				$this->view->component = false; // 是否组件
				$this->view->context = $this->context;
				$this->view->code = $this->code;
				$this->view->message = $this->message;
				$this->view->data = $this->data;
				$this->view->layoutDir = $this->viewDir . "layout/";
				$this->view->layout = $this->layout;
				$this->view->templateDir = $this->viewDir;
				$this->view->compiledDir = $this->viewTplDir;
				$this->view->autoCompile = $this->viewTplAutoCompile;
				if (empty($this->template))
				{
					$this->template = $this->context->uri["module"] . "-" . $this->context->uri["action"];
				}
				$this->view->template = $this->template;
				$this->view->render();
				break;

			case 'html':
			case 'wml':
			default:
				if (null === $this->view)
				{
					$this->view = new LtView;
				}
				$this->view->context = $this->context;
				$this->view->code = $this->code;
				$this->view->message = $this->message;
				$this->view->data = $this->data;
				$this->view->layoutDir = $this->viewDir . "layout/";
				$this->view->layout = $this->layout;
				$this->view->templateDir = $this->viewDir;
				if (empty($this->template))
				{
					$this->template = $this->context->uri["module"] . "-" . $this->context->uri["action"];
				}
				$this->view->template = $this->template;
				$this->view->render();
				break;
		}
	}
}