text:
"""Defused xml.dom.pulldom
"""
from __future__ import print_function, absolute_import

from xml.dom.pulldom import parse as _parse
from xml.dom.pulldom import parseString as _parseString
from .sax import make_parser

__origin__ = "xml.dom.pulldom"

def parse(stream_or_string, parser=None, bufsize=None, forbid_dtd=False,
          forbid_entities=True, forbid_external=True):
    if parser is None:
        parser = make_parser()
        parser.forbid_dtd = forbid_dtd
        parser.forbid_entities = forbid_entities
        parser.forbid_external = forbid_external
    return _parse(stream_or_string, parser, bufsize)

def parseString(string, parser=None, forbid_dtd=False,
                forbid_entities=True, forbid_external=True):
    if parser is None:
        parser = make_parser()
        parser.forbid_dtd = forbid_dtd
        parser.forbid_entities = forbid_entities
        parser.forbid_external = forbid_external
    return _parseString(string, parser)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="styles/base.css" type="text/css" rel="stylesheet">
    <link href="styles/layout.css" type="text/css" rel="stylesheet">
    <link href="styles/modules.css" type="text/css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

    <title>Rosemary Tuttle's Website</title>

A Glimpse Into My Background

Home

About

Projects

Welcome to my home page!

Where to reach me:

Email: rosemary.brinton@gmail.com

Phone: 208-818-4893

Location: Seattle, WA

© Rosemary Tuttle Portfolio

I grew up in Coeur d' Alene, Idaho for 18 years, and I went to college at the University of Montana in Missoula, MT. There, I studied Business-Finance for four years, and I met my husband, Phil.

We moved to Denver, CO and we lived there for four years. I audited mortgage-backed securities, and then we moved to Seattle due to Phil pursuing a job at Eddie Bauer. I worked in commercial lending for a year at two different banks; however, I decided I needed a change from the financial industry. I got a job as a Product Data Specialist at C.C. Filson doing product data management and data analytics.

 I decided to pursue Web Development as my next professional chapter in life, and I am currently learning these skills during evenings at Code Fellows in Seattle.

My hobbies include anything outdoors: primarily snowboarding, skiing, hiking, biking, camping, backpacking, wakeboarding, swimming, kayaking, etc. I also enjoy ballet, yoga, jogging, and living a healthy, fit lifestyle in general. Causes I care about inculde: the environment, equal rights, civil rights, and more.

redpajama_set_name: RedPajamaGithub


text:
package com.zfgc.model.pm;

import java.util.List;

import com.zfgc.model.BaseZfgcModel;
import com.zfgc.model.users.Users;

public class PmTemplateConfig extends BaseZfgcModel{

	private Integer pmConversationId;
	private String subject;
	private List<Integer> receivers;

	@Override
	public String getHMAC() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Integer> getReceivers() {
		return receivers;
	}

	public void setReceivers(List<Integer> receivers) {
		this.receivers = receivers;
	}

	public Integer getPmConversationId() {
		return pmConversationId;
	}

	public void setPmConversationId(Integer pmConversationId) {
		this.pmConversationId = pmConversationId;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

}


text:
package org.cgfork.tools.common.component;

import javax.inject.Named;

/**
 * @author cgfork
 * @since 1.0.0
 */
@Named("testCaseImpl")
public class ComponentCaseImplCopy implements ComponentCase {
    @Override
    public String getCaseName() {
        return "testCaseImplCopy";
    }
}


text:
With the [Database](./Tools/Database.cs) interface representing the sample database, implement the following projections:

1. Detailed view of the shopping cart:
    - total amount of products in the basket,
    - total number of products
    - list of products (e.g. if someone added the same product twice, then we should have one element with the sum).
2. View with short information about pending shopping carts. It's intended to be used as list view for administration:
    - total amount of products in the basket,
    - total number of products
    - confirmed and canceled shopping carts should not be visible.

Add event handlers registrations in [ProjectionsTests](ProjectionsTests.cs) calling [EventBus.Register](./Tools/EventBus.cs) method.

Track and implement proper idempotency and eventual consistency handling in projection event handlers.

## Solutions

Read more in my articles:
- [Dealing with Eventual Consistency and Idempotency in MongoDB projections](https://event-driven.io/en/dealing_with_eventual_consistency_and_idempotency_in_mongodb_projections/?utm_source=event_sourcing_net_workshop)
- [A simple trick for idempotency handling in the Elastic Search read model](https://event-driven.io/en/simple_trick_for_idempotency_handling_in_elastic_search_readm_model/?utm_source=event_sourcing_net_workshop)


text:
#ifndef BSFM_DEPTH_MAP_H
#define BSFM_DEPTH_MAP_H

#include <utils/image/image.h>
#include <Eigen/Dense>

using Eigen::Vector3d;

namespace bsfm {

  class DepthMap : public Image {
  public:
    using Image::Image;

    // Constructors.
    DepthMap();
    DepthMap(bool inverted);

    // Helpers.
    Vector3d Unproject(size_t u, size_t v) const;
    bool SaturatedAt(size_t u, size_t v) const;

    // Setters.
    void SetInverted(bool value);

    // Getters.
    uchar GetValue(size_t u, size_t v) const;
    bool IsInverted() const;

  private:
    bool inverted_;
  }; //\ class DepthMap

  // ------------------------- IMPLEMENTATION --------------------------------

  DepthMap::DepthMap()
    : inverted_(false) {}

  DepthMap::DepthMap(bool inverted)
    : inverted_(inverted) {}

  void DepthMap::SetInverted(bool value) {
    inverted_ = value;
  }

  bool DepthMap::IsInverted() const {
    return inverted_;
  }

  uchar DepthMap::GetValue(size_t u, size_t v) const {
    uchar value = at<uchar>(v, u * 3);
    if (IsInverted()) {
        value = 255 - value;
    }
    return value;
  }

  Vector3d DepthMap::Unproject(size_t u, size_t v) const {
    // @TODO jds: Need to load these from a parameter or something
    double focal_length_x = 248.9;
    double focal_length_y = 247.6;

    double z = GetValue(u, v);
    double x = (u - Width() / 2.0) * z / focal_length_x;
    double y = (v - Height() / 2.0) * z / focal_length_y;

    Vector3d point = Vector3d(x, y, z);
    return point;
  }

  bool DepthMap::SaturatedAt(size_t u, size_t v) const {
    return GetValue(u, v) <= 0 || GetValue(u, v) >= 255;
  }

} //\ namespace bsfm

#endif


text:
import json
import requests
import urllib
from oauthlib import oauth1

class YBossResult(dict):
    """
    A dictionary that answers to attribute lookups
    result["url"] returns the same as result.url
    """

    def __getattr__(self, name):
        return self[name]

class YBossResponse(object):
    """
    Aggregates a list of YBossResult
    """

    def __init__(self, result=None, service="limitedweb"):
        result = result or {}
        self.results = []
        self.bossresponse = result.get('bossresponse', {})
        self.responsecode = self.bossresponse.get('responsecode')
        self.web = self.bossresponse.get(service, {})

        for k, v in self.web.iteritems():
            setattr(self, k, v)

    def __iter__(self):
        for result in self.results:
            yield YBossResult(result)

    def next(self):
        if not self.results:
            raise StopIteration
        return YBossResult(self.results.pop())

    def __len__(self):
        return len(self.results)

    def __getitem__(self, index):
        return YBossResult(self.results[index])

    def objects(self):
        return [YBossResult(result) for result in self.results]

class YBoss(object):
    """
    .: methods.
        __init__
        .: params
            key
            secret
            service = "limitedweb, web"
        search
        .: params.
            q = "string term"
            abstract = "long"
            style = "raw"
            type = "html, text"
            title = "some title"

    >>> from yboss import YBoss
    >>> boss = YBoss(key=key, secret=secret)
    >>> results = boss.search("Solar Filter")
    >>> for result in results:
    ...     print result
    {u"abstract": "...long text...",
     u"clickurl":"http://...",
     u"clickurl":"http://...",
     u"date": "",
     u"title": u"Solar Filter page etc..",
     u"url": "http://....."}
    >>> print result.url
    u"http://....."

    """

    def __init__(self, key, secret, service="limitedweb"):
        """
        Register on Yahoo Boss API to get key and secret
        """
        self.key = key
        self.secret = secret
        self.service = service
        self.base_url = 'http://yboss.yahooapis.com/ysearch/'

    def authenticate(self, url):
        """
        Each url call must be authenticated individually
        """
        client = oauth1.Client(self.key, client_secret=self.secret)
        self.uri, self.headers, self.body = client.sign(url)
        return self.headers

    def search(self, q, **kwargs):
        """
        Any keyed argument passed to .search is directly
        converted to querystring parameters in YBoss API
        Search filters must be passed together with search query (q)
        look: http://www.searchengineshowdown.com/features/yahoo/
        """
        if isinstance(q, unicode):
            q = q.encode("utf-8")

        params = {"q": q}
        params.update(kwargs)
        url = "{base_url}{service}?{params}".format(
            base_url=self.base_url,
            service=self.service,
            params=urllib.urlencode(params)
        ).replace("+", "%20")
        # Yboss API does not allow the use of + in urls
        response = requests.get(
            url,
            headers=self.authenticate(url)
        )

        if response.status_code >= 400:
            return YBossResponse(
                {
                    "error": True,
                    "status_code": response.status_code,
                    "content": response.content
                },
                service=self.service
            )

        return YBossResponse(
            json.loads(response.content),
            service=self.service
        )


text:
module MyMoip
  class Error < StandardError;      end

  class InvalidComission < Error;   end

  class InvalidCreditCard < Error;  end

  class InvalidInstruction < Error; end

  class InvalidPayer < Error;       end

  class InvalidPaymentSlip < Error; end

  class InvalidBankDebit < Error;   end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CivilOctave: sage Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

CivilOctave

Main Page

Related Pages

Packages

Files

Packages

Package Functions

Namespaces

sage Namespace Reference

Namespaces

  	settings

 	Django settings for sage project.

  	urls

 	This module contain urlspatterns to map to civilsage.urls in django.

  	wsgi

<address class="footer">
Generated on Fri Dec 18 2015 17:44:38 for CivilOctave by

 1.8.11
</address>


text:
<?php

include 'functions.php';

header("Content-type: text/xml");

/**
 * Let's call this 'educated call forwarding' and combine it with the voicemail example
 *
 * There are some people - like maybe a boss or high value customer - that
 *   should ring through every time while other people get voice mail
 *   automatically at certain times.
 */

$whitelist = array('17035551212', '12025551212');

$from = preg_replace("/[^0-9]/", "", $_POST['From']);

$allowed = is_allowed($from, $whitelist, 7, 15);

$response = new Services_Twilio_Twiml();

if ($allowed) {
    $response->dial($toPhone);
} else {
    $response->say("I'm sorry, $name is not available at this time. Please leave a message after the tone.");
    $response->record(array(
        'transcribeCallback' => 'rev2-transcribed.php?From=' . $from,
        // Note: since we used transcribeCallback, 'transcribe' => 'true' is assumed
    ));
}

print $response;


text:
using testing::Return;
using testing::_;

class CertificateManagerBrowserTest : public options::OptionsUIBrowserTest {
 public:
  CertificateManagerBrowserTest() {}
  virtual ~CertificateManagerBrowserTest() {}

 protected:
  virtual void SetUp() OVERRIDE {
#if defined(OS_CHROMEOS)
    policy::UserNetworkConfigurationUpdater::
        SetSkipCertificateImporterCreationForTest(true);
#endif
    options::OptionsUIBrowserTest::SetUp();
  }

  virtual void TearDown() OVERRIDE {
#if defined(OS_CHROMEOS)
    policy::UserNetworkConfigurationUpdater::
        SetSkipCertificateImporterCreationForTest(false);
#endif
    options::OptionsUIBrowserTest::TearDown();
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
#if defined(OS_CHROMEOS)
    device_policy_test_helper_.MarkAsEnterpriseOwned();
#endif
    // Setup the policy provider for injecting certs through ONC policy.
    EXPECT_CALL(provider_, IsInitializationComplete(_))
        .WillRepeatedly(Return(true));
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  }

  void SetUpOnIOThread() {
#if defined(OS_CHROMEOS)
    test_nssdb_.reset(new crypto::ScopedTestNSSDB());
#endif
  }

  void TearDownOnIOThread() {
#if defined(OS_CHROMEOS)
    test_nssdb_.reset();
#endif
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    content::BrowserThread::PostTask(
        content::BrowserThread::IO,
        FROM_HERE,
        base::Bind(&CertificateManagerBrowserTest::SetUpOnIOThread, this));

    content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
    content::RunAllPendingInMessageLoop();

#if defined(OS_CHROMEOS)
    // UserNetworkConfigurationUpdater's onc::CertificateImporter is usually
    // passed the NSSCertDatabase fetched during testing profile
    // constrution. Unfortunately, test database gets setup after that, so we
    // would end up with |PK11_GetInternalKeySlot|. The cause of this is in
    // |crypto::InitializeNSSForChromeOSUser|, which does not open new
    // database slot for primary user, but it just uses the singleton one (which
    // is not set in tests before |test_nssdb_| is created). To handle this,
    // creating certificate importer during the UserNetworkConfiguirationUpdater
    // service creation is set to be skipped (see |SetUp|), and cert importer
    // is set up here.
    // Note that creating |test_nssdb_| sooner (in SetUp) would break thread
    // restrictions, which require it to be used on IO thread only.
    // TODO(tbarzic): Update InitializeNSSForChromeOSUser not to special case
    // the primary user.
    GetNSSCertDatabaseForProfile(
        browser()->profile(),
        base::Bind(
            &CertificateManagerBrowserTest::UpdateNetworkConfigurationUpdater,
            base::Unretained(this)));

    content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
    content::RunAllPendingInMessageLoop();
#endif
  }

  virtual void CleanUpOnMainThread() OVERRIDE {
    content::BrowserThread::PostTask(
        content::BrowserThread::IO,
        FROM_HERE,
        base::Bind(&CertificateManagerBrowserTest::TearDownOnIOThread, this));
    content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
  }

#if defined(OS_CHROMEOS)
  void UpdateNetworkConfigurationUpdater(net::NSSCertDatabase* database) {
    policy::UserNetworkConfigurationUpdaterFactory::GetForProfile(
        browser()->profile())->SetCertificateImporterForTest(
            scoped_ptr<chromeos::onc::CertificateImporter>(
                new chromeos::onc::CertificateImporterImpl(database)));
  }

  void LoadONCPolicy(const std::string& filename) {
    const std::string& user_policy_blob =
        chromeos::onc::test_utils::ReadTestData(filename);
    policy::PolicyMap policy;
    policy.Set(policy::key::kOpenNetworkConfiguration,
               policy::POLICY_LEVEL_MANDATORY,
               policy::POLICY_SCOPE_USER,
               base::Value::CreateStringValue(user_policy_blob),
               NULL);
    provider_.UpdateChromePolicy(policy);
    content::RunAllPendingInMessageLoop();
  }
#endif

  void ClickElement(const std::string& selector) {
    EXPECT_TRUE(content::ExecuteScriptInFrame(
        browser()->tab_strip_model()->GetActiveWebContents(),
        "//div[@id='settings']/iframe",
        "document.querySelector(\"" + selector + "\").click()"));
  }

  bool HasElement(const std::string& selector) {
    bool result;
    EXPECT_TRUE(content::ExecuteScriptInFrameAndExtractBool(
        browser()->tab_strip_model()->GetActiveWebContents(),
        "//div[@id='settings']/iframe",
        "window.domAutomationController.send("
        "    !!document.querySelector('" + selector + "'));",
        &result));
    return result;
  }

  policy::MockConfigurationPolicyProvider provider_;
#if defined(OS_CHROMEOS)
  policy::DevicePolicyCrosTestHelper device_policy_test_helper_;
  scoped_ptr<crypto::ScopedTestNSSDB> test_nssdb_;
#endif
};

#if defined(OS_CHROMEOS)
// Ensure policy-installed certificates without web trust do not display
// the managed setting indicator (only on Chrome OS).

// Triggers a Blink ASSERT in Debug configurations: http://crbug.com/337102
#if !defined(NDEBUG)
#define MAYBE_PolicyCertificateWithoutWebTrustHasNoIndicator \
    DISABLED_PolicyCertificateWithoutWebTrustHasNoIndicator
#else
#define MAYBE_PolicyCertificateWithoutWebTrustHasNoIndicator \
    PolicyCertificateWithoutWebTrustHasNoIndicator
#endif
IN_PROC_BROWSER_TEST_F(CertificateManagerBrowserTest,
                       MAYBE_PolicyCertificateWithoutWebTrustHasNoIndicator) {
  LoadONCPolicy("certificate-authority.onc");
  NavigateToSettings();
  ClickElement("#certificatesManageButton");
  ClickElement("#ca-certs-nav-tab");
  EXPECT_FALSE(HasElement(".cert-policy"));
}
#endif

// Triggers a Blink ASSERT in Debug configurations: http://crbug.com/337102
#if defined(OS_CHROMEOS)
// Ensure policy-installed certificates with web trust display the
// managed setting indicator (only on Chrome OS).

// Triggers a Blink ASSERT in Debug configurations: http://crbug.com/337102
#if !defined(NDEBUG)
#define MAYBE_PolicyCertificateWithWebTrustHasIndicator \
    DISABLED_PolicyCertificateWithWebTrustHasIndicator
#else
#define MAYBE_PolicyCertificateWithWebTrustHasIndicator \
    PolicyCertificateWithWebTrustHasIndicator
#endif
IN_PROC_BROWSER_TEST_F(CertificateManagerBrowserTest,
                       MAYBE_PolicyCertificateWithWebTrustHasIndicator) {
  LoadONCPolicy("certificate-web-authority.onc");
  NavigateToSettings();
  ClickElement("#certificatesManageButton");
  ClickElement("#ca-certs-nav-tab");
  EXPECT_TRUE(HasElement(".cert-policy"));
}
#endif


text:
package strftime

import (
	"fmt"
	"sync"

	"github.com/pkg/errors"
)

// because there is no such thing was a sync.RWLocker
type rwLocker interface {
	RLock()
	RUnlock()
	sync.Locker
}

// SpecificationSet is a container for patterns that Strftime uses.
// If you want a custom strftime, you can copy the default
// SpecificationSet and tweak it
type SpecificationSet interface {
	Lookup(byte) (Appender, error)
	Delete(byte) error
	Set(byte, Appender) error
}

type specificationSet struct {
	mutable bool
	lock    rwLocker
	store   map[byte]Appender
}

// The default specification set does not need any locking as it is never
// accessed from the outside, and is never mutated.
var defaultSpecificationSet SpecificationSet

func init() {
	defaultSpecificationSet = newImmutableSpecificationSet()
}

func newImmutableSpecificationSet() SpecificationSet {
	// Create a mutable one so that populateDefaultSpecifications work through
	// its magic, then copy the associated map
	// (NOTE: this is done this way because there used to be
	// two struct types for specification set, united under an interface.
	// it can now be removed, but we would need to change the entire
	// populateDefaultSpecifications method, and I'm currently too lazy
	// PRs welcome)
	tmp := NewSpecificationSet()

	ss := &specificationSet{
		mutable: false,
		lock:    nil, // never used, so intentionally not initialized
		store:   tmp.(*specificationSet).store,
	}

	return ss
}

// NewSpecificationSet creates a specification set with the default specifications.
func NewSpecificationSet() SpecificationSet {
	ds := &specificationSet{
		mutable: true,
		lock:    &sync.RWMutex{},
		store:   make(map[byte]Appender),
	}
	populateDefaultSpecifications(ds)

	return ds
}

var defaultSpecifications = map[byte]Appender{
	'A': fullWeekDayName,
	'a': abbrvWeekDayName,
	'B': fullMonthName,
	'b': abbrvMonthName,
	'C': centuryDecimal,
	'c': timeAndDate,
	'D': mdy,
	'd': dayOfMonthZeroPad,
	'e': dayOfMonthSpacePad,
	'F': ymd,
	'H': twentyFourHourClockZeroPad,
	'h': abbrvMonthName,
	'I': twelveHourClockZeroPad,
	'j': dayOfYear,
	'k': twentyFourHourClockSpacePad,
	'l': twelveHourClockSpacePad,
	'M': minutesZeroPad,
	'm': monthNumberZeroPad,
	'n': newline,
	'p': ampm,
	'R': hm,
	'r': imsp,
	'S': secondsNumberZeroPad,
	'T': hms,
	't': tab,
	'U': weekNumberSundayOrigin,
	'u': weekdayMondayOrigin,
	'V': weekNumberMondayOriginOneOrigin,
	'v': eby,
	'W': weekNumberMondayOrigin,
	'w': weekdaySundayOrigin,
	'X': natReprTime,
	'x': natReprDate,
	'Y': year,
	'y': yearNoCentury,
	'Z': timezone,
	'z': timezoneOffset,
	'%': percent,
}

func populateDefaultSpecifications(ds SpecificationSet) {
	for c, handler := range defaultSpecifications {
		if err := ds.Set(c, handler); err != nil {
			panic(fmt.Sprintf("failed to set default specification for %c: %s", c, err))
		}
	}
}

func (ds *specificationSet) Lookup(b byte) (Appender, error) {
	if ds.mutable {
		ds.lock.RLock()
		defer ds.lock.RLock()
	}
	v, ok := ds.store[b]
	if !ok {
		return nil, errors.Errorf(`lookup failed: '%%%c' was not found in specification set`, b)
	}
	return v, nil
}

func (ds *specificationSet) Delete(b byte) error {
	if !ds.mutable {
		return errors.New(`delete failed: this specification set is marked immutable`)
	}

	ds.lock.Lock()
	defer ds.lock.Unlock()
	delete(ds.store, b)
	return nil
}

func (ds *specificationSet) Set(b byte, a Appender) error {
	if !ds.mutable {
		return errors.New(`set failed: this specification set is marked immutable`)
	}

	ds.lock.Lock()
	defer ds.lock.Unlock()
	ds.store[b] = a
	return nil
}


text:
/**
 *
 */
package net.violet.platform.datamodel.mock;

import net.violet.db.records.AbstractMockRecord;
import net.violet.platform.datamodel.MessageCounter;

public class MessageCounterMock extends AbstractMockRecord<MessageCounter, MessageCounterMock> implements MessageCounter {

	protected Integer rabbit_state;
	protected Integer w_o_nabcast;
	protected Integer w_nabcast;

	public MessageCounterMock(long inId, int inState, Integer inWNabcast) {
		super(inId);
		this.rabbit_state = inState;
		this.w_nabcast = inWNabcast;
	}

	public long getMessenger_id() {
		return getId();
	}

	public RABBIT_STATE getRabbit_state() {
		return RABBIT_STATE.getState(this.rabbit_state);
	}

	public Integer getW_nabcast() {
		return this.w_nabcast;
	}

	public Integer getW_o_nabcast() {
		return this.w_o_nabcast;
	}

	public void setRabbit_state(RABBIT_STATE rabbit_state) {
		this.rabbit_state = rabbit_state.getValue();
	}

	public void resetCount() {
		setRabbit_state(RABBIT_STATE.INVALIDE);
		setW_o_nabcast(0);
		setW_nabcast(0);
	}

	public void setW_nabcast(int w_nabcast) {
		this.w_nabcast = w_nabcast;
	}

	public void setW_o_nabcast(int inWONabcast) {
		this.w_o_nabcast = inWONabcast;
	}

	public void invalidateDecrement() {
		this.rabbit_state = RABBIT_STATE.INVALIDE.getValue();
		this.w_nabcast = null;
		this.w_o_nabcast = null;
	}

	public void invalidateIncrement() {
		// Récupération de l'état.
		if ((getRabbit_state() != RABBIT_STATE.INVALIDE) && (getRabbit_state() != RABBIT_STATE.MORE)) {
			// Tout est incorrect.
			this.rabbit_state = RABBIT_STATE.INVALIDE.getValue();
		}
		this.w_nabcast = null;
		this.w_o_nabcast = null;
	}

}


text:
from time import time
import os
from os.path import join
import utils
from buildercore import core, project, config, cloudformation, utils as core_utils
from buildercore.utils import first, remove_ordereddict, errcho, lfilter, lmap, isstr, ensure
from functools import wraps, partial
from pprint import pformat
import logging

LOG = logging.getLogger(__name__)

# http://stackoverflow.com/questions/1622943/timeit-versus-timing-decorator
def timeit(fn):
    @wraps(fn)
    def wrap(*args, **kw):
        ts = time()
        result = fn(*args, **kw)
        te = time()
        LOG.info('func:%r args:[%r, %r] took: %2.4f sec',
                 fn.__name__, args, kw, te - ts)
        return result
    return wrap

def deffile(fname):
    "returns the proper path to the given default file"
    return join(config.TEMP_PATH, fname)

def setdefault(fname, value):
    "writes the given value to the given default file"
    open(deffile(fname), 'w').write(value)

def requires_filtered_project(filterfn=None):
    def wrap1(func):
        @wraps(func)
        def wrap2(_pname=None, *args, **kwargs):
            pname = config.ENV['PROJECT'] or _pname # used by Vagrant ...?
            project_list = project.filtered_projects(filterfn)
            if not pname or not pname.strip() or pname not in project_list:
                # TODO:
                # if config.BUILDER_NON_INTERACTIVE:
                #    print('project name not found or not provided and input is disabled, cannot continue.')
                #    return
                pname = utils._pick("project", sorted(project_list), default_file=deffile('.project'))
            return func(pname, *args, **kwargs)
        return wrap2
    return wrap1

# pylint: disable=invalid-name
requires_project = requires_filtered_project(None)

def requires_aws_project_stack(*plist):
    if not plist:
        plist = [utils._pick("project", project.project_list(), default_file=deffile('.project'))]

    def wrap1(func):
        @wraps(func)
        def _wrapper(stackname=None, *args, **kwargs):
            region = utils.find_region(stackname)
            asl = core.active_stack_names(region)
            if not asl:
                print('\nno AWS stacks exist, cannot continue.')
                return

            def pname_startswith(stack):
                for pname in plist:
                    if stack.startswith(pname):
                        return stack
            asl = lfilter(pname_startswith, asl)
            if not stackname or stackname not in asl:
                stackname = utils._pick("stack", asl)
            return func(stackname, *args, **kwargs)
        return _wrapper
    return wrap1

def requires_aws_stack(func):
    """requires a stack to exist and will prompt if one was not provided."""
    @wraps(func)
    def call(*args, **kwargs):
        stackname = first(args) or config.ENV['INSTANCE']
        region = utils.find_region(stackname)
        if stackname:
            args = args[1:]
            return func(stackname, *args, **kwargs)
        # note: this assumes all stacks have an ec2 instance.
        asl = core.active_stack_names(region)
        if not asl:
            raise RuntimeError('\nno AWS stacks *in an active state* exist, cannot continue.')
        if not stackname or stackname not in asl:
            stackname = utils._pick("stack", asl, default_file=deffile('.active-stack'))
        args = args[1:]
        return func(stackname, *args, **kwargs)
    return call

def requires_aws_stack_template(func):
    """downloads the cloudformation JSON template and writes it to disk before calling wrapped function.
    assumes first argument to task is a `stackname`."""
    @wraps(func)
    def call(stackname, *args, **kwargs):
        stack_template_path = cloudformation.find_template_path(stackname)
        msg = "task requires cloudformation template to exist locally, but template not found and could not be downloaded: " + stack_template_path
        ensure(os.path.exists(stack_template_path), msg, utils.TaskExit)
        return func(stackname, *args, **kwargs)
    return call

def requires_steady_stack(func):
    @wraps(func)
    def call(*args, **kwargs):
        ss = core.steady_aws_stacks(utils.find_region())
        keys = lmap(first, ss)
        idx = dict(zip(keys, ss))
        helpfn = lambda pick: idx[pick][1]
        if not keys:
            print('\nno AWS stacks *in a steady state* exist, cannot continue.')
            return
        stackname = first(args) or config.ENV['INSTANCE']
        if not stackname or stackname not in keys:
            stackname = utils._pick("stack", sorted(keys), helpfn=helpfn, default_file=deffile('.active-stack'))
        return func(stackname, *args[1:], **kwargs)
    return call

def echo_output(func):
    "pretty-prints the return value of the task(s) being run to stdout"
    @wraps(func)
    def _wrapper(*args, **kwargs):
        res = func(*args, **kwargs)
        errcho('output:') # printing to stderr avoids corrupting structured data
        if isstr(res):
            print(res)
        else:
            print(pformat(remove_ordereddict(res)))
        return res
    return _wrapper

def format_output(default_output_format='json'):
    """like `echo_output`, but the output can be formatted in different ways, defaults to json.
    use 'python' to replicate `echo_output` without the leading 'output:' on stderr."""
    output_format_map = {
        'json': partial(core_utils.json_dumps, dangerous=True, indent=4),
        'yaml': core_utils.yaml_dumps,
        'python': pformat
    }

    def _wrap1(fn):
        @wraps(fn)
        def _wrap2(*args, **kwargs):
            output_format = default_output_format
            if 'output_format' in kwargs:
                output_format = kwargs.pop('output_format')
            ensure(output_format in output_format_map,
                   "unsupported output format %r: %s" % (str(output_format), ", ".join(output_format_map)))
            data = fn(*args, **kwargs)
            print(output_format_map[output_format](data))
            return data
        return _wrap2
    return _wrap1

# ---

def requires_stack_config(func):
    "ensures the given `stackname` exists in the known stack config"
    @wraps(func)
    def call(*args, **kwargs):
        stackname = first(args)  # or config.ENV['INSTANCE'] # preserve this? I can't see anything using it.
        ensure(stackname, "stack-config name required", utils.TaskExit)
        stack_list = project.stack_map()
        ensure(stackname in stack_list, "stack-config with name %r not found" % stackname, utils.TaskExit)
        return func(stackname, *args[1:], **kwargs)
    return call


text:
#include <modules/python3qt/python3qtmodule.h>  // for Python3QtModule

// Note: Need to put any python includes first since qt defines some "slots" macro
// which python also uses from some structs
#include <pybind11/cast.h>           // for arg
#include <pybind11/detail/common.h>  // for pybind11
#include <pybind11/detail/descr.h>   // for operator+
#include <pybind11/pybind11.h>       // for class_, module_, init
#include <pybind11/pytypes.h>        // for str, none, reinterp...

#include <inviwo/core/common/inviwoapplication.h>                     // IWYU pragma: keep
#include <inviwo/core/common/inviwomodule.h>                          // for InviwoModule
#include <inviwo/core/properties/fileproperty.h>                      // for FileProperty
#include <inviwo/core/properties/propertysemantics.h>                 // for PropertySemantics
#include <inviwo/core/properties/stringproperty.h>                    // for StringProperty
#include <inviwo/core/util/exception.h>                               // for Exception, Exceptio...
#include <inviwo/core/util/glmvec.h>                                  // for ivec2
#include <inviwo/core/util/settings/settings.h>                       // for Settings
#include <inviwo/core/util/sourcecontext.h>                           // for IVW_CONTEXT
#include <modules/python3qt/properties/pythonfilepropertywidgetqt.h>  // for PythonFilePropertyW...
#include <modules/python3qt/properties/pythonpropertywidgetqt.h>      // for PythonPropertyWidgetQt
#include <modules/python3qt/pythonmenu.h>                             // for PythonMenu
#include <modules/python3qt/pythonsyntaxhighlight.h>                  // for PythonSyntaxHighlight
#include <modules/qtwidgets/inviwoqtutils.h>                          // for toGLM, getApplicati...
#include <modules/qtwidgets/propertylistwidget.h>                     // for PropertyListWidget

#include <atomic>       // for atomic
#include <exception>    // for exception
#include <memory>       // for make_unique, unique...
#include <string>       // for string
#include <string_view>  // for string_view

#include <QByteArray>        // for QByteArray
#include <QCoreApplication>  // for QCoreApplication
#include <QFlags>            // for QFlags
#include <QInputDialog>      // for QInputDialog
#include <QLineEdit>         // for QLineEdit, QLineEdi...
#include <QMainWindow>       // for QMainWindow
#include <QString>           // for QString
#include <Qt>                // for MSWindowsFixedSizeD...
#include <glm/vec2.hpp>      // for vec<>::(anonymous)

namespace inviwo {

namespace {
pybind11::object prompt(std::string title, std::string message, std::string defaultResponse = "") {

    bool ok;
    QString text = QInputDialog::getText(nullptr, title.c_str(), message.c_str(), QLineEdit::Normal,
                                         defaultResponse.c_str(), &ok,
                                         Qt::WindowFlags() | Qt::MSWindowsFixedSizeDialogHint);
    if (ok && !text.isEmpty()) {
        return pybind11::str(text.toLocal8Bit().constData());
    } else if (ok) {
        return pybind11::str("");
    }
    return pybind11::none();
}
}  // namespace

Python3QtModule::Python3QtModule(InviwoApplication* app)
    : InviwoModule(app, "Python3Qt")
    , abortPythonEvaluation_{false}
    , menu_(std::make_unique<PythonMenu>(this, app)) {
    namespace py = pybind11;

    try {
        auto inviwopy = py::module::import("inviwopy");
        auto m = inviwopy.def_submodule("qt", "Qt dependent stuff");

        m.def("prompt", &prompt, py::arg("title"), py::arg("message"),
              py::arg("defaultResponse") = "");
        m.def("update", [this]() {
            QCoreApplication::processEvents();
            QCoreApplication::sendPostedEvents();
            if (abortPythonEvaluation_) {
                abortPythonEvaluation_ = false;
                throw PythonAbortException("Evaluation aborted");
            }
        });

        py::class_<PropertyListWidget>(m, "PropertyListWidget")
            .def(py::init([](InviwoApplication* app) {
                auto mainwin = utilqt::getApplicationMainWindow();
                auto plw = new PropertyListWidget(mainwin, app);
                plw->setFloating(true);
                return plw;
            }))
            .def("addProcessorProperties", &PropertyListWidget::addProcessorProperties)
            .def("removeProcessorProperties", &PropertyListWidget::removeProcessorProperties)
            .def_property("visible", &PropertyListWidget::isVisible,
                          &PropertyListWidget::setVisible)
            .def_property(
                "dimensions", [](const PropertyListWidget& w) { return utilqt::toGLM(w.size()); },
                [](PropertyListWidget& w, ivec2 dim) { w.resize(dim.x, dim.y); })
            .def_property(
                "position", [](const PropertyListWidget& w) { return utilqt::toGLM(w.pos()); },
                [](PropertyListWidget& w, ivec2 pos) { w.move(pos.x, pos.y); })

            .def("removeAndDeleteProcessorProperties",
                 &PropertyListWidget::removeAndDeleteProcessorProperties)

            .def("addPropertyWidgets", &PropertyListWidget::addPropertyWidgets)
            .def("removePropertyWidgets", &PropertyListWidget::removePropertyWidgets)
            .def("removeAndDeletePropertyWidgets",
                 &PropertyListWidget::removeAndDeletePropertyWidgets)

            .def("show", &PropertyListWidget::show)
            .def("hide", &PropertyListWidget::hide)
            .def("move", [](PropertyListWidget* w, int x, int y) { w->move(x, y); });

    } catch (const std::exception& e) {
        throw ModuleInitException(e.what(), IVW_CONTEXT);
    }

    registerSettings(std::make_unique<PythonSyntaxHighlight>());

    registerPropertyWidget<PythonFilePropertyWidgetQt, FileProperty>(
        PropertySemantics::PythonEditor);
    registerPropertyWidget<PythonPropertyWidgetQt, StringProperty>(PropertySemantics::PythonEditor);
}

Python3QtModule::~Python3QtModule() = default;

void Python3QtModule::abortPythonEvaluation() { abortPythonEvaluation_ = true; }

PythonAbortException::PythonAbortException(const std::string& message, ExceptionContext context)
    : Exception(message, context) {}

}  // namespace inviwo


text:
<?php

namespace EasyForms\Elements;

use EasyForms\View\ElementView;

class Password extends Input
{
    /** @var array */
    protected $attributes = [
        'type' => 'password',
    ];

    /**
     * Clear value before rendering
     *
     * @param ElementView $view = null
     * @return \Forms\View\ElementView
     */
    public function buildView(ElementView $view = null)
    {
        $this->setValue('');

        return parent::buildView();
    }
}


text:
using FluentValidation.AspNetCore;
using LMS.Data;
using LMS.Web.Infrastructure;
using LMS.Web.Infrastructure.Filters;
using LMS.Web.Infrastructure.Identity;
using MediatR;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace LMS.Web
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                            .SetBasePath(env.ContentRootPath)
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                            .AddEnvironmentVariables();
            Configuration = builder.Build();

            AppSettings.SetEnviornmentalSettings(Configuration);
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc(opt =>
            {
                opt.Filters.Add(typeof(DbContextTransactionFilter));
            })
                .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining<Startup>(); })
                .AddJsonOptions(opt =>
                {
                    opt.SerializerSettings.ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    };
                });

            //DI
            services.AddScoped<MultipartContentValidatorActionFilter>();
            services.AddMediatR(typeof(Startup));
            services.AddScoped(_ => new LmsContext(Configuration.GetConnectionString(AppSettings.ConnectionStringName)));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //make sure this is called first in the pipeline!!!
            app.UseCors(builder =>
                builder.WithOrigins(AppSettings.AppRoot)
                    .AllowAnyMethod()
                    .AllowAnyHeader());

            var options = new JwtBearerOptions
            {
                Authority = AppSettings.Auth0Domain,
                Audience = AppSettings.Auth0Domain
            };

            app.UseJwtBearerAuthentication(options);
            app.UseClaimsTransformation(new ClaimsTransformationOptions
            {
                Transformer = new Auth0ClaimsTransformer()
            });

            app.UseMvc();
        }
    }
}


text:
import Ember from 'ember';
import DS from 'ember-data';

export
default Ember.Mixin.create({
  _rev: DS.attr('string'),
  _syncedAt: DS.attr('date'),
  createdAt: DS.attr('date'),
  updatedAt: DS.attr('date'),
  createdBy: DS.attr('string'),
  type: DS.attr('string')
});


text:
using UnityEngine;
using System.Collections;

public class PowerMeter : MonoBehaviour {
	/*public GameObject[] levels;
	public Material[] levelMaterials;
	public Material offMaterial;*/

	public string[] levels;

	//public UIAtlas meterAtlas;

	private UISprite meterSprite;

	private int level;

	// Use this for initialization
	void Start () {
		meterSprite = GetComponent<UISprite>();
		setLevel(level);
	}

	// Update is called once per frame
	void Update () {

	}

	public void setLevel(int newLevel) {
		level = Mathf.Clamp(newLevel, 0, levels.Length);
		meterSprite.spriteName = levels[level];
		/*for(int i = 0; i < levels.Length; i++) {
			if(i > level - 1) {
				levels[i].renderer.material = offMaterial;
			} else {
				levels[i].renderer.material = levelMaterials[i];
			}
		}*/
	}

	public void OnGameOver() {
		gameObject.SetActive(false);
		enabled = false;
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import java.util.List;

/** The visibility list of the private link service. */
@Fluent
public final class PrivateLinkServicePropertiesVisibility extends ResourceSet {
    /** Creates an instance of PrivateLinkServicePropertiesVisibility class. */
    public PrivateLinkServicePropertiesVisibility() {
    }

    /** {@inheritDoc} */
    @Override
    public PrivateLinkServicePropertiesVisibility withSubscriptions(List<String> subscriptions) {
        super.withSubscriptions(subscriptions);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.kie.server.testing</groupId>
    <artifactId>multimodule-project-parent</artifactId>
    <version>2.0.0.Final</version>
  </parent>

  <artifactId>multimodule-project-rules2</artifactId>
  <packaging>kjar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.kie.server.testing</groupId>
      <artifactId>multimodule-project-domain</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-model-compiler</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.kie</groupId>
        <artifactId>kie-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>


text:
package net.derohimat.firebasebasemvp.di.module;

import com.google.firebase.auth.FirebaseAuth;

import net.derohimat.firebasebasemvp.FireAuthApplication;
import net.derohimat.firebasebasemvp.data.local.PreferencesHelper;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module
public class ApplicationModule {

    private final FireAuthApplication mBaseApplication;

    public ApplicationModule(FireAuthApplication baseApplication) {
        this.mBaseApplication = baseApplication;
    }

    @Provides
    @Singleton
    FireAuthApplication provideApplication() {
        return mBaseApplication;
    }

    @Provides
    @Singleton
    FirebaseAuth provideFireBaseAuth() {
        return FirebaseAuth.getInstance();
    }

    @Provides
    @Singleton
    EventBus eventBus() {
        return new EventBus();
    }

    @Provides
    @Singleton
    PreferencesHelper prefsHelper() {
        return new PreferencesHelper(mBaseApplication);
    }

}


text:
"""
Tests for smoothing and estimation of unobserved states and disturbances

- Predicted states: :math:`E(\alpha_t | Y_{t-1})`
- Filtered states: :math:`E(\alpha_t | Y_t)`
- Smoothed states: :math:`E(\alpha_t | Y_n)`
- Smoothed disturbances :math:`E(\varepsilon_t | Y_n), E(\eta_t | Y_n)`
- Simulation smoothing

Tested against R (FKF, KalmanRun / KalmanSmooth), Stata (sspace), and
MATLAB (ssm toolbox)

Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function

import numpy as np
import pandas as pd
import os

from statsmodels.tsa.statespace import sarimax
from numpy.testing import assert_almost_equal, assert_raises
from nose.exc import SkipTest

current_path = os.path.dirname(os.path.abspath(__file__))

class TestStatesAR3(object):
    def __init__(self, *args, **kwargs):
        # Dataset / Stata comparison
        path = current_path + os.sep + 'results/results_wpi1_ar3_stata.csv'
        self.stata = pd.read_csv(path)
        self.stata.index = pd.date_range(start='1960-01-01', periods=124,
                                         freq='QS')
        # Matlab comparison
        path = current_path + os.sep+'results/results_wpi1_ar3_matlab_ssm.csv'
        matlab_names = [
            'a1','a2','a3','detP','alphahat1','alphahat2','alphahat3',
            'detV','eps','epsvar','eta','etavar'
        ]
        self.matlab_ssm = pd.read_csv(path, header=None, names=matlab_names)
        # Regression tests data
        path = current_path + os.sep+'results/results_wpi1_ar3_regression.csv'
        self.regression = pd.read_csv(path)

        self.model = sarimax.SARIMAX(
            self.stata['wpi'], order=(3, 1, 0), simple_differencing=True,
            hamilton_representation=True, *args, **kwargs
        )

        # Parameters from from Stata's sspace MLE estimation
        params = np.r_[.5270715, .0952613, .2580355, .5307459]
        self.results = self.model.smooth(params)

        # Calculate the determinant of the covariance matrices (for easy
        # comparison to other languages without having to store 2-dim arrays)
        self.results.det_predicted_state_cov = np.zeros((1, self.model.nobs))
        self.results.det_smoothed_state_cov = np.zeros((1, self.model.nobs))
        for i in range(self.model.nobs):
            self.results.det_predicted_state_cov[0,i] = np.linalg.det(
                self.results.filter_results.predicted_state_cov[:,:,i])
            self.results.det_smoothed_state_cov[0,i] = np.linalg.det(
                self.results.smoother_results.smoothed_state_cov[:,:,i])

    def test_predict_obs(self):
        assert_almost_equal(
            self.results.filter_results.predict().forecasts[0],
            self.stata.ix[1:, 'dep1'], 4
        )

    def test_standardized_residuals(self):
        assert_almost_equal(
            self.results.filter_results.standardized_forecasts_error[0],
            self.stata.ix[1:, 'sr1'], 4
        )

    def test_predicted_states(self):
        assert_almost_equal(
            self.results.filter_results.predicted_state[:,:-1].T,
            self.stata.ix[1:, ['sp1', 'sp2', 'sp3']], 4
        )
        assert_almost_equal(
            self.results.filter_results.predicted_state[:,:-1].T,
            self.matlab_ssm[['a1', 'a2', 'a3']], 4
        )

    def test_predicted_states_cov(self):
        assert_almost_equal(
            self.results.det_predicted_state_cov.T,
            self.matlab_ssm[['detP']], 4
        )

    def test_filtered_states(self):
        assert_almost_equal(
            self.results.filter_results.filtered_state.T,
            self.stata.ix[1:, ['sf1', 'sf2', 'sf3']], 4
        )

    def test_smoothed_states(self):
        assert_almost_equal(
            self.results.smoother_results.smoothed_state.T,
            self.stata.ix[1:, ['sm1', 'sm2', 'sm3']], 4
        )
        assert_almost_equal(
            self.results.smoother_results.smoothed_state.T,
            self.matlab_ssm[['alphahat1', 'alphahat2', 'alphahat3']], 4
        )

    def test_smoothed_states_cov(self):
        assert_almost_equal(
            self.results.det_smoothed_state_cov.T,
            self.matlab_ssm[['detV']], 4
        )

    def test_smoothed_measurement_disturbance(self):
        assert_almost_equal(
            self.results.smoother_results.smoothed_measurement_disturbance.T,
            self.matlab_ssm[['eps']], 4
        )

    def test_smoothed_measurement_disturbance_cov(self):
        res = self.results.smoother_results
        assert_almost_equal(
            res.smoothed_measurement_disturbance_cov[0].T,
            self.matlab_ssm[['epsvar']], 4
        )

    def test_smoothed_state_disturbance(self):
        assert_almost_equal(
            self.results.smoother_results.smoothed_state_disturbance.T,
            self.matlab_ssm[['eta']], 4
        )

    def test_smoothed_state_disturbance_cov(self):
        assert_almost_equal(
            self.results.smoother_results.smoothed_state_disturbance_cov[0].T,
            self.matlab_ssm[['etavar']], 4
        )

class TestStatesMissingAR3(object):
    def __init__(self, alternate_timing=True, *args, **kwargs):
        # Dataset
        path = current_path + os.sep + 'results/results_wpi1_ar3_stata.csv'
        self.stata = pd.read_csv(path)
        self.stata.index = pd.date_range(start='1960-01-01', periods=124,
                                         freq='QS')
        # Matlab comparison
        path = current_path + os.sep+'results/results_wpi1_missing_ar3_matlab_ssm.csv'
        matlab_names = [
            'a1','a2','a3','detP','alphahat1','alphahat2','alphahat3',
            'detV','eps','epsvar','eta','etavar'
        ]
        self.matlab_ssm = pd.read_csv(path, header=None, names=matlab_names)
        # Regression tests data
        path = current_path + os.sep+'results/results_wpi1_missing_ar3_regression.csv'
        self.regression = pd.read_csv(path)

        # Create missing observations
        self.stata['dwpi'] = self.stata['wpi'].diff()
        self.stata.ix[10:21, 'dwpi'] = np.nan

        self.model = sarimax.SARIMAX(
            self.stata.ix[1:,'dwpi'], order=(3, 0, 0),
            hamilton_representation=True, *args, **kwargs
        )

        # Parameters from from Stata's sspace MLE estimation
        self.params = np.r_[.5270715, .0952613, .2580355, .5307459]

    def test_missing_smooth(self):
        assert_raises(RuntimeError, self.model.smooth, self.params)


text:
import $ from 'jquery'

import throttle from '../utils/throttle'
import removeFromArray from '../utils/remove-array-like'

const NAME = 'lazyload'
const DEFAULTS = {
  throttle: 1000,
  offset: 200,
  selector: 'data-lazy'
}

class LazyLoad {
  constructor (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, DEFAULTS, (options || {}))
  }

  init () {
    this.bindListeners()
    this.checkVisiblePlaceholders()

    return this
  }

  bindListeners () {
    this.onScrollHandler = throttle(this.onScroll.bind(this), this.options.throttle)
    $(window).on('scroll', this.onScrollHandler)
  }

  onScroll () {
    return this.$element.length ? this.checkVisiblePlaceholders() : $(window).off('scroll', this.onScrollHandler)
  }

  checkVisiblePlaceholders () {
    this.windowHeight = $(window).height()
    this.windowWidth = $(window).width()

    Array.prototype.forEach.call(this.$element, this.checkPlaceholder.bind(this))
  }

  checkPlaceholder (placeholder) {
    if (this.isPlaceholderVisible(placeholder)) {
      this.renderImage(placeholder)
      removeFromArray(this.$element, placeholder)
    }
  }

  isPlaceholderVisible (placeholder) {
    return placeholder.getBoundingClientRect().top <= (this.windowHeight + this.options.offset)
  }

  renderImage (placeholder) {
    placeholder.parentNode.replaceChild(this.createImage(placeholder), placeholder)
  }

  createImage (placeholder) {
    let image = document.createElement('img')

    this.parseAttributes(image, placeholder.attributes)

    image.removeAttribute('data-lazy')

    if (placeholder.getAttribute('data-srcset')) {
      this.parseBreakpoints(image, placeholder.getAttribute('data-srcset'))

      return image
    }

    image.src = placeholder.getAttribute('data-src')

    return image
  }

  parseAttributes (image, attributes) {
    Array.prototype.forEach.call(attributes, (attr) => {
      if (attr.name !== this.options.selector || attr.name !== 'data-srcset' || attr.name !== 'data-src') {
        image.setAttribute(attr.name, attr.value)
      }
    })

    return image
  }

  parseBreakpoints (image, breakpoints) {
    image.removeAttribute('data-srcset')

    breakpoints = breakpoints.split(/,\s+/g).map(breakpoint => {
      breakpoint = breakpoint.trim().split(/\s+/)

      return {
        src: breakpoint[0],
        width: breakpoint[1]
      }
    })
      .sort((a, b) => b.width - a.width)

    for (let i = 0; i < breakpoints.length; i++) {
      let breakpoint = breakpoints[i]

      if (breakpoint.width <= this.windowWidth) {
        image.src = breakpoint.src
        break
      }
    }

    return image
  }

  destroy () {
    $(window).off('scroll', this.onScrollHandler)
  }
}

/* istanbul ignore next */
$.fn[NAME] = function (options) {
  options = options || {}

  return this.each(function () {
    if (!$.data(this, NAME)) {
      $.data(this, NAME, new LazyLoad(this, options).init())
    }
  })
}

export default LazyLoad


text:
package org.apache.commons.httpclient;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * Simple tests for HTTPS support in HttpClient.
 *
 * To run this test you'll need:
 *  + a JSSE implementation installed (see README.txt)
 *  + the java.protocol.handler.pkgs system property set
 *    for your provider.  e.g.:
 *     -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol
 *    (see build.xml)
 *
 * @author Rodney Waldhoff
 * @author Ortwin Glück
 * @version $Id: TestHttps.java 480424 2006-11-29 05:56:49Z bayard $
 */
public class TestHttps extends TestCase {

    // ---------------------------------------------------------------- Members
    private String _urlWithPort = null;
    private String _urlWithoutPort = null;
    private final String PROXY_HOST = System.getProperty("httpclient.test.proxyHost");
    private final String PROXY_PORT = System.getProperty("httpclient.test.proxyPort");
    private final String PROXY_USER = System.getProperty("httpclient.test.proxyUser");
    private final String PROXY_PASS = System.getProperty("httpclient.test.proxyPass");

    // ------------------------------------------------------------ Constructor
    public TestHttps(String testName) {
        super(testName);
    }

    // ------------------------------------------------------------------- Main
    public static void main(String args[]) {
        String[] testCaseName = { TestHttps.class.getName() };
        junit.textui.TestRunner.main(testCaseName);
    }

    // ------------------------------------------------------- TestCase Methods
    public static Test suite() {
        return new TestSuite(TestHttps.class);
    }

    public void setUp() throws Exception {
        _urlWithPort = "https://www.verisign.com:443/";
        _urlWithoutPort = "https://www.verisign.com/";
    }

    public void testHttpsGet() {
        HttpClient client = new HttpClient();
        if (PROXY_HOST != null) {
            if (PROXY_USER != null) {
                HttpState state = client.getState();
                state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    PROXY_USER, PROXY_PASS));
            }
            client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT));
        }
        GetMethod method = new GetMethod(_urlWithPort);

        try {
            client.executeMethod(method);
        } catch (Throwable t) {
            t.printStackTrace();
            fail("Exception thrown during HTTPS GET: " + t.toString());
        }

        try {
            String data = method.getResponseBodyAsString();
            // This enumeration musn't be empty
            assertTrue("No data returned.", (data.length() > 0));
        } catch (Throwable t) {
            t.printStackTrace();
            fail("Exception thrown while retrieving data : " + t.toString());
        }
    }

    public void testHttpsGetNoPort() {
        HttpClient client = new HttpClient();
        if (PROXY_HOST != null) {
            if (PROXY_USER != null) {
                HttpState state = client.getState();
                state.setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    PROXY_USER, PROXY_PASS));
            }
            client.getHostConfiguration().setProxy(PROXY_HOST, Integer.parseInt(PROXY_PORT));
        }
        GetMethod method = new GetMethod(_urlWithoutPort);

        try {
            client.executeMethod(method);
        } catch (Throwable t) {
            t.printStackTrace();
            fail("Exception thrown during HTTPS GET: " + t.toString());
        }

        try {
            String data = method.getResponseBodyAsString();
            // This enumeration musn't be empty
            assertTrue("No data returned.", (data.length() > 0));
        } catch (Throwable t) {
            t.printStackTrace();
            fail("Exception thrown while retrieving data : " + t.toString());
        }
    }
}


text:
"""
Weighted forest with MapReduce

Weighted forest is a novel ensemble algorithm.

Fit phase
Weighted forest algorithm builds multiple decision trees with a bootstrap method on a subset of data. In each tree node,
 it estimates sqrt(num. of attributes)+1 randomly selected attributes (without replacement).
 It uses decision tree to predict out-of-bag samples. For each prediction of an out-of-bag sample,
 it measures margin (classifier confidence in prediction) and leaf identifier that outputs prediction.
 Algorithm uses similarity matrix, where it stores similarities for each out-of-bag sample that was predicted with the
 same leaf. We assume that samples are similar, if the same leaf predicts them multiple times in multiple
 decision trees.

After algorithm builds all decision trees, it passes similarity matrix to k-medoids algorithm. Similarity matrix presents
distances between test samples. We set parameter k as sqrt(num. of attributes)+1. k-medoids algorithm outputs medoids,
which are test samples in the cluster centers of the dataset. Medoids are actual samples in a dataset, unlike centroids
which are centers of clusters. Algorithm measures average margin for all samples that are in the cluster of certain medoid.
It saves the average margin of a decision tree in its model. Algorithm uses this scores as weights of decision trees in predict phase.
Algorithm builds a forest on each subset of the data and it merges them in large ensemble. Each forest has its own medoids.

Predict phase
Algorithm selects a forest (or more, if it finds equal similarities with medoids in multiple forests), that contain most
similar medoid with a test sample. Then it uses the same procedure like with small data. Algorithm calculates Gower
similarity coefficient with a test sample and every medoid. Only decision trees with high margin on similar test samples
output prediction and algorithm stores decision tree margin for each prediction. Algorithm calculates final values
 for each prediction: (number of margins) * avg(margins) and it selects prediction with highest value.

"""

def simple_init(interface, params):
    return params

def map_init(interface, params):
    """Intialize random number generator with given seed `params.seed`."""
    import numpy as np
    import random
    np.random.seed(params['seed'])
    random.seed(params['seed'])

    return params

def map_fit(interface, state, label, inp):
    import numpy as np
    from itertools import permutations
    import decision_tree, measures, k_medoids

    out = interface.output(0)
    x, y, margins, forest = [], [], [], []
    attr_mapping, y_mapping, similarity_mat = {}, {}, {}
    missing_vals_attr = set()

    for row in inp:
        row = row.strip().split(state["delimiter"])
        if len(row) > 1:
            new_row = []
            for i, j in enumerate(state["X_indices"]):
                if row[j] in state["missing_vals"]:
                    new_row.append(row[j])
                    missing_vals_attr.add(i)
                elif state["X_meta"][i] == "c":
                    new_row.append(float(row[j]))
                else:
                    if row[j] not in attr_mapping:
                        attr_mapping[row[j]] = len(attr_mapping)
                    new_row.append(attr_mapping[row[j]])
            x.append(new_row)

            if row[state["y_index"]] not in y_mapping:
                y_mapping[row[state["y_index"]]] = len(y_mapping)
            y.append(y_mapping[row[state["y_index"]]])
    if len(y_mapping) == 1:
        print "Warning: Only one class in the subset!"
        return

    fill_in_values = []
    attr_mapping = {v: k for k, v in attr_mapping.iteritems()}
    y_mapping = {v: k for k, v in y_mapping.iteritems()}
    if len(missing_vals_attr) > 0:
        for i in range(len(state["X_indices"])):
            if state["X_meta"][i] == "c":
                value = np.average([sample[i] for sample in x if type(sample[i]) == float])
                fill_in_values.append(value)
            else:
                value = np.bincount([sample[i] for sample in x if type(sample[i]) == int]).argmax()
                fill_in_values.append(attr_mapping[value])
            if i in missing_vals_attr:
                for j in range(len(x)):
                    if x[j][i] in state["missing_vals"]:
                        x[j][i] = value
    x, y = np.array(x), np.array(y)

    iteration = 0
    while len(forest) < state["trees_per_chunk"]:
        if iteration == state["trees_per_chunk"] * 2:
            return
        bag_indices = np.random.randint(len(x), size=(len(x)))
        unique = set(bag_indices)
        out_of_bag_indices = [i for i in range(len(x)) if i not in unique][:500]
        iteration += 1

        if len(np.unique(y[bag_indices])) == 1:
            continue

        tree = decision_tree.fit(
            x=x[bag_indices],
            y=y[bag_indices],
            t=state["X_meta"],
            randomized=True,
            max_tree_nodes=state["max_tree_nodes"],
            min_samples_leaf=state["min_samples_leaf"],
            min_samples_split=state["min_samples_split"],
            class_majority=state["class_majority"],
            measure=measures.info_gain if state["measure"] == "info_gain" else measures.mdl,
            accuracy=state["accuracy"],
            separate_max=state["separate_max"])

        if len(tree) < 2:
            continue
        # calculate margins
        tree_margins, leafs_grouping = {}, {}
        for j in out_of_bag_indices:
            leaf, margin = decision_tree.predict(tree, x[j], y[j])
            tree_margins[j] = margin
            if leaf in leafs_grouping:
                leafs_grouping[leaf].append(j)
            else:
                leafs_grouping[leaf] = [j]
        margins.append(tree_margins)

        for k, v in leafs_grouping.iteritems():
            for cx, cy in permutations(v, 2):
                if cx in similarity_mat:
                    similarity_mat[cx][cy] = similarity_mat[cx].get(cy, 0) - 1
                else:
                    similarity_mat[cx] = {cy: -1}

        tree_mapped = {}
        for k, v in tree.iteritems():
            tree_mapped[k] = [None for i in range(2)]
            for i, node in enumerate(v):
                dist_map = dict([(y_mapping[label], freq) for label, freq in node[3].iteritems()])
                split_map = set([attr_mapping[int(s)] for s in list(node[2])]) if node[5] == "d" else node[2]
                tree_mapped[k][i] = (node[0], node[1], split_map, dist_map, node[4], node[5])
        forest.append(tree_mapped)

    min_elements = []
    for k, v in similarity_mat.iteritems():
        min_id = min(similarity_mat[k], key=similarity_mat[k].get)
        min_elements.append((similarity_mat[k][min_id], min_id))
    min_elements = sorted(min_elements)

    if state["k"] == "sqrt":
        k = int(np.sqrt(len(x[0]))) + 1
    elif state["k"] == "square":
        k = len(np.unique(y)) * len(np.unique(y))

    cidx = set()
    counter = 0
    while counter < len(min_elements) and len(cidx) < k:
        cidx.add(min_elements[counter][1])
        counter += 1

    inds, medoids_i = k_medoids.fit(similarity_mat, len(x), list(cidx))
    sample_ids = np.array(similarity_mat.keys())
    medoids_i = [sample_ids[i] for i in medoids_i]

    clusters = [sample_ids[np.where(inds == i)[0]] for i in np.unique(inds)]
    medoids = x[medoids_i].tolist()  # set medoids without sample identifier

    cont, disc = [], []
    for i in range(len(medoids)):
        cont.append([medoids[i][j] for j in range(len(medoids[i])) if state["X_meta"][j] == "c"])
        disc.append([attr_mapping[int(medoids[i][j])] for j in range(len(medoids[i])) if state["X_meta"][j] == "d"])
    medoids = [np.array(cont), np.array(disc)]

    stats = [[] for i in range(len(medoids_i))]
    for i in range(len(forest)):  # for every tree in forest
        for num, cluster in enumerate(clusters):
            # calculate average margin for cluster
            values = [margins[i][sample_id] for sample_id in cluster if int(sample_id) in margins[i]]
            if values != []:
                avg = np.average(values)
                forest[i]["margin" + str(num)] = avg
                stats[num].append(avg)

    stats = [np.median(value) for value in stats]
    gower_range = np.array([np.ptp(x[:, i]) for i in range(len(state["X_meta"])) if state["X_meta"][i] == "c"])
    gower_range[gower_range == 0] = 1e-9
    out.add("model", (forest, medoids, stats, gower_range))
    out.add("fill_in_values", fill_in_values)

def reduce_fit(interface, state, label, inp):
    import numpy as np
    out = interface.output(0)
    out.add("X_names", state["X_names"])

    forest, medoids, stats, gower_ranges, group_fillins = [], [], [], [], []
    for i, (k, value) in enumerate(inp):
        if k == "model":
            forest.append(value[0])
            medoids.append(value[1])
            stats.append(value[2])
            gower_ranges.append(value[3])
        elif len(value) > 0:
            group_fillins.append(value)
    out.add("forest", forest)
    out.add("medoids", medoids)
    out.add("stats", stats)
    out.add("gower_ranges", gower_ranges)

    fill_in_values = []
    if len(group_fillins) > 0:
        for i, type in enumerate(state["X_meta"]):
            if type == "c":
                fill_in_values.append(np.average([sample[i] for sample in group_fillins]))
            else:
                fill_in_values.append(np.bincount([sample[i] for sample in group_fillins]).argmax())
    out.add("fill_in_values", fill_in_values)

def map_predict(interface, state, label, inp):
    import decision_tree
    import numpy as np

    out = interface.output(0)
    fill_in_values = state["fill_in_values"]
    coeff = state["coeff"]

    for row in inp:
        row = row.strip().split(state["delimiter"])
        if len(row) > 1:
            x_id = "" if state["id_index"] == -1 else row[state["id_index"]]

            x, cont, disc = [], [], []
            for i, j in enumerate(state["X_indices"]):
                if row[j] in state["missing_vals"]:
                    row[j] = fill_in_values[i]

                if state["X_meta"][i] == "c":
                    x.append(float(row[j]))
                    cont.append(float(row[j]))
                else:
                    x.append(row[j])
                    disc.append(row[j])
            cont, disc = np.array(cont), np.array(disc)

            similarities = []
            for i, medoids in enumerate(state["medoids"]):
                gower = 0 if len(cont) == 0 else np.sum(
                    1 - np.true_divide(np.abs(cont - medoids[0]), state["gower_ranges"][i]), axis=1)
                gower += 0 if len(disc) == 0 else np.sum(disc == medoids[1], axis=1)
                similarities += zip(np.round(1 - gower / float(len(x)), 4), [(i, j) for j in range(len(x))])

            similarities = sorted(similarities)
            threshold = similarities[0][0] * (1 + coeff)
            similar_medoids = [similarities[0][1]]
            pos = 1
            while pos < len(similarities) and similarities[pos][0] <= threshold:
                similar_medoids.append(similarities[pos][1])
                pos += 1

            global_predictions = {}
            for i, j in similar_medoids:
                predictions = {}
                margin = "margin" + str(j)
                for tree in state["forest"][i]:
                    if margin in tree and tree[margin] >= state["stats"][i][j]:
                        pred = decision_tree.predict(tree, x)
                        predictions[pred] = predictions.get(pred, []) + [tree[margin]]

                for k, v in predictions.iteritems():
                    predictions[k] = np.average(v) * len(v)

                max_pred = max(predictions, key=predictions.get)
                if max_pred not in global_predictions:
                    global_predictions[max_pred] = predictions[max_pred]
                elif predictions[max_pred] > global_predictions[max_pred]:
                    global_predictions[max_pred] = predictions[max_pred]

            out.add(x_id, (max(global_predictions, key=global_predictions.get),))

def fit(dataset, trees_per_chunk=3, max_tree_nodes=50, min_samples_leaf=10, min_samples_split=5, class_majority=1,
        measure="info_gain", k="sqrt", accuracy=1, random_state=None, separate_max=True, save_results=True, show=False):
    from disco.worker.pipeline.worker import Worker, Stage
    from disco.core import Job
    import discomll

    path = "/".join(discomll.__file__.split("/")[:-1] + ["ensemble", "core", ""])

    try:
        trees_per_chunk = int(trees_per_chunk)
        max_tree_nodes = int(max_tree_nodes) if max_tree_nodes != None else max_tree_nodes
        min_samples_leaf = int(min_samples_leaf)
        min_samples_split = int(min_samples_split)
        class_majority = float(class_majority)
        separate_max = separate_max
        accuracy = int(accuracy)

        if trees_per_chunk <= 0 or min_samples_leaf <= 0 or min_samples_split <= 0 or class_majority <= 0 or accuracy < 0:
            raise Exception("Parameters should be greater than 0.")
    except ValueError:
        raise Exception("Parameters should be numerical.")

    if measure not in ["info_gain", "mdl"]:
        raise Exception("measure should be set to info_gain or mdl.")

    job = Job(worker=Worker(save_results=save_results))
    job.pipeline = [
        ("split", Stage("map", input_chain=dataset.params["input_chain"], init=map_init, process=map_fit)),
        ('group_all', Stage("reduce", init=simple_init, process=reduce_fit, combine=True))]

    job.params = dataset.params
    job.params["trees_per_chunk"] = trees_per_chunk
    job.params["max_tree_nodes"] = max_tree_nodes
    job.params["min_samples_leaf"] = min_samples_leaf
    job.params["min_samples_split"] = min_samples_split
    job.params["class_majority"] = class_majority
    job.params["measure"] = measure
    job.params["accuracy"] = accuracy
    job.params["k"] = k
    job.params['seed'] = random_state
    job.params['separate_max'] = separate_max

    job.run(name="distributed_weighted_forest_fit", input=dataset.params["data_tag"],
            required_files=[path + "decision_tree.py", path + "measures.py", path + "k_medoids.py"])

    fitmodel_url = job.wait(show=show)
    return {"dwf_fitmodel": fitmodel_url}  # return results url

def predict(dataset, fitmodel_url, coeff=0.5, save_results=True, show=False):
    from disco.worker.pipeline.worker import Worker, Stage
    from disco.core import Job, result_iterator
    import discomll
    path = "/".join(discomll.__file__.split("/")[:-1] + ["ensemble", "core", ""])

    job = Job(worker=Worker(save_results=save_results))
    job.pipeline = [
        ("split", Stage("map", input_chain=dataset.params["input_chain"], init=simple_init, process=map_predict))]

    if "dwf_fitmodel" not in fitmodel_url:
        raise Exception("Incorrect fit model.")

    try:
        coeff = float(coeff)
        if coeff < 0:
            raise Exception("Parameter coeff should be greater than 0.")
    except ValueError:
        raise Exception("Parameter coeff should be numerical.")

    job.params = dataset.params
    job.params["coeff"] = coeff
    for k, v in result_iterator(fitmodel_url["dwf_fitmodel"]):
        job.params[k] = v

    if len(job.params["forest"]) == 0:
        print "Warning: There is no decision trees in forest"
        return []

    job.run(name="distributed_weighted_forest_predict", input=dataset.params["data_tag"],
            required_files=[path + "decision_tree.py"])

    return job.wait(show=show)


text:
package malcjohn;

import Prog1Tools.IOTools;
import java.util.Scanner;

public class Aufgabe6vonUbungen {

	public static class Personen {
		String vorname;
		String name;
		String email;
		int telefon;
	}

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		Personen[] freunde = new Personen[5];

		System.out.println("freund 1");

		freunde[0] = new Personen();
		freunde[0].telefon = scan.nextInt();
		freunde[0].email = scan.nextLine();
		freunde[0].name = scan.nextLine();
		freunde[0].vorname = scan.nextLine();

		// Vypise prvniho cloveka

		System.out.println("freund 2");

		freunde[1] = new Personen();
		freunde[1].email = scan.nextLine();
		freunde[1].name = scan.nextLine();
		freunde[1].telefon = IOTools.readInt("telefon ");
		freunde[1].vorname = scan.nextLine();

		// vypise dalisho cloveka
		freunde[2] = new Personen();
		System.out.println("freund 3");
		freunde[2].email = scan.nextLine();
		freunde[2].name = scan.nextLine();
		freunde[2].telefon = IOTools.readInt("telefon ");
		freunde[2].vorname = scan.nextLine();

		// vypise 3 cloveka

		System.out.println("freund 4");
		freunde[3] = new Personen();
		freunde[3].email = scan.nextLine();
		freunde[3].name = scan.nextLine();
		freunde[3].telefon = IOTools.readInt("telefon ");
		freunde[3].vorname = scan.nextLine();

		System.out.println("freund 5");
		freunde[4] = new Personen();
		freunde[4].email = scan.nextLine();
		freunde[4].name = scan.nextLine();
		freunde[4].telefon = IOTools.readInt("telefon ");
		freunde[4].vorname = scan.nextLine();

		for (int i = 0; i < 5; i++) {
			// vypise petkrat co jsem zadal
			System.out.println(freunde[i].email);
			System.out.println(freunde[i].name);
			System.out.println(freunde[i].vorname);
			System.out.println(freunde[i].telefon);

		}
		scan.close();
	}

}


text:
<?php

require_once dirname( __FILE__ ) . '/../AbstractTest.php';

/**
 * Abstract base test case.
 *
 * @category  QualityAssurance
 * @package   VersionControl
 * @author    Manuel Pichler <mapi@manuel-pichler.de>
 * @copyright 2007-2010 Manuel Pichler. All rights reserved.
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   Release: @package_version@
 * @link      http://www.phpundercontrol.org/
 */
abstract class phpucAbstractCheckoutTest extends phpucAbstractTest
{
    /**
     * Tests that the magic __get() method fails with an exception for an unknown
     * property.
     *
     * @return void
     * @expectedException OutOfRangeException
     */
    public function testGetterUnknownPropertyFail()
    {
        $checkout = $this->createCheckout();
        $property = $checkout->phpuc;
    }

    /**
     * Tests that the magic __set() method fails with an exception for an unknown
     * property.
     *
     * @return void
     */
    public function testSetterUnknownPropertyFail()
    {
        $this->setExpectedException(
            'OutOfRangeException',
            'Unknown or readonly property $phpuc.'
        );

        $checkout = $this->createCheckout();
        $checkout->phpuc = true;
    }

    /**
     * Marks a test case as skipped when the remote host is not available.
     *
     * @param string $remote The remote host name + port.
     *
     * @return void
     */
    protected function markTestSkippedWhenRemoteHostNotAvailable( $remote )
    {
        $url = parse_url( $remote );

        $socket = @fsockopen( $url['host'], $url['port'], $errno, $errstr, 1);
        if ( is_resource( $socket ) )
        {
            fclose( $socket );
        }
        else
        {
            $this->markTestSkipped( 'Cannot connect to host ' . $remote . '.' );
        }
    }

    /**
     * Test factory method.
     *
     * @return phpucCheckoutI
     */
    protected abstract function createCheckout();

}


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.Storage.Models
{
    /// <summary> The property is for NFS share only. The default is NoRootSquash. </summary>
    public readonly partial struct RootSquashType : IEquatable<RootSquashType>
    {
        private readonly string _value;

        /// <summary> Determines if two <see cref="RootSquashType"/> values are the same. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public RootSquashType(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string NoRootSquashValue = "NoRootSquash";
        private const string RootSquashValue = "RootSquash";
        private const string AllSquashValue = "AllSquash";

        /// <summary> NoRootSquash. </summary>
        public static RootSquashType NoRootSquash { get; } = new RootSquashType(NoRootSquashValue);
        /// <summary> RootSquash. </summary>
        public static RootSquashType RootSquash { get; } = new RootSquashType(RootSquashValue);
        /// <summary> AllSquash. </summary>
        public static RootSquashType AllSquash { get; } = new RootSquashType(AllSquashValue);
        /// <summary> Determines if two <see cref="RootSquashType"/> values are the same. </summary>
        public static bool operator ==(RootSquashType left, RootSquashType right) => left.Equals(right);
        /// <summary> Determines if two <see cref="RootSquashType"/> values are not the same. </summary>
        public static bool operator !=(RootSquashType left, RootSquashType right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="RootSquashType"/>. </summary>
        public static implicit operator RootSquashType(string value) => new RootSquashType(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is RootSquashType other && Equals(other);
        /// <inheritdoc />
        public bool Equals(RootSquashType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
#include "SkImage.h"
#include "SkPDFBitmap.h"
#include "SkPDFCanon.h"
#include "SkPDFFont.h"
#include "SkPDFShader.h"

////////////////////////////////////////////////////////////////////////////////

void SkPDFCanon::reset() {
    for (int i = 0; i < fFontRecords.count(); ++i) {
        fFontRecords[i].fFont->unref();
    }
    fFontRecords.reset();
    fFunctionShaderRecords.unrefAll();
    fFunctionShaderRecords.reset();
    fAlphaShaderRecords.unrefAll();
    fAlphaShaderRecords.reset();
    fImageShaderRecords.unrefAll();
    fImageShaderRecords.reset();
    fGraphicStateRecords.foreach ([](WrapGS w) { w.fPtr->unref(); });
    fGraphicStateRecords.reset();

    fPDFBitmapMap.foreach([](SkBitmapKey, SkPDFObject** p) { (*p)->unref(); });
    fPDFBitmapMap.reset();
}

////////////////////////////////////////////////////////////////////////////////

template <class T> T* assert_ptr(T* p) { SkASSERT(p); return p; }

// requires `bool T::equals(const U&) const`
template <typename T, typename U>
T* find_item(const SkTDArray<T*>& ptrArray, const U& object) {
    for (int i = 0; i < ptrArray.count(); ++i) {
        if (ptrArray[i]->equals(object)) {
            return ptrArray[i];
        }
    }
    return nullptr;
}

////////////////////////////////////////////////////////////////////////////////

SkPDFFont* SkPDFCanon::findFont(uint32_t fontID,
                                uint16_t glyphID,
                                SkPDFFont** relatedFontPtr) const {
    SkASSERT(relatedFontPtr);

    SkPDFFont* relatedFont = nullptr;
    for (int i = 0; i < fFontRecords.count(); ++i) {
        SkPDFFont::Match match = SkPDFFont::IsMatch(
                fFontRecords[i].fFont, fFontRecords[i].fFontID,
                fFontRecords[i].fGlyphID, fontID, glyphID);
        if (SkPDFFont::kExact_Match == match) {
            return fFontRecords[i].fFont;
        } else if (!relatedFont && SkPDFFont::kRelated_Match == match) {
            relatedFont = fFontRecords[i].fFont;
        }
    }
    *relatedFontPtr = relatedFont;  // May still be nullptr.
    return nullptr;
}

void SkPDFCanon::addFont(SkPDFFont* font, uint32_t fontID, uint16_t fGlyphID) {
    SkPDFCanon::FontRec* rec = fFontRecords.push();
    rec->fFont = SkRef(font);
    rec->fFontID = fontID;
    rec->fGlyphID = fGlyphID;
}

////////////////////////////////////////////////////////////////////////////////

SkPDFFunctionShader* SkPDFCanon::findFunctionShader(
        const SkPDFShader::State& state) const {
    return find_item(fFunctionShaderRecords, state);
}
void SkPDFCanon::addFunctionShader(SkPDFFunctionShader* pdfShader) {
    fFunctionShaderRecords.push(SkRef(pdfShader));
}

////////////////////////////////////////////////////////////////////////////////

SkPDFAlphaFunctionShader* SkPDFCanon::findAlphaShader(
        const SkPDFShader::State& state) const {
    return find_item(fAlphaShaderRecords, state);
}
void SkPDFCanon::addAlphaShader(SkPDFAlphaFunctionShader* pdfShader) {
    fAlphaShaderRecords.push(SkRef(pdfShader));
}

////////////////////////////////////////////////////////////////////////////////

SkPDFImageShader* SkPDFCanon::findImageShader(
        const SkPDFShader::State& state) const {
    return find_item(fImageShaderRecords, state);
}

void SkPDFCanon::addImageShader(SkPDFImageShader* pdfShader) {
    fImageShaderRecords.push(SkRef(pdfShader));
}

////////////////////////////////////////////////////////////////////////////////

const SkPDFGraphicState* SkPDFCanon::findGraphicState(
        const SkPDFGraphicState& key) const {
    const WrapGS* ptr = fGraphicStateRecords.find(WrapGS(&key));
    return ptr ? ptr->fPtr : nullptr;
}

void SkPDFCanon::addGraphicState(const SkPDFGraphicState* state) {
    SkASSERT(state);
    WrapGS w(SkRef(state));
    SkASSERT(!fGraphicStateRecords.contains(w));
    fGraphicStateRecords.add(w);
}

////////////////////////////////////////////////////////////////////////////////

sk_sp<SkPDFObject> SkPDFCanon::findPDFBitmap(SkBitmapKey key) const {
    SkPDFObject** ptr = fPDFBitmapMap.find(key);
    return ptr ? sk_ref_sp(*ptr) : sk_sp<SkPDFObject>();
}

void SkPDFCanon::addPDFBitmap(SkBitmapKey key, sk_sp<SkPDFObject> pdfBitmap) {
    fPDFBitmapMap.set(key, pdfBitmap.release());
}

////////////////////////////////////////////////////////////////////////////////

sk_sp<SkPDFStream> SkPDFCanon::makeInvertFunction() {
    if (fInvertFunction) {
        return fInvertFunction;
    }
    fInvertFunction = SkPDFGraphicState::MakeInvertFunction();
    return fInvertFunction;
}
sk_sp<SkPDFDict> SkPDFCanon::makeNoSmaskGraphicState() {
    if (fNoSmaskGraphicState) {
        return fNoSmaskGraphicState;
    }
    fNoSmaskGraphicState = SkPDFGraphicState::MakeNoSmaskGraphicState();
    return fNoSmaskGraphicState;
}
sk_sp<SkPDFArray> SkPDFCanon::makeRangeObject() {
    if (fRangeObject) {
        return fRangeObject;
    }
    fRangeObject = SkPDFShader::MakeRangeObject();
    return fRangeObject;
}


text:
package com.gs.obevo.util;

import java.util.regex.Pattern;

/**
 * Utility to easily convert a wildcard string into a regexp so that we can still rely on {@link Pattern}.
 * (wildcard strings are much easier for users to use).
 */
public class RegexUtil {
    /**
     * Converts the incoming wildcardPattern (* and % are glob patterns) to the Java-regexp pattern.
     */
    public static String convertWildcardPatternToRegex(String wildcardPattern) {
        return wildcardPattern
                .replace(".", "\\.")
                .replace("*", ".*")
                .replace("%", ".*")
                ;
    }
}


text:
/*
 * IMPORTANT NOTICE
 *
 * This C++ header defines C++ wrapper classes around the OCILIB C API
 * It requires a compatible version of OCILIB
 *
 */

#ifndef OCILIBCPP_H_INCLUDED
#define OCILIBCPP_H_INCLUDED

/**
 * @namespace ocilib
 * @brief OCILIB ++ Namespace
 *
 */

namespace ocilib
{

/**
 * @defgroup OcilibCppApi C++ API
 * @{
 */

/**
 * @defgroup OcilibCppApiOverview Overview
 * @{
 *
 * @par Introduction
 * OCILIB++ is a C++ API for Oracle built on top of the C OCILIB API:
 *  - Full C API ported to C++
 *  - Implemented as a set of header files, no library compilation needed
 *  - Based on C++ and STL paradigms (Strong typing, templates, containers, RAII, exception handling, operators, stack objects)
 *  - Based on design patterns (RAII, delegation, reference counting, smart pointers, proxies, singleton)
 *  - No user dynamic object allocation required
 *  - The only dependencies are : STL and OCILIB C API
 *
 * @par C++ language requirements
 * - The OCILIB C++ API requires only C++03 features.
 * - It does not required C++11/14/17 but uses some CXX features when target compiler support them
 *
 * @par Reference counting model
 * - API usage is very simple, based on stack objects wrapping OCILIB handles using reference counting.
 * - OCILIB handles are automatically allocated internally by C++ objects constructors or methods.
 * - They are also automatically freed when the last C++ object referencing it goes out of scope.
 * - Dynamic memory allocation is not required at all.
 * - OCILIB++ allows simple and safe usage of Oracle client without the worries of memory leakages.
 * - Using stack objects also makes error handling easier and program logic more robust
 *
 * @par C++ API classes usage
 * Most C++ API classes wrap C API handles.
 * When instances are created using the default constructors, they hold no C handles and have
 * their method IsNull() returning true.
 * Any use of other methods and functions on such object methods will throw an C++ exception.
 * Thus, in order to have a valid object :
 * - use a parametrized constructor
 * - use the default constructor and then later assign a value to the instance using assignment operator.
 * In the later case, the value can be provided by a function return value or using the object class constructor
 *
 * @par Exception model
 * - Any failure occurring within an OCILIB C API call will throw a ocilib::Exception
 * - For conformance reasons, this class derives from std::Exception
 *
 * @warning
 *  - OCILIB++ wraps the whole OCILIB C API.
 *  - Each C OCILIB object handle has its C++ class counter part.
 *  - The whole OCILIB C Documentation (concepts, use cases, features) is still valid for OCILIB++
 *
 * @} OcilibCppApiOverview
 */

/**
 * @defgroup OcilibCppApiMainDemoApplication OCILIB main C++ demo application code
 * @{
 *
 * Main C++ demo  source
 * @include ocilib_demo.cpp
 *
 * @} OcilibCppApiMainDemoApplication
 */

 /**
  * @defgroup OcilibCppApiDemoListApplication Some OCILIB C++ sample codes
  * @{
  *
  * Here are some C++ samples code. More samples can be found under the demo folder of ocilib packages.
  *
  * @par Fetching data
  * @include fetch.cpp
  *
  * @par Binding vectors
  * @include array.cpp
  *
  * @par Using collections
  * @include coll.cpp
  *
  * @par Using connection pools
  * @include pool.cpp
  *
  * @par Oracle 12c Implicit resultsets
  * @include implicit_resultset.cpp
  *
  * @par Using Oracle objects
  * @include object.cpp
  *
  * @par Database notifications
  * @include notification.cpp
  *
  * @} OcilibCppApiDemoListApplication
  */

 /**
 *
 * @} OcilibCppApi
 */

}

/*
 * IMPORTANT NOTICE
 *
 * This C++ header defines C++ wrapper classes around the OCILIB C API
 * It requires a compatible version of OCILIB
 *
 */

/* Including declarations  */

#include "ocilibcpp/config.hpp"
#include "ocilibcpp/core.hpp"
#include "ocilibcpp/support.hpp"
#include "ocilibcpp/types.hpp"

/* Including core implementations  */

#include "ocilibcpp/detail/core/Utils.hpp"
#include "ocilibcpp/detail/core/Enum.hpp"
#include "ocilibcpp/detail/core/Flags.hpp"
#include "ocilibcpp/detail/core/ManagedBuffer.hpp"
#include "ocilibcpp/detail/core/HandleHolder.hpp"
#include "ocilibcpp/detail/core/Locker.hpp"
#include "ocilibcpp/detail/core/Lockable.hpp"
#include "ocilibcpp/detail/core/ConcurrentMap.hpp"
#include "ocilibcpp/detail/core/ConcurrentList.hpp"
#include "ocilibcpp/detail/core/SmartHandle.hpp"
#include "ocilibcpp/detail/core/MemoryDebugInfo.hpp"

/* Including support implementations  */

#include "ocilibcpp/detail/support/BindResolver.hpp"
#include "ocilibcpp/detail/support/BindObject.hpp"
#include "ocilibcpp/detail/support/BindArray.hpp"
#include "ocilibcpp/detail/support/BindObjectAdaptor.hpp"
#include "ocilibcpp/detail/support/BindTypeAdaptor.hpp"
#include "ocilibcpp/detail/support/BindsHolder.hpp"
#include "ocilibcpp/detail/support/NumericTypeResolver.hpp"

/* Including types implementations  */

#include "ocilibcpp/detail/Exception.hpp"
#include "ocilibcpp/detail/Environment.hpp"
#include "ocilibcpp/detail/Mutex.hpp"
#include "ocilibcpp/detail/Thread.hpp"
#include "ocilibcpp/detail/ThreadKey.hpp"
#include "ocilibcpp/detail/Pool.hpp"
#include "ocilibcpp/detail/Connection.hpp"
#include "ocilibcpp/detail/Transaction.hpp"
#include "ocilibcpp/detail/Number.hpp"
#include "ocilibcpp/detail/Date.hpp"
#include "ocilibcpp/detail/Interval.hpp"
#include "ocilibcpp/detail/Timestamp.hpp"
#include "ocilibcpp/detail/Lob.hpp"
#include "ocilibcpp/detail/File.hpp"
#include "ocilibcpp/detail/TypeInfo.hpp"
#include "ocilibcpp/detail/Object.hpp"
#include "ocilibcpp/detail/Reference.hpp"
#include "ocilibcpp/detail/Collection.hpp"
#include "ocilibcpp/detail/CollectionIterator.hpp"
#include "ocilibcpp/detail/CollectionElement.hpp"
#include "ocilibcpp/detail/Long.hpp"
#include "ocilibcpp/detail/BindInfo.hpp"
#include "ocilibcpp/detail/Statement.hpp"
#include "ocilibcpp/detail/Resultset.hpp"
#include "ocilibcpp/detail/Column.hpp"
#include "ocilibcpp/detail/Subscription.hpp"
#include "ocilibcpp/detail/Event.hpp"
#include "ocilibcpp/detail/Agent.hpp"
#include "ocilibcpp/detail/Message.hpp"
#include "ocilibcpp/detail/Enqueue.hpp"
#include "ocilibcpp/detail/Dequeue.hpp"
#include "ocilibcpp/detail/DirectPath.hpp"
#include "ocilibcpp/detail/Queue.hpp"
#include "ocilibcpp/detail/QueueTable.hpp"

#endif


text:
package com.whenling.shop.controller;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.querydsl.core.types.Predicate;
import com.whenling.shop.entity.Specification;
import com.whenling.shop.entity.SpecificationValue;
import com.whenling.shop.support.mvc.CrudController;

@Controller
@RequestMapping("/specification")
public class SpecificationController extends CrudController<Specification, Long> {

	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@ResponseBody
	public Page<Specification> doPage(Predicate predicate, Pageable pageable) {
		return getBaseJpaRepository().findAll(predicate, pageable);
	}

	@Override
	protected void onBeforeSave(Specification entity) {
		super.onBeforeSave(entity);

		Integer specificationValueCount = getParameter("specificationValueCount", Integer.class, 0);
		List<SpecificationValue> submitedValues = entity.getSpecificationValues().subList(0, specificationValueCount);
		submitedValues.forEach(specificationValue -> specificationValue.setSpecification(entity));
		entity.setSpecificationValues(submitedValues);
	}

}


text:
import re, os, time
from flask import request, render_template

def about():
    """
        Renders a static about page.
    """
    return render_template('about.html', header=True)

def app():
    """
        Renders the application template directly for debugging and issues
        where the user agent isn't properly recognized.
    """
    env = os.environ.get('ENVIRONMENT_TYPE', 'prod')

    current_time = int(time.time()) if env == 'dev' else None

    return render_template('index.html', invalidate=current_time)

def help():
    """
        Renders a static help page.
    """
    return render_template('help.html', header=True)

def index():
    """
        The style of the index page served up depends on whether the user is
        making a request from a mobile or desktop device.
    """
    user_agent = request.headers.get('User-Agent')
    is_mobile = re.search('android|ipad|iphone', user_agent, re.IGNORECASE)
    tmpl = 'index' if is_mobile else 'marketing'

    return render_template('%s.html' % tmpl)


text:
from flask_lwadmin.pager import Pager
from lightningwolf_smp.models.user_query import UserQuery
from lightningwolf_smp.application import db

uq = UserQuery(db=db)

class UserPager(Pager):
    def initialize(self, configuration):
        from lightningwolf_smp.forms.user import (
            FormUsernameFilter,
            FormUserBatchActions
        )
        self.configure(configuration)
        filter_data = self.get_filter_data()
        self.set_filter_form(FormUsernameFilter(**filter_data))
        self.set_batch_form(FormUserBatchActions())
        self.set_count(uq.admin_get_user_list_count(filter_data))
        self.calculate_pages()

    def get_pk(self):
        return 'id'

    def get_results(self):
        if self.results is None:
            self.results = uq.admin_get_user_list(self.get_filter_data(), offset=self.get_offset(), limit=self.get_limit())

        return self.results


text:
package codetoanalyze.java.performance;

public class FieldAccess {

  public class Test {
    int a;
  }

  void iterate_upto_field_size_linear(Test test) {
    for (int ci = 0; ci < test.a; ++ci) {}
  }
}


text:
package com.thinkgem.jeesite.modules.pro.dao;

import com.thinkgem.jeesite.common.persistence.TreeDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.pro.entity.ProIssueYear;

/**
 * 出品年份DAO接口
 * @author lin
 * @version 2016-05-18
 */
@MyBatisDao
public interface ProIssueYearDao extends TreeDao<ProIssueYear> {

}