text:
<?php
namespace Apigee\Mint\DataStructures;

use ReflectionClass;
use Apigee\Util\APIObject;

class DataStructure
{

    private static $childSetters = array();

    private static function getSetterMethods($class_name)
    {
        $class = new ReflectionClass($class_name);
        $setter_methods = array();
        foreach ($class->getMethods() as $method) {
            if ($method->getDeclaringClass() != $class) {
                continue;
            }
            $method_name = $method->getName();
            if (strpos($method_name, 'set') !== 0) {
                continue;
            }
            if ($method->isPrivate()) {
                $method->setAccessible(true);
            }
            $setter_methods[$method_name] = $method;
        }
        return $setter_methods;
    }

    protected function loadFromRawData($data, $exclude_variables = array())
    {
        $class_name = get_class($this);
        if (!array_key_exists($class_name, self::$childSetters)) {
            self::$childSetters[$class_name] = self::getSetterMethods($class_name);
        }

        foreach ($data as $property_name => $property_value) {
            if (in_array($property_name, $exclude_variables)) {
                continue;
            }
            $property_setter_name = 'set' . ucfirst($property_name);
            if (array_key_exists($property_setter_name, self::$childSetters[$class_name])) {
                $method = self::$childSetters[$class_name][$property_setter_name];
                $method->invoke($this, $property_value);
            } else {
                $notice = 'No setter method was found for property "%s" on class "%s".';
                APIObject::$logger->notice(sprintf($notice, $property_name, $class_name));
            }
        }
    }

    /**
     * Encapsulation enforcement for old consumers of this class and its children
     *
     * This magic method is meant never to be used, it is only for backwards
     * compatibility for those consumers of classes that inherit from this class that in
     * the beginning did not provide mutators for its properties. Those consumers should
     * also update the way they set its properties to the mutators method instead of the
     * property, since properties are now marked as private.
     *
     * @param string $name Name of the private property to set
     * @param mixed $value Value to be set
     */
    public function __set($name, $value)
    {
        $class_name = get_class($this);
        if (!array_key_exists($class_name, self::$childSetters)) {
            self::$childSetters[$class_name] = self::getSetterMethods($class_name);
        }
        $property_setter_name = 'set' . ucfirst($name);
        if (array_key_exists($property_setter_name, self::$childSetters[$class_name])) {
            $method = self::$childSetters[$class_name][$property_setter_name];
            $method->invoke($this, $value);
        } else {
            $notice = 'No setter method was found for property "%s" on class "%s".';
            APIObject::$logger->notice(sprintf($notice, $name, $class_name));
        }
        $warning = 'Attempt to access property "%s" without its accessor in class "%s".';
        APIObject::$logger->warning(sprintf($warning, $name, $class_name));
    }

    /**
     * Encapsulation enforcement for old consumers of this class and its children.
     *
     * This magic method is meant to never be used. It is only for backwards
     * compatibility to provide old consumers of the classes that inherit this class
     * which at the beginning did not provide accessors methods. These old references
     * must be upgraded to accessor methods since properties are now marked as private
     *
     * @param string $name Name of the property
     * @return mixed
     */
    public function __get($name)
    {
        $class_name = get_class($this);
        $notice = 'Attempt to access property "%s" without its accessor on class "%s" from %s';
        $noticeArgs = array($name, $class_name, json_encode(debug_backtrace()));
        APIObject::$logger->notice(vsprintf($notice, $noticeArgs));
        $property_accessor_name = 'get' . ucfirst($name);
        if (method_exists($this, $name)) {
            return $this->$property_accessor_name();
        } else {
            $warning = 'No accessor method was found for property "%s" on class "%s".';
            APIObject::$logger->warning(sprintf($warning, $name, $class_name));
            return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: module.exports = require("./../_gen/openfl/Lib");


text:
require 'we_meet/message'
require 'we_meet/user'

module WeMeet
	describe Message do
		context "created by an user" do
			before do
				@before = Time.now
				@user = User.new("Dani","Caba","dani.caba@mymail.com")
				@after = Time.now
				@message = Message.new("hello world!",@user)
			end
			it "sender is the expected one" do
				expect(@message.creator).to be == @user
			end
			it "provides the date when it was created" do
				expect(@message.date).to be_a_kind_of(Time)
				expect(@message.date.to_i).to be_within(@after.to_i-@before.to_i).of(@before.to_i)
			end
			it "has the expected text" do
				expect(@message.content).to be == "hello world!"
			end
		end
	end
end


text:
package io.bot.email.handlers;

import io.bot.email.model.Preferences;
import io.bot.email.model.SetupState;
import io.bot.email.model.Vendor;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.api.objects.Chat;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;

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

import static java.lang.StrictMath.toIntExact;

public class ChangeVendorHandler extends AbstractHandler{
    @Override
    boolean accept(Update update, Preferences preferences) {
        return update.hasCallbackQuery()
                && update.getCallbackQuery().getData().equals("changeVendor");
    }

    @Override
    BotApiMethod handle(Update update, Preferences preferences) {
        Message message = update.hasMessage() ? update.getMessage() : update.getCallbackQuery().getMessage();
        preferences.setSetupState(SetupState.CHANGE_VENDOR);
        return new EditMessageText()
                .setReplyMarkup(getInlineKeyboard())
                .setChatId(message.getChatId())
                .setMessageId(toIntExact(message.getMessageId()))
                .setText("Please select your Email provider");
    }

    private InlineKeyboardMarkup getInlineKeyboard() {
        InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
        List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
        List<InlineKeyboardButton> rowInline = new ArrayList<>();
        rowInline.add(new InlineKeyboardButton().setText("Yandex").setCallbackData("yandex"));
        rowInline.add(new InlineKeyboardButton().setText("Gmail").setCallbackData("gmail"));
        rowInline.add(new InlineKeyboardButton().setText("MailRU").setCallbackData("mailru"));
        rowsInline.add(rowInline);
        rowInline = new ArrayList<>();
        rowInline.add(new InlineKeyboardButton().setText("<< Back").setCallbackData("backInSettings"));
        rowsInline.add(rowInline);
        markupInline.setKeyboard(rowsInline);
        return markupInline;
    }
}


text:
package edu.harvard.iq.dataverse.api;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import org.junit.Test;
import org.junit.BeforeClass;
import java.util.UUID;
import static javax.ws.rs.core.Response.Status.CREATED;
import static org.hamcrest.CoreMatchers.equalTo;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;

public class AdminIT {

    private static String nonSuperuserUsername;
    private static String nonSuperuserApiToken;

    private static String superuserUsername;
    private static String superuserApiToken;

    private static Long idOfUserToConvert;
    private static String usernameOfUserToConvert;
    private static String emailOfUserToConvert;

    @BeforeClass
    public static void setUp() {

        RestAssured.baseURI = UtilIT.getRestAssuredBaseUri();

        Response createNonSuperuser = UtilIT.createRandomUser();
        nonSuperuserUsername = UtilIT.getUsernameFromResponse(createNonSuperuser);
        nonSuperuserApiToken = UtilIT.getApiTokenFromResponse(createNonSuperuser);

        Response createUserToConvert = UtilIT.createRandomUser();
        createUserToConvert.prettyPrint();

        idOfUserToConvert = createUserToConvert.body().jsonPath().getLong("data.authenticatedUser.id");
        emailOfUserToConvert = createUserToConvert.body().jsonPath().getString("data.user.email");
        usernameOfUserToConvert = UtilIT.getUsernameFromResponse(createUserToConvert);

        Response createSuperuser = UtilIT.createRandomUser();
        superuserUsername = UtilIT.getUsernameFromResponse(createSuperuser);
        superuserApiToken = UtilIT.getApiTokenFromResponse(createSuperuser);
        Response toggleSuperuser = UtilIT.makeSuperUser(superuserUsername);
        toggleSuperuser.then().assertThat()
                .statusCode(OK.getStatusCode());
    }

    @Test
    public void testListAuthenticatedUsers() throws Exception {
        Response anon = UtilIT.listAuthenticatedUsers("");
        anon.prettyPrint();
        anon.then().assertThat().statusCode(FORBIDDEN.getStatusCode());

        Response nonSuperuser = UtilIT.listAuthenticatedUsers(nonSuperuserApiToken);
        nonSuperuser.prettyPrint();
        nonSuperuser.then().assertThat().statusCode(FORBIDDEN.getStatusCode());

        Response superuser = UtilIT.listAuthenticatedUsers(superuserApiToken);
        superuser.prettyPrint();
        superuser.then().assertThat().statusCode(OK.getStatusCode());

    }

    @Test
    public void testConvertShibUserToBuiltin() throws Exception {

        String password = usernameOfUserToConvert;
        String newEmailAddressToUse = "builtin2shib." + UUID.randomUUID().toString().substring(0, 8) + "@mailinator.com";
        String data = emailOfUserToConvert + ":" + password + ":" + newEmailAddressToUse;

        Response builtinToShibAnon = UtilIT.migrateBuiltinToShib(data, "");
        builtinToShibAnon.prettyPrint();
        builtinToShibAnon.then().assertThat().statusCode(FORBIDDEN.getStatusCode());

        Response makeShibUser = UtilIT.migrateBuiltinToShib(data, superuserApiToken);
        makeShibUser.prettyPrint();
        makeShibUser.then().assertThat()
                .statusCode(OK.getStatusCode())
                .body("data.affiliation", equalTo("TestShib Test IdP")
                );

        /**
         * @todo Write more failing tests such as expecting a non-OK response if
         * the Shib user has an invalid email address:
         * https://github.com/IQSS/dataverse/issues/2998
         */
        Response shibToBuiltinAnon = UtilIT.migrateShibToBuiltin(Long.MAX_VALUE, "", "");
        shibToBuiltinAnon.prettyPrint();
        shibToBuiltinAnon.then().assertThat().statusCode(FORBIDDEN.getStatusCode());

        Response nonSuperuser = UtilIT.migrateShibToBuiltin(Long.MAX_VALUE, "", "");
        nonSuperuser.prettyPrint();
        nonSuperuser.then().assertThat().statusCode(FORBIDDEN.getStatusCode());

        Response infoOfUserToConvert = UtilIT.getAuthenticatedUser(usernameOfUserToConvert, superuserApiToken);
        infoOfUserToConvert.prettyPrint();

        String invalidEmailAddress = "invalidEmailAddress";
        Response invalidEmailFail = UtilIT.migrateShibToBuiltin(idOfUserToConvert, invalidEmailAddress, superuserApiToken);
        invalidEmailFail.prettyPrint();
        invalidEmailFail.then().assertThat().statusCode(BAD_REQUEST.getStatusCode());

        String existingEmailAddress = "dataverse@mailinator.com";
        Response existingEmailFail = UtilIT.migrateShibToBuiltin(idOfUserToConvert, existingEmailAddress, superuserApiToken);
        existingEmailFail.prettyPrint();
        existingEmailFail.then().assertThat().statusCode(BAD_REQUEST.getStatusCode());

        String newEmailAddress = UUID.randomUUID().toString().substring(0, 8) + "@mailinator.com";
        Response shouldWork = UtilIT.migrateShibToBuiltin(idOfUserToConvert, newEmailAddress, superuserApiToken);
        shouldWork.prettyPrint();
        shouldWork.then().assertThat().statusCode(OK.getStatusCode());

    }

    @Test
    public void testFindPermissonsOn() {
        Response createUser = UtilIT.createRandomUser();
        createUser.prettyPrint();
        String username = UtilIT.getUsernameFromResponse(createUser);
        String apiToken = UtilIT.getApiTokenFromResponse(createUser);

        Response createDataverse = UtilIT.createRandomDataverse(apiToken);
        createDataverse.prettyPrint();
        createDataverse.then().assertThat()
                .statusCode(CREATED.getStatusCode());

        String dataverseAlias = JsonPath.from(createDataverse.body().asString()).getString("data.alias");

        Response findPerms = UtilIT.findPermissionsOn(dataverseAlias, apiToken);
        findPerms.prettyPrint();
        findPerms.then().assertThat()
                .body("data.user", equalTo("@" + username))
                .statusCode(OK.getStatusCode());

        Response findRoleAssignee = UtilIT.findRoleAssignee("@" + username, apiToken);
        findRoleAssignee.prettyPrint();
        findRoleAssignee.then().assertThat()
                .body("data.title", equalTo(username + " " + username))
                .statusCode(OK.getStatusCode());

    }

    @AfterClass
    public static void tearDownClass() {
        boolean disabled = false;

        if (disabled) {
            return;
        }

        Response deleteNonSuperuser = UtilIT.deleteUser(nonSuperuserUsername);
        assertEquals(200, deleteNonSuperuser.getStatusCode());

        Response deleteUserToConvert = UtilIT.deleteUser(usernameOfUserToConvert);
        assertEquals(200, deleteUserToConvert.getStatusCode());

        Response deleteSuperuser = UtilIT.deleteUser(superuserUsername);
        assertEquals(200, deleteSuperuser.getStatusCode());

    }

}


text:
package validator_examples

import (
	fmt "fmt"
	math "math"
	proto "github.com/golang/protobuf/proto"
	_ "github.com/mwitkow/go-proto-validators"
	regexp "regexp"
	github_com_mwitkow_go_proto_validators "github.com/mwitkow/go-proto-validators"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

func (this *InnerMessage) Validate() error {
	if !(this.SomeInteger > 0) {
		return github_com_mwitkow_go_proto_validators.FieldError("SomeInteger", fmt.Errorf(`value '%v' must be greater than '0'`, this.SomeInteger))
	}
	if !(this.SomeInteger < 100) {
		return github_com_mwitkow_go_proto_validators.FieldError("SomeInteger", fmt.Errorf(`value '%v' must be less than '100'`, this.SomeInteger))
	}
	return nil
}

var _regex_OuterMessage_ImportantString = regexp.MustCompile(`^[a-z]{2,5}$`)

func (this *OuterMessage) Validate() error {
	if !_regex_OuterMessage_ImportantString.MatchString(this.ImportantString) {
		return github_com_mwitkow_go_proto_validators.FieldError("ImportantString", fmt.Errorf(`value '%v' must be a string conforming to regex "^[a-z]{2,5}$"`, this.ImportantString))
	}
	if nil == this.Inner {
		return github_com_mwitkow_go_proto_validators.FieldError("Inner", fmt.Errorf("message must exist"))
	}
	if this.Inner != nil {
		if err := github_com_mwitkow_go_proto_validators.CallValidatorIfExists(this.Inner); err != nil {
			return github_com_mwitkow_go_proto_validators.FieldError("Inner", err)
		}
	}
	return nil
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.brilliantbear.wallpapers.MainActivity">

    <FrameLayout
        android:id="@+id/frame_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>[cfedu6] D. Professor GukiZ and Two Arrays — amoshyc's CPsolution 1.0 documentation</title>

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

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

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="amoshyc's CPsolution 1.0 documentation" href="../../index.html"/>
        <link rel="up" title="Educational Round #6" href="index.html"/>
        <link rel="next" title="[cfedu6] E. New Year Tree" href="pe.html"/>
        <link rel="prev" title="[cfedu6] C. Pearls in a Row" href="pc.html"/>

             amoshyc's CPsolution

                1.0

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

1. 常用演算法教學

2. CF

Regular Round

Educational Round

#17

#16

#12

#9

#8

#7

#6

[cfedu6] A. Professor GukiZ's Robot

[cfedu6] B. Grandfather Dovlet's calculator

[cfedu6] C. Pearls in a Row

[cfedu6] D. Professor GukiZ and Two Arrays

[cfedu6] E. New Year Tree

Gym

3. POJ

4. UVA

5. PTC

6. Other

7. Template

8. Tags

9. Cheatsheet

          amoshyc's CPsolution

Docs »

2. CF »

Educational Round #6 »

[cfedu6] D. Professor GukiZ and Two Arrays

             View page source

[cfedu6] D. Professor GukiZ and Two Arrays¶

Tags

tag_enum

tag_half_enum

tag_binary_search

TOC

[cfedu6] D. Professor GukiZ and Two Arrays

題目

Specification

分析

AC Code

題目¶

給定一個長度為 N 的序列 A,與一長度為 M 的序列 B。
定義一次交換為將 A 中的某一項與 B 中的某一項交換。
定義兩序列的和的差值為 v,即 |sum(A) - sum(B)|

請問在最多交換二次的情況下,v 值的最小可能是多少?
同時,你必需輸出你是交換了哪些項。

Specification¶

1 <= N, M <= 2000
-10^9 <= A[i], B[j] <= 10^9

分析¶

Note

枚舉交換次數

枚舉交換次數,看各個交換次數哪個最好。

零次時,v = sum(A) - sum(B)。

一次時,枚舉 A 中的每一項,並枚舉 B 中的每一項,看交換後的結果怎樣最好

sumA = sum(A)
sumB = sum(B)
v = INF
for a in A:
    for b in B:
        new_sumA = sumA - a + b
        new_sumB = sumB - b + a
        v = min(v, abs(new_sumA - new_sumB))

二次時,使用折半列舉的技巧,首先,先建表:

Let AA = [sumB + 2 * (A[i] + A[j]) for i in [0, N) for j in [i + 1, N)]
    BB = [sumA + 2 * (B[i] + B[j]) for i in [0, M) for j in [i + 1, M)]

sort(BB)

之後枚舉 AA 中的每一項 AA[i],看 BB 中最 接近 AA[i] 的是多少,交換看看。
這麼做是正確的是因為新的總和變成:

假設是選到 AA[a], BB[b] 這兩項
new_sumA = sumA - AA[a] + BB[b]
new_sumB = sumB - BB[b] + AA[a]

v = sumA - 2 * AA[a] - sumB + 2 * BB[b]
  = (sumA + 2 * BB[b]) - (sumB + 2 * AA[a]) -> 0

而在實作中,最接近(差值最小)這次事情可以透過 lower_bound 並枚舉較大與較小的那兩項來達成。

下邊給出的程式碼,我 AA, BB 剛好反過來了…
程式碼中是枚舉 BB ,看 AA 中的最接近項,不好意思~
題解太晚打了,都忘了那時 code 是怎麼寫的,重想了一遍…結果不太一樣,又懶得重寫,就將就吧。

這題我覺得出得不錯~

AC Code¶

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;

const int max_n = 2000;
const int max_m = 2000;
int n, m;
ll a[max_n];
ll b[max_m];

ll ans;
pii swap1 = pii(-1, -1);
pii swap2 = pii(-1, -1);

ll Sa;
ll Sb;
map<ll, pii> mm;

void update(int i, int j, int k, int l) {
    ll nSa = Sa - a[i] - a[j] + b[k] + b[l];
    ll nSb = Sb - b[k] - b[l] + a[i] + a[j];
    ll new_ans = abs(nSa - nSb);

    if (new_ans < ans) {
        ans = new_ans;
        swap1 = pii(i, k);
        swap2 = pii(j, l);
    }
}

void solve() {
    Sa = accumulate(a, a + n, 0ll);
    Sb = accumulate(b, b + m, 0ll);

    // 0 swap
    ans = abs(Sa - Sb);

    // 1 swap
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            ll nSa = Sa - a[i] + b[j];
            ll nSb = Sb - b[j] + a[i];
            ll new_ans = abs(nSa - nSb);
            if (new_ans < ans) {
                ans = new_ans;
                swap1 = pii(i, j);
            }
        }
    }

    // 2 swaps
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            mm[Sb + 2 * (a[i] + a[j])] = pii(i, j);
        }
    }

    for (int k = 0; k < m - 1; k++) {
        for (int l = k + 1; l < m; l++) {
            ll val = Sa + 2 * (b[k] + b[l]);
            auto it = mm.lower_bound(val);

            if (it != mm.end())
                update((it->second).first, (it->second).second, k, l);
            if (it != mm.begin()) {
                it--;
                update((it->second).first, (it->second).second, k, l);
            }
        }
    }
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%lld", &a[i]);
    scanf("%d", &m);
    for (int i = 0; i < m; i++)
        scanf("%lld", &b[i]);

    solve();

    printf("%lld\n", ans);
    // printf("%I64d\n", ans);
    if (swap1.first == -1) {
        puts("0");
    }
    else if (swap2.first == -1) {
        puts("1");
        printf("%d %d\n", swap1.first + 1, swap1.second + 1);
    }
    else {
        puts("2");
        printf("%d %d\n", swap1.first + 1, swap1.second + 1);
        printf("%d %d\n", swap2.first + 1, swap2.second + 1);
    }

    return 0;
}

        Next

         Previous

        © Copyright 2016, amoshyc.

  Built with Sphinx using a theme provided by Read the Docs.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using C3.XNA;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Primitives2DSample
{
	/// <summary>
	/// This is the main type for your game
	/// </summary>
	public class Game1 : Microsoft.Xna.Framework.Game
	{
		GraphicsDeviceManager graphics;
		SpriteBatch spriteBatch;

		public Game1()
		{
			graphics = new GraphicsDeviceManager(this);
			Content.RootDirectory = "Content";
		}

		/// <summary>
		/// Allows the game to perform any initialization it needs to before starting to run.
		/// This is where it can query for any required services and load any non-graphic
		/// related content.  Calling base.Initialize will enumerate through any components
		/// and initialize them as well.
		/// </summary>
		protected override void Initialize()
		{
			// TODO: Add your initialization logic here

			base.Initialize();
		}

		/// <summary>
		/// LoadContent will be called once per game and is the place to load
		/// all of your content.
		/// </summary>
		protected override void LoadContent()
		{
			// Create a new SpriteBatch, which can be used to draw textures.
			spriteBatch = new SpriteBatch(GraphicsDevice);

			// TODO: use this.Content to load your game content here
		}

		/// <summary>
		/// UnloadContent will be called once per game and is the place to unload
		/// all content.
		/// </summary>
		protected override void UnloadContent()
		{
			// TODO: Unload any non ContentManager content here
		}

		/// <summary>
		/// Allows the game to run logic such as updating the world,
		/// checking for collisions, gathering input, and playing audio.
		/// </summary>
		/// <param name="gameTime">Provides a snapshot of timing values.</param>
		protected override void Update(GameTime gameTime)
		{
			// Allows the game to exit
			if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
				this.Exit();

			// TODO: Add your update logic here

			base.Update(gameTime);
		}

		/// <summary>
		/// This is called when the game should draw itself.
		/// </summary>
		/// <param name="gameTime">Provides a snapshot of timing values.</param>
		protected override void Draw(GameTime gameTime)
		{
			GraphicsDevice.Clear(Color.CornflowerBlue);
			spriteBatch.Begin();

			spriteBatch.DrawRectangle(new Rectangle(100, 100, 100, 200), Color.Purple, 20);

			spriteBatch.DrawRectangle(new Rectangle(10, 10, 100, 200), Color.Yellow, 2);
			spriteBatch.DrawRectangle(new Rectangle(20, 20, 100, 200), Color.Yellow, 1);
			spriteBatch.DrawRectangle(new Vector2(30, 30), new Vector2(100, 200), Color.Yellow);
			spriteBatch.DrawRectangle(new Vector2(40, 40), new Vector2(100, 200), Color.Yellow, 5);

			spriteBatch.DrawCircle(400, 100, 90, 3, Color.White * 0.2f);
			spriteBatch.DrawCircle(400, 100, 90, 4, Color.White * 0.3f);
			spriteBatch.DrawCircle(400, 100, 90, 5, Color.White * 0.4f);
			spriteBatch.DrawCircle(400, 100, 90, 6, Color.White * 0.5f);
			spriteBatch.DrawCircle(400, 100, 90, 7, Color.White * 0.6f);
			spriteBatch.DrawCircle(400, 100, 90, 8, Color.White * 0.7f);
			spriteBatch.DrawCircle(400, 100, 90, 9, Color.White * 0.8f);
			spriteBatch.DrawCircle(400, 100, 90, 10, Color.White * 0.9f);
			spriteBatch.DrawCircle(400, 100, 90, 20, Color.Red);

			spriteBatch.DrawCircle(600, 100, 100, 50, Color.Green, 10);
			spriteBatch.DrawCircle(new Vector2(600, 100), 40, 30, Color.Green, 30);

			spriteBatch.FillRectangle(350, 340, 100, 100, Color.Red * 0.4f);
			spriteBatch.FillRectangle(new Rectangle(350, 340, 100, 100), Color.Red * 0.3f, (float)Math.PI / 4f);
			spriteBatch.FillRectangle(new Vector2(350, 340), new Vector2(100, 100), Color.Red * 0.2f, (float)Math.PI / 3f);
			spriteBatch.FillRectangle(350, 340, 100, 100, Color.Red * 0.5f, (float)Math.PI);

			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(180), Color.Navy, 1);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(160), Color.Navy * 0.9f, 2);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(140), Color.Navy * 0.8f, 4);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(120), Color.Navy * 0.7f, 6);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(90), Color.Navy * 0.6f, 8);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(80), Color.Navy * 0.5f, 10);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(65), Color.Navy * 0.4f, 12);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(45), Color.Navy * 0.3f, 14);
			spriteBatch.DrawArc(new Vector2(600, 350), 100, 180, MathHelper.ToRadians(180), MathHelper.ToRadians(12), Color.Navy * 0.2f, 16);

			spriteBatch.DrawArc(new Vector2(600, 400), 80, 90, MathHelper.ToRadians(90), MathHelper.ToRadians(220), Color.Navy, 10);

			base.Draw(gameTime);
			spriteBatch.End();
		}
	}
}


text:
<?php

// require_once 'Zend/Stdlib/CallbackHandler.php';

/**
 * Interface for intercepting filter chains
 *
 * @category   Zend
 * @package    Zend_EventManager
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_EventManager_Filter
{
    /**
     * Execute the filter chain
     *
     * @param  string|object $context
     * @param  array $params
     * @return mixed
     */
    public function run($context, array $params = array());

    /**
     * Attach an intercepting filter
     *
     * @param  callback $callback
     * @return Zend_Stdlib_CallbackHandler
     */
    public function attach($callback);

    /**
     * Detach an intercepting filter
     *
     * @param  Zend_Stdlib_CallbackHandler $filter
     * @return bool
     */
    public function detach(Zend_Stdlib_CallbackHandler $filter);

    /**
     * Get all intercepting filters
     *
     * @return array
     */
    public function getFilters();

    /**
     * Clear all filters
     *
     * @return void
     */
    public function clearFilters();

    /**
     * Get all filter responses
     *
     * @return Zend_EventManager_ResponseCollection
     */
    public function getResponses();
}


text:
package io.fabric8.openshift.api.model.operator.v1;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "observedGeneration",
    "zones"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
    @BuildableReference(ObjectMeta.class),
    @BuildableReference(LabelSelector.class),
    @BuildableReference(Container.class),
    @BuildableReference(PodTemplateSpec.class),
    @BuildableReference(ResourceRequirements.class),
    @BuildableReference(IntOrString.class),
    @BuildableReference(ObjectReference.class),
    @BuildableReference(LocalObjectReference.class),
    @BuildableReference(PersistentVolumeClaim.class)
})
public class DNSRecordStatus implements KubernetesResource
{

    @JsonProperty("observedGeneration")
    private Long observedGeneration;
    @JsonProperty("zones")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<DNSZoneStatus> zones = new ArrayList<DNSZoneStatus>();
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public DNSRecordStatus() {
    }

    /**
     *
     * @param zones
     * @param observedGeneration
     */
    public DNSRecordStatus(Long observedGeneration, List<DNSZoneStatus> zones) {
        super();
        this.observedGeneration = observedGeneration;
        this.zones = zones;
    }

    @JsonProperty("observedGeneration")
    public Long getObservedGeneration() {
        return observedGeneration;
    }

    @JsonProperty("observedGeneration")
    public void setObservedGeneration(Long observedGeneration) {
        this.observedGeneration = observedGeneration;
    }

    @JsonProperty("zones")
    public List<DNSZoneStatus> getZones() {
        return zones;
    }

    @JsonProperty("zones")
    public void setZones(List<DNSZoneStatus> zones) {
        this.zones = zones;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
.. Py.Saunter documentation master file, created by
   sphinx-quickstart on Thu Sep  8 12:12:06 2011.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Py.Saunter
==========

This is the class documentation for Py.Saunter. For the larger documentation set in context, see the `Py.Saunter page <http://element34.ca/products/pysaunter>`_ at Element 34.

Remote Control:

.. toctree::
   :maxdepth: 2

   testcase/remotecontrol
   po/remotecontrol

WebDriver:

.. toctree::
  :maxdepth: 2

  testcase/webdriver
  po/webdriver

Common:

.. toctree::
   :maxdepth: 2

   testcase/base
   generators
   providers

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
Issues
======
If you're opening a support ticket about coveralls not working,
please add ``coveralls debug`` output.

Pull requests
=============
Pull requests with untested code will not be merged straight away.
If you would like to speed up the process, please, write tests.


text:
package org.sterl.education.messgaging;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@SpringBootApplication
@EnableWebSocketMessageBroker
public class MessagingApplication extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/message").withSockJS();
    }

    public static void main(String[] args) {
        SpringApplication.run(MessagingApplication.class, args);
    }
}


text:
module Game.Tile where

import Data.Binary
import Data.Maybe (isNothing)
import Game.TypeClasses

data Tile = BlockTile
          | GrassTile
          | TreeTile
          | Tree2Tile
          | RockTile
          | Rock2Tile
          | WaterTile
          | MudTile deriving (Eq, Ord, Show, Enum)

instance Binary Tile where
    put = putWord8 . fromIntegral . fromEnum
    get = getWord8 >>= \t -> return . toEnum $ fromIntegral t

tileAp :: Tile -> Maybe Int
tileAp BlockTile = Nothing
tileAp GrassTile = Just 2
tileAp MudTile   = Just 3
tileAp RockTile  = Just 4
tileAp Rock2Tile = Just 4
tileAp WaterTile = Just 4
tileAp _ = Nothing

tileBlocking :: Tile -> Bool
tileBlocking = isNothing . tileAp

tileAttBonus :: Tile -> Float
tileAttBonus _ = 0 -- todo eri tiilityypeille eri arvot

tileDefBonus :: Tile -> Float
tileDefBonus _ = 0

instance Describable Tile where
    describe GrassTile = "Basic tile"
    describe BlockTile = "Impassable tile"
    describe _ = "Magical mystery tile"

instance Drawable Tile where
    filename GrassTile = "grass.png"
    filename BlockTile = "wall.png"
    filename TreeTile  = "tree.png"
    filename Tree2Tile = "tree2.png"
    filename MudTile   = "mud.png"
    filename RockTile  = "stone2.png"
    filename Rock2Tile = "stone3.png"
    filename WaterTile = "water.png"


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

namespace Mosa.TinyCPUSimulator.x86.Emulate
{
	public class MosaKernel : BaseSimDevice
	{
		public static readonly uint GdtTable = 0x1401000;
		public static readonly uint IdtTable = 0x1411000;
		public static readonly uint PageTable = 1024 * 1024 * 16;
		public static readonly uint PageDirectory = 1024 * 1024 * 20;
		public static readonly uint PageFrameTable = 1024 * 1024 * 28;
		public static readonly uint FreeMemory = 1024 * 1024 * 32; // start at 32Mb
		public static readonly uint VirtualPageBitMap = 1024 * 1024 * 21; // 0x1500000

		public MosaKernel(SimCPU simCPU)
			: base(simCPU)
		{
		}

		public override void Initialize()
		{
			var x86 = simCPU as CPUx86;

			simCPU.AddMemory(PageDirectory, 1024 * 4, 1); // Page Directory (4K)
			simCPU.AddMemory(PageTable, 1024 * 1024 * 4, 1); // Page Table (4Mb)
			simCPU.AddMemory(FreeMemory, 1024 * 1024 * 64, 1); // Free Memory (64Mb)
			simCPU.AddMemory(IdtTable, 256 * 256, 1); // IDT Table
			simCPU.AddMemory(GdtTable, 8 * 256, 1); // GDT Table
			simCPU.AddMemory(PageFrameTable, 1024 * 1024 * 4, 1); // Page Table (4Mb)
			simCPU.AddMemory(VirtualPageBitMap, 1024 * 1024 * 4, 1); // Virtual Page BitMap (4Mb)
		}
	}
}


text:
<Alloy>
	<View layout="vertical" class="container" backgroundColor="#E6E7E9" fullscreen="true">
		<Require src="_header" ></Require>
		<View height="20%" backgroundColor="#1C6D83">
			Online Purchases
		</View>
		<ScrollView layout="vertical">
			<View layout="horizontal" height="30%" width="100%">
				<View height="100%" width="50%" backgroundColor="red" onClick="panda">
					1600 PANDAS SIM PACK
				</View>
				<View height="100%" width="50%" backgroundColor="blue" onClick="hopOn">
					HOP ON
				</View>
			</View>
			<View layout="horizontal" height="30%" width="100%">
				<View height="100%" width="50%" backgroundColor="green" onClick="seasonPass">
					SEASON PASS
				</View>
				<View height="100%" width="50%" backgroundColor="yellow" onClick="topUp">
					TOP UP
				</View>
			</View>
			<View layout="horizontal" height="30%" width="100%">
				<View height="100%" width="50%" backgroundColor="red" onClick="penang">
					PENANG PACK UNITED PACK SIGNATURE BASIC
				</View>
				<View height="100%" width="50%" backgroundColor="blue" onClick="premium">
					PREMIUM
				</View>
			</View>
			<View layout="horizontal" height="30%" width="100%">
				<View height="100%" width="50%" backgroundColor="green" onClick="switchXOX">
					#1758 SWITCH TO XOX
				</View>
				<View height="100%" width="50%" backgroundColor="yellow" onClick="mobileData">
					HIGH SPEED MOBILE DATA
				</View>
			</View>
		</ScrollView>
	</View>
</Alloy>


text:
"""
Created on Fri Oct 27 14:26:03 2017

@author: cdonovan
"""

# Python 3.5
# Monte Carlo method of estimating pi

import random
import math
import pandas as pd

# radius = 1

def montecarlo_pi(num_iterations):
    num_circ = 0
    num_sq = 0
    for i in range(num_iterations):
        num_sq+=1
        p1, p2 = (random.random() for j in range(2))
        if (p1**2+p2**2)**0.5<=1:
            num_circ+=1

    pi_approx = 4*num_circ/num_sq

    # show results of simulation
    results = pd.DataFrame({'pi_approx':pi_approx, 'actual_pi':math.pi, 'percentage_error':(pi_approx-math.pi)*100/math.pi}, index=[0])
    return results

result_df = montecarlo_pi(100000)

# plot the absolute value of the error by various iteration sizes
import matplotlib.pyplot as plt
iter_sizes = range(1000, 1000000, 1000)
results2 = pd.DataFrame([(item, abs(montecarlo_pi(item)['percentage_error'][0])) for item in iter_sizes], columns=['num_iterations','abs_error'])

results2.plot(x='num_iterations', y='abs_error')
max1 = results2['abs_error'].max()+2
axes = plt.gca()
axes.set_ylim([0,max1])


text:
using System;
using System.Collections.Generic;
using BeeDevelopment.Brazil;
namespace BeeDevelopment.Sega8Bit.Hardware {

	///
	/// Emulates an SN76489 programmable sound generator.
	///
	[Serializable()]
	public partial class ProgrammableSoundGenerator {

		#region Types

		/// Represents various presets for the noise register.
		public enum NoisePresets {
			/// The noise generated by the Sega Master System and compatible hardware.
			SegaMasterSystem,
			/// The noise generated by the SC-3000.
			SC3000,
			/// The noise generated by the BBC Micro.
			BbcMicro
		}

		#endregion

		#region Properties

		///
		/// Gets the <see cref="Emulator"/> that contains the <see cref="ProgrammableSoundGenerator"/>.
		///
		[StateNotSaved()]
		public Emulator Emulator { get; private set; }

		private int clockSpeed;
		///
		/// Gets or sets the clock speed of the sound generator.
		///
		public int ClockSpeed {
			get { return this.clockSpeed; }
			set { this.clockSpeed = value; }
		}

		private int shiftRegisterWidth;
		///
		/// Gets or sets the width of the linear feedback shift register.
		///
		public int ShiftRegisterWidth {
			get { return this.shiftRegisterWidth; }
			set {
				if (value < 1 || value > 16) throw new InvalidOperationException("The shift register must be between 1 and 16 bits wide.");
				this.shiftRegisterWidth = value;
			}
		}

		private int tappedBits;
		/// Gets or sets the tapped bits for noise generation.
		public int TappedBits {
			get { return this.tappedBits; }
			set { this.tappedBits = value; }
		}

		#endregion

		#region Constructor

		///
		/// Creates an instance of a <see cref="ProgrammableSoundGenerator"/>
		///
		/// <param name="emulator">The emulator that contains the <see cref="ProgrammableSoundGenerator"/>.</param>
		public ProgrammableSoundGenerator(Emulator emulator) {
			this.Emulator = emulator;
			this.clockSpeed = this.Emulator.ClockSpeed / 16;
			this.ShiftRegisterWidth = 16;
			this.tappedBits = 0x9;
			this.Reset();
		}

		#endregion

		#region Methods

		///
		/// Resets the <see cref="ProgrammableSoundGenerator"/> to its default state.
		///
		public void Reset() {
			this.LatchedChannel = 0;
			this.LatchedMode = LatchMode.Tone;
			this.QueuedWrites = new Queue<QueuedWrite>(256);
			this.volumeRegisters = new byte[] { 0x0F, 0x0F, 0x0F, 0x0F };
			this.toneRegisters = new ushort[4];
			this.countDown = new int[4];
			this.levels = new int[] { 1, 1, 1, 1 };
			this.shiftRegister = (ushort)(1 << (this.ShiftRegisterWidth - 1));
			this.stereoDistribution = 0xFF;
		}

		///
		/// Sets the noise mode by a preset.
		///
		/// <param name="preset">The <see cref="NoisePresets"/> to use.</param>
		public void SetNoiseByPreset(NoisePresets preset) {
			switch (preset) {
				case NoisePresets.SegaMasterSystem:
					this.ShiftRegisterWidth = 16;
					this.tappedBits = 0x0009;
					break;
				case NoisePresets.SC3000:
					this.ShiftRegisterWidth = 16;
					this.tappedBits = 0x0006;
					break;
				case NoisePresets.BbcMicro:
					this.ShiftRegisterWidth = 15;
					this.tappedBits = 0x8005;
					break;
			}
		}

		#endregion

	}
}


text:
namespace integral {
    namespace detail {
        template<typename T>
        class FunctionTraits : public FunctorTraits<T> {};

        template<typename R, typename ...A>
        class FunctionTraits<std::function<R(A...)>> : public FunctionSignature<R(A...)> {};

        template<typename R, typename ...A>
        class FunctionTraits<R(*)(A...)> : public FunctionSignature<R(A...)> {};

        template<typename R, typename ...A>
        class FunctionTraits<R(&)(A...)> : public FunctionSignature<R(A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...)> : public FunctionSignature<R(T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) const> : public FunctionSignature<R(const T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) volatile> : public FunctionSignature<R(volatile T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) const volatile> : public FunctionSignature<R(const volatile T &, A...)> {};

        template<typename R, typename ...A>
        class FunctionTraits<R(*)(A...) noexcept> : public FunctionSignature<R(A...)> {};

        template<typename R, typename ...A>
        class FunctionTraits<R(&)(A...) noexcept> : public FunctionSignature<R(A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) noexcept> : public FunctionSignature<R(T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) const noexcept> : public FunctionSignature<R(const T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) volatile noexcept> : public FunctionSignature<R(volatile T &, A...)> {};

        template<typename R, typename T, typename ...A>
        class FunctionTraits<R(T::*)(A...) const volatile noexcept> : public FunctionSignature<R(const volatile T &, A...)> {};
    }
}

#endif