text:
<?php

class b2c_mdl_archive_reship extends archive_model{

    var $has_many = array(
        'reship_items'=>'archive_reship_items:contrast:reship_id^reship_id',
        'orders'=>'archive_order_delivery:contrast:reship_id^dly_id',
    );

    var $defaultOrder = array('t_begin','DESC');

    public function extra_search_info(){
        return array(
            'key'=>array(
                'column'=>'reship_id',
                'label'=>'退货单号',
            ),
            'time_column'=>'t_begin',
        );
    }

    public function document2time($reship_id){
        return array(
            'start' => strtotime(substr($reship_id,1,8).'000000'),
            'end' => strtotime(substr($reship_id,1,8).'235959'),
        );
    }

    public function modifier_money($row)
    {
        $app_ectools = app::get('ectools');
        $row = $app_ectools->model('currency')->changer_odr($row,null,false,false,$this->app->getConf('system.money.decimals'),$this->app->getConf('system.money.operation.carryset'));

        return $row;
    }

    public function modifier_delivery($row)
    {
        $obj_dlytype = $this->app->model('dlytype');
        $arr_dlytype = $obj_dlytype->dump($row, 'dt_name');

        return $arr_dlytype['dt_name'] ? $arr_dlytype['dt_name'] : '-';
    }

}


text:
package com.cloudera.flume.reporter.charts;

import com.cloudera.flume.reporter.charts.google.GoogleChartPackage;
import com.cloudera.flume.reporter.histogram.HistogramChartGen;
import com.cloudera.flume.reporter.history.TimelineChartGen;

/**
 * This is singleton object used to construct chart generators. It defaults to
 * GoogleCharts based charts, but can be overridden with other chart generation
 * packages.
 */
abstract public class ChartPackage {
  // Default to google charts for now.
  static ChartPackage pkg = new GoogleChartPackage();

  public static void setChartGenerators(ChartPackage c) {
    pkg = c;
  }

  public static HistogramChartGen<String> createHistogramGen() {
    return pkg.histogramGen();
  }

  public static TimelineChartGen<Long> createTimelineGen() {
    return pkg.timelineGen();
  }

  public abstract HistogramChartGen<String> histogramGen();

  public abstract TimelineChartGen<Long> timelineGen();
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>JRBaseSubreportReturnValue (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jasperreports.engine.base

Class JRBaseSubreportReturnValue

java.lang.Object

net.sf.jasperreports.engine.base.JRBaseSubreportReturnValue

All Implemented Interfaces:

java.io.Serializable, java.lang.Cloneable, JRCloneable, JRSubreportReturnValue

Direct Known Subclasses:

JRDesignSubreportReturnValue

public class JRBaseSubreportReturnValue
extends java.lang.Object
implements JRSubreportReturnValue, java.io.Serializable

Base implementation of JRSubreportReturnValue.

Version:

$Id: JRBaseSubreportReturnValue.java 5878 2013-01-07 20:23:13Z teodord $

Author:

Lucian Chirita (lucianc@users.sourceforge.net)

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

protected CalculationEnum
calculationValue

The calculation type.

protected java.lang.String
incrementerFactoryClassName

The incrementer factory class name.

protected java.lang.String
subreportVariable

The name of the subreport variable to be copied.

protected java.lang.String
toVariable

The name of the master variable where the value should be copied.

Constructor Summary

Constructors

Modifier
Constructor and Description

protected
JRBaseSubreportReturnValue()

protected
JRBaseSubreportReturnValue(JRSubreportReturnValue returnValue,
                          JRBaseObjectFactory factory)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.Object
clone()

CalculationEnum
getCalculationValue()

Returns the calculation type.

java.lang.String
getIncrementerFactoryClassName()

Returns the incrementer factory class name.

java.lang.String
getSubreportVariable()

Returns the name of the subreport variable whose value should be copied.

java.lang.String
getToVariable()

Returns the name of the master report variable where the value should be copied.

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

subreportVariable

protected java.lang.String subreportVariable

The name of the subreport variable to be copied.

toVariable

protected java.lang.String toVariable

The name of the master variable where the value should be copied.

calculationValue

protected CalculationEnum calculationValue

The calculation type.

incrementerFactoryClassName

protected java.lang.String incrementerFactoryClassName

The incrementer factory class name.

Constructor Detail

JRBaseSubreportReturnValue

protected JRBaseSubreportReturnValue()

JRBaseSubreportReturnValue

protected JRBaseSubreportReturnValue(JRSubreportReturnValue returnValue,
                          JRBaseObjectFactory factory)

Method Detail

getSubreportVariable

public java.lang.String getSubreportVariable()

Returns the name of the subreport variable whose value should be copied.

Specified by:

getSubreportVariable in interface JRSubreportReturnValue

Returns:

the name of the subreport variable whose value should be copied.

getToVariable

public java.lang.String getToVariable()

Returns the name of the master report variable where the value should be copied.

Specified by:

getToVariable in interface JRSubreportReturnValue

Returns:

the name of the master report variable where the value should be copied.

getCalculationValue

public CalculationEnum getCalculationValue()

Returns the calculation type.

 When copying the value from the subreport, a formula can be applied such that sum,
 maximum, average and so on can be computed.

Specified by:

getCalculationValue in interface JRSubreportReturnValue

Returns:

the calculation type.

getIncrementerFactoryClassName

public java.lang.String getIncrementerFactoryClassName()

Returns the incrementer factory class name.

 The factory will be used to increment the value of the master report variable
 with the value from the subreport.

Specified by:

getIncrementerFactoryClassName in interface JRSubreportReturnValue

Returns:

the incrementer factory class name.

clone

public java.lang.Object clone()

Specified by:

clone in interface JRCloneable

Overrides:

clone in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
declare namespace ಠ_ಠ.clutz.goog.ns {
  function fn (a : GlobalEventTarget ) : void ;
}
declare module 'goog:goog.ns' {
  import ns = ಠ_ಠ.clutz.goog.ns;
  export = ns;
}
// Generated from src/test/java/com/google/javascript/clutz/testdata/shadowed_global_with_platform.js
declare namespace ಠ_ಠ.clutz.goog.ns {
  class EventTarget {
    private noStructuralTyping_goog_ns_EventTarget : any;
  }
}
declare module 'goog:goog.ns.EventTarget' {
  import EventTarget = ಠ_ಠ.clutz.goog.ns.EventTarget;
  export default EventTarget;
}


text:
<?xml version="1.0"?>
<!DOCTYPE root [
<!ELEMENT root (#PCDATA)>
]>
</root>
<!--* Missing start tag and no content -->


text:
import {CSS} from '../../../build/amp-ad-0.1.css';
import {isLayoutSizeDefined} from '../../../src/layout';
import {AmpAd3PImpl} from './amp-ad-3p-impl';
import {a4aRegistry} from '../../../ads/_a4a-config';
import {dev, user} from '../../../src/log';
import {extensionsFor} from '../../../src/extensions';
import {userNotificationManagerFor} from '../../../src/user-notification';

/**
 * Construct ad network type-specific tag and script name.  Note that this
 * omits the version number and '.js' suffix for the extension script, which
 * will be handled by the extension loader.
 *
 * @param {!string} type
 * @return !string
 * @private
 */
function networkImplementationTag(type) {
  return `amp-ad-network-${type}-impl`;
}

export class AmpAd extends AMP.BaseElement {

  /** @override */
  upgradeCallback() {
    // Block whole ad load if a consent is needed.
    /** @const {string} */
    const consentId = this.element.getAttribute('data-consent-notification-id');
    const consent = consentId
        ? userNotificationManagerFor(this.win)
            .then(service => service.get(consentId))
        : Promise.resolve();

    return consent.then(() => {
      const type = this.element.getAttribute('type');
      if (!type) {
        // Unspecified or empty type.  Nothing to do here except bail out.
        return null;
      }
      window.ampAdSlotIdCounter = window.ampAdSlotIdCounter || 0;
      const slotId = window.ampAdSlotIdCounter++;
      this.element.setAttribute('data-amp-slot-index', slotId);
      // TODO(tdrl): Check amp-ad registry to see if they have this already.
      if (!a4aRegistry[type] ||
          !a4aRegistry[type](this.win, this.element)) {
        // Network either has not provided any A4A implementation or the
        // implementation exists, but has explicitly chosen not to handle this
        // tag as A4A.  Fall back to the 3p implementation.
        return new AmpAd3PImpl(this.element);
      }
      const extensionTagName = networkImplementationTag(type);
      this.element.setAttribute('data-a4a-upgrade-type', extensionTagName);
      return extensionsFor(this.win).loadElementClass(extensionTagName)
        .then(ctor => new ctor(this.element))
        .catch(error => {
          // Work around presubmit restrictions.
          const TAG = this.element.tagName;
          // Report error and fallback to 3p
          user().error(TAG, 'Unable to load ad implementation for type ', type,
              ', falling back to 3p, error: ', error);
          return new AmpAd3PImpl(this.element);
        });
    });
  }

  /** @override */
  isLayoutSupported(layout) {
    return isLayoutSizeDefined(layout);
  }

  /** @override */
  buildCallback() {
    // This is only called when no type was set on the element and thus
    // upgrade element fell through.
    dev().assert(this.element.getAttribute('type'), 'Required attribute type');
  }
}

AMP.registerElement('amp-ad', AmpAd, CSS);
AMP.registerElement('amp-embed', AmpAd, CSS);


text:
package com.gk969.gallery.gallery3d.util;

/**
 * Bucket names for buckets that are created and used in the Gallery.
 */
public class BucketNames {

    public static final String CAMERA = "DCIM/Camera";
    public static final String IMPORTED = "Imported";
    public static final String DOWNLOAD = "download";
    public static final String EDITED_ONLINE_PHOTOS = "EditedOnlinePhotos";
    public static final String SCREENSHOTS = "Pictures/Screenshots";
}


text:
"""Test i18n module."""
#
# (C) Pywikibot team, 2007-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

__version__ = '$Id$'

import sys

import pywikibot

from pywikibot import i18n, bot, plural

from tests.aspects import unittest, TestCase, DefaultSiteTestCase, PwbTestCase

if sys.version_info[0] == 3:
    basestring = (str, )

class TestTranslate(TestCase):

    """Test translate method."""

    net = False

    def setUp(self):
        self.msg_localized = {'en': u'test-localized EN',
                              'nl': u'test-localized NL',
                              'fy': u'test-localized FY'}
        self.msg_semi_localized = {'en': u'test-semi-localized EN',
                                   'nl': u'test-semi-localized NL'}
        self.msg_non_localized = {'en': u'test-non-localized EN'}
        self.msg_no_english = {'ja': u'test-no-english JA'}
        super(TestTranslate, self).setUp()

    def testLocalized(self):
        """Test fully localized translations."""
        self.assertEqual(i18n.translate('en', self.msg_localized,
                                        fallback=True),
                         u'test-localized EN')
        self.assertEqual(i18n.translate('nl', self.msg_localized,
                                        fallback=True),
                         u'test-localized NL')
        self.assertEqual(i18n.translate('fy', self.msg_localized,
                                        fallback=True),
                         u'test-localized FY')

    def testSemiLocalized(self):
        """Test translate by fallback to an alternative language."""
        self.assertEqual(i18n.translate('en', self.msg_semi_localized,
                                        fallback=True),
                         u'test-semi-localized EN')
        self.assertEqual(i18n.translate('nl', self.msg_semi_localized,
                                        fallback=True),
                         u'test-semi-localized NL')
        self.assertEqual(i18n.translate('fy', self.msg_semi_localized,
                                        fallback=True),
                         u'test-semi-localized NL')

    def testNonLocalized(self):
        """Test translate with missing localisation."""
        self.assertEqual(i18n.translate('en', self.msg_non_localized,
                                        fallback=True),
                         u'test-non-localized EN')
        self.assertEqual(i18n.translate('fy', self.msg_non_localized,
                                        fallback=True),
                         u'test-non-localized EN')
        self.assertEqual(i18n.translate('nl', self.msg_non_localized,
                                        fallback=True),
                         u'test-non-localized EN')
        self.assertEqual(i18n.translate('ru', self.msg_non_localized,
                                        fallback=True),
                         u'test-non-localized EN')

    def testNoEnglish(self):
        """Test translate with missing English text."""
        self.assertEqual(i18n.translate('en', self.msg_no_english,
                                        fallback=True),
                         u'test-no-english JA')
        self.assertEqual(i18n.translate('fy', self.msg_no_english,
                                        fallback=True),
                         u'test-no-english JA')
        self.assertEqual(i18n.translate('nl', self.msg_no_english,
                                        fallback=True),
                         u'test-no-english JA')

class UserInterfaceLangTestCase(TestCase):

    """Base class for tests using config.userinterface_lang."""

    def setUp(self):
        """Change the userinterface language to the site's code."""
        super(UserInterfaceLangTestCase, self).setUp()
        self.orig_userinterface_lang = pywikibot.config.userinterface_lang
        pywikibot.config.userinterface_lang = self.get_site().code

    def tearDown(self):
        """Reset the userinterface language."""
        pywikibot.config.userinterface_lang = self.orig_userinterface_lang
        super(UserInterfaceLangTestCase, self).tearDown()

class TWNSetMessagePackageBase(TestCase):

    """Partial base class for TranslateWiki tests."""

    message_package = None

    def setUp(self):
        """Load the test translations."""
        self.orig_messages_package_name = i18n._messages_package_name
        i18n.set_messages_package(self.message_package)
        super(TWNSetMessagePackageBase, self).setUp()

    def tearDown(self):
        """Load the original translations back."""
        super(TWNSetMessagePackageBase, self).tearDown()
        i18n.set_messages_package(self.orig_messages_package_name)

class TWNTestCaseBase(TWNSetMessagePackageBase):

    """Base class for TranslateWiki tests."""

    @classmethod
    def setUpClass(cls):
        """Verify that the test translations are not empty."""
        if not isinstance(cls.message_package, basestring):
            raise TypeError('%s.message_package must be a package name'
                            % cls.__name__)
        # The call to set_messages_package below exists only to confirm
        # that the package exists and messages are available, so
        # that tests can be skipped if the i18n data doesnt exist.
        cls.orig_messages_package_name = i18n._messages_package_name
        i18n.set_messages_package(cls.message_package)
        has_messages = i18n.messages_available()
        i18n._messages_package_name = cls.orig_messages_package_name
        if not has_messages:
            raise unittest.SkipTest("i18n messages package '%s' not available."
                                    % cls.message_package)
        super(TWNTestCaseBase, cls).setUpClass()

class TestTWTranslate(TWNTestCaseBase):

    """Test twtranslate method."""

    net = False
    message_package = 'tests.i18n'

    def testLocalized(self):
        """Test fully localized entry."""
        self.assertEqual(i18n.twtranslate('en', 'test-localized'),
                         u'test-localized EN')
        self.assertEqual(i18n.twtranslate('nl', 'test-localized'),
                         u'test-localized NL')
        self.assertEqual(i18n.twtranslate('fy', 'test-localized'),
                         u'test-localized FY')

    def testSemiLocalized(self):
        """Test translating with fallback to alternative language."""
        self.assertEqual(i18n.twtranslate('en', 'test-semi-localized'),
                         u'test-semi-localized EN')
        self.assertEqual(i18n.twtranslate('nl', 'test-semi-localized'),
                         u'test-semi-localized NL')
        self.assertEqual(i18n.twtranslate('fy', 'test-semi-localized'),
                         u'test-semi-localized NL')

    def testNonLocalized(self):
        """Test translating non localized entries."""
        self.assertEqual(i18n.twtranslate('en', 'test-non-localized'),
                         u'test-non-localized EN')
        self.assertEqual(i18n.twtranslate('fy', 'test-non-localized'),
                         u'test-non-localized EN')
        self.assertEqual(i18n.twtranslate('nl', 'test-non-localized'),
                         u'test-non-localized EN')
        self.assertEqual(i18n.twtranslate('ru', 'test-non-localized'),
                         u'test-non-localized EN')

    def testNoEnglish(self):
        """Test translating into English with missing entry."""
        self.assertRaises(i18n.TranslationError, i18n.twtranslate,
                          'en', 'test-no-english')

class TestTWNTranslate(TWNTestCaseBase):

    """Test {{PLURAL:}} support."""

    net = False
    message_package = 'tests.i18n'

    def testNumber(self):
        """Use a number."""
        self.assertEqual(
            i18n.twntranslate('de', 'test-plural', 0) % {'num': 0},
            u'Bot: Ändere 0 Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-plural', 1) % {'num': 1},
            u'Bot: Ändere 1 Seite.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-plural', 2) % {'num': 2},
            u'Bot: Ändere 2 Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-plural', 3) % {'num': 3},
            u'Bot: Ändere 3 Seiten.')
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', 0) % {'num': 'no'},
            u'Bot: Changing no pages.')
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', 1) % {'num': 'one'},
            u'Bot: Changing one page.')
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', 2) % {'num': 'two'},
            u'Bot: Changing two pages.')
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', 3) % {'num': 'three'},
            u'Bot: Changing three pages.')

    def testString(self):
        """Use a string."""
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', '1') % {'num': 'one'},
            u'Bot: Changing one page.')

    def testDict(self):
        """Use a dictionary."""
        self.assertEqual(
            i18n.twntranslate('en', 'test-plural', {'num': 2}),
            u'Bot: Changing 2 pages.')

    def testExtended(self):
        """Use additional format strings."""
        self.assertEqual(
            i18n.twntranslate('fr', 'test-plural', {'num': 1, 'descr': 'seulement'}),
            u'Robot: Changer seulement une page.')

    def testExtendedOutside(self):
        """Use additional format strings also outside."""
        self.assertEqual(
            i18n.twntranslate('fr', 'test-plural', 1) % {'descr': 'seulement'},
            u'Robot: Changer seulement une page.')

    def testMultiple(self):
        """Test using multiple plural entries."""
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', 1)
            % {'action': u'Ändere', 'line': u'eine'},
            u'Bot: Ändere eine Zeile von einer Seite.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', 2)
            % {'action': u'Ändere', 'line': u'zwei'},
            u'Bot: Ändere zwei Zeilen von mehreren Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', 3)
            % {'action': u'Ändere', 'line': u'drei'},
            u'Bot: Ändere drei Zeilen von mehreren Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', (1, 2, 2))
            % {'action': u'Ändere', 'line': u'eine'},
            u'Bot: Ändere eine Zeile von mehreren Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', [3, 1, 1])
            % {'action': u'Ändere', 'line': u'drei'},
            u'Bot: Ändere drei Zeilen von einer Seite.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', ["3", 1, 1])
            % {'action': u'Ändere', 'line': u'drei'},
            u'Bot: Ändere drei Zeilen von einer Seite.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals', "321")
            % {'action': u'Ändere', 'line': u'dreihunderteinundzwanzig'},
            u'Bot: Ändere dreihunderteinundzwanzig Zeilen von mehreren Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals',
                              {'action': u'Ändere', 'line': 1, 'page': 1}),
            u'Bot: Ändere 1 Zeile von einer Seite.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals',
                              {'action': u'Ändere', 'line': 1, 'page': 2}),
            u'Bot: Ändere 1 Zeile von mehreren Seiten.')
        self.assertEqual(
            i18n.twntranslate('de', 'test-multiple-plurals',
                              {'action': u'Ändere', 'line': "11", 'page': 2}),
            u'Bot: Ändere 11 Zeilen von mehreren Seiten.')

    def testMultipleWrongParameterLength(self):
        """Test wrong parameter length."""
        err_msg = 'Length of parameter does not match PLURAL occurrences'
        with self.assertRaisesRegex(ValueError, err_msg):
            i18n.twntranslate('de', 'test-multiple-plurals', (1, 2))

        with self.assertRaisesRegex(ValueError, err_msg):
            i18n.twntranslate('de', 'test-multiple-plurals', ["321"])

    def testMultipleNonNumbers(self):
        """Test error handling for multiple non-numbers."""
        with self.assertRaisesRegex(ValueError, "invalid literal for int\(\) with base 10: 'drei'"):
            i18n.twntranslate('de', 'test-multiple-plurals', ["drei", "1", 1])
        with self.assertRaisesRegex(ValueError, "invalid literal for int\(\) with base 10: 'elf'"):
            i18n.twntranslate('de', 'test-multiple-plurals',
                              {'action': u'Ändere', 'line': "elf", 'page': 2})

    def testAllParametersExist(self):
        """Test that all parameters are required when using a dict."""
        with self.assertRaisesRegex(KeyError, repr(u'line')):
            # all parameters must be inside twntranslate
            i18n.twntranslate('de', 'test-multiple-plurals',
                              {'line': 1, 'page': 1}) % {'action': u'Ändere'}

    def test_fallback_lang(self):
        """
        Test that twntranslate uses the translation's language.

        twntranslate calls _twtranslate which might return the translation for
        a different language and then the plural rules from that language need
        to be applied.
        """
        # co has fr as altlang but has no plural rules defined (otherwise this
        # test might not catch problems) so it's using the plural variant for 0
        # although French uses the plural variant for numbers > 1 (so not 0)
        assert 'co' not in plural.plural_rules
        assert plural.plural_rules['fr']['plural'](0) is False
        self.assertEqual(
            i18n.twntranslate('co', 'test-plural', {'num': 0, 'descr': 'seulement'}),
            u'Robot: Changer seulement une page.')
        self.assertEqual(
            i18n.twntranslate('co', 'test-plural', {'num': 1, 'descr': 'seulement'}),
            u'Robot: Changer seulement une page.')

class ScriptMessagesTestCase(TWNTestCaseBase):

    """Real messages test."""

    net = False
    message_package = 'scripts.i18n'

    def test_basic(self):
        """Verify that real messages are able to be loaded."""
        self.assertEqual(i18n.twntranslate('en', 'pywikibot-enter-new-text'),
                         'Please enter the new text:')

    def test_missing(self):
        """Test a missing message from a real message bundle."""
        self.assertRaises(i18n.TranslationError,
                          i18n.twntranslate, 'en', 'pywikibot-missing-key')

class InputTestCase(TWNTestCaseBase, UserInterfaceLangTestCase, PwbTestCase):

    """Test i18n.input."""

    family = 'wikipedia'
    code = 'arz'

    message_package = 'scripts.i18n'

    @classmethod
    def setUpClass(cls):
        """Verify that a translation does not yet exist."""
        super(InputTestCase, cls).setUpClass()

        if cls.code in i18n.twget_keys('pywikibot-enter-category-name'):
            raise unittest.SkipTest(
                '%s has a translation for %s'
                % (cls.code, 'pywikibot-enter-category-name'))

    def test_pagegen_i18n_input(self):
        """Test i18n.input via ."""
        result = self._execute(args=['listpages', '-cat'],
                               data_in='non-existant-category\n',
                               timeout=5)

        self.assertIn('Please enter the category name:', result['stderr'])

class MissingPackageTestCase(TWNSetMessagePackageBase,
                             UserInterfaceLangTestCase,
                             DefaultSiteTestCase):

    """Test misssing messages package."""

    message_package = 'scripts.foobar.i18n'

    def _capture_output(self, text, *args, **kwargs):
        self.output_text = text

    def setUp(self):
        """Patch the output and input methods."""
        super(MissingPackageTestCase, self).setUp()
        self.output_text = ''
        self.orig_raw_input = bot.ui._raw_input
        self.orig_output = bot.ui.output
        bot.ui._raw_input = lambda *args, **kwargs: 'dummy input'
        bot.ui.output = self._capture_output

    def tearDown(self):
        """Restore the output and input methods."""
        bot.ui._raw_input = self.orig_raw_input
        bot.ui.output = self.orig_output
        super(MissingPackageTestCase, self).tearDown()

    def test_pagegen_i18n_input(self):
        """Test i18n.input falls back with missing message package."""
        rv = i18n.input('pywikibot-enter-category-name',
                        fallback_prompt='dummy output')
        self.assertEqual(rv, 'dummy input')
        self.assertIn('dummy output: ', self.output_text)

if __name__ == '__main__':
    try:
        unittest.main()
    except SystemExit:
        pass


text:
<link rel="import" href="../polymer/polymer.html">

<polymer-element name="timedemo-smartgrid-distortioncurve">

    <template>

    </template>

</polymer-element>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/iam/admin/v1/iam.proto

package com.google.iam.admin.v1;

/**
 *
 *
 *

 * Supported private key output formats.
 *

 *
 * Protobuf enum {@code google.iam.admin.v1.ServiceAccountPrivateKeyType}
 */
public enum ServiceAccountPrivateKeyType implements com.google.protobuf.ProtocolMessageEnum {
  /**
   *
   *
   *

   * Unspecified. Equivalent to `TYPE_GOOGLE_CREDENTIALS_FILE`.
   *

   *
   * TYPE_UNSPECIFIED = 0;
   */
  TYPE_UNSPECIFIED(0),
  /**
   *
   *
   *

   * PKCS12 format.
   * The password for the PKCS12 file is `notasecret`.
   * For more information, see https://tools.ietf.org/html/rfc7292.
   *

   *
   * TYPE_PKCS12_FILE = 1;
   */
  TYPE_PKCS12_FILE(1),
  /**
   *
   *
   *

   * Google Credentials File format.
   *

   *
   * TYPE_GOOGLE_CREDENTIALS_FILE = 2;
   */
  TYPE_GOOGLE_CREDENTIALS_FILE(2),
  UNRECOGNIZED(-1),
  ;

  /**
   *
   *
   *

   * Unspecified. Equivalent to `TYPE_GOOGLE_CREDENTIALS_FILE`.
   *

   *
   * TYPE_UNSPECIFIED = 0;
   */
  public static final int TYPE_UNSPECIFIED_VALUE = 0;
  /**
   *
   *
   *

   * PKCS12 format.
   * The password for the PKCS12 file is `notasecret`.
   * For more information, see https://tools.ietf.org/html/rfc7292.
   *

   *
   * TYPE_PKCS12_FILE = 1;
   */
  public static final int TYPE_PKCS12_FILE_VALUE = 1;
  /**
   *
   *
   *

   * Google Credentials File format.
   *

   *
   * TYPE_GOOGLE_CREDENTIALS_FILE = 2;
   */
  public static final int TYPE_GOOGLE_CREDENTIALS_FILE_VALUE = 2;

  public final int getNumber() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalArgumentException(
          "Can't get the number of an unknown enum value.");
    }
    return value;
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   * @deprecated Use {@link #forNumber(int)} instead.
   */
  @java.lang.Deprecated
  public static ServiceAccountPrivateKeyType valueOf(int value) {
    return forNumber(value);
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   */
  public static ServiceAccountPrivateKeyType forNumber(int value) {
    switch (value) {
      case 0:
        return TYPE_UNSPECIFIED;
      case 1:
        return TYPE_PKCS12_FILE;
      case 2:
        return TYPE_GOOGLE_CREDENTIALS_FILE;
      default:
        return null;
    }
  }

  public static com.google.protobuf.Internal.EnumLiteMap<ServiceAccountPrivateKeyType>
      internalGetValueMap() {
    return internalValueMap;
  }

  private static final com.google.protobuf.Internal.EnumLiteMap<ServiceAccountPrivateKeyType>
      internalValueMap =
          new com.google.protobuf.Internal.EnumLiteMap<ServiceAccountPrivateKeyType>() {
            public ServiceAccountPrivateKeyType findValueByNumber(int number) {
              return ServiceAccountPrivateKeyType.forNumber(number);
            }
          };

  public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalStateException(
          "Can't get the descriptor of an unrecognized enum value.");
    }
    return getDescriptor().getValues().get(ordinal());
  }

  public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
    return getDescriptor();
  }

  public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
    return com.google.iam.admin.v1.Iam.getDescriptor().getEnumTypes().get(1);
  }

  private static final ServiceAccountPrivateKeyType[] VALUES = values();

  public static ServiceAccountPrivateKeyType valueOf(
      com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
    if (desc.getType() != getDescriptor()) {
      throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
    }
    if (desc.getIndex() == -1) {
      return UNRECOGNIZED;
    }
    return VALUES[desc.getIndex()];
  }

  private final int value;

  private ServiceAccountPrivateKeyType(int value) {
    this.value = value;
  }

  // @@protoc_insertion_point(enum_scope:google.iam.admin.v1.ServiceAccountPrivateKeyType)
}


text:
package com.arialyy.aria.core.common.controller;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.SOURCE) public @interface ControllerType {
  /**
   * 仅用于第一次创建任务,后续可调用`#create()、#add()、#setHighestPriority()`方法。
   */
  Class<BuilderController> CREATE_CONTROLLER = BuilderController.class;
  /**
   * 用于后续的任务控制,后续可调用`#stop()、#resume()、#cancel()、#cancel(boolean)、#retry()、#restart()`方法。
   */
  Class<NormalController> TASK_CONTROLLER = NormalController.class;
}


text:
#include "newrelic_profiler.h"
#include "hphp/runtime/ext/hotprofiler/ext_hotprofiler.h"

namespace HPHP {
    void NewRelicProfiler::beginFrameEx(const char *symbol) {

        NewRelicProfilerFrame *frame = dynamic_cast<NewRelicProfilerFrame *>(m_stack);

        if (m_stack->m_parent) {
            NewRelicProfilerFrame *p = dynamic_cast<NewRelicProfilerFrame *>(frame->m_parent);
            frame->m_nr_depth = p->m_nr_depth + 1;
        } else {
            frame->m_nr_depth  = 0;
        }
        frame->m_nr_segement_code = 0;
        if (frame->m_nr_depth < max_depth) {
            frame->m_nr_segement_code = newrelic_segment_generic_begin(NEWRELIC_AUTOSCOPE, NEWRELIC_AUTOSCOPE, frame->m_name);
        }

    }

    void NewRelicProfiler::endFrameEx(const TypedValue *retval,
    const char *given_symbol) {

        char symbol[512];
        NewRelicProfilerFrame *frame = dynamic_cast<NewRelicProfilerFrame *>(m_stack);
        frame->getStack(2, symbol, sizeof(symbol));

        if (frame->m_nr_segement_code > 0) {
            newrelic_segment_end(NEWRELIC_AUTOSCOPE, frame->m_nr_segement_code);
            frame->m_nr_segement_code = 0;
        }
    }

}


text:
package com.hhx.manage.interceptor;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class AccessListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		 ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
		 ServletContext sc = sce.getServletContext();
		 sc.setAttribute("aa", "hhhh");
	}

}


text:
package com.alexstyl.specialdates.util;

import java.util.List;

import org.junit.Test;

import static org.fest.assertions.api.Assertions.assertThat;

public class HashMapListTest {

    @Test
    public void name() throws Exception {
        HashMapList<Integer, Integer> hashMapList = new HashMapList<>();
        hashMapList.addValue(1, 5);
        List<Integer> integers = hashMapList.get(1);
        assertThat(integers.get(0)).isEqualTo(5);
    }
}


text:
//////////////////////////////////////////////////////
//  discreteSearch.cpp
//
//  Created on: Jul 3, 2013
//      Author: joselusl
//
//  Last modification on: Oct 26, 2013
//      Author: joselusl
//
//////////////////////////////////////////////////////

#include "discreteSearch.h"

using namespace std;

AStar::AStar() : maxCost(MAX_COST_A_STAR)
{
    std::default_random_engine generator;
    std::time_t result = std::time(NULL);
    generator.seed(result);
    std::uniform_real_distribution<double> distribution(1.0,1.5);

    double randnum=distribution(generator);

    maxCost/=randnum;

    cout<<"randnum="<<randnum<<"; maxCost="<<maxCost<<endl;

    init();
}

AStar::~AStar()
{   // TODO_P: What do you think about opening brackets here?
    return;
}

int AStar::init()
{
    return 1;
}

int AStar::clear()
{
    return 1;
}

int AStar::setGraphToSearch(DiscreteGraph *GraphToSearchIn)
{
    GraphToSearch=GraphToSearchIn;

    return 1;
}

int AStar::clearSearch()
{

    //Matriz de secuenciamiento de acciones
    secuenciamientoAcciones.clear(); //[identif nodo 1; identif nodo 2]

    //Matriz de almacenamiento de estados visitados
    statesVisitedStates.clear();
    statesVisitedPotencial.clear();

    //matriz de estados ya evaluados y ya expandidos
    statesClosedStates.clear();
    statesClosedPotencial.clear();

    //Matriz de estados abiertos. Todavia no evaluados
    statesOpenStates.clear();
    statesOpenPotencial.clear();

    //AllStates
    statesAllStates.clear();
    statesAllPotencial.clear();

    //Matriz de estados solucion
    statesSolutionStates.clear();
    statesSolutionPotencial.clear();

    return 1;
}

int AStar::gCost(double &costOut, std::vector<double> nodeI, std::vector<double> nodeJ)
{
    costOut=0.0;
    return 0;
}

int AStar::hCost(double &costOut, std::vector<double> nodeI, std::vector<double> nodeJ)
{
    costOut=0.0;
    return 0;
}

int AStar::searchInGraph(bool& pathFound)
{
    pathFound=false;

    //Clear previous search
    if(!clearSearch())
        return 0;

    //Usefull variables
    std::vector<unsigned int> secuencia(2);
    //Parent variables
    unsigned int parentId=0;
    vector<double> parentPotencial(3);
    //Child varianles
    unsigned int childId=0;
    vector<double> childPotencial(3);
    //Childs
    vector<unsigned int> childStatesIds;
    //Nodes for potencial
    vector<double> node1;
    vector<double> node2;

    //Start the search.
    //Put the init state in the list of open states
    statesOpenStates.push_back(nodeInitId);
    //Calculate potencials
    //g
    parentPotencial[1]=0.0; //g=0
    //h
    if(!GraphToSearch->findNode(node1,nodeFinId))
        return 0;
    if(!GraphToSearch->findNode(node2,nodeInitId))
        return 0;
    if(!hCost(parentPotencial[2],node1,node2))
        return 0;
    //f
    parentPotencial[0]=parentPotencial[1]+parentPotencial[2];
    statesOpenPotencial.push_back(parentPotencial);

    //Insertamos to all states
    for(unsigned int i=0;i<statesOpenStates.size();i++)
    {
        statesAllStates.push_back(statesOpenStates[i]);
        statesAllPotencial.push_back(statesOpenPotencial[i]);
    }

    //Search loop
    //bool endLoop=false;

    //cout<<"aqui"<<endl;

    //while(!endLoop && (statesVisitedStates.size()>0 || statesOpenStates.size()>0))
    while(statesVisitedStates.size()>0 || statesOpenStates.size()>0)
    {
        //cout<<"checking open states"<<endl;
        //Check the openStatesLists
        for(unsigned int i=0;i<statesOpenStates.size();i++)
        {
            //cout<<i<<"; "<<statesOpenStates.size()<<endl;
            //Put in the list of visited States
            statesVisitedStates.push_back(statesOpenStates[i]);
            statesVisitedPotencial.push_back(statesOpenPotencial[i]);
            //cout<<"venga!"<<endl;

            //cout<<statesOpenStates[i]<<endl;
            //cout<<nodeFinId<<endl;

            //Check we achieve the goal
            if(statesOpenStates[i]==nodeFinId)
            {
                //endLoop=true;
                pathFound=true;
                return 1;
            }
            //cout<<"here!"<<endl;
        }
        //cout<<"open states checked!"<<endl;
        //Clear the list of open states
        statesOpenStates.clear();
        statesOpenPotencial.clear();

        ///// Expandimos el estado
        //cout<<"expanding state"<<endl;
        //Selection of the parentState in the visited states list
        unsigned int parentIVisitedStates=0;
        double minPotencial=9e99;
        for(unsigned int i=0;i<statesVisitedPotencial.size();i++)
        {
            if(statesVisitedPotencial[i][0]<minPotencial)
            {
                parentIVisitedStates=i;
                minPotencial=statesVisitedPotencial[parentIVisitedStates][0]; //f
            }
        }

        //Check minimun cost
        //cout<<"checking cost"<<endl;
        if(minPotencial>maxCost)
        {
            pathFound=false;
            return 1;
        }

        //if(statesVisitedPotencial[parentIVisitedStates][1]>maxCost)
        //    return 0;
        //Habria que hacer lazy-PRM y generar nuevos nodos en las zonas de muy alto potencial!!

        //Parent
        parentId=statesVisitedStates[parentIVisitedStates];
        parentPotencial=statesVisitedPotencial[parentIVisitedStates];

        //cout<<"Parent node="<<parentId<<endl;

        //Eliminamos el estado padre de la lista de visited states
        statesVisitedStates.erase(statesVisitedStates.begin()+parentIVisitedStates);
        statesVisitedPotencial.erase(statesVisitedPotencial.begin()+parentIVisitedStates);

        //Añadimos el estado padre a la lista de closed states
        statesClosedStates.push_back(parentId);
        statesClosedPotencial.push_back(parentPotencial);

        //cout<<parentIVisitedStates<<"; "<<parentId<<endl;
        //getchar();
        //GraphToSearch.findNode(parentState,parentId);

        //Buscamos vecinos (hijos) del estado padre -> Expandimos
        if(!GraphToSearch->findNeighbordsNodes(parentId,childStatesIds))
            return 0;

        //cout<<"Padre:"<<parentId<<endl;

        ///// Hacemos crecer a los hijos!
        for(unsigned int numChildI=0;numChildI<childStatesIds.size();numChildI++)
        {
            //cout<<"hola bucle!!!!! "<<childStatesIds.size()<<endl;

            childId=childStatesIds[numChildI];

            //cout<<"-Hijo="<<childStatesIds[numChildI]<<endl;

            //Comprobamos si el estado ya está visitado. Está en la lista de estados visitados
            bool alreadyVisited=false;
            unsigned int nodeIVisitedStates=0;
            for(unsigned int i=0;i<statesVisitedStates.size();i++)
            {
                if(statesVisitedStates[i]==childId)
                {
                    nodeIVisitedStates=i;
                    alreadyVisited=true;
                    //cout<<" -Estado visitado: "<<statesVisitedStates[i]<<endl;
                    break;
                }
            }

            //Comprobamos si el estado ya está en la lista de estados cerrados
            bool alreadyClosed=false;
            for(unsigned int i=0;i<statesClosedStates.size();i++)
            {
                if(statesClosedStates[i]==childStatesIds[numChildI])
                {
                    alreadyClosed=true;
                    //cout<<" -Estado cerrado: "<<statesClosedStates[i]<<endl;
                    break;
                }
            }

            //Calculamos el nuevo potencial

            //cout<<"   .Potencial"<<endl;

            //g
            if(!GraphToSearch->findNode(node1,parentId))
                return 0;
            if(!GraphToSearch->findNode(node2,childId))
                return 0;
            //cout<<"ei"<<endl;
            if(!gCost(childPotencial[1],node1,node2))
                return 0;
            childPotencial[1]+=parentPotencial[1];

            //cout<<"ei"<<endl;

            //h
            if(!GraphToSearch->findNode(node1,childId))
                return 0;
            if(!GraphToSearch->findNode(node2,nodeFinId))
                return 0;
            if(!hCost(childPotencial[2],node1,node2))
                return 0;

            //f
            childPotencial[0]=childPotencial[1]+childPotencial[2];

            //Si el estado no ha sido visitado nunca. Es nuevo
            if(!alreadyVisited && !alreadyClosed)
            {
                //cout<<"  estado nuevo"<<endl;

                //Añadimos a la lista de estados abiertos
                statesOpenStates.push_back(childId);
                statesOpenPotencial.push_back(childPotencial);

                //Añadimos a la lista de all states
                statesAllStates.push_back(childId);
                statesAllPotencial.push_back(childPotencial);

                //Añadimos la secuencia
                secuencia[0]=parentId;
                secuencia[1]=childId;
                secuenciamientoAcciones.push_back(secuencia);

                //cout<<"  yiee!!"<<endl;
                //cout<<"hola!!"<<endl;

            }
            else if(alreadyVisited)
            {
            //El estado ya habia sido visitado. Y está en la lista de visitados

                //cout<<"  estado ya visitado!!"<<endl;

                //Comparamos el potencial para alcanzar ese nodo
                if(childPotencial[1]<statesVisitedPotencial[nodeIVisitedStates][1])
                {
                    //Cambiamos el potencial en la lista de visitados
                    statesVisitedPotencial[nodeIVisitedStates]=childPotencial;

                    //Cambiamos el potencial en la lista de all states
                    for(unsigned int i=0;i<statesAllStates.size();i++)
                    {
                        if(statesAllStates[i]==childId)
                        {
                            statesAllPotencial[i]=childPotencial;
                            break;
                        }
                    }

                    //Cambiamos el secuenciamiento
                    for(unsigned int i=0;i<secuenciamientoAcciones.size();i++)
                    {
                        if(secuenciamientoAcciones[i][1]==childId)
                        {
                            secuenciamientoAcciones[i][0]=parentId;
                        }
                    }

                }

            }
            else
            {
            //El estado está en la lista de cerrados. No pasa nada
            }
            //cout<<"dime"<<endl;
            //cout<<"aqui"<<endl;
        }
        //cout<<"fin bucle"<<endl;
    }
    //cout<<"problema!"<<endl;

    pathFound=false;
    return 0;
}

int AStar::planCreation()
{

    //Init
    unsigned int idPadre=nodeFinId;
    unsigned int idHijo=nodeFinId;

    //statesSolutionStates.clear();
    //statesSolutionPotencial.clear();

    statesSolutionStates.push_back(nodeFinId);

    while(idPadre!=nodeInitId)
    {
        //Search parent of child
        for(unsigned int i=0;i<secuenciamientoAcciones.size();i++)
        {
            if(secuenciamientoAcciones[i][1]==idHijo)
            {
                idPadre=secuenciamientoAcciones[i][0];
                break;
            }
        }
        //Add parent to the list
        statesSolutionStates.push_back(idPadre);

        //Update for next loop
        idHijo=idPadre;
    }

    std::reverse(statesSolutionStates.begin(),statesSolutionStates.end());

    //Añadimos el potencial
    for(unsigned int i=0;i<statesSolutionStates.size();i++)
    {
        for(unsigned int j=0;j<statesAllStates.size();j++)
        {
            if(statesSolutionStates[i]==statesAllStates[j])
            {
                statesSolutionPotencial.push_back(statesAllPotencial[j]);
                break;
            }
        }
    }

    return 1;
}

int AStar::search(std::vector<double> nodeInitIn, std::vector<double> nodeFinIn, bool& pathFound)
{
    pathFound=false;

    //Set nodes init and fin
    nodeInit=nodeInitIn;
    nodeFin=nodeFinIn;

    //Add the nodes init and end
    if(!GraphToSearch->findNode(nodeInitId,nodeInit))
        return 0;
    if(!GraphToSearch->findNode(nodeFinId,nodeFin))
        return 0;

    //cout<<"searching in graph!"<<endl;

    //Search in the graph
    if(!searchInGraph(pathFound))
        return 0;

    //cout<<"creating plan!"<<endl;

    //Creation of the plan
    if(pathFound)
    {
        if(!planCreation())
            return 0;
    }

    //cout<<"plan created!"<<endl;

    //Solution
    vector<double> nodeAux;
    solutionNodes.clear();
    for(unsigned int i=0;i<statesSolutionStates.size();i++)
    {
        GraphToSearch->findNode(nodeAux,statesSolutionStates[i]);
        solutionNodes.push_back(nodeAux);
    }

    return 1;
}

int AStar::getSolution(std::vector< std::vector<double> > &solutionNodesOut)
{
    solutionNodesOut=solutionNodes;

    return 1;
}

int AStar::saveSolutionNodes(std::string nameNodesSol)
{
    ofstream myfile;

    myfile.open(nameNodesSol);

    /*for(unsigned int i=0;i<statesSolutionStates.size();i++)
    {
        //cout<<"-node: "<<statesSolutionStates[i]<<endl;
        myfile<<statesSolutionStates[i]<<endl;
    }
    */

    std::vector<double> nodeAux;

    for(unsigned int i=0;i<statesSolutionStates.size();i++)
    {

        GraphToSearch->findNode(nodeAux,statesSolutionStates[i]);

        for(unsigned int j=0;j<nodeAux.size();j++)
        {
            myfile<<nodeAux[j];
            if(j==nodeAux.size()-1)
                myfile<<endl;
            else
                myfile<<";";
        }

        //cout<<"-node: "<<statesSolutionStates[i]<<endl;
        //myfile<<simplifiedStatesSolution[i]<<endl;
    }

    myfile.close();

    return 1;

}

//////////////////////// AStarWithPotencialFieldMap /////////////////////////

AStarWithPotencialFieldMap::AStarWithPotencialFieldMap() : h_sobrecoste(H_OVERCOST) {
}

int AStarWithPotencialFieldMap::gCost(double &costOut, std::vector<double> nodeInitIn, std::vector<double> nodeFinIn)
{
    //cout<<"gcost"<<endl;

    return MyPotFieldMap->calculateDistPotMap(costOut,nodeInitIn,nodeFinIn,true,true);

    //return 1;
}

int AStarWithPotencialFieldMap::hCost(double &costOut, std::vector<double> nodeInitIn, std::vector<double> nodeFinIn)
{
    int ok=MyPotFieldMap->calculateDistPotMap(costOut,nodeInitIn,nodeFinIn,false,true);
    //int ok=MyPotFieldMap->calculateDistPotMap(costOut,nodeInitIn,nodeFinIn,true,true);

    costOut*=h_sobrecoste;

    return ok;
}

int AStarWithPotencialFieldMap::postCost(double &costOut, std::vector<double> nodeInitIn, std::vector<double> nodeFinIn)
{
    return MyPotFieldMap->calculateDistPotMap(costOut,nodeInitIn,nodeFinIn,true,false);

    //return 1;
}

int AStarWithPotencialFieldMap::setPotencialFieldMap(PotencialFieldMap* MyPotFieldMapIn)
{
    MyPotFieldMap=MyPotFieldMapIn;
    return 1;
}

int AStarWithPotencialFieldMap::postProcessSolution()
{
    //Init
    simplifiedStatesSolution.clear();

    //Previuos checks
    if(statesSolutionStates.size()<2)
        return 0;

    vector<double> costVector;
    double costI;

    costVector.push_back(0.0);

    vector<double> node1;
    unsigned int node1Id;
    vector<double> node2;
    unsigned int node2Id;

    node1Id=statesSolutionStates[0];
    if(!GraphToSearch->findNode(node1,node1Id))
        return 0;

    //Coste para alcanzar el estado I desde el estado I-1
    for(unsigned int i=1;i<statesSolutionStates.size();i++)
    {
        node2Id=statesSolutionStates[i];
        if(!GraphToSearch->findNode(node2,node2Id))
            return 0;

        if(!postCost(costI,node1,node2))
            return 0;

        costVector.push_back(costI);

        //Update for the next step
        node1=node2;

    }

    /*
    cout<<"cost vector="<<endl;
    for(unsigned int i=0;i<costVector.size();i++)
        cout<<costVector[i]<<"; ";
    cout<<endl;
    */

    //cout<<"aqui"<<endl;

    //simplified solution
    //vector<unsigned int> simplifiedSolution;

    //Ultimo nodo!
    node1Id=statesSolutionStates[statesSolutionStates.size()-1];
    if(!GraphToSearch->findNode(node1,node1Id))
        return 0;

    unsigned int lastNodeToSearch=statesSolutionStates.size()-1;

    simplifiedStatesSolution.push_back(node1Id);

    double simplifiedCost=0.0;
    double nonSimplifiedCost=0.0;

    while(node1Id!=statesSolutionStates[0])
    {
        //cout<<"lastNodeToSearch="<<lastNodeToSearch<<endl;
        for(unsigned int i=0;i<lastNodeToSearch;i++)
        {
            //Set node
            node2Id=statesSolutionStates[i];
            if(!GraphToSearch->findNode(node2,node2Id))
                return 0;

            //Coste simplificado
            if(!postCost(simplifiedCost,node1,node2))
                return 0;

            //Coste no simplificado
            nonSimplifiedCost=0.0;
            for(unsigned int j=i;j<=lastNodeToSearch;j++)
                nonSimplifiedCost+=costVector[j];

            //cout<<i<<endl;
            //cout<<"simplifiedCost="<<simplifiedCost<<endl;
            //cout<<"nonSimplifiedCost="<<nonSimplifiedCost<<endl;
            if(simplifiedCost<=nonSimplifiedCost)
            {
                lastNodeToSearch=i;
                node1=node2;
                node1Id=node2Id;
                simplifiedStatesSolution.push_back(node2Id);
                break;
            }

            //else
            //{
                /*
                for(unsigned int j=lastNodeToSearch-1;j>0;j--)
                {
                    simplifiedStatesSolution.push_back(statesSolutionStates[j]);
                }
                */
                //simplifiedStatesSolution.push_back(node2Id);

                //lastNodeToSearch=i;
                //node1=node2;
                //node1Id=node2Id;

                //node1Id=statesSolutionStates[0];

                //break;
            //}

        }
        //cout<<"simplifiedCost="<<simplifiedCost<<endl;
        //cout<<"nonSimplifiedCost="<<nonSimplifiedCost<<endl;

        if(simplifiedCost>nonSimplifiedCost)
        {
            simplifiedStatesSolution.push_back(node2Id);
            lastNodeToSearch--;
            node1=node2;
            node1Id=node2Id;
        }

        //Comprobamos que hemos alcanzado el nodo inicial
        //cout<<"node1Id="<<node1Id<<endl;
        //cout<<"statesSolutionStates[0]="<<statesSolutionStates[0]<<endl;
        /*
        if(node1Id==statesSolutionStates[0])
        {
            break;
        }
        */

    }

    //statesSolutionStates.clear();
    //statesSolutionPotencial.clear();

    //statesSolutionStates=simplifiedSolution;

    //std::reverse(statesSolutionStates.begin(),statesSolutionStates.end());

    std::reverse(simplifiedStatesSolution.begin(),simplifiedStatesSolution.end());

    return 1;
}

int AStarWithPotencialFieldMap::search(std::vector<double> nodeInitIn, std::vector<double> nodeFinIn, bool& pathFound)
{
    pathFound=false;

    //Discrete search
    if(!AStar::search(nodeInitIn,nodeFinIn,pathFound))
        return 0;

    if(!pathFound)
    {
        simplifiedStatesSolution.clear();
        return 1;
    }

    //Admisible solution. Already done in the A Star, but por si aca!
    if(statesSolutionPotencial[statesSolutionStates.size()-1][1]>maxCost)
    {
        statesSolutionStates.clear();
        statesSolutionPotencial.clear();
        return 0;
    }

    //cout<<"Postprocessing solution"<<endl;

    //Postprocess solution
    if(!postProcessSolution())
        return 0;

    //cout<<"solution postprocessed!"<<endl;

    //Solution override
    vector<double> nodeAux;
    solutionNodes.clear();
    for(unsigned int i=0;i<simplifiedStatesSolution.size();i++)
    {
        GraphToSearch->findNode(nodeAux,simplifiedStatesSolution[i]);
        solutionNodes.push_back(nodeAux);
    }

    return 1;
}

int AStarWithPotencialFieldMap::saveSolutionNodes(std::string nameNodesSol, std::string nameNodesSolSimplif)
{
    AStar::saveSolutionNodes(nameNodesSol);

    //Simplified solution nodes
    ofstream myfile;

    myfile.open(nameNodesSolSimplif);

    std::vector<double> nodeAux;

    for(unsigned int i=0;i<simplifiedStatesSolution.size();i++)
    {

        GraphToSearch->findNode(nodeAux,simplifiedStatesSolution[i]);

        for(unsigned int j=0;j<nodeAux.size();j++)
        {
            myfile<<nodeAux[j];
            if(j==nodeAux.size()-1)
                myfile<<endl;
            else
                myfile<<";";
        }

        //cout<<"-node: "<<statesSolutionStates[i]<<endl;
        //myfile<<simplifiedStatesSolution[i]<<endl;
    }

    myfile.close();

    return 1;

}


text:
package com.chiralBehaviors.groo;

import com.hellblazer.slp.InvalidSyntaxException;

/**
 * @author hhildebrand
 *
 */
public interface ChakaalMBean {

    String[] getDiscovered();

    String[] getQueries();

    void listenFor(String query) throws InvalidSyntaxException;

    void listenForService(String service) throws InvalidSyntaxException;

    void listenForService(String service, String q)
                                                   throws InvalidSyntaxException;

    void removeQuery(String query) throws InvalidSyntaxException;

    void removeServiceNameQuery(String serviceName)
                                                   throws InvalidSyntaxException;

    void removeServiceNameQuery(String serviceName, String query)
                                                                 throws InvalidSyntaxException;

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Öst. bot. Z. 55: 78 (1905)

#### Original name
null

### Remarks
null


text:
package org.jetbrains.idea.maven.dom;

import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.codeInsight.documentation.DocumentationManager;
import com.intellij.codeInsight.highlighting.HighlightUsagesHandler;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.rename.PsiElementRenameHandler;
import com.intellij.refactoring.rename.RenameHandler;
import com.intellij.refactoring.rename.RenameHandlerRegistry;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.testFramework.MapDataContext;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.testFramework.fixtures.CodeInsightTestUtil;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.usages.UsageTarget;
import com.intellij.usages.UsageTargetUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.MavenImportingTestCase;
import org.jetbrains.idea.maven.dom.inspections.MavenModelInspection;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.jetbrains.idea.maven.dom.references.MavenPsiElementWrapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class MavenDomTestCase extends MavenImportingTestCase {
  protected CodeInsightTestFixture myFixture;
  private final Map<VirtualFile, Long> myConfigTimestamps = new THashMap<VirtualFile, Long>();
  private boolean myOriginalAutoCompletion;

  @Override
  protected void setUpFixtures() throws Exception {
    myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName()).getFixture();

    myFixture = IdeaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(myTestFixture);
    myFixture.setUp();
    ((CodeInsightTestFixtureImpl)myFixture).canChangeDocumentDuringHighlighting(true); // org.jetbrains.idea.maven.utils.MavenRehighlighter

    myFixture.enableInspections(MavenModelInspection.class);

    myOriginalAutoCompletion = CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION;
    CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
  }

  @Override
  protected void tearDownFixtures() throws Exception {
    CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = myOriginalAutoCompletion;
    myFixture.tearDown();
    myFixture = null;
    myConfigTimestamps.clear();
  }

  protected PsiFile findPsiFile(VirtualFile f) {
    return PsiManager.getInstance(myProject).findFile(f);
  }

  protected void configTest(VirtualFile f) throws IOException {
    if (Comparing.equal(myConfigTimestamps.get(f), f.getTimeStamp())) return;
    myFixture.configureFromExistingVirtualFile(f);
    myConfigTimestamps.put(f, f.getTimeStamp());
  }

  protected void type(VirtualFile f, char c) throws IOException {
    configTest(f);
    myFixture.type(c);
  }

  protected PsiReference getReferenceAtCaret(VirtualFile f) throws IOException {
    configTest(f);
    return findPsiFile(f).findReferenceAt(getEditorOffset(f));
  }

  protected PsiReference getReferenceAt(VirtualFile f, int offset) throws IOException {
    configTest(f);
    return findPsiFile(f).findReferenceAt(offset);
  }

  protected PsiElement getElementAtCaret(VirtualFile f) throws IOException {
    configTest(f);
    return findPsiFile(f).findElementAt(getEditorOffset(f));
  }

  protected Editor getEditor() throws IOException {
    return getEditor(myProjectPom);
  }

  protected Editor getEditor(VirtualFile f) throws IOException {
    configTest(f);
    return myFixture.getEditor();
  }

  protected int getEditorOffset() throws IOException {
    return getEditorOffset(myProjectPom);
  }

  protected int getEditorOffset(VirtualFile f) throws IOException {
    return getEditor(f).getCaretModel().getOffset();
  }

  protected PsiFile getTestPsiFile() throws IOException {
    return getTestPsiFile(myProjectPom);
  }

  private PsiFile getTestPsiFile(VirtualFile f) throws IOException {
    configTest(f);
    return myFixture.getFile();
  }

  protected XmlTag findTag(String path) {
    return findTag(myProjectPom, path);
  }

  protected XmlTag findTag(VirtualFile file, String path) {
    return findTag(file, path, MavenDomProjectModel.class);
  }

  protected XmlTag findTag(VirtualFile file, String path, Class<? extends MavenDomElement> clazz) {
    MavenDomElement model = MavenDomUtil.getMavenDomModel(myProject, file, clazz);
    assertNotNull("Model is not of " + clazz, model);
    return MavenDomUtil.findTag(model, path);
  }

  protected void assertNoReferences(VirtualFile file, Class refClass) throws IOException {
    PsiReference ref = getReferenceAtCaret(file);
    if (ref == null) return;
    PsiReference[] refs = ref instanceof PsiMultiReference ? ((PsiMultiReference)ref).getReferences() : new PsiReference[]{ref};
    for (PsiReference each : refs) {
      assertFalse(each.toString(), refClass.isInstance(each));
    }
  }

  protected void assertUnresolved(VirtualFile file) throws IOException {
    PsiReference ref = getReferenceAtCaret(file);
    assertNotNull(ref);
    assertNull(ref.resolve());
  }

  protected void assertUnresolved(VirtualFile file, String expectedText) throws IOException {
    PsiReference ref = getReferenceAtCaret(file);
    assertNotNull(ref);
    assertNull(ref.resolve());
    assertEquals(expectedText, ref.getCanonicalText());
  }

  protected void assertResolved(VirtualFile file, @NotNull PsiElement expected) throws IOException {
    doAssertResolved(file, expected);
  }

  @Nullable
  protected PsiReference getReference(VirtualFile file, @NotNull String referenceText) throws IOException {
    String text = VfsUtilCore.loadText(file);
    int index = text.indexOf(referenceText);
    assert index >= 0;

    assert text.indexOf(referenceText, index + referenceText.length()) == -1 : "Reference text '" + referenceText + "' occurs more than one times";

    return getReferenceAt(file, index);
  }

  @Nullable
  protected PsiReference getReference(VirtualFile file, @NotNull String referenceText, int index) throws IOException {
    String text = VfsUtilCore.loadText(file);
    int k = -1;

    do {
      k = text.indexOf(referenceText, k + 1);
      assert k >= 0 : index;
    }
    while (--index >= 0);

    return getReferenceAt(file, k);
  }

  @Nullable
  protected PsiElement resolveReference(VirtualFile file, @NotNull String referenceText) throws IOException {
    PsiReference ref = getReference(file, referenceText);
    assertNotNull(ref);

    PsiElement resolved = ref.resolve();
    if (resolved instanceof MavenPsiElementWrapper) {
      resolved = ((MavenPsiElementWrapper)resolved).getWrappee();
    }

    return resolved;
  }

  protected void assertResolved(VirtualFile file, @NotNull PsiElement expected, String expectedText) throws IOException {
    PsiReference ref = doAssertResolved(file, expected);
    assertEquals(expectedText, ref.getCanonicalText());
  }

  private PsiReference doAssertResolved(VirtualFile file, PsiElement expected) throws IOException {
    assertNotNull("expected reference is null", expected);

    PsiReference ref = getReferenceAtCaret(file);
    assertNotNull(ref);
    PsiElement resolved = ref.resolve();
    if (resolved instanceof MavenPsiElementWrapper) {
      resolved = ((MavenPsiElementWrapper)resolved).getWrappee();
    }
    assertEquals(expected, resolved);
    return ref;
  }

  protected void assertCompletionVariants(VirtualFile f, String... expected) throws IOException {
    List<String> actual = getCompletionVariants(f);
    assertUnorderedElementsAreEqual(actual, expected);
  }

  protected void assertCompletionVariantsInclude(VirtualFile f, String... expected) throws IOException {
    assertContain(getCompletionVariants(f), expected);
  }

  protected void assertCompletionVariantsDoNotInclude(VirtualFile f, String... expected) throws IOException {
    assertDoNotContain(getCompletionVariants(f), expected);
  }

  protected List<String> getCompletionVariants(VirtualFile f) throws IOException {
    configTest(f);
    LookupElement[] variants = myFixture.completeBasic();

    List<String> result = new ArrayList<String>();
    for (LookupElement each : variants) {
      result.add(each.getLookupString());
    }
    return result;
  }

  protected void assertDocumentation(String expectedText) throws IOException {
    PsiElement originalElement = getElementAtCaret(myProjectPom);
    PsiElement targetElement = DocumentationManager.getInstance(myProject)
      .findTargetElement(getEditor(), getTestPsiFile(), originalElement);

    DocumentationProvider provider = DocumentationManager.getProviderFromElement(targetElement);
    assertEquals(expectedText, provider.generateDoc(targetElement, originalElement));

    // should work for lookup as well as for tags
    PsiElement lookupElement = provider.getDocumentationElementForLookupItem(PsiManager.getInstance(myProject),
                                                                             originalElement.getText(),
                                                                             originalElement);
    assertSame(targetElement, lookupElement);
  }

  protected void checkHighlighting() throws IOException {
    checkHighlighting(myProjectPom);
  }

  protected void checkHighlighting(VirtualFile f) throws IOException {
    checkHighlighting(f, true, true, true);
  }

  protected void checkHighlighting(VirtualFile f, boolean checkWarnings, boolean checkInfos, boolean checkWeakWarnings) throws IOException {
    configTest(myProjectPom);
    try {
      myFixture.testHighlighting(checkWarnings, checkInfos, checkWeakWarnings, f);
    }
    catch (Throwable throwable) {
      throw new RuntimeException(throwable);
    }
  }

  protected IntentionAction getIntentionAtCaret(String intentionName) throws IOException {
    return getIntentionAtCaret(myProjectPom, intentionName);
  }

  protected IntentionAction getIntentionAtCaret(VirtualFile pomFile, String intentionName) throws IOException {
    configTest(pomFile);
    try {
      List<IntentionAction> intentions = myFixture.getAvailableIntentions();

      return CodeInsightTestUtil.findIntentionByText(intentions, intentionName);
    }
    catch (Throwable throwable) {
      throw new RuntimeException(throwable);
    }
  }

  protected void assertRenameResult(String value, String expectedXml) throws Exception {
    doRename(myProjectPom, value);
    assertEquals(createPomXml(expectedXml), getTestPsiFile(myProjectPom).getText());
  }

  protected void doRename(final VirtualFile f, String value) throws IOException {
    final MapDataContext context = createRenameDataContext(f, value);
    final RenameHandler renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(context);
    assertNotNull(renameHandler);

    invokeRename(context, renameHandler);
  }

  protected void assertCannotRename() throws Exception {
    MapDataContext context = createRenameDataContext(myProjectPom, "new name");
    RenameHandler handler = RenameHandlerRegistry.getInstance().getRenameHandler(context);
    if (handler == null) return;
    try {
      invokeRename(context, handler);
    }
    catch (CommonRefactoringUtil.RefactoringErrorHintException e) {
      if (!e.getMessage().startsWith("Cannot perform refactoring.")) {
        throw e;
      }
    }
  }

  private void invokeRename(final MapDataContext context, final RenameHandler renameHandler) {
    renameHandler.invoke(myProject, PsiElement.EMPTY_ARRAY, context);
  }

  private MapDataContext createDataContext(VirtualFile f) throws IOException {
    MapDataContext context = new MapDataContext();
    context.put(PlatformDataKeys.EDITOR, getEditor(f));
    context.put(LangDataKeys.PSI_FILE, getTestPsiFile(f));
    context.put(LangDataKeys.PSI_ELEMENT, TargetElementUtil.findTargetElement(getEditor(f),
                                                                              TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED
                                                                              | TargetElementUtilBase.ELEMENT_NAME_ACCEPTED));
    return context;
  }

  private MapDataContext createRenameDataContext(VirtualFile f, String value) throws IOException {
    MapDataContext context = createDataContext(f);
    context.put(PsiElementRenameHandler.DEFAULT_NAME, value);
    return context;
  }

  protected void assertSearchResults(VirtualFile file, PsiElement... expected) throws IOException {
    assertUnorderedElementsAreEqual(search(file), expected);
  }

  protected void assertSearchResultsInclude(VirtualFile file, PsiElement... expected) throws IOException {
    assertContain(search(file), expected);
  }

  protected List<PsiElement> search(VirtualFile file) throws IOException {
    final MapDataContext context = createDataContext(file);
    UsageTarget[] targets = UsageTargetUtil.findUsageTargets(new DataProvider() {
      @Override
      public Object getData(@NonNls String dataId) {
        return context.getData(dataId);
      }
    });
    PsiElement target = ((PsiElement2UsageTargetAdapter)targets[0]).getElement();
    List<PsiReference> result = new ArrayList<PsiReference>(ReferencesSearch.search(target).findAll());
    return ContainerUtil.map(result, new Function<PsiReference, PsiElement>() {
      @Override
      public PsiElement fun(PsiReference psiReference) {
        return psiReference.getElement();
      }
    });
  }

  protected void assertHighlighted(VirtualFile file, HighlightInfo... expected) throws IOException {
    Editor editor = getEditor(file);
    HighlightUsagesHandler.invoke(myProject, editor, getTestPsiFile(file));

    RangeHighlighter[] highlighters = editor.getMarkupModel().getAllHighlighters();
    List<HighlightInfo> actual = new ArrayList<HighlightInfo>();
    for (RangeHighlighter each : highlighters) {
      if (!each.isValid()) continue;
      int offset = each.getStartOffset();
      PsiElement element = getTestPsiFile(file).findElementAt(offset);
      element = PsiTreeUtil.getParentOfType(element, XmlTag.class);
      String text = editor.getDocument().getText().substring(offset, each.getEndOffset());
      actual.add(new HighlightInfo(element, text));
    }

    assertUnorderedElementsAreEqual(actual, expected);
  }

  protected static class HighlightInfo {
    public PsiElement element;
    public String text;

    public HighlightInfo(PsiElement element, String text) {
      this.element = element;
      this.text = text;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      HighlightInfo that = (HighlightInfo)o;

      if (element != null ? !element.equals(that.element) : that.element != null) return false;
      if (text != null ? !text.equals(that.text) : that.text != null) return false;

      return true;
    }

    @Override
    public int hashCode() {
      int result = element != null ? element.hashCode() : 0;
      result = 31 * result + (text != null ? text.hashCode() : 0);
      return result;
    }
  }
}


text:
<?php require_once('includes/config.php'); ?>
<?php require_once('includes/db-connect.php'); ?>
<?php global $TITLE, $SITE_ROOT, $conn; ?>
<?php $TITLE = "View All Subjects"; ?>
<?php
  $deleted = false;
  if( isset($_GET["delete"]) ) {
    $sql = "CALL remove_subject( :id )";
    $stmt = $conn->prepare( $sql );
    $stmt->bindParam(':id', $_GET["delete"], PDO::PARAM_INT );
    if( $stmt->execute() )
      $deleted = true;
  }
  $subjects = $conn->query("SELECT * FROM SUBJECTS");
  if( $subjects ) {
    $error = false;
  }
  else {
    $error = true;
  }
?>
<!DOCTYPE html>
<html>
<?php require_once('includes/_head.php'); ?>
    <body class="skin-black">
      <!-- DATA TABLES -->
      <link href="<?= $SITE_ROOT ?>../bower_components/AdminLTE/plugins/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
        <div class='wrapper'>
<?php require_once('includes/_header.php'); ?>
<?php require_once('includes/subject/_list.php'); ?>
<?php require_once('includes/_footer.php'); ?>
        </div>
        <!-- DATA TABES SCRIPT -->
        <script src="<?= $SITE_ROOT ?>../bower_components/AdminLTE/plugins/datatables/jquery.dataTables.js" type="text/javascript"></script>
        <script src="<?= $SITE_ROOT ?>../bower_components/AdminLTE/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
        <script type="text/javascript">
          $("#subjects-table").dataTable();
          $('[data-title]').tooltip();
        </script>
    </body>
</html>
<?php require_once('includes/db-close.php'); ?>


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

    angular
        .module('app')
        .controller('RegistrationController', function ($http, $rootScope, $state) {
            var vm = this;

            angular.extend(vm, {
                user: {
                    username: '',
                    password: '',
                    password2: ''
                },
                register: register,
                errorMessage: false
            })

            function register(user) {
                console.log(vm.user);
                $rootScope.errorregister = false;
                //todo verify passwors are the same and notify user
                if (vm.user.password == vm.user.password2) {
                    $http.post('/registration', vm.user)
                        .success(function (user) {
                            $rootScope.currentUser = user;
                            console.log(user);
                            $state.go('profile');

                        });
                }
                else {
                    vm.errorMessage = true;
                    vm.user = { username: '', password: '', password2: '' }
                }

            };
        });
})();


text:
export interface ValueType {
  [index: string]:
    | null
    | boolean
    | string
    | number
    | ValueType
    | Array<string | number | ValueType>;
}

// INTERNAL ONLY. This function is not exposed to external callers.
export function googleProtobufValueFromObject(
  object: ValueType,
  create: (result: object) => object
): object | null | ValueType | protobuf.common.IValue {
  if (object === null) {
    return create({
      kind: 'nullValue',
      nullValue: 0,
    });
  }
  if (typeof object === 'boolean') {
    return create({
      kind: 'boolValue',
      boolValue: object,
    });
  }
  if (typeof object === 'number') {
    return create({
      kind: 'numberValue',
      numberValue: object,
    });
  }
  if (typeof object === 'string') {
    return create({
      kind: 'stringValue',
      stringValue: object,
    });
  }
  if (Array.isArray(object)) {
    const array = object.map(element => {
      return googleProtobufValueFromObject(element, create);
    });
    return create({
      kind: 'listValue',
      listValue: {
        values: array,
      },
    });
  }
  if (typeof object === 'object') {
    // tslint:disable-next-line no-explicit-any
    const fields: any = {},
      names: string[] = Object.keys(object);
    for (let i = 0; i < names.length; ++i) {
      const fieldName = names[i];
      fields[fieldName] = googleProtobufValueFromObject(
        object[fieldName] as ValueType,
        create
      );
    }
    return create({
      kind: 'structValue',
      structValue: {
        fields: fields,
      },
    });
  }
  return null;
}

// INTERNAL ONLY. This function not exposed to external callers.
// recursive google.protobuf.Value to plain JS object
export function googleProtobufValueToObject(
  message: protobuf.common.IValue
): object | null | undefined | boolean | number | string {
  if (message.kind === 'boolValue') {
    return message.boolValue;
  }
  if (message.kind === 'nullValue') {
    return null;
  }
  if (message.kind === 'numberValue') {
    return message.numberValue;
  }
  if (message.kind === 'stringValue') {
    return message.stringValue;
  }
  if (message.kind === 'listValue') {
    return message.listValue?.values?.map(googleProtobufValueToObject);
  }
  if (message.kind === 'structValue') {
    if (!message.structValue?.fields) {
      return {};
    }
    const names = Object.keys(message.structValue.fields),
      // tslint:disable-next-line no-explicit-any
      struct: any = {};
    for (let i = 0; i < names.length; ++i) {
      struct[names[i]] = googleProtobufValueToObject(
        message.structValue['fields'][names[i]]
      );
    }
    return struct;
  }
  return undefined;
}


text:
'use strict';

import angular from "angular";
import uirouter from "angular-ui-router";
import ngAria from "angular-aria";

import RetailerController from "./controllers/RetailerController";
import RetailerCreateController from "./controllers/RetailerCreateController";
import RetailerConfirmationController from "./controllers/RetailerConfirmationController";

import RetailerCreateComponent from './components/retailerCreate/RetailerCreateComponent';
import RetailerTotalBalancesComponent from './components/retailerTotalBalances/RetailerTotalBalancesComponent';
import RetailerBalancesComponent from './components/retailerBalances/RetailerBalancesComponent';
import RetailerAcceptedComponent from './components/retailerAccepted/RetailerAcceptedComponent';

import EthereumRetailersService from "../ethereum/services/EthereumRetailersService";

const retailer = 'app.retailer';

angular.module(retailer, [
    uirouter,
    ngAria,
])
    .component(RetailerCreateComponent.name, RetailerCreateComponent.config)
    .component(RetailerBalancesComponent.name, RetailerBalancesComponent.config)
    .component(RetailerTotalBalancesComponent.name, RetailerTotalBalancesComponent.config)
    .component(RetailerAcceptedComponent.name, RetailerAcceptedComponent.config)

    .factory('EthereumRetailersService', EthereumRetailersService)

    .config(['$stateProvider', '$urlRouterProvider', '$mdToastProvider', function($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.when('retailer', 'retailer.create');
        $stateProvider
            .state({
                name: retailer,
                url: '',
                template: require('./templates/RetailerTemplate.html'),
                controller: ('RetailerController', RetailerController),
                redirect: `${retailer}.confirmation`
            })
            .state({
                name: `${retailer}.confirmation`,
                url: 'retailer',
                template: require('./templates/RetailerConfirmationTemplate.html'),
                controller: ('RetailerConfirmationController', RetailerConfirmationController),
                data: {
                    permissions: {
                        only: ['INSURANCE'],
                        redirectTo: 'app.home'
                    }
                }
            })
            .state({
                name: `${retailer}.create`,
                url: 'retailer/create',
                template: require('./templates/RetailerCreateTemplate.html'),
                controller: ('RetailerCreateController', RetailerCreateController),
                data: {
                    permissions: {
                        only: ['UNDEFINED'],
                        redirectTo: 'app.home'
                    }
                }
            })
    }]);

export default retailer


text:
from django import http
from django.urls import reverse

def user_is_not_logged_in(func):
    def decorated(*args, **kwargs):
        if args[0].user.is_authenticated:
            url = reverse('studygroups_login_redirect')
            return http.HttpResponseRedirect(url)
        return func(*args, **kwargs)
    return decorated


text:
/**
 * After successful addition of a new textbooks document, go to List page.
 * See: https://github.com/aldeed/meteor-autoform#callbackshooks
 */
AutoForm.hooks({
  AddTextbooksForm: {
    /**
     * After successful form submission, go to the Listtextbooks page.
     * @param formType The form.
     * @param result The result of form submission.
     */
    onSuccess: function(formType, result) {
      Router.go('Textbooks');
    }
  }
});


text:
"""Tests for methods in the interaction registry."""

from __future__ import annotations

import json
import os

from core import feconf
from core import schema_utils
from core import utils
from core.domain import exp_services
from core.domain import interaction_registry
from core.tests import test_utils
from extensions.interactions import base

from typing import Any, Dict, Final

EXPECTED_TERMINAL_INTERACTIONS_COUNT: Final = 1

class InteractionDependencyTests(test_utils.GenericTestBase):
    """Tests for the calculation of dependencies for interactions."""

    def setUp(self) -> None:
        super().setUp()

        # Register and login as an editor.
        self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)
        self.login(self.EDITOR_EMAIL)

    def test_deduplication_of_dependency_ids(self) -> None:
        self.assertItemsEqual(
            interaction_registry.Registry.get_deduplicated_dependency_ids(
                ['CodeRepl']),
            ['skulpt', 'codemirror'])

        self.assertItemsEqual(
            interaction_registry.Registry.get_deduplicated_dependency_ids(
                ['CodeRepl', 'CodeRepl', 'CodeRepl']),
            ['skulpt', 'codemirror'])

        self.assertItemsEqual(
            interaction_registry.Registry.get_deduplicated_dependency_ids(
                ['CodeRepl', 'AlgebraicExpressionInput']),
            ['skulpt', 'codemirror', 'guppy', 'nerdamer'])

    def test_no_dependencies_in_non_exploration_pages(self) -> None:
        response = self.get_html_response(feconf.LIBRARY_INDEX_URL)
        response.mustcontain(no=['dependency_html.html'])

    def test_dependencies_loaded_in_exploration_editor(self) -> None:

        exp_services.load_demo('0')

        # Ensure that dependencies are added in the exploration editor page.
        response = self.get_html_response('/create/0')
        response.mustcontain('dependency_html.html')

        self.logout()

class InteractionRegistryUnitTests(test_utils.GenericTestBase):
    """Test for the interaction registry."""

    def test_interaction_registry(self) -> None:
        """Do some sanity checks on the interaction registry."""
        self.assertEqual(
            {
                type(i).__name__
                for i in interaction_registry.Registry.get_all_interactions()
            },
            set(interaction_registry.Registry.get_all_interaction_ids()))

        with self.swap(interaction_registry.Registry, '_interactions', {}):
            self.assertEqual(
                {
                    type(i).__name__
                    for i in
                    interaction_registry.Registry.get_all_interactions()
                },
                set(interaction_registry.Registry.get_all_interaction_ids()))

    def test_get_all_specs(self) -> None:
        """Test the get_all_specs() method."""

        specs_dict = interaction_registry.Registry.get_all_specs()
        self.assertEqual(
            set(specs_dict.keys()),
            set(interaction_registry.Registry.get_all_interaction_ids()))

        terminal_interactions_count = 0
        for item in specs_dict.values():
            self.assertIn(item['display_mode'], base.ALLOWED_DISPLAY_MODES)
            self.assertTrue(isinstance(item['is_terminal'], bool))
            if item['is_terminal']:
                terminal_interactions_count += 1

        self.assertEqual(
            terminal_interactions_count, EXPECTED_TERMINAL_INTERACTIONS_COUNT)

    def test_interaction_specs_json_sync_all_specs(self) -> None:
        """Test to ensure that the interaction_specs.json file is upto date
        with additions in the individual interaction files.
        """
        all_specs = interaction_registry.Registry.get_all_specs()

        spec_file = os.path.join(
            'extensions', 'interactions', 'interaction_specs.json')
        with utils.open_file(spec_file, 'r') as f:
            specs_from_json = json.loads(f.read())

        self.assertDictEqual(all_specs, specs_from_json)

    def test_interaction_specs_customization_arg_specs_names_are_valid(
        self
    ) -> None:
        """Test to ensure that all customization argument names in
        interaction specs only include alphabetic letters and are
        lowerCamelCase. This is because these properties are involved in the
        generation of content_ids for customization arguments.
        """
        all_specs = interaction_registry.Registry.get_all_specs()
        ca_names_in_schema = []

        # Here we use type Any because values in schema dictionary can
        # be of type str, int, List, Dict and other types too. So to make
        # it generalized for every type of value we used Any here.
        def traverse_schema_to_find_names(schema: Dict[str, Any]) -> None:
            """Recursively traverses the schema to find all name fields.
            Recursion is required because names can be nested within
            'type: dict' inside a schema.

            Args:
                schema: dict. The schema to traverse.
            """
            if 'name' in schema:
                ca_names_in_schema.append(schema['name'])

            schema_type = schema['type']
            if schema_type == schema_utils.SCHEMA_TYPE_LIST:
                traverse_schema_to_find_names(schema['items'])
            elif schema_type == schema_utils.SCHEMA_TYPE_DICT:
                for schema_property in schema['properties']:
                    ca_names_in_schema.append(schema_property['name'])
                    traverse_schema_to_find_names(schema_property['schema'])

        for interaction_id in all_specs:
            for ca_spec in all_specs[interaction_id]['customization_arg_specs']:
                ca_names_in_schema.append(ca_spec['name'])
                traverse_schema_to_find_names(ca_spec['schema'])
        for name in ca_names_in_schema:
            self.assertTrue(name.isalpha())
            self.assertTrue(name[0].islower())

    def test_interaction_specs_customization_arg_default_values_are_valid(
        self
    ) -> None:
        """Test to ensure that all customization argument default values
        that contain content_ids are properly set to None.
        """
        all_specs = interaction_registry.Registry.get_all_specs()

        # Here we use type Any because values in schema dictionary can
        # be of type str, int, List, Dict and other types too. So to make
        # it generalized for every type of value we used Any here.
        def traverse_schema_to_find_and_validate_subtitled_content(
            value: Any, schema: Dict[str, Any]
        ) -> None:
            """Recursively traverse the schema to find SubtitledHtml or
            SubtitledUnicode contained or nested in value.

            Args:
                value: *. The value of the customization argument.
                schema: dict. The customization argument schema.
            """
            is_subtitled_html_spec = (
                schema['type'] == schema_utils.SCHEMA_TYPE_CUSTOM and
                schema['obj_type'] ==
                schema_utils.SCHEMA_OBJ_TYPE_SUBTITLED_HTML)
            is_subtitled_unicode_spec = (
                schema['type'] == schema_utils.SCHEMA_TYPE_CUSTOM and
                schema['obj_type'] ==
                schema_utils.SCHEMA_OBJ_TYPE_SUBTITLED_UNICODE)

            if is_subtitled_html_spec or is_subtitled_unicode_spec:
                self.assertIsNone(value['content_id'])
            elif schema['type'] == schema_utils.SCHEMA_TYPE_LIST:
                for x in value:
                    traverse_schema_to_find_and_validate_subtitled_content(
                        x, schema['items'])
            elif schema['type'] == schema_utils.SCHEMA_TYPE_DICT:
                for schema_property in schema['properties']:
                    traverse_schema_to_find_and_validate_subtitled_content(
                        x[schema_property.name],
                        schema_property['schema']
                    )

        for interaction_id in all_specs:
            for ca_spec in all_specs[interaction_id]['customization_arg_specs']:
                traverse_schema_to_find_and_validate_subtitled_content(
                    ca_spec['default_value'], ca_spec['schema'])

    def test_get_all_specs_for_state_schema_version_for_unsaved_version(
        self
    ) -> None:
        with self.assertRaisesRegex(
            IOError, 'No specs JSON file found for state schema'
        ):
            (
                interaction_registry.Registry
                .get_all_specs_for_state_schema_version(10)
            )

    def test_get_interaction_by_id_raises_error_for_none_interaction_id(
        self
    ) -> None:
        with self.assertRaisesRegex(
            Exception, 'No interaction exists for the None interaction_id.'
        ):
            interaction_registry.Registry.get_interaction_by_id(None)


text:
/*
 * Author:  Donna Converse, MIT X Consortium
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/Xmu/StdCmap.h>

#define lowbit(x) ((x) & (~(x) + 1))

/*
 * Prototypes
 */
/* argument restrictions */
static Status valid_args(XVisualInfo*, unsigned long, unsigned long,
			 unsigned long, Atom);

/*
 * To create any one standard colormap, use XmuStandardColormap().
 *
 * Create a standard colormap for the given screen, visualid, and visual
 * depth, with the given red, green, and blue maximum values, with the
 * given standard property name.  Return a pointer to an XStandardColormap
 * structure which describes the newly created colormap, upon success.
 * Upon failure, return NULL.
 *
 * XmuStandardColormap() calls XmuCreateColormap() to create the map.
 *
 * Resources created by this function are not made permanent; that is the
 * caller's responsibility.
 */

XStandardColormap *
XmuStandardColormap(Display *dpy, int screen, VisualID visualid,
		    unsigned int depth, Atom property, Colormap cmap,
		    unsigned long red_max, unsigned long green_max,
		    unsigned long blue_max)
     /*
      * dpy				- specifies X server connection
      * screen				- specifies display screen
      * visualid			- identifies the visual type
      * depth				- identifies the visual type
      * property			- a standard colormap property
      * cmap				- specifies colormap ID or None
      * red_max, green_max, blue_max	- allocations
      */
{
    XStandardColormap	*stdcmap;
    Status		status;
    XVisualInfo		vinfo_template, *vinfo;
    long		vinfo_mask;
    int			n;

    /* Match the required visual information to an actual visual */
    vinfo_template.visualid = visualid;
    vinfo_template.screen = screen;
    vinfo_template.depth = depth;
    vinfo_mask = VisualIDMask | VisualScreenMask | VisualDepthMask;
    if ((vinfo = XGetVisualInfo(dpy, vinfo_mask, &vinfo_template, &n)) == NULL)
	return NULL;

    /* Check the validity of the combination of visual characteristics,
     * allocation, and colormap property.  Create an XStandardColormap
     * structure.
     */

    if (! valid_args(vinfo, red_max, green_max, blue_max, property)
	|| ((stdcmap = XAllocStandardColormap()) == NULL)) {
	XFree((char *) vinfo);
	return NULL;
    }

    /* Fill in the XStandardColormap structure */

    if (cmap == DefaultColormap(dpy, screen)) {
	/* Allocating out of the default map, cannot use XFreeColormap() */
	Window win = XCreateWindow(dpy, RootWindow(dpy, screen), 1, 1, 1, 1,
				   0, 0, InputOnly, vinfo->visual,
				   (unsigned long) 0,
				   (XSetWindowAttributes *)NULL);
	stdcmap->killid  = (XID) XCreatePixmap(dpy, win, 1, 1, depth);
	XDestroyWindow(dpy, win);
	stdcmap->colormap = cmap;
    } else {
	stdcmap->killid = ReleaseByFreeingColormap;
	stdcmap->colormap = XCreateColormap(dpy, RootWindow(dpy, screen),
					    vinfo->visual, AllocNone);
    }
    stdcmap->red_max = red_max;
    stdcmap->green_max = green_max;
    stdcmap->blue_max = blue_max;
    if (property == XA_RGB_GRAY_MAP)
	stdcmap->red_mult = stdcmap->green_mult = stdcmap->blue_mult = 1;
    else if (vinfo->class == TrueColor || vinfo->class == DirectColor) {
	stdcmap->red_mult = lowbit(vinfo->red_mask);
	stdcmap->green_mult = lowbit(vinfo->green_mask);
	stdcmap->blue_mult = lowbit(vinfo->blue_mask);
    } else {
	stdcmap->red_mult = (red_max > 0)
	    ? (green_max + 1) * (blue_max + 1) : 0;
	stdcmap->green_mult = (green_max > 0) ? blue_max + 1 : 0;
	stdcmap->blue_mult = (blue_max > 0) ? 1 : 0;
    }
    stdcmap->base_pixel = 0;			/* base pixel may change */
    stdcmap->visualid = vinfo->visualid;

    /* Make the colormap */

    status = XmuCreateColormap(dpy, stdcmap);

    /* Clean up */

    XFree((char *) vinfo);
    if (!status) {

	/* Free the colormap or the pixmap, if we created one */
	if (stdcmap->killid == ReleaseByFreeingColormap)
	    XFreeColormap(dpy, stdcmap->colormap);
	else if (stdcmap->killid != None)
	    XFreePixmap(dpy, stdcmap->killid);

	XFree((char *) stdcmap);
	return (XStandardColormap *) NULL;
    }
    return stdcmap;
}

/****************************************************************************/
static Status
valid_args(XVisualInfo *vinfo, unsigned long red_max, unsigned long green_max,
	   unsigned long blue_max, Atom property)
     /*
      * vinfo				- specifies visual
      * red_max, green_max, blue_max	- specifies alloc
      * property			- specifies property name
      */
{
    unsigned long	ncolors;	/* number of colors requested */

    /* Determine that the number of colors requested is <= map size */

    if ((vinfo->class == DirectColor) || (vinfo->class == TrueColor)) {
	unsigned long mask;

	mask = vinfo->red_mask;
	while (!(mask & 1))
	    mask >>= 1;
	if (red_max > mask)
	    return 0;
	mask = vinfo->green_mask;
	while (!(mask & 1))
	    mask >>= 1;
	if (green_max > mask)
	    return 0;
	mask = vinfo->blue_mask;
	while (!(mask & 1))
	    mask >>= 1;
	if (blue_max > mask)
	    return 0;
    } else if (property == XA_RGB_GRAY_MAP) {
	ncolors = red_max + green_max + blue_max + 1;
	if (ncolors > vinfo->colormap_size)
	    return 0;
    } else {
	ncolors = (red_max + 1) * (green_max + 1) * (blue_max + 1);
	if (ncolors > vinfo->colormap_size)
	    return 0;
    }

    /* Determine that the allocation and visual make sense for the property */

    switch (property)
    {
      case XA_RGB_DEFAULT_MAP:
	if (red_max == 0 || green_max == 0 || blue_max == 0)
	    return 0;
	break;
      case XA_RGB_RED_MAP:
	if (red_max == 0)
	    return 0;
	break;
      case XA_RGB_GREEN_MAP:
	if (green_max == 0)
	    return 0;
	break;
      case XA_RGB_BLUE_MAP:
	if (blue_max == 0)
	    return 0;
	break;
      case XA_RGB_BEST_MAP:
	if (red_max == 0 || green_max == 0 || blue_max == 0)
	    return 0;
	break;
      case XA_RGB_GRAY_MAP:
	if (red_max == 0 || blue_max == 0 || green_max == 0)
	    return 0;
	break;
      default:
	return 0;
    }
    return 1;
}


text:
package ikube.web.service;

import java.net.MalformedURLException;

/**
 * @author Michael Couck
 * @version 01.00
 * @since 21-11-2012
 */
public class SearcherXmlIntegration extends SearcherIntegration {

    @SuppressWarnings("StringBufferReplaceableByString")
    protected String getSearchUrl(String path) throws MalformedURLException {
        return getServiceUrl(SearcherXml.SEARCH + SearcherXml.XML + path);
    }

}


text:
function checkEntries(actualEntries, expectedEntries) {
  assert_equals(actualEntries.length, expectedEntries.length,
      `The length of actual and expected entries should match.
      actual: ${JSON.stringify(actualEntries)},
      expected: ${JSON.stringify(expectedEntries)}`);
  const actualEntrySet = new Set(actualEntries.map(ae=>ae.name));
  assert_equals(actualEntrySet.size, actualEntries.length, `Actual entry names are not unique: ${JSON.stringify(actualEntries)}`);
  const expectedEntrySet = new Set(expectedEntries.map(ee=>ee.name));
  assert_equals(expectedEntrySet.size, expectedEntries.length, `Expected entry names are not unique: ${JSON.stringify(expectedEntries)}`);
  actualEntries.forEach(ae=>{
    const expectedEntry = expectedEntries.find(e=>e.name === ae.name);
    assert_true(!!expectedEntry, `Entry name '${ae.name}' was not found.`);
    checkEntry(ae, expectedEntry);
  });
}

function checkEntry(entry, {name, entryType, startTime, detail, duration}) {
  assert_equals(entry.name, name);
  assert_equals(entry.entryType, entryType);
  if (startTime !== undefined)
    assert_equals(entry.startTime, startTime);
  if (detail !== undefined)
    assert_equals(JSON.stringify(entry.detail), JSON.stringify(detail));
  if (duration !== undefined)
    assert_equals(entry.duration, duration);
}