text:
package com.amazonaws.services.lightsail.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartInstanceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The name of the instance (a virtual private server) to start.
     *

     */
    private String instanceName;

    /**
     *

     * The name of the instance (a virtual private server) to start.
     *

     *
     * @param instanceName
     *        The name of the instance (a virtual private server) to start.
     */

    public void setInstanceName(String instanceName) {
        this.instanceName = instanceName;
    }

    /**
     *

     * The name of the instance (a virtual private server) to start.
     *

     *
     * @return The name of the instance (a virtual private server) to start.
     */

    public String getInstanceName() {
        return this.instanceName;
    }

    /**
     *

     * The name of the instance (a virtual private server) to start.
     *

     *
     * @param instanceName
     *        The name of the instance (a virtual private server) to start.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public StartInstanceRequest withInstanceName(String instanceName) {
        setInstanceName(instanceName);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInstanceName() != null)
            sb.append("InstanceName: ").append(getInstanceName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof StartInstanceRequest == false)
            return false;
        StartInstanceRequest other = (StartInstanceRequest) obj;
        if (other.getInstanceName() == null ^ this.getInstanceName() == null)
            return false;
        if (other.getInstanceName() != null && other.getInstanceName().equals(this.getInstanceName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInstanceName() == null) ? 0 : getInstanceName().hashCode());
        return hashCode;
    }

    @Override
    public StartInstanceRequest clone() {
        return (StartInstanceRequest) super.clone();
    }

}


text:
require 'spec_helper'

describe LostInTranslation do
  it 'has a version number' do
    expect(LostInTranslation::VERSION).not_to be nil
  end

  it 'does something useful' do
    expect(false).to eq(false)
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!DOCTYPE document [
  <!ENTITY project SYSTEM "project.xml">
]>
<document>

    &project;

    <properties>
        <author email="glenn@apache.org">Glenn L. Nielsen</author>
        <title>CGI How To</title>
    </properties>

The CGI (Common Gateway Interface) defines a way for a web server to
interact with external content-generating programs, which are often
referred to as CGI programs or CGI scripts.

Within Tomcat CGI support can be added when using Tomcat as your
HTTP server and you require CGI support.  Typically this is done
during development when you don't want to run a web server like Apache.

CGI support is implemented using the servlet class
org.apache.catalina.servlets.CGIServlet.  Traditionally,
this servlet is mapped to the URL pattern "/cgi-bin/*".

By default CGI support is disabled in Tomcat.

CAUTION - CGI scripts are used to execute programs
external to the Tomcat JVM. If you are using the Java SecurityManager this
will bypass your security policy configuration in catalina.policy.

Rename $CATALINA_BASE/server/lib/servlets-cgi.renametojar
to $CATALINA_BASE/server/lib/servlets-cgi.jar.

Remove the XML comments from around the CGI servlet and servlet-mapping
configuration in $CATALINA_BASE/conf/web.xml.

There are several servlet init parameters which can be used to
configure the behaviour of the CGI servlet.

cgiPathPrefix - The CGI search path will start at
the web application root directory + File.separator + this prefix.
The default cgiPathPrefix is /WEB-INF/cgi

clientInputTimeout - The time (in milliseconds) to
wait for input from the browser before assuming that there is none.
Default is 100 seconds.

debug - Debugging detail level for messages logged
by this servlet. Default 0.

</document>


text:
begin
andy = User.create!(
  email: 'andy@example.org',
  password: 'corn'
)
rescue ActiveRecord::RecordInvalid
end

a = Piece.create!(
  title: 'Bacon Ipsum',
  content: "\tBacon ipsum dolor amet swine beef corned beef prosciutto meatloaf filet mignon \
beef ribs drumstick bresaola fatback rump jowl ribeye cupim. Sirloin ball tip cow \
rump, boudin pork jerky ham meatloaf tenderloin tail. Ham hock short loin ribeye, \
corned beef boudin tri-tip salami sirloin. Meatloaf shoulder tri-tip pork venison \
doner landjaeger meatball, salami tongue sausage. Tail spare ribs picanha jowl \
landjaeger shank leberkas turkey beef ribeye cupim fatback.\n \
\tShort loin pork chop picanha drumstick brisket chuck. Bacon tail shoulder \
kielbasa, ribeye corned beef spare ribs. Ball tip pancetta tail bacon cupim jerky \
boudin kielbasa short loin pork chop. Andouille ribeye tail short loin sausage, \
bresaola turducken capicola picanha short ribs. Tenderloin jowl tongue short ribs \
shoulder pastrami beef ribs ribeye porchetta, boudin filet mignon shank ground round \
hamburger drumstick. Spare ribs pig cow kielbasa.\n"
)

User.first.pieces << a


text:
class TinyTownAnim extends createjs.Container {

    sprite: SBSprite;
    type: TinyTownAnimationType;
    showCount: number;

    constructor(type: TinyTownAnimationType) {

        super();

        this.showCount = 0;
        this.type = type;
        var ss = this.getSpriteSheet(type.id);
        this.sprite = new SBSprite(ss, type.id);
        this.addChild(this.sprite);

        this.sprite.regX = type.regX;
        this.sprite.regY = type.regY;
        this.sprite.framerate = type.framerate;
        this.sprite.currentAnimationFrame = Math.floor(Math.random() * ss.getNumFrames(type.id));
    }

    private getSpriteSheet(type: string): SBSpriteSheet {
        var d = beanstalk.resources.getResource("tiny_town_json");
        d.images = [beanstalk.resources.getResource("tiny_town_png")];
        return beanstalk.sprites.getSpriteSheet(type, new createjs.SpriteSheet(d));
    }

    public update(delta: number) {
    }

}


text:
package sune.ssp.etc;

import java.io.Serializable;

public enum DataListType {

	CONNECTED_CLIENTS;

	@SuppressWarnings("unchecked")
	public <T extends Serializable> DataList<T> create(T... data) {
		return DataList.create(this, data);
	}
}


text:
<?xml version="1.0" encoding="utf-8" ?>

<percentiles>
    <percentile>
        <lower>1</lower>
        <content>Air walk</content>
        <upper>5</upper>
    </percentile>
    <percentile>
        <lower>6</lower>
        <content>Antiplant shell</content>
        <upper>7</upper>
    </percentile>
    <percentile>
        <lower>8</lower>
        <content>Blight</content>
        <upper>9</upper>
    </percentile>
    <percentile>
        <lower>10</lower>
        <content>Break enchantment</content>
        <upper>11</upper>
    </percentile>
    <percentile>
        <lower>12</lower>
        <content>Command plants</content>
        <upper>13</upper>
    </percentile>
    <percentile>
        <lower>14</lower>
        <content>Control water</content>
        <upper>15</upper>
    </percentile>
    <percentile>
        <lower>16</lower>
        <content>Cure critical wounds</content>
        <upper>21</upper>
    </percentile>
    <percentile>
        <lower>22</lower>
        <content>Death ward</content>
        <upper>26</upper>
    </percentile>
    <percentile>
        <lower>27</lower>
        <content>Dimensional anchor</content>
        <upper>31</upper>
    </percentile>
    <percentile>
        <lower>32</lower>
        <content>Discern lies</content>
        <upper>34</upper>
    </percentile>
    <percentile>
        <lower>35</lower>
        <content>Dismissal</content>
        <upper>37</upper>
    </percentile>
    <percentile>
        <lower>38</lower>
        <content>Divination</content>
        <upper>39</upper>
    </percentile>
    <percentile>
        <lower>40</lower>
        <content>Divine power</content>
        <upper>42</upper>
    </percentile>
    <percentile>
        <lower>43</lower>
        <content>Freedom of movement</content>
        <upper>47</upper>
    </percentile>
    <percentile>
        <lower>48</lower>
        <content>Giant vermin</content>
        <upper>49</upper>
    </percentile>
    <percentile>
        <lower>50</lower>
        <content>Holy sword</content>
        <upper>51</upper>
    </percentile>
    <percentile>
        <lower>52</lower>
        <content>Imbue with spell ability</content>
        <upper>54</upper>
    </percentile>
    <percentile>
        <lower>55</lower>
        <content>Inflict critical wounds</content>
        <upper>57</upper>
    </percentile>
    <percentile>
        <lower>58</lower>
        <content>Greater magic weapon</content>
        <upper>60</upper>
    </percentile>
    <percentile>
        <lower>61</lower>
        <content>Nondetection</content>
        <upper>62</upper>
    </percentile>
    <percentile>
        <lower>63</lower>
        <content>Lesser planar ally</content>
        <upper>64</upper>
    </percentile>
    <percentile>
        <lower>65</lower>
        <content>Poison</content>
        <upper>67</upper>
    </percentile>
    <percentile>
        <lower>68</lower>
        <content>Reincarnate</content>
        <upper>69</upper>
    </percentile>
    <percentile>
        <lower>70</lower>
        <content>Repel vermin</content>
        <upper>71</upper>
    </percentile>
    <percentile>
        <lower>72</lower>
        <content>Restoration</content>
        <upper>76</upper>
    </percentile>
    <percentile>
        <lower>77</lower>
        <content>Rusting grasp</content>
        <upper>78</upper>
    </percentile>
    <percentile>
        <lower>79</lower>
        <content>Sending</content>
        <upper>81</upper>
    </percentile>
    <percentile>
        <lower>82</lower>
        <content>Spell immunity</content>
        <upper>85</upper>
    </percentile>
    <percentile>
        <lower>86</lower>
        <content>Spike stones</content>
        <upper>87</upper>
    </percentile>
    <percentile>
        <lower>88</lower>
        <content>Summon monster IV</content>
        <upper>90</upper>
    </percentile>
    <percentile>
        <lower>91</lower>
        <content>Summon nature's ally IV</content>
        <upper>93</upper>
    </percentile>
    <percentile>
        <lower>94</lower>
        <content>Tongues</content>
        <upper>98</upper>
    </percentile>
    <percentile>
        <lower>99</lower>
        <content>Tree stride</content>
        <upper>100</upper>
    </percentile>
</percentiles>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.uff.ic.oceano.experiments.ourico;

import br.uff.ic.oceano.core.control.ApplicationConstants;
import br.uff.ic.oceano.core.dao.controle.JPAUtil;
import br.uff.ic.oceano.core.exception.ObjetoNaoEncontradoException;
import br.uff.ic.oceano.core.factory.ObjectFactory;
import br.uff.ic.oceano.ourico.model.VerificacaoPosCheckout;
import br.uff.ic.oceano.ourico.service.CheckOutService;
import br.uff.ic.oceano.ourico.service.VerificacaoPosCheckoutService;
import java.util.List;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 *
 * @author marapao
 */
public class VerificacaoPost {

    private VerificacaoPosCheckoutService verificacaoPosCheckoutService = ObjectFactory.getObjectWithDataBaseDependencies(VerificacaoPosCheckoutService.class);
    private CheckOutService checkOutService = ObjectFactory.getObjectWithDataBaseDependencies(CheckOutService.class);

    @BeforeClass
    public void before(){
        JPAUtil.setCurrentPersistenceUnit(JPAUtil.PERSISTENCE_UNIT_LOCAL);
        JPAUtil.startUp();
    }

    @AfterClass
    public void after(){

    }

    @Test
    public void insere() throws ObjetoNaoEncontradoException{

        VerificacaoPosCheckout verificacaoPosCheckout = new VerificacaoPosCheckout();

        verificacaoPosCheckout.setSemantica(false);
        verificacaoPosCheckout.setSintatica(false);
        verificacaoPosCheckout.setVerificado(false);
        verificacaoPosCheckout.setVerificando(false);
        verificacaoPosCheckout.setCheckOut(checkOutService.getbyAutobranch(new Long("1")));

        verificacaoPosCheckoutService.save(verificacaoPosCheckout);

    }

    @Test(dependsOnMethods="insere")
    public void recupera(){
        List<VerificacaoPosCheckout> naoVerificado = verificacaoPosCheckoutService.getNaoVerificado();
        for (VerificacaoPosCheckout verificacaoPosCheckout : naoVerificado) {
            System.out.println(verificacaoPosCheckout.getSemantica().toString());
        }
    }
}


text:
export CK_REPOS=$PWD/CK
export CK_TOOLS=$PWD/CK-TOOLS

cb init mlperf-inference-v0.5-image-classification-openvino-resnet50-imagenet-val-500-linux \
        --name="Image classification; MLPerf inference v0.5; OpenVINO; ResNet 50; ImageNet; 500 images validation; Linux; benchmark; portable workflows" \
        --tags="validated,image-classification,mlperf,mlperf-inference,mlperf-inference-v0.5,openvino,resnet,resnet50,imagenet,500,benchmark,linux,portable-workflows,crowd-benchmarking" \
        --workflow_repo_url="local" \
        --workflow="program:mlperf-inference-v0.5" \
        --workflow_cmd_before="export NPROCS=\`grep -c processor /proc/cpuinfo\`" \
        --workflow_cmd="image-classification" \
        --workflow_cmd_extra="--repetitions=1 --no_state_check --skip_print_timers --env.CK_OPENVINO_MODEL_NAME=resnet50 --env.CK_LOADGEN_SCENARIO=Offline --env.CK_LOADGEN_MODE=Accuracy --env.CK_LOADGEN_DATASET_SIZE=500 --env.CK_OPENVINO_NTHREADS=\$NPROCS --env.CK_OPENVINO_NSTREAMS=\$NPROCS --env.CK_OPENVINO_NIREQ=\$NPROCS" \
        --workflow_output_dir="tmp" \
        --add_extra_meta_from_file="$PWD/extra-meta.json" \
        --desc_prereq="$PWD/prereq.txt" \
        --desc_prepare="$PWD/prepare.txt" \
        --result_file="tmp/tmp-ck-timer.json" \
        --python_version_from="3.6" \
        --python_version_to="3.7.99" \
        --graph_convertor="$PWD/graph-convertor.json"
#        --update_meta_and_stop


text:
/**
 prepare.js

 Generates lib/version.js
 Set environment variable DEV=1 to append git hash to version string
 */

'use strict';

const util = require('util');
const exec = util.promisify(require('child_process').exec);
const fs = require('fs');
const path = require('path');

var pjson = require('../package.json');
var VERSION_DIR = 'lib'
var VERSION_FILE = 'version.js';

(async function(dir, file, pversion) {

  var githash = '';
  if (process.env.DEV) {
    const o = await exec('git log -1 --pretty=format:%h');
    githash = '-' + o.stdout;
  }

  if (!fs.existsSync(VERSION_DIR)) {
    fs.mkdirSync(VERSION_DIR);
  }

  let target = path.join(VERSION_DIR, VERSION_FILE);
  if (fs.existsSync(target)) {
    fs.unlinkSync(target);
  }

  var str = '// Auto-generated by npm run prepare\nmodule.exports = \'' +
      pversion + githash + '\';';
  fs.writeFile(target, str, 'utf8', function(err) {
    if (err) {
      throw err;
    }
  });

})(VERSION_DIR, VERSION_FILE, pjson.version);


text:
from distutils.core import setup
from os import path

ROOT = path.dirname(__file__)
README = path.join(ROOT, 'README.rst')

setup(
    name='hurl',
    py_modules=['hurl'],
    url='https://github.com/oinopion/hurl',
    author='Tomek Paczkowski & Aleksandra Sendecka',
    author_email='tomek@hauru.eu',
    version='2.1',
    license='New BSD License',
    long_description=open(README).read(),
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Framework :: Django',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)


text:
set (PLATFORM_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR})

add_definitions(-DBH_PLATFORM_RTT)

include_directories(${PLATFORM_SHARED_DIR})
include_directories(${PLATFORM_SHARED_DIR}/../include)

# include (${CMAKE_CURRENT_LIST_DIR}/../common/math/platform_api_math.cmake)

file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c)

set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_MATH_SOURCE})


text:
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__$plus$eq__Lscala_collection_mutable_ObservableBuffer__O__Lscala_collection_mutable_ObservableBuffer = (function($$this, element) {
  $$this.scala$collection$mutable$ObservableBuffer$$super$$plus$eq__O__Lscala_collection_mutable_ObservableBuffer(element);
  $$this.publish__O__V(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$2().init___Lscala_collection_mutable_ObservableBuffer__O($$this, element));
  return $$this
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__$plus$plus$eq__Lscala_collection_mutable_ObservableBuffer__Lscala_collection_TraversableOnce__Lscala_collection_mutable_ObservableBuffer = (function($$this, xs) {
  xs.foreach__Lscala_Function1__V(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(arg$outer) {
    return (function(x) {
      return arg$outer.$$plus$eq__O__Lscala_collection_mutable_ObservableBuffer(x)
    })
  })($$this)));
  return $$this
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__$plus$eq$colon__Lscala_collection_mutable_ObservableBuffer__O__Lscala_collection_mutable_ObservableBuffer = (function($$this, element) {
  $$this.scala$collection$mutable$ObservableBuffer$$super$$plus$eq$colon__O__Lscala_collection_mutable_ObservableBuffer(element);
  $$this.publish__O__V(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$3().init___Lscala_collection_mutable_ObservableBuffer__O($$this, element));
  return $$this
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__update__Lscala_collection_mutable_ObservableBuffer__I__O__V = (function($$this, n, newelement) {
  var oldelement = $$this.apply__I__O(n);
  $$this.scala$collection$mutable$ObservableBuffer$$super$update__I__O__V(n, newelement);
  $$this.publish__O__V(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$4().init___Lscala_collection_mutable_ObservableBuffer__O__I__O($$this, oldelement, n, newelement))
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__remove__Lscala_collection_mutable_ObservableBuffer__I__O = (function($$this, n) {
  var oldelement = $$this.apply__I__O(n);
  $$this.scala$collection$mutable$ObservableBuffer$$super$remove__I__O(n);
  $$this.publish__O__V(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$5().init___Lscala_collection_mutable_ObservableBuffer__O__I($$this, oldelement, n));
  return oldelement
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__clear__Lscala_collection_mutable_ObservableBuffer__V = (function($$this) {
  $$this.scala$collection$mutable$ObservableBuffer$$super$clear__V();
  $$this.publish__O__V(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$6().init___Lscala_collection_mutable_ObservableBuffer($$this))
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__insertAll__Lscala_collection_mutable_ObservableBuffer__I__Lscala_collection_Traversable__V = (function($$this, n, elems) {
  $$this.scala$collection$mutable$ObservableBuffer$$super$insertAll__I__Lscala_collection_Traversable__V(n, elems);
  var curr = new ScalaJS.c.scala_runtime_IntRef().init___I((n - 1));
  var msg = ScalaJS.as.scala_collection_script_Script(elems.foldLeft__O__Lscala_Function2__O(new ScalaJS.c.scala_collection_mutable_ObservableBuffer$$anon$1().init___Lscala_collection_mutable_ObservableBuffer($$this), new ScalaJS.c.scala_scalajs_runtime_AnonFunction2().init___Lscala_scalajs_js_Function2((function(curr$1) {
    return (function(x0$1, x1$1) {
      var x1 = new ScalaJS.c.scala_Tuple2().init___O__O(x0$1, x1$1);
      if ((x1 !== null)) {
        var msg = ScalaJS.as.scala_collection_script_Script(x1.$$und1__O());
        var elem = x1.$$und2__O();
        curr$1.elem$1 = (curr$1.elem$1 + 1);
        return ScalaJS.as.scala_collection_script_Script(msg.$$plus$eq__O__Lscala_collection_mutable_ArrayBuffer(new ScalaJS.c.scala_collection_script_Include().init___Lscala_collection_script_Location__O(new ScalaJS.c.scala_collection_script_Index().init___I(curr$1.elem$1), elem)))
      };
      throw new ScalaJS.c.scala_MatchError().init___O(x1)
    })
  })(curr))));
  $$this.publish__O__V(msg)
});
ScalaJS.impls.scala_collection_mutable_ObservableBuffer$class__$init$__Lscala_collection_mutable_ObservableBuffer__V = (function($$this) {
  /*<skip>*/
});
//@ sourceMappingURL=ObservableBuffer$class.js.map


text:
SPEC_BEGIN(AEFCrashReporterSpec)

describe(@"AEFCrashReporter", ^{

    __block AEFCrashReporter *reporter;

    beforeEach(^{
        reporter = [AEFCrashReporter sharedReporter];
    });

    context(@"public interface", ^{

        it(@"should conform to the the crash reporter protocol", ^{
            [[reporter should] conformToProtocol:@protocol(AEFCrashReporting)];
        });

        it(@"should have a repo", ^{
            [[reporter should] respondToSelector:@selector(repo)];
        });

        it(@"should have a clientID", ^{
            [[reporter should] respondToSelector:@selector(clientID)];
        });

        it(@"should have a client secret", ^{
            [[reporter should] respondToSelector:@selector(clientSecret)];
        });

        it(@"should have labels", ^{
            [[reporter should] respondToSelector:@selector(labels)];
        });
    });

    context(@"when configuring", ^{

        beforeEach(^{
            [reporter setRepo:@"repo" clientID:@"id" clientSecret:@"secret"];
        });

        it(@"should set a repo", ^{
            [[reporter.repo should] equal:@"repo"];
        });

        it(@"should set a clientID", ^{
            [[reporter.clientID should] equal:@"id"];
        });

        it(@"should set a clientSecret", ^{
            [[reporter.clientSecret should] equal:@"secret"];
        });
    });
});

SPEC_END


text:
package com.alibaba.json.bvt.jsonp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import junit.framework.TestCase;

/**
 * Created by wenshao on 21/02/2017.
 */
public class JSONPParseTest extends TestCase {
    public void test_f() throws Exception {
        String text = "callback ({'id':1, 'name':'idonans'} );";

        JSONPObject jsonpObject = JSON.parseObject(text, JSONPObject.class);
        assertEquals("callback", jsonpObject.getFunction());

        assertEquals(1, jsonpObject.getParameters().size());
        JSONObject param = (JSONObject) jsonpObject.getParameters().get(0);
        assertEquals(1, param.get("id"));
        assertEquals("idonans", param.get("name"));

        String json = JSON.toJSONString(jsonpObject);
        System.out.println(json);
    }
}


text:
import unittest
import newsprocess
import datetime
import news
import pdb

class TestParseURL(unittest.TestCase):
    def setUp(self):
        pass
    def tearDown(self):
        pass

    def Sem(self):
        source = u"北京科技大学"
        api_url = "http://wiki.ibeike.com/api.php"
        print newsprocess.semanticParse(source, api_url)

    def testDate(self):
        d = datetime.date(2013, 1, 8)
        print newsprocess._wikiDate("Foo", d)

    def WikiNews(self):
        dir = "/Users/shichao/Documents/test/"
        url = [
               "http://news.ustb.edu.cn/html/Article_Class2_1_1.html",
               "http://news.ustb.edu.cn/html/Article_Class2_1_2.html"
               ]
        num = 4
        pattern = r"Article_Show\.asp\?ArticleID=(\d+)"
        q_pattern = "http://news.ustb.edu.cn/html/article/Article_show%s.html"
        api_url = "http://wiki.ibeike.com/api.php"
        #pdb.set_trace()
        wiki = news.WikiNews(dir, url, num, pattern, q_pattern, api_url)
        print wiki
        wiki.start()
        #wiki.put()
        #print wiki

if __name__ == '__main__':
    unittest.main()


text:
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase, OverloadedStrings #-}

module Model
       ( Step(..)
       , MaybeStep(..)
       , MatchAlgo(..)
       , nextStep
       , undo
       , context
       , suggest
       , setCurrentComment
       , getCurrentComment
       , setTransactionComment
       , getTransactionComment

       -- * Helpers exported for easier testing
       , accountsByFrequency
       , isDuplicateTransaction
       ) where

import           Data.Function
import           Data.List
import qualified Data.HashMap.Lazy as HM
import           Data.Maybe
import           Data.Monoid
import           Data.Ord (Down(..))
import           Data.Text (Text)
import qualified Data.Text as T
import           Data.Time.Ext hiding (parseTime)
import qualified Hledger as HL
import           Data.Foldable
import           Control.Applicative

import           AmountParser
import           DateParser

type Comment = Text
type Duplicate = Bool

data Step = DateQuestion Comment
          | DescriptionQuestion Day Comment
          | AccountQuestion HL.Transaction Comment
          | AmountQuestion HL.AccountName HL.Transaction Comment
          | FinalQuestion HL.Transaction Duplicate
          deriving (Eq, Show)

data MaybeStep = Finished HL.Transaction
               | Step Step
               deriving (Eq, Show)

data MatchAlgo = Fuzzy | Substrings
  deriving (Eq, Show)

nextStep :: HL.Journal -> DateFormat -> Either Text Text -> Step -> IO (Either Text MaybeStep)
nextStep journal dateFormat entryText current = case current of
  DateQuestion comment ->
    fmap (Step . flip DescriptionQuestion comment)
       <$> either (parseDateWithToday dateFormat) parseHLDateWithToday entryText

  DescriptionQuestion day comment -> return $ Right $ Step $
    AccountQuestion HL.nulltransaction { HL.tdate = day
                                       , HL.tdescription = (fromEither entryText)
                                       , HL.tcomment = comment
                                       }
                                       "" -- empty comment
  AccountQuestion trans comment
    | T.null (fromEither entryText) && transactionBalanced trans
      -> return $ Right $ Step $ FinalQuestion trans (isDuplicateTransaction journal trans)
    | T.null (fromEither entryText)  -- unbalanced
      -> return $ Left $ "Transaction not balanced! Please balance your transaction before adding it to the journal."
    | otherwise        -> return $ Right $ Step $
      AmountQuestion (fromEither entryText) trans comment
  AmountQuestion name trans comment -> case parseAmount journal (fromEither entryText) of
    Left err -> return $ Left (T.pack err)
    Right amount -> return $ Right $ Step $
      let newPosting = post' name amount comment
      in AccountQuestion (addPosting newPosting trans) ""

  FinalQuestion trans _
    | fromEither entryText == "y" -> return $ Right $ Finished trans
    | otherwise -> return $ Right $ Step $ AccountQuestion trans ""

-- | Reverses the last step.
--
-- Returns (Left errorMessage), if the step can't be reversed
undo :: Step -> Either Text Step
undo current = case current of
  DateQuestion _ -> Left "Already at oldest step in current transaction"
  DescriptionQuestion _ comment -> return (DateQuestion comment)
  AccountQuestion trans _ -> return $ case HL.tpostings trans of
    []     -> DescriptionQuestion (HL.tdate trans) (HL.tcomment trans)
    ps -> AmountQuestion (HL.paccount (last ps)) trans { HL.tpostings = init ps } (HL.pcomment (last ps))
  AmountQuestion _ trans comment -> Right $ AccountQuestion trans comment
  FinalQuestion trans _ -> undo (AccountQuestion trans "")

context :: HL.Journal -> MatchAlgo -> DateFormat -> Text -> Step -> IO [Text]
context _ _ dateFormat entryText (DateQuestion _) = parseDateWithToday dateFormat entryText >>= \case
  Left _ -> return []
  Right date -> return [T.pack $ HL.showDate date]
context j matchAlgo _ entryText (DescriptionQuestion _ _) = return $
  let descs = HL.journalDescriptions j
  in sortBy (descUses j) $ filter (matches matchAlgo entryText) descs
context j matchAlgo _ entryText (AccountQuestion _ _) = return $
  let names = accountsByFrequency j
  in  filter (matches matchAlgo entryText) names
context journal _ _ entryText (AmountQuestion _ _ _) = return $
  maybeToList $ T.pack . HL.showMixedAmount <$> trySumAmount journal entryText
context _ _ _ _  (FinalQuestion _ _) = return []

-- | Suggest the initial text of the entry box for each step
--
-- For example, it suggests today for the date prompt
suggest :: HL.Journal -> DateFormat -> Step -> IO (Maybe Text)
suggest _ dateFormat (DateQuestion _) =
  Just . printDate dateFormat <$> getLocalDay
suggest _ _ (DescriptionQuestion _ _) = return Nothing
suggest journal _ (AccountQuestion trans _) = return $
  if numPostings trans /= 0 && transactionBalanced trans
    then Nothing
    else HL.paccount <$> (suggestAccountPosting journal trans)
suggest journal _ (AmountQuestion account trans _) = return $ fmap (T.pack . HL.showMixedAmount) $ do
  case findLastSimilar journal trans of
    Nothing
      | null (HL.tpostings trans)
        -> Nothing  -- Don't suggest an amount for first account
      | otherwise
        -> Just $ negativeAmountSum trans
    Just last
      | transactionBalanced trans || (trans `isSubsetTransaction` last)
        -> HL.pamount <$> (findPostingByAcc account last)
      | otherwise
        -> Just $ negativeAmountSum trans
suggest _ _ (FinalQuestion _ _) = return $ Just "y"

getCurrentComment :: Step -> Comment
getCurrentComment step = case step of
  DateQuestion c -> c
  DescriptionQuestion _ c -> c
  AccountQuestion _ c -> c
  AmountQuestion _ _ c -> c
  FinalQuestion trans _ -> HL.tcomment trans

setCurrentComment :: Comment -> Step -> Step
setCurrentComment comment step = case step of
  DateQuestion _ -> DateQuestion comment
  DescriptionQuestion date _ -> DescriptionQuestion date comment
  AccountQuestion trans _ -> AccountQuestion trans comment
  AmountQuestion trans name _ -> AmountQuestion trans name comment
  FinalQuestion trans duplicate -> FinalQuestion trans { HL.tcomment = comment } duplicate

getTransactionComment :: Step -> Comment
getTransactionComment step = case step of
  DateQuestion c -> c
  DescriptionQuestion _ c -> c
  AccountQuestion trans _ -> HL.tcomment trans
  AmountQuestion _ trans _ -> HL.tcomment trans
  FinalQuestion trans _ -> HL.tcomment trans

setTransactionComment :: Comment -> Step -> Step
setTransactionComment comment step = case step of
  DateQuestion _ -> DateQuestion comment
  DescriptionQuestion date _ -> DescriptionQuestion date comment
  AccountQuestion trans comment' ->
    AccountQuestion (trans { HL.tcomment = comment }) comment'
  AmountQuestion name trans comment' ->
    AmountQuestion name (trans { HL.tcomment = comment }) comment'
  FinalQuestion trans duplicate -> FinalQuestion trans { HL.tcomment = comment } duplicate

-- | Returns true if the pattern is not empty and all of its words occur in the string
--
-- If the pattern is empty, we don't want any entries in the list, so nothing is
-- selected if the users enters an empty string. Empty inputs are special cased,
-- so this is important.
matches :: MatchAlgo -> Text -> Text -> Bool
matches algo a b
  | T.null a = False
  | otherwise = matches' (T.toCaseFold a) (T.toCaseFold b)
  where
    matches' a' b'
      | algo == Fuzzy && T.any (== ':') b' = all (`fuzzyMatch` (T.splitOn ":" b')) (T.words a')
      | otherwise = all (`T.isInfixOf` b') (T.words a')

fuzzyMatch :: Text -> [Text] -> Bool
fuzzyMatch _ [] = False
fuzzyMatch query (part : partsRest) = case (T.uncons query) of
  Nothing -> True
  Just (c, queryRest)
    | c == ':' -> fuzzyMatch queryRest partsRest
    | otherwise -> fuzzyMatch query partsRest || case (T.uncons part) of
      Nothing -> False
      Just (c2, partRest)
        | c == c2 -> fuzzyMatch queryRest (partRest : partsRest)
        | otherwise -> False

post' :: HL.AccountName -> HL.MixedAmount -> Comment -> HL.Posting
post' account amount comment = HL.nullposting
  { HL.paccount = account
  , HL.pamount = amount
  , HL.pcomment = comment
  }

addPosting :: HL.Posting -> HL.Transaction -> HL.Transaction
addPosting p t = t { HL.tpostings = (HL.tpostings t) ++ [p] }

trySumAmount :: HL.Journal -> Text -> Maybe HL.MixedAmount
trySumAmount ctx = either (const Nothing) Just . parseAmount ctx

-- | Given a previous similar transaction, suggest the next posting to enter
--
-- This next posting is the one the user likely wants to type in next.
suggestNextPosting :: HL.Transaction -> HL.Transaction -> Maybe HL.Posting
suggestNextPosting current reference =
  -- Postings that aren't already used in the new posting
  let unusedPostings = filter (`notContainedIn` curPostings) refPostings
  in listToMaybe unusedPostings

  where [refPostings, curPostings] = map HL.tpostings [reference, current]
        notContainedIn p = not . any (((==) `on` HL.paccount) p)

-- | Given the last transaction entered, suggest the likely most comparable posting
--
-- Since the transaction isn't necessarily the same type, we can't rely on matching the data
-- so we must use the order. This way if the user typically uses a certain order
-- like expense category and then payment method. Useful if entering many similar postings
-- in a row. For example, when entering transactions from a credit card statement
-- where the first account is usually food, and the second posting is always the credit card.
suggestCorrespondingPosting :: HL.Transaction -> HL.Transaction -> Maybe HL.Posting
suggestCorrespondingPosting current reference =
  let postingsEntered = length curPostings in
  if postingsEntered < (length refPostings) then
    Just (refPostings !! postingsEntered)
  else
    suggestNextPosting current reference
  where [refPostings, curPostings] = map HL.tpostings [reference, current]

findLastSimilar :: HL.Journal -> HL.Transaction -> Maybe HL.Transaction
findLastSimilar journal desc =
  maximumBy (compare `on` HL.tdate) <$>
    listToMaybe' (filter (((==) `on` HL.tdescription) desc) $ HL.jtxns journal)

suggestAccountPosting :: HL.Journal -> HL.Transaction -> Maybe HL.Posting
suggestAccountPosting journal trans =
  case findLastSimilar journal trans of
    Just t -> suggestNextPosting trans t
    Nothing -> (last <$> listToMaybe' (HL.jtxns journal)) >>= (suggestCorrespondingPosting trans)

-- | Return the first Posting that matches the given account name in the transaction
findPostingByAcc :: HL.AccountName -> HL.Transaction -> Maybe HL.Posting
findPostingByAcc account = find ((==account) . HL.paccount) . HL.tpostings

-- | Returns True if the first transaction is a subset of the second one.
--
-- That means, all postings from the first transaction are present in the
-- second one.
isSubsetTransaction :: HL.Transaction -> HL.Transaction -> Bool
isSubsetTransaction current origin =
  let
    origPostings = HL.tpostings origin
    currPostings = HL.tpostings current
  in
    null (deleteFirstsBy cmpPosting currPostings origPostings)
  where
    cmpPosting a b =  HL.paccount a == HL.paccount b
                   && HL.pamount a  == HL.pamount b

listToMaybe' :: [a] -> Maybe [a]
listToMaybe' [] = Nothing
listToMaybe' ls = Just ls

numPostings :: HL.Transaction -> Int
numPostings = length . HL.tpostings

-- | Returns True if all postings balance and the transaction is not empty
transactionBalanced :: HL.Transaction -> Bool
transactionBalanced trans = HL.isTransactionBalanced Nothing trans

-- | Computes the sum of all postings in the transaction and inverts it
negativeAmountSum :: HL.Transaction -> HL.MixedAmount
negativeAmountSum trans =
  let (rsum, _, _) = HL.transactionPostingBalances trans
  in HL.divideMixedAmount (-1) rsum

-- | Compare two transaction descriptions based on their number of occurences in
-- the given journal.
descUses :: HL.Journal -> Text -> Text -> Ordering
descUses journal = compare `on` (Down . flip HM.lookup usesMap)
  where usesMap = foldr (count . HL.tdescription) HM.empty $
                  HL.jtxns journal
        -- Add one to the current count of this element
        count :: Text -> HM.HashMap Text (Sum Int) -> HM.HashMap Text (Sum Int)
        count = HM.alter (<> Just 1)

-- | All accounts occuring in the journal sorted in descending order of
-- appearance.
accountsByFrequency :: HL.Journal -> [HL.AccountName]
accountsByFrequency journal =
  let
    usedAccounts = map HL.paccount (HL.journalPostings journal)
    frequencyMap :: HM.HashMap HL.AccountName Int = foldr insertOrPlusOne HM.empty usedAccounts
    mapWithSubaccounts = foldr insertIfNotPresent frequencyMap (subaccounts frequencyMap)
    declaredAccounts = HL.expandAccountNames (HL.journalAccountNamesDeclared journal)
    mapWithDeclared = foldr insertIfNotPresent mapWithSubaccounts declaredAccounts
  in
    map fst (sortBy (compare `on` (Down . snd)) (HM.toList mapWithDeclared))

  where
    insertOrPlusOne = HM.alter (Just . maybe 1 (+1))
    insertIfNotPresent account = HM.insertWith (flip const) account 0
    subaccounts m = HL.expandAccountNames (HM.keys m)

-- | Deterimine if a given transaction already occurs in the journal
--
-- This function ignores certain attributes of transactions, postings and
-- amounts that are either artifacts of knot-tying or are purely for
-- presentation.
--
-- See the various ...attributes functions in the where clause for details.
isDuplicateTransaction :: HL.Journal -> HL.Transaction -> Bool
isDuplicateTransaction  journal trans = any ((==EQ) . cmpTransaction trans) (HL.jtxns journal)
  where
    -- | Transaction attributes that are compared to determine duplicates
    transactionAttributes =
      [ cmp HL.tdate, cmp HL.tdate2, cmp HL.tdescription, cmp HL.tstatus
      , cmp HL.tcode, cmpPostings `on` HL.tpostings
      ]

    -- | Posting attributes that are compared to determine duplicates
    postingAttributes =
      [ cmp HL.pdate, cmp HL.pdate2, cmp HL.pstatus, cmp HL.paccount
      , cmpMixedAmount `on` HL.pamount, cmpPType `on` HL.ptype
      , (fmap fold . liftA2 cmpBalanceAssertion) `on` HL.pbalanceassertion
      ]

    -- | Ammount attributes that are compared to determine duplicates
    amountAttributes =
      [ cmp HL.acommodity, cmp HL.aprice, cmp HL.aquantity ]

    -- | Compare two transactions but ignore unimportant details
    cmpTransaction :: HL.Transaction -> HL.Transaction -> Ordering
    cmpTransaction = lexical transactionAttributes

    -- | Compare two posting lists of postings by sorting them deterministically
    -- and then compare correspondings list elements
    cmpPostings :: [HL.Posting] -> [HL.Posting] -> Ordering
    cmpPostings ps1 ps2 =
      mconcat (zipWith (lexical postingAttributes) (sortPostings ps1) (sortPostings ps2))

    -- | Compare two posting styles (this should really be an Eq instance)
    cmpPType :: HL.PostingType -> HL.PostingType -> Ordering
    cmpPType = compare `on` pTypeToInt
      where
        pTypeToInt :: HL.PostingType -> Int
        pTypeToInt HL.RegularPosting = 0
        pTypeToInt HL.VirtualPosting = 1
        pTypeToInt HL.BalancedVirtualPosting = 2

    -- | Compare two amounts ignoring unimportant details
    cmpAmount :: HL.Amount -> HL.Amount -> Ordering
    cmpAmount = lexical amountAttributes

    -- | Compare two mixed amounts by first sorting the individual amounts
    -- deterministically and then comparing them one-by-one.
    cmpMixedAmount :: HL.MixedAmount -> HL.MixedAmount -> Ordering
    cmpMixedAmount (HL.Mixed as1) (HL.Mixed as2) =
      let
        sortedAs1 = sortBy cmpAmount as1
        sortedAs2 = sortBy cmpAmount as2
      in
        mconcat $
          compare (length as1) (length as2) : zipWith cmpAmount sortedAs1 sortedAs2

    cmpBalanceAssertion :: HL.BalanceAssertion -> HL.BalanceAssertion -> Ordering
    cmpBalanceAssertion = lexical [cmp HL.baamount, cmp HL.batotal]

    sortPostings :: [HL.Posting] -> [HL.Posting]
    sortPostings = sortBy (lexical postingAttributes)

    -- | Shortcut for 'compare `on`'
    cmp :: Ord b => (a -> b) -> a -> a -> Ordering
    cmp f = compare `on` f

    -- | Apply two things with multiple predicats and combine the results lexicographically
    lexical :: [a -> b -> Ordering] -> a -> b -> Ordering
    lexical = fold -- hehe

fromEither :: Either a a -> a
fromEither = either id id


text:
using kmldom::FeaturePtr;
using kmldom::KmlFactory;
using kmldom::PairPtr;
using kmldom::LineStylePtr;
using kmldom::StylePtr;
using kmldom::StyleMapPtr;
using kmldom::StyleSelectorPtr;

namespace kmlengine {

static const size_t kKmlNetCacheCacheSize = 10;

class StyleMergerTest : public testing::Test {
 protected:
  virtual void SetUp() {
    kml_file_net_cache_.reset(new KmlFileNetCache(&test_data_net_fetcher_,
                                                  kKmlNetCacheCacheSize));
    kml_file_ = KmlFile::CreateFromString("<kml/>");
    style_merger_normal_.reset(
        StyleMerger::CreateFromKmlFile(*kml_file_, kmldom::STYLESTATE_NORMAL));
    style_merger_highlight_.reset(
        StyleMerger::CreateFromKmlFile(*kml_file_,
                                       kmldom::STYLESTATE_HIGHLIGHT));
    factory_ = KmlFactory::GetFactory();
    style_ = factory_->CreateStyle();
    stylemap_ = factory_->CreateStyleMap();
  }

  PairPtr CreateStylePair(kmldom::StyleStateEnum style_state,
                          const StyleSelectorPtr& styleselector) const;
  StylePtr CreateStyleLineStyle(const string& id,
                                const string& color,
                                double width) const;
  void VerifyEmptyStyle(const StylePtr& style) const;
  void VerifyStyleLineStyle(const StylePtr& style, const string& id,
                            const string& color, double width) const;
  void VerifyStyleMergersEmpty() const;
  KmlFilePtr kml_file_;
  kmlbase::TestDataNetFetcher test_data_net_fetcher_;
  boost::scoped_ptr<KmlFileNetCache> kml_file_net_cache_;
  KmlFactory* factory_;
  boost::scoped_ptr<StyleMerger> style_merger_normal_;
  boost::scoped_ptr<StyleMerger> style_merger_highlight_;
  StylePtr style_;
  StyleMapPtr stylemap_;
};

// This is a helper function to verify that Style has no SubStyles.
void StyleMergerTest::VerifyEmptyStyle(const StylePtr& style) const {
  ASSERT_FALSE(style->has_iconstyle());
  ASSERT_FALSE(style->has_labelstyle());
  ASSERT_FALSE(style->has_linestyle());
  ASSERT_FALSE(style->has_polystyle());
  ASSERT_FALSE(style->has_balloonstyle());
  ASSERT_FALSE(style->has_liststyle());
}

// This is a helper function to verify empty state of the StyleMergers in the
// test fixture.
void StyleMergerTest::VerifyStyleMergersEmpty() const {
  StylePtr style = style_merger_normal_->GetResolvedStyle();
  ASSERT_TRUE(style != 0);
  VerifyEmptyStyle(style);
  style = style_merger_highlight_->GetResolvedStyle();
  ASSERT_TRUE(style != 0);
  VerifyEmptyStyle(style);
}

// Verify that the Style has the given id and LineStyle with the given color
// and width.
void StyleMergerTest::VerifyStyleLineStyle(const StylePtr& style,
                                           const string& id,
                                           const string& color,
                                           double width) const {
  ASSERT_EQ(id, style->get_id());
  ASSERT_TRUE(style->get_linestyle() != 0);
  ASSERT_EQ(color,
                       style->get_linestyle()->get_color().to_string_abgr());
  ASSERT_EQ(width, style->get_linestyle()->get_width());
}

// This is a helper function to create a Pair with key and StyleSelector.
PairPtr StyleMergerTest::CreateStylePair(
      kmldom::StyleStateEnum style_state,
      const StyleSelectorPtr& styleselector) const {
  PairPtr pair = factory_->CreatePair();
  pair->set_key(style_state);
  pair->set_styleselector(styleselector);
  return pair;
}

// This helper function creates Style with the given id and gives it a
// LineStyle of the given color and width.
StylePtr StyleMergerTest::CreateStyleLineStyle(const string& id,
                                               const string& color,
                                               double width) const {
  StylePtr style = factory_->CreateStyle();
  style->set_id(id);
  LineStylePtr linestyle = factory_->CreateLineStyle();
  linestyle->set_color(color);
  linestyle->set_width(width);
  style->set_linestyle(linestyle);
  return style;
}

// Verify a freshly constructed StyleMerger's GetResolvedStyle() returns an
// empty Style.
TEST_F(StyleMergerTest, TestConstructor) {
  // Test style_merger_normal_, style_merger_highlight_ created in SetUp()
  // which uses CreateFromKmlFile().
  VerifyStyleMergersEmpty();
  // Test use of the StyleMerge ctor.
  style_merger_normal_.reset(
      new StyleMerger(kml_file_->get_shared_style_map(),
                      kml_file_->get_kml_cache(),
                      kml_file_->get_url(),
                      kmldom::STYLESTATE_NORMAL));
  style_merger_highlight_.reset(
      new StyleMerger(kml_file_->get_shared_style_map(),
                      kml_file_->get_kml_cache(),
                      kml_file_->get_url(),
                      kmldom::STYLESTATE_HIGHLIGHT));
  VerifyStyleMergersEmpty();
}

// Verify the MergeStyle() method on NULL, empty and bad arguments.
TEST_F(StyleMergerTest, TestMergeStyleNullEmptyBad) {
  string empty_styleurl;

  // Verify that an empty styleurl and NULL StyleSelector behaves fine.
  style_merger_normal_->MergeStyle(empty_styleurl, NULL);
  VerifyStyleMergersEmpty();

  // Verify that MergeStyle takes an empty Style and empty StyleMap.
  style_merger_normal_->MergeStyle(empty_styleurl, style_);
  style_merger_normal_->MergeStyle(empty_styleurl, stylemap_);
  VerifyStyleMergersEmpty();

  // Verify that MergeStyle() is well behaved with a garbage styleUrl.
  string garbage("not at all a URL");
  style_merger_normal_->MergeStyle(empty_styleurl, NULL);
  VerifyStyleMergersEmpty();

  // Verify that MergeStyle() is well behaved with a validly formed styleurl
  // for an object that does not exist.
  string valid_fragment("#no-such-object");
  style_merger_normal_->MergeStyle(valid_fragment, NULL);
  VerifyStyleMergersEmpty();
}

// Test basic usage of the MergeStyle() method with various valid arguments.
TEST_F(StyleMergerTest, TestMergeStyleBasic) {
  // Set one SubStyle (LineStyle), merge it in and verify it comes out the
  // other end.  No shared styles are in the KML file.
  style_->set_linestyle(factory_->CreateLineStyle());
  style_merger_normal_->MergeStyle("", style_);
  StylePtr style = style_merger_normal_->GetResolvedStyle();
  ASSERT_FALSE(style->has_iconstyle());
  ASSERT_FALSE(style->has_labelstyle());
  ASSERT_TRUE(style->has_linestyle());
  ASSERT_FALSE(style->has_polystyle());
  ASSERT_FALSE(style->has_balloonstyle());
  ASSERT_FALSE(style->has_liststyle());

  // Set another.
  style_->set_polystyle(factory_->CreatePolyStyle());
  style_merger_normal_->MergeStyle("", style_);
  style = style_merger_normal_->GetResolvedStyle();
  ASSERT_FALSE(style->has_iconstyle());
  ASSERT_FALSE(style->has_labelstyle());
  ASSERT_TRUE(style->has_linestyle());
  ASSERT_TRUE(style->has_polystyle());
  ASSERT_FALSE(style->has_balloonstyle());
  ASSERT_FALSE(style->has_liststyle());

  // Set all SubStyles.
  style_->set_iconstyle(factory_->CreateIconStyle());
  style_->set_labelstyle(factory_->CreateLabelStyle());
  style_->set_balloonstyle(factory_->CreateBalloonStyle());
  style_->set_liststyle(factory_->CreateListStyle());

  style_merger_normal_->MergeStyle("", style_);
  style = style_merger_normal_->GetResolvedStyle();
  ASSERT_TRUE(style->has_iconstyle());
  ASSERT_TRUE(style->has_labelstyle());
  ASSERT_TRUE(style->has_linestyle());
  ASSERT_TRUE(style->has_polystyle());
  ASSERT_TRUE(style->has_balloonstyle());
  ASSERT_TRUE(style->has_liststyle());

  // Verify all behaves well a StyleMerger in highlight mode.
  style_merger_highlight_->MergeStyle("", style_);
  style = style_merger_highlight_->GetResolvedStyle();
  ASSERT_TRUE(style->has_iconstyle());
  ASSERT_TRUE(style->has_labelstyle());
  ASSERT_TRUE(style->has_linestyle());
  ASSERT_TRUE(style->has_polystyle());
  ASSERT_TRUE(style->has_balloonstyle());
  ASSERT_TRUE(style->has_liststyle());
}

// Verify the MergeStyleMap() method on NULL and empty args.
TEST_F(StyleMergerTest, TestMergeStyleMapNullEmpty) {
  style_merger_normal_->MergeStyleMap(NULL);
  style_merger_highlight_->MergeStyleMap(NULL);
  VerifyStyleMergersEmpty();

  // An internal check to verify that the StyleMap is empty.
  ASSERT_EQ(static_cast<size_t>(0),
                       stylemap_->get_pair_array_size());
  style_merger_normal_->MergeStyleMap(stylemap_);
  style_merger_highlight_->MergeStyleMap(stylemap_);
  VerifyStyleMergersEmpty();

  // Create a StyleMap with no StyleSelector for the normal and highlight keys.
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_NORMAL, NULL));
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_HIGHLIGHT, NULL));
  style_merger_normal_->MergeStyleMap(stylemap_);
  style_merger_highlight_->MergeStyleMap(stylemap_);
  VerifyStyleMergersEmpty();
}

// Create a StyleMap with an empty Style for the normal and highlight keys.
TEST_F(StyleMergerTest, TestMergeStyleMapEmptyStyle) {
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_NORMAL,
                                      factory_->CreateStyle()));
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_HIGHLIGHT,
                                      factory_->CreateStyle()));
  style_merger_normal_->MergeStyleMap(stylemap_);
  style_merger_highlight_->MergeStyleMap(stylemap_);
  VerifyStyleMergersEmpty();
}

// Create a StyleMap with an empty StyleMap for the normal and highlight keys.
TEST_F(StyleMergerTest, TestMergeStyleMapEmptyStyleMap) {
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_NORMAL,
                                      factory_->CreateStyleMap()));
  stylemap_->add_pair(CreateStylePair(kmldom::STYLESTATE_HIGHLIGHT,
                                      factory_->CreateStyleMap()));
  style_merger_normal_->MergeStyleMap(stylemap_);
  style_merger_highlight_->MergeStyleMap(stylemap_);
  VerifyStyleMergersEmpty();
}

// Verify basic usage of the MergeStyleMap() method with a simple StyleMap.
TEST_F(StyleMergerTest, TestMergeStyleMapBasic) {
  // Create a StyleMap with different values for normal and highlight LineStyle.
  const string kNormalId("normal-id");
  const string kNormalColor("1f331122");
  const double kNormalWidth(2.3);
  const string kHighlightId("highlight-id");
  const string kHighlightColor("7f112233");
  const double kHighlightWidth(4.4);
  stylemap_->add_pair(
      CreateStylePair(kmldom::STYLESTATE_NORMAL,
                      CreateStyleLineStyle(kNormalId, kNormalColor,
                                           kNormalWidth)));
  stylemap_->add_pair(
      CreateStylePair(kmldom::STYLESTATE_HIGHLIGHT,
                      CreateStyleLineStyle(kHighlightId, kHighlightColor,
                                           kHighlightWidth)));
  // Merge the StyleMap into the normal merger.
  style_merger_normal_->MergeStyleMap(stylemap_);
  // Merge the same StyleMap into the highlight merger.
  style_merger_highlight_->MergeStyleMap(stylemap_);
  // Verify the normal values appear properly in the normal resolved style.
  VerifyStyleLineStyle(style_merger_normal_->GetResolvedStyle(), kNormalId,
                       kNormalColor, kNormalWidth);
  // Verify the highlight values appear properly in the highlight resolved
  // style.
  VerifyStyleLineStyle(style_merger_highlight_->GetResolvedStyle(),
                       kHighlightId, kHighlightColor, kHighlightWidth);
}

// Verify the MergeStyleSelector() method with NULL and empty arguments.
TEST_F(StyleMergerTest, TestMergeStyleSelector) {
  style_merger_normal_->MergeStyleSelector(NULL);
  style_merger_highlight_->MergeStyleSelector(NULL);
  VerifyStyleMergersEmpty();

  style_merger_normal_->MergeStyleSelector(style_);
  style_merger_highlight_->MergeStyleSelector(style_);
  VerifyStyleMergersEmpty();

  style_merger_normal_->MergeStyleSelector(stylemap_);
  style_merger_highlight_->MergeStyleSelector(stylemap_);
  VerifyStyleMergersEmpty();
}

// Verify the nesting depth detection.
TEST_F(StyleMergerTest, TestNestingDepthDetection) {
  SharedStyleMap shared_style_map;
  // <Style><LineStyle>...
  const string kStyleId("style0");
  style_->set_linestyle(factory_->CreateLineStyle());
  shared_style_map[kStyleId] = style_;
  // <StyleMap><Pair><key>normal><Style><IconStyle>...
  const string kStyleMapId("stylemap0");
  PairPtr pair = factory_->CreatePair();
  pair->set_key(kmldom::STYLESTATE_NORMAL);
  StylePtr style = factory_->CreateStyle();
  style->set_iconstyle(factory_->CreateIconStyle());
  pair->set_styleselector(style);
  stylemap_->add_pair(pair);
  shared_style_map[kStyleMapId] = stylemap_;
  style_merger_normal_.reset(new StyleMerger(shared_style_map, NULL, "",
                                             kmldom::STYLESTATE_NORMAL,
                                             1));
  ASSERT_EQ(1, style_merger_normal_->get_nesting_depth());
  // Resolve a styleUrl and the count decrements.
  style_merger_normal_->MergeStyleUrl(string("#") + kStyleId);
  ASSERT_EQ(0, style_merger_normal_->get_nesting_depth());
  // The resolved style is the one with a <LineStyle>
  StylePtr resolved_style = style_merger_normal_->GetResolvedStyle();
  ASSERT_TRUE(resolved_style != 0);
  ASSERT_TRUE(resolved_style->has_linestyle());
  ASSERT_FALSE(resolved_style->has_iconstyle());
  // Now try to resolve against another styleUrl to another StyleSelector.
  style_merger_normal_->MergeStyleUrl(string("#") + kStyleMapId);
  ASSERT_EQ(-1, style_merger_normal_->get_nesting_depth());
  // Verify that no further merging happened.
  ASSERT_TRUE(resolved_style != 0);
  ASSERT_TRUE(resolved_style->has_linestyle());
  ASSERT_FALSE(resolved_style->has_iconstyle());
}

}  // end namespace kmlengine


text:
<?PHP
// Copyright (c) 2011 Martin Ueding <dev@martin-ueding.de>

session_start();
if (empty($_SESSION['benutzer_id']))
	header('location:../index.php');

include('../../login.inc.php');

$sql = 'DELETE FROM abi_mottostimmen WHERE mottostimmen_von='.$_SESSION['benutzer_id'].';';
mysql_query($sql);

$insert = 'INSERT INTO abi_mottostimmen SET mottostimmen_von='.$_SESSION['benutzer_id'].', mottostimmen_fuer='.$_POST['motto'].';';
mysql_query($insert);

header('location:auswahl.php');

?>


text:
from base64 import urlsafe_b64decode
from enum import Enum
from secrets import token_urlsafe

from django.db import models

# I'd prefer this to be in ddcz.notifications, but we can't as it's used in charfield choices
# and I want to avoid circular imports

class NotificationEvent(Enum):
    NEWS_ADDED = "Nová aktualita"

class ScheduledNotification(models.Model):
    event = models.CharField(
        choices=((i.name, i.value) for i in NotificationEvent), max_length=255
    )
    serialized_model = models.TextField()
    extra_data = models.TextField()
    scheduled_at = models.DateTimeField(auto_now_add=True)

class ScheduledEmail(models.Model):
    recipient_email = models.CharField(max_length=150)
    email_subject = models.CharField(max_length=255)
    email_text = models.TextField()
    sending_failures = models.IntegerField(default=0)
    scheduled_at = models.DateTimeField(auto_now_add=True)
    # TODO: Migration to foreign key
    user_profile_id = models.IntegerField()

class CreationEmailSubscription(models.Model):
    user_profile_id = models.IntegerField(db_column="id_uz")
    creative_page_slug = models.CharField(max_length=20, db_column="rubrika")
    user_email = models.CharField(max_length=40, db_column="email_uz")
    # MIME can be ignored for now (I think it was meant to be used to select between HTML
    # and plain, but was never used and hence it's always set to "p"
    mime = models.CharField(
        db_column="MIME", max_length=1
    )  # Field name made lowercase.

    django_id = models.AutoField(primary_key=True)

    class Meta:
        db_table = "uzivatele_maillist"
        unique_together = (("user_profile_id", "creative_page_slug"),)

class BlacklistedEmail(models.Model):
    # SHA512 is used. In case of extending, we cannot rehash anyway, so we'll add
    # additional field with cipher type
    # If the purpose would be to only validate links, it would be better to use password-like
    # strong crypt (blake/scrypt/...), but here we need to do a global lookup against the whole
    # table, not per-item validation. sha512 seems like a good tradeoff for lookup ability
    # vs. how hard it would be to get the mails in case of the leak
    # The database is not large enough to be worth it given the current state of the black market
    CIPHER_NAME = "sha3_512"
    CIPHER_CLEARTEXT_ENCODING = "utf8"
    email_hash = models.CharField(max_length=255, primary_key=True)

class EmailSubscriptionAuth(models.Model):
    # TODO: Foreign Key is only usable between InnoDB tables
    # Migrate after all tables are migrated, see <https://github.com/dracidoupe/graveyard/issues/109>
    # user_profile = models.OneToOneField(
    #     "UserProfile", primary_key=True, on_delete=models.CASCADE
    # )
    user_profile_id = models.IntegerField(primary_key=True)
    token_secret = models.CharField(max_length=255)

    def generate_token(self):
        self.token_secret = token_urlsafe()
        return self.token_secret

    def save(self, *args, **kwargs):
        if not self.token_secret:
            self.generate_token()
        super().save(*args, **kwargs)


text:
package wint.sessionx.servlet;

import wint.lang.utils.StringUtil;
import wint.lang.utils.UrlUtil;
import wint.sessionx.filter.FilterContext;
import wint.sessionx.store.SessionStore;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

@SuppressWarnings("deprecation")
public class WintSessionHttpServletRequest extends HttpServletRequestWrapper implements HttpServletRequest {

	private WintHttpSession wintHttpSession;

	private ServletContext servletContext;

    private SessionStore sessionStore;

    private String scheme;

    private Integer serverPort;

    private Boolean secure;

	public WintSessionHttpServletRequest(HttpServletRequest request, ServletContext servletContext, SessionStore sessionStore) {
		super(request);
		this.servletContext = servletContext;
        this.sessionStore = sessionStore;
	}

	private void createSession() {
		WintHttpSession wintHttpSession = new WintHttpSession(sessionStore, servletContext);
		this.wintHttpSession = wintHttpSession;
	}

	public void commit(FilterContext filterContext) {
		if (wintHttpSession != null) {
			wintHttpSession.commit(filterContext);
		}
	}

	@Override
	public HttpSession getSession(boolean create) {
		// 这里线程未做同步
		if (wintHttpSession != null) {
			return wintHttpSession;
		}

		if (create) {
			createSession();
		}
		return wintHttpSession;
	}

	@Override
	public HttpSession getSession() {
		return getSession(true);
	}

	@Override
	public boolean isRequestedSessionIdValid() {
		return true;
	}

	@Override
	public boolean isRequestedSessionIdFromCookie() {
		return true;
	}

	@Override
	public boolean isRequestedSessionIdFromURL() {
		return false;
	}

	@Override
	public boolean isRequestedSessionIdFromUrl() {
		return false;
	}

    public String getScheme() {
        if (StringUtil.isEmpty(scheme)) {
            return super.getScheme();
        }
        return scheme;
    }

    public void setScheme(String scheme) {
        this.scheme = scheme;
    }

    public int getServerPort() {
        if (serverPort == null) {
            return super.getServerPort();
        }
        return serverPort;
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public boolean isSecure() {
        if (secure == null) {
            return super.isSecure();
        }
        return secure;
    }

    public void setSecure(boolean secure) {
        this.secure = secure;
    }

    @Override
    public StringBuffer getRequestURL() {
        final StringBuffer url = new StringBuffer(48);
        String scheme = getScheme();
        int port = getServerPort();

        url.append(scheme);
        url.append("://");
        url.append(getServerName());
        if (port > 0 && ((scheme.equalsIgnoreCase(UrlUtil.HTTP) && port != UrlUtil.DEFAULT_HTTP_PORT)
                || (scheme.equalsIgnoreCase(UrlUtil.HTTPS) && port != UrlUtil.DEFAULT_HTTPS_PORT)))
        {
            url.append(':');
            url.append(port);
        }
        url.append(getRequestURI());
        return url;
      //  return super.getRequestURL();
    }
}


text:
ACCEPTED

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

#### Published in
Rhizoctonia-Forming Fungi (Richmond) 117 (1999)

#### Original name
Sebacina prolifera D.P. Rogers, 1936

### Remarks
null


text:
export class A {}
export class B {}


text:
using Cuemon.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;

namespace Cuemon.Extensions.AspNetCore.Authentication
{
    /// <summary>
    /// Extension methods for the <see cref="IServiceCollection"/> interface.
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// Adds a <see cref="MemoryNonceTracker"/> service to the specified <see cref="IServiceCollection"/>.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param>
        /// <returns>An <see cref="IServiceCollection"/> that can be used to further configure other services.</returns>
        public static IServiceCollection AddInMemoryDigestAuthenticationNonceTracker(this IServiceCollection services)
        {
            Validator.ThrowIfNull(services, nameof(services));
            services.AddSingleton<INonceTracker, MemoryNonceTracker>();
            return services;
        }
    }
}


text:
<?php

?>
<?php
class ProjectionsPeriod extends AppModel {
	var $name = 'ProjectionsPeriod';
	var $useDbConfig = 'mssql_sistemas';
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'ProjectionsCorporations' => array(
			'className' => 'ProjectionsCorporation',
			'foreignKey' => 'projections_corporations_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
}


text:
package org.onosproject.pcepio;

import java.util.LinkedList;

import org.junit.Test;
import org.onosproject.pcepio.types.IPv4TERouterIdOfLocalNodeTlv;
import org.onosproject.pcepio.types.NodeFlagBitsTlv;
import org.onosproject.pcepio.types.PcepValueType;
import org.onosproject.pcepio.types.TENodeAttributesTlv;

import com.google.common.testing.EqualsTester;

/**
 * Test case for TE Node Attribute tlv.
 */
public class TENodeAttributesTlvTest {

    private final NodeFlagBitsTlv nodeFlagBitsTlv1 = new NodeFlagBitsTlv((byte) 10);
    private final IPv4TERouterIdOfLocalNodeTlv iPv4TERouterIdOfLocalNodeTlv1 = new
            IPv4TERouterIdOfLocalNodeTlv(0x01010101);

    private final NodeFlagBitsTlv nodeFlagBitsTlv2 = new NodeFlagBitsTlv((byte) 20);
    private final IPv4TERouterIdOfLocalNodeTlv iPv4TERouterIdOfLocalNodeTlv2 = new
            IPv4TERouterIdOfLocalNodeTlv(0x02020202);

    private final LinkedList<PcepValueType> llNodeAttributesSubTLV1 = new LinkedList<>();
    private final boolean a = llNodeAttributesSubTLV1.add(nodeFlagBitsTlv1);
    private final boolean b = llNodeAttributesSubTLV1.add(iPv4TERouterIdOfLocalNodeTlv1);

    private final LinkedList<PcepValueType> llNodeAttributesSubTLV2 = new LinkedList<>();

    private final boolean c = llNodeAttributesSubTLV2.add(nodeFlagBitsTlv2);
    private final boolean d = llNodeAttributesSubTLV2.add(iPv4TERouterIdOfLocalNodeTlv2);

    private final TENodeAttributesTlv tlv1 = TENodeAttributesTlv.of(llNodeAttributesSubTLV1);
    private final TENodeAttributesTlv sameAsTlv1 = TENodeAttributesTlv.of(llNodeAttributesSubTLV1);
    private final TENodeAttributesTlv tlv2 = TENodeAttributesTlv.of(llNodeAttributesSubTLV2);

    @Test
    public void basics() {
        new EqualsTester().addEqualityGroup(tlv1, sameAsTlv1).addEqualityGroup(tlv2).testEquals();
    }

}


text:
build: node_modules
	npm run postinstall
build-production: node_modules
	npm run bundle-production
node_modules:
	npm -s install
test: node_modules
	npm test
start:
	npm start
watch: node_modules
	npm run watch
.PHONY: test watch


text:
<?php

namespace Suplink\LinkBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Link
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Suplink\LinkBundle\Entity\LinkRepository")
 */
class Link
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="originalUrl", type="string", length=255)
     */
    private $originalUrl;

    /**
     * @var string
     *
     * @ORM\Column(name="tinyUrl", type="string", length=255)
     */
    private $tinyUrl;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateCreated", type="date")
     */
    private $dateCreated;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateModified", type="date")
     */
    private $dateModified;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean", nullable=true)
     */
    private $active;

    /**
     * @ORM\OneToMany(targetEntity="Suplink\LinkBundle\Entity\Stats", mappedBy="link")
     */
    protected $stats;

    /**
     * Author of the link
     *
     * @ORM\ManyToOne(targetEntity="Suplink\UserBundle\Entity\User")
     * @var User
     */
    protected $user;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Link
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set originalUrl
     *
     * @param string $originalUrl
     * @return Link
     */
    public function setOriginalUrl($originalUrl)
    {
        $this->originalUrl = $originalUrl;
        $uniqueshortlink = uniqid();
        $this->setTinyUrl($uniqueshortlink);
    }

    /**
     * Get originalUrl
     *
     * @return string
     */
    public function getOriginalUrl()
    {
        return $this->originalUrl;
    }

    /**
     * Set tinyUrl
     *
     * @param string $tinyUrl
     * @return Link
     */
    public function setTinyUrl($tinyUrl)
    {
        $this->tinyUrl = $tinyUrl;
        return $this;
    }

    /**
     * Get tinyUrl
     *
     * @return string
     */
    public function getTinyUrl()
    {
        return $this->tinyUrl;
    }

    /**
     * Set dateCreated
     *
     * @param \DateTime $dateCreated
     * @return Link
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;

        return $this;
    }

    /**
     * Get dateCreated
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * Set dateModified
     *
     * @param \DateTime $dateModified
     * @return Link
     */
    public function setDateModified($dateModified)
    {
        $this->dateModified = $dateModified;

        return $this;
    }

    /**
     * Get dateModified
     *
     * @return \DateTime
     */
    public function getDateModified()
    {
        return $this->dateModified;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return Link
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * Set user
     *
     * @param \Suplink\UserBundle\Entity\User $user
     * @return Link
     */
    public function setUser(\Suplink\UserBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Suplink\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    public function createdAt()
    {

    }

    public function __construct(){
        $this->stats = new ArrayCollection();
        $this->dateCreated = new \DateTime('now');
        $this->dateModified = new \DateTime('now');
        $this->active = true;

    }

    /**
     * Add stats
     *
     * @param \Suplink\LinkBundle\Entity\Stats $stats
     * @return Link
     */
    public function addStat(\Suplink\LinkBundle\Entity\Stats $stats)
    {
        $this->stats[] = $stats;

        return $this;
    }

    /**
     * Remove stats
     *
     * @param \Suplink\LinkBundle\Entity\Stats $stats
     */
    public function removeStat(\Suplink\LinkBundle\Entity\Stats $stats)
    {
        $this->stats->removeElement($stats);
    }

    /**
     * Get stats
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getStats()
    {
        return $this->stats;
    }
}


text:
/* The compiler was failing to adjust pointer dereferences into array
   references after propagating &equot[0] into p.  */

/* { dg-do compile } */
/* { dg-options "-O -ftree-dominator-opts" } */

static unsigned short equot[(6 +3)];
int
foo (num)
     unsigned short num[];
{
  unsigned short *p = &equot[0];
  *p++ = num[0];
  *p++ = num[1];
}


text:
package com.zxy.tiny.core;

import android.net.Uri;
import android.text.TextUtils;

import com.zxy.tiny.common.TinyException;
import com.zxy.tiny.common.UriUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by zhengxiaoyong on 2017/4/1.
 */
public class HttpUrlConnectionFetcher {

    private static final int MAX_REDIRECTS = 5;

    private static final int HTTP_TEMPORARY_REDIRECT = 307;

    private static final int HTTP_PERMANENT_REDIRECT = 308;

    private static final int TIMEOUT = 10000;

    static {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{new TinyTrustManager()}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            //do not verify
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    //for google store reject,see https://support.google.com/faqs/answer/7188426.
                    return !"www.abcdefgzxy.com".equalsIgnoreCase(hostname);
                }
            });
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            //ignore...
        }
    }

    public static void fetch(String url, ResponseCallback callback) {
        if (TextUtils.isEmpty(url))
            return;
        Uri uri = Uri.parse(url);
        fetch(uri, callback);
    }

    public static void fetch(Uri uri, ResponseCallback callback) {
        if (!UriUtil.isNetworkUri(uri))
            return;

        HttpURLConnection connection = null;
        InputStream is = null;

        connection = obtainHttpURLConnection(uri, MAX_REDIRECTS);

        if (connection == null)
            return;
        try {
            is = connection.getInputStream();
            if (callback != null)
                callback.callback(is);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    //ignore...
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static HttpURLConnection obtainHttpURLConnection(Uri uri, int maxRedirects) {
        if (uri == null)
            return null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri.toString());
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode >= HttpURLConnection.HTTP_OK &&
                    responseCode < HttpURLConnection.HTTP_MULT_CHOICE)
                return connection;

            if (isHttpRedirect(responseCode)) {
                String nextUriString = connection.getHeaderField("Location");
                connection.disconnect();
                Uri nextUri = nextUriString == null ? null : Uri.parse(nextUriString);
                String originalScheme = uri.getScheme();
                if (maxRedirects > 0 && nextUri != null && !nextUri.getScheme().equals(originalScheme)) {
                    return obtainHttpURLConnection(nextUri, maxRedirects - 1);
                } else {
                    String message = maxRedirects == 0
                            ? "URL %s follows too many redirects, uri:" + uri.toString()
                            : "URL %s returned %d without a valid redirect, uri:" + uri.toString() + ", responseCode:" + responseCode;
                    throw new TinyException.NetworkIOException(message);
                }
            } else {
                connection.disconnect();
                connection = null;
            }

        } catch (MalformedURLException e) {
            connection = null;
            e.printStackTrace();
        } catch (IOException e) {
            connection = null;
            e.printStackTrace();
        } catch (Exception e) {
            connection = null;
            e.printStackTrace();
        }
        return connection;
    }

    private static boolean isHttpRedirect(int responseCode) {
        switch (responseCode) {
            case HttpURLConnection.HTTP_MULT_CHOICE:
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMPORARY_REDIRECT:
            case HTTP_PERMANENT_REDIRECT:
                return true;
            default:
                return false;
        }
    }

    /**
     * Trust all certificates.
     */
    private static final class TinyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                chain[0].checkValidity();
            } catch (Exception e) {
                throw new CertificateException("Certificate not valid or trusted.");
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public interface ResponseCallback {

        void callback(InputStream is);

    }

}


text:
from zerver.lib.test_classes import WebhookTestCase

class RaygunHookTests(WebhookTestCase):
    STREAM_NAME = 'raygun'
    URL_TEMPLATE = "/api/v1/external/raygun?&api_key={api_key}&stream={stream}"
    FIXTURE_DIR_NAME = 'raygun'

    def test_status_changed_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
[Error](https://app.raygun.com/error-url) status changed to **Ignored** by Emma Cat:
* **Timestamp**: Wed Jan 28 01:49:36 1970
* **Application details**: [Best App](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('error_status_changed',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_comment_added_to_error_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
Anita Peacock commented on [Error](https://app.raygun.com/error-url):

``` quote
Ignoring these errors
```
* **Timestamp**: Wed Jan 28 01:49:36 1970
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('comment_added_to_error',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_error_assigned_to_user_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
Amy Loondon assigned [Error](https://app.raygun.com/error-url) to Kyle Kenny:
* **Timestamp**: Wed Jan 28 01:49:36 1970
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('error_assigned_to_user',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_one_minute_followup_error_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
One minute [follow-up error](http://app.raygun.io/error-url):
* **First occurred**: Wed Jan 28 01:49:36 1970
* **Last occurred**: Wed Jan 28 01:49:36 1970
* 1 users affected with 1 total occurrences
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('one_minute_followup_error',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_hourly_followup_error_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
Hourly [follow-up error](http://app.raygun.io/error-url):
* **First occurred**: Wed Jan 28 01:49:36 1970
* **Last occurred**: Wed Jan 28 01:49:36 1970
* 1 users affected with 1 total occurrences
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('hourly_followup_error',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_new_error_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
New [Error](http://app.raygun.io/error-url) occurred:
* **First occurred**: Wed Jan 28 01:49:36 1970
* **Last occurred**: Wed Jan 28 01:49:36 1970
* 1 users affected with 1 total occurrences
* **Tags**: test, error-page, v1.0.1, env:staging
* **Affected user**: a9b7d8...33846
* **pageName**: Error Page
* **userLoggedIn**: True
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('new_error',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def test_reoccurred_error_message(self) -> None:
        expected_topic = u"test"
        expected_message = """
[Error](http://app.raygun.io/error-url) reoccurred:
* **First occurred**: Wed Jan 28 01:49:36 1970
* **Last occurred**: Wed Jan 28 01:49:36 1970
* 1 users affected with 1 total occurrences
* **Tags**: test, error-page, v1.0.1, env:staging
* **Affected user**: a9b7d8...33846
* **pageName**: Error Page
* **userLoggedIn**: True
* **Application details**: [application name](http://app.raygun.io/application-url)
""".strip()

        self.send_and_test_stream_message('reoccurred_error',
                                          expected_topic,
                                          expected_message,
                                          content_type=
                                          "application/x-www-form-urlencoded")

    def get_body(self, fixture_name: str) -> str:
        return self.webhook_fixture_data("raygun", fixture_name, file_type="json")


text:
module('confusion')
output('../temp')
config(checkTypes=True)

entryPoint('beConfused', inst('bool'))
entryPoint('beConfusedSite', inst('bool'))
entryPoint('beConfusedConst', inst('int'))

entryPoint('confuseMethods', inst('int'), inst('int'), inst('int'), inst('int'), inst('int'), inst('int'))


text:
package org.jtheque.resources.impl;

import org.jtheque.resources.Resource;
import org.jtheque.utils.annotations.Immutable;
import org.jtheque.utils.bean.Version;

/**
 * A resource implementation.
 *
 * @author Baptiste Wicht
 */
@Immutable
public final class ResourceImpl implements Resource {
    private final String id;
    private final Version version;
    private final String url;
    private final String file;
    private final boolean library;

    /**
     * Construct a new ResourceImpl.
     *
     * @param id      The id of the resource.
     * @param version The version of the resource set.
     * @param url     The url of the resource set.
     * @param file    The file of the resource.
     * @param library The library of the resource.
     */
    public ResourceImpl(String id, Version version, String url, String file, boolean library) {
        super();

        this.id = id;
        this.version = version;
        this.url = url;
        this.file = file;
        this.library = library;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public Version getVersion() {
        return version;
    }

    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public String getFile() {
        return file;
    }

    @Override
    public boolean isLibrary() {
        return library;
    }
}


text:
package org.apache.druid.guice;

import com.fasterxml.jackson.databind.Module;
import com.google.inject.Binder;
import org.apache.druid.initialization.DruidModule;

import java.util.Collections;
import java.util.List;

public class BloomFilterExtensionModule implements DruidModule
{

  @Override
  public List<? extends Module> getJacksonModules()
  {
    return Collections.singletonList(new BloomFilterSerializersModule());
  }

  @Override
  public void configure(Binder binder)
  {

  }
}


text: A basic pixel editor for the MacOS


text:
module.exports = (router) => {
  const Controller = require('./tokens.controller')
  const controller = new Controller()

  router.post('/tokens', (req, res) => controller.post(req, res))
  router.delete('/tokens', (req, res) => controller.delete(req, res))

  return router
}


text:
package monitor

import (
	"errors"
	"regexp"
	"time"

	cfclient "github.com/cloudfoundry-community/go-cfclient"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

var _ = Describe("Monitor", func() {
	var (
		taskRatePerSecond int64
		targetReliability float64
	)

	BeforeEach(func() {
		taskRatePerSecond = 20
		targetReliability = 99.95
	})

	Context("When a task is registered", func() {
		It("should handle successful runs", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)
			monitor.Add("test", func(cfg *cfclient.Config) error {
				<-time.After(1 * time.Second)
				return nil
			})
			time.AfterFunc(3*time.Second, func() {
				monitor.Stop()
			})
			report := monitor.Run()

			Eventually(report.SuccessCount, 4*time.Second).Should(BeNumerically(">", 0))
			Eventually(report.FailureCount, 4*time.Second).Should(Equal(int64(0)))
			Eventually(report.WarningCount, 4*time.Second).Should(Equal(int64(0)))
		})

		It("should handle errors", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)
			monitor.Add("test", func(cfg *cfclient.Config) error {
				<-time.After(1 * time.Second)
				return errors.New("some error")
			})
			time.AfterFunc(3*time.Second, func() {
				monitor.Stop()
			})
			report := monitor.Run()

			Eventually(report.SuccessCount, 4*time.Second).Should(Equal(int64(0)))
			Eventually(report.FailureCount, 4*time.Second).Should(BeNumerically(">", 0))
			Eventually(report.WarningCount, 4*time.Second).Should(Equal(int64(0)))
		})

		It("should handle specific errors as warning", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2,
				[]*regexp.Regexp{regexp.MustCompile("this is a warning")},
				taskRatePerSecond, targetReliability,
			)
			monitor.Add("test", func(cfg *cfclient.Config) error {
				<-time.After(1 * time.Second)
				return errors.New("foo, this is a warning, bar")
			})
			time.AfterFunc(3*time.Second, func() {
				monitor.Stop()
			})
			report := monitor.Run()

			Eventually(report.SuccessCount, 4*time.Second).Should(Equal(int64(0)))
			Eventually(report.FailureCount, 4*time.Second).Should(Equal(int64(0)))
			Eventually(report.WarningCount, 4*time.Second).Should(BeNumerically(">", 0))
		})
	})

	Context("Rate limiting", func() {
		It("should limit the rate by which tasks are added to the queue", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)
			monitor.Add("consume as fast as possible", func(cfg *cfclient.Config) error {
				return nil
			})
			time.AfterFunc(3*time.Second, func() {
				monitor.Stop()
			})
			report := monitor.Run()

			expectedTaskLimit := taskRatePerSecond * 3

			Expect(report.SuccessCount).To(BeNumerically("<", expectedTaskLimit))
		})
	})

	Context("Acceptance or failure", func() {
		It("should fail if the targetReliability is not set", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, 0.0,
			)

			Expect(monitor.HaveTestsPassed(Review{})).To(Equal(false))
		})

		It("should fail if the tests have not run", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 0, WarningCount: 0, FailureCount: 0,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(false))
		})

		It("should fail if there are no successes", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 0, WarningCount: 7, FailureCount: 9,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(false))
		})

		It("should pass if there are no failures", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 1, WarningCount: 0, FailureCount: 0,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(true))
		})

		It("should pass if there are some warnings", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 5000, WarningCount: 2, FailureCount: 0,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(true))
		})

		It("should pass if there are some failures", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 5000, WarningCount: 0, FailureCount: 2,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(true))
		})

		It("should pass if there are bad executions", func() {
			monitor := NewMonitor(
				&cfclient.Config{}, GinkgoWriter, 2, []*regexp.Regexp{},
				taskRatePerSecond, targetReliability,
			)

			report := Review{
				SuccessCount: 5000, WarningCount: 1, FailureCount: 1,
			}

			Expect(monitor.HaveTestsPassed(report)).To(Equal(true))
		})
	})
})


text:
//================ Copyright (c) 2014, PG, All rights reserved. =================//
//
// Purpose:		handles multiple window interactions
//
// $NoKeywords: $
//===============================================================================//

#include "CWindowManager.h"

#include "Engine.h"
#include "ResourceManager.h"
#include "CBaseUIWindow.h"

CWindowManager::CWindowManager()
{
	m_bVisible = true;
	m_bEnabled = true;
	m_iLastEnabledWindow = 0;
	m_iCurrentEnabledWindow = 0;
}

CWindowManager::~CWindowManager()
{
	for (size_t i=0; i<m_windows.size(); i++)
	{
		delete m_windows[i];
	}
}

void CWindowManager::draw(Graphics *g)
{
	if (!m_bVisible) return;

	for (int i=m_windows.size()-1; i>=0; i--)
	{
		m_windows[i]->draw(g);
	}

	/*
	for (size_t i=0; i<m_windows.size(); i++)
	{
		UString text = UString::format(" -%i-  ", i);
		text.append(m_windows[i]->getName());
		g->pushTransform();
			g->translate(20, i*40+350);
			g->drawString(engine->getResourceManager()->getFont("FONT_DEFAULT"), text);
		g->popTransform();
	}

	g->pushTransform();
	g->translate(20, 500);
	g->drawString(engine->getResourceManager()->getFont("FONT_DEFAULT"), UString::format("currentEnabled = %i, lastEnabled = %i, topIndex = %i", m_iCurrentEnabledWindow, m_iLastEnabledWindow, getTopMouseWindowIndex()));
	g->popTransform();
	*/
}

void CWindowManager::update()
{
	if (!m_bVisible || m_windows.size() == 0) return;

	// update all windows, detect depth changes
	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->update();
	}
	int topMouseWindowIndex = getTopMouseWindowIndex();

	// don't event think about switching if we are disabled
	if (!m_bEnabled)
		return;

	// TODO: the logic here is fucked
	// if the topmost window isn't doing anything, we may be switching
	if (!m_windows[0]->isBusy())
	{
		if (topMouseWindowIndex < m_windows.size())
			m_iCurrentEnabledWindow = topMouseWindowIndex;

		// enable the closest window under the cursor on a change, disable the others
		if (m_iCurrentEnabledWindow != m_iLastEnabledWindow)
		{
			m_iLastEnabledWindow = m_iCurrentEnabledWindow;
			if (m_iLastEnabledWindow < m_windows.size())
			{
				m_windows[m_iLastEnabledWindow]->setEnabled(true);
				//debugLog("enabled %s @%f\n", m_windows[m_iLastEnabledWindow]->getName().toUtf8(), engine->getTime());
				for (size_t i=0; i<m_windows.size(); i++)
				{
					if (i != m_iLastEnabledWindow)
						m_windows[i]->setEnabled(false);
				}
			}
		}

		// now check if we have to switch any windows
		bool topSwitch = false;
		int newTop = 0;
		for (size_t i=0; i<m_windows.size(); i++)
		{
			if (m_windows[i]->isBusy() && !topSwitch)
			{
				topSwitch = true;
				newTop = i;
			}
		}

		// switch top window to m_windows[0], all others get pushed down
		if (topSwitch && newTop != 0)
		{
			//debugLog("top switch @%f\n", engine->getTime());
			if (m_windows.size() > 1)
			{
				CBaseUIWindow *newTopWindow = m_windows[newTop];
				newTopWindow->setEnabled(true);

				for (int i=newTop-1; i>=0; i--)
				{
					m_windows[i+1] = m_windows[i];
				}

				m_windows[0] = newTopWindow;
				m_iCurrentEnabledWindow = m_iLastEnabledWindow = 0;
			}
		}
	}
}

int CWindowManager::getTopMouseWindowIndex()
{
	int tempEnabledWindow = m_windows.size()-1;
	for (size_t i=0; i<m_windows.size(); i++)
	{
		if (m_windows[i]->isMouseInside() && i < tempEnabledWindow)
			tempEnabledWindow = i;
	}
	return tempEnabledWindow;
}

void CWindowManager::addWindow(CBaseUIWindow *window)
{
	if (window == NULL)
		engine->showMessageError("Window Manager Error", "addWindow(NULL), you maggot!");

	m_windows.insert(m_windows.begin(), window);

	// disable all other windows
	for (size_t i=1; i<(int)(m_windows.size()-1); i++)
	{
		m_windows[i]->setEnabled(false);
	}
}

void CWindowManager::onResolutionChange(Vector2 newResolution)
{
	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->onResolutionChange(newResolution);
	}
}

void CWindowManager::setFocus(CBaseUIWindow *window)
{
	if (window == NULL)
		engine->showMessageError("Window Manager Error", "setFocus(NULL), you noodle!");

	for (int i=0; i<m_windows.size(); i++)
	{
		if (m_windows[i] == window && i != 0)
		{
			CBaseUIWindow *newTopWindow = m_windows[i];
			for (int i2=i-1; i2>=0; i2--)
			{
				m_windows[i2+1] = m_windows[i2];
			}
			m_windows[0] = newTopWindow;
			break;
		}
	}
}

void CWindowManager::openAll()
{
	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->open();
	}
}

void CWindowManager::closeAll()
{
	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->close();
	}
}

bool CWindowManager::isMouseInside()
{
	for (size_t i=0; i<m_windows.size(); i++)
	{
		if (m_windows[i]->isMouseInside())
			return true;
	}
	return false;
}

bool CWindowManager::isVisible()
{
	if (!m_bVisible)
		return false;

	for (size_t i=0; i<m_windows.size(); i++)
	{
		if (m_windows[i]->isVisible())
			return true;
	}
	return false;
}

bool CWindowManager::isActive()
{
	if (!m_bVisible)
		return false;
	for (size_t i=0; i<m_windows.size(); i++)
	{
		if (m_windows[i]->isActive() || m_windows[i]->isBusy()) // TODO: is this correct? (busy)
			return true;
	}
	return false;
}

void CWindowManager::onKeyDown(KeyboardEvent &e)
{
	if (!m_bVisible) return;

	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->onKeyDown(e);
	}
}

void CWindowManager::onKeyUp(KeyboardEvent &e)
{
	if (!m_bVisible) return;

	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->onKeyUp(e);
	}
}

void CWindowManager::onChar(KeyboardEvent &e)
{
	if (!m_bVisible) return;

	for (size_t i=0; i<m_windows.size(); i++)
	{
		m_windows[i]->onChar(e);
	}
}

void CWindowManager::setEnabled(bool enabled)
{
	m_bEnabled = enabled;
	if (!m_bEnabled)
	{
		for (size_t i=0; i<m_windows.size(); i++)
		{
			m_windows[i]->setEnabled(false);
		}
	}
	else
		m_windows[m_iCurrentEnabledWindow]->setEnabled(true);
}


text:
"""
This class is inspired by the Black Knight scene in the movie
"Monty Python and the Holy Grail", where King Arthur fights the
Black Knight, slicing off his arms and legs, but the knight
refuses to concede defeat.

# BEGIN BLACK_KNIGHT_DEMO
    >>> knight = BlackKnight()
    >>> knight.member
    next member is:
    'an arm'
    >>> del knight.member
    BLACK KNIGHT (loses an arm)
    -- 'Tis but a scratch.
    >>> del knight.member
    BLACK KNIGHT (loses another arm)
    -- It's just a flesh wound.
    >>> del knight.member
    BLACK KNIGHT (loses a leg)
    -- I'm invincible!
    >>> del knight.member
    BLACK KNIGHT (loses another leg)
    -- All right, we'll call it a draw.

# END BLACK_KNIGHT_DEMO
"""

# BEGIN BLACK_KNIGHT
class BlackKnight:

    def __init__(self):
        self.members = ['an arm', 'another arm',
                        'a leg', 'another leg']
        self.phrases = ["'Tis but a scratch.",
                        "It's just a flesh wound.",
                        "I'm invincible!",
                        "All right, we'll call it a draw."]

    @property
    def member(self):
        print('next member is:')
        return self.members[0]

    @member.deleter
    def member(self):
        text = 'BLACK KNIGHT (loses {})\n-- {}'
        print(text.format(self.members.pop(0), self.phrases.pop(0)))
# END BLACK_KNIGHT


text:
namespace DapperTest.Models.Domain
{
    public class SubProduct : DomainBase
    {
        public string Name { get; set; }
    }
}


text:
SET DEFINE OFF;
ALTER TABLE AFW_20_MODL_PARMT ADD (
  CONSTRAINT AFW_20_MODL_PARMT_FK1
  FOREIGN KEY (REF_MODL)
  REFERENCES AFW_20_MODL (SEQNC)
  ON DELETE CASCADE
  ENABLE VALIDATE)
/