text:
module ActiveAdminJcrop
  module DSL

    def jcropable
      member_action :jcropper, method: :put do
        resource.active_admin_crop! params[:image_data]

        respond_to do |format|
          format.js { render json: true }
        end
      end
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.jutt.assignment1.TimerActivity"
    android:padding="0dp">

    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Wait..."
        android:id="@+id/measure_reaction"
        android:contextClickable="true"
        android:background="#505050"
        android:textSize="24dp"
        android:layout_centerHorizontal="true" />

</RelativeLayout>


text:
"""
File: otp.py
Author: Matthew Cole, Anh Quach, Dan Townley,
Date: 11/20/16
"""
import time
import sys
import otp
import argparse
try:
	from PIL import Image
	import zbarlight
except(ImportError):
	print("Prerequisites not met! pyOTP requires zbarlight.", file=sys.stderr)
	print("See https://github.com/Polyconseil/zbarlight for more information.", file=sys.stderr)
	sys.exit(0)

"""
Utility functions
"""
def _printURI(uri):
	"""
	Read a URI from a .png image file. Return its contents as a pretty string.
	"""
	### QR Code reading using zbarlite
	try:
		with open(uri, 'rb') as image_file:
			image = Image.open(image_file)
			image.load()
		codes = zbarlight.scan_codes('qrcode', image)
	except(IOError):
		print("Cannot open %s" % uri, file=sys.stderr)
		return

	#If there's a readable barcode, deprovision it
	if len(codes) == 1:
		type,name,secret,issuer,algorithm,digits,period = otp.deprovision(codes[0].decode())
	else:
		print("Found %i valid QR Codes in %s. Cannot decode!" % (len(codes), uri), file=sys.stderr)
		return

	#Log URI contents
	print("Type:", type)
	print("Name:", name)
	print("Secret:", secret)
	print("Issuer:", issuer)
	print("Algorithm:", algorithm)
	print("Digits:", digits)
	print("Period:", period)

def _header(mode="TOTP", digits=6):
	return  " ".join(["Timestamp".ljust(24), "Time Step".ljust(18), mode.ljust(digits), "Expired".ljust(10),\
					  "\n"+"-"*24,           "-"*18,                "-"*digits,         "-"*10])

def _expirebar(t, width=10, filltime=30):
	"""
	Print a timed expire bar of @param width '▩' characters.
	<t> is a number of seconds since the Unix epoch.
	The caller is responsible to add any ending whitespace
	characters needed after the final '▩'.
	"""

	#Calcuate the step time (time between each fill block)
	# and stop time (time when the bar is filled)
	start = t - (t % filltime) # (Unix Epoch) + (k)(filltime)
	step = filltime // width
	stop = start + filltime	   # (Unix Epoch) + (k+1)(filltime)

	#Initialy fill the bar, reflecting fraction expired at calltime
	intfill = ((t - start) // filltime) * width
	print(chr(9641)*(intfill),end="")

	# For each of (filltime / width) intervals,
	# print a fill block
	for t in range(start, stop, step):
		# Wait until the next time interval has passed
		while (int(time.time()) < t):
			pass

		# Print another fill block and flush
		print(chr(9641), end="")
		sys.stdout.flush()

if __name__ == "__main__":

	# Argument parsing
	parser = argparse.ArgumentParser(description='demonstrate the TOTP algorithm')
	parser.add_argument('--displayuri', help='display the contents of the URI', action="store_true")
	parser.add_argument('qrfile', help="path to the shared secret key QR Code .png file")
	args = parser.parse_args()

	### QR Code reading using zbarlite
	try:
		with open(args.qrfile, 'rb') as image_file:
			image = Image.open(image_file)
			image.load()
		codes = zbarlight.scan_codes('qrcode', image)
	except(IOError):
		print("Cannot open %s" % args.qrfile, file=sys.stderr)
		exit(0)

	#If there's a readable barcode, deprovision it
	if len(codes) == 1:
		_,_,secret,_,mode,digit,x = otp.deprovision(codes[0].decode())
		mode = otp.DIGESTS[mode]

	else:
		print("Found %i valid QR Codes in %s. Cannot decode!" % (len(codes), args.qrfile), file=sys.stderr)
		exit(0)

	# Print the URI read
	if args.displayuri:
		_printURI(args.qrfile)

	# Print the header
	print(_header())

	# Calculate first step
	now = int(time.time())
	next = now - (now % x) + x
	ts = otp.T(now, x)
	totp = otp.TOTP(secret,ts,digit=digit, digest=mode)

	# Continue generating TOTP passwords until halted by user
	while(True):

		# Print the next TOTP data
		print(time.asctime(time.localtime(now)), hex(ts).ljust(18), totp.ljust(digit), sep=" ", end = " ")
		sys.stdout.flush()

		# Print the next expiration bar
		try:
			_expirebar(now, filltime=x)
		except (KeyboardInterrupt, SystemExit):
			print("\nExiting OTP Demo...")
			sys.exit(0)
		finally:
			print("")
			sys.stdout.flush()

		# Step forward, recalculate T
		now = next
		next += x
		ts = otp.T(now, x)
		totp = otp.TOTP(secret,ts,digit=digit, digest=mode)


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Nucleo.State
{
	[TestClass]
	public class StatePropertyCollectionTest
	{
		#region " Tests "

		[TestMethod]
		public void AccessingPropertiesByNameReturnsCorrectReference()
		{
			StatePropertyCollection collection = new StatePropertyCollection();
			collection.Add(new StateProperty("Test", "Test"));
			collection.Add(new StateProperty("ColorScheme", "Blue"));
			collection.Add(new StateProperty("Region", "Northern"));

			Assert.IsNotNull(collection["Test"]);
			Assert.IsNotNull(collection["Region"]);

			Assert.IsNull(collection["First"]);
			Assert.IsNull(collection["ColorScheme2"]);

		}

		#endregion
	}
}


text:
package com.cloudant.se.util;

import java.io.File;

public class UFile {
    public static File ensureReadWriteDirectory(File directory) {
        if (directory.exists()) {
            if (directory.isDirectory()) {
                if (directory.canRead() && directory.canWrite()) {
                    return directory;
                } else {
                    throw new IllegalArgumentException(directory.getName() + " must be a directory that we can read/write to");
                }
            } else {
                throw new IllegalArgumentException(directory.getName() + " must point at a directory not a file");
            }
        } else {
            if (directory.mkdirs()) {
                return directory;
            } else {
                throw new RuntimeException("Unable to create directory for \"" + directory.getName() + "\"");
            }
        }
    }
}


text:
package de.dakror.spamwars.layer;

import java.awt.Font;
import java.awt.Graphics2D;
import java.net.InetAddress;

import de.dakror.gamesetup.ui.ClickEvent;
import de.dakror.gamesetup.util.Helper;
import de.dakror.spamwars.game.Game;
import de.dakror.spamwars.net.packet.Packet;
import de.dakror.spamwars.settings.CFG;
import de.dakror.spamwars.ui.MenuButton;

/**
 * @author Dakror
 */
public class MenuLayer extends MPLayer {
    int goingto;

    static LobbyLayer ll;

    @Override
    public void draw(Graphics2D g) {
        g.drawImage(Game.getImage("gui/menu.png"), 0, 0, Game.getWidth(), Game.getHeight(), Game.w);
        Helper.drawImageCenteredRelativeScaled(Game.getImage("gui/title.png"), 80, 1920, 1080, Game.getWidth(), Game.getHeight(), g);

        if (!CFG.INTERNET && Game.user.getIP() != null) {
            Font old = g.getFont();
            g.setFont(new Font("", Font.PLAIN, 20));
            Helper.drawHorizontallyCenteredString("Offline-Mode: " + Game.user.getUsername() + " (" + Game.user.getIP().getHostAddress() + ")", Game.getWidth(), 20, g, 20);
            g.setFont(old);
        }

        drawComponents(g);
    }

    @Override
    public void update(int tick) {
        updateComponents(tick);
        if (Game.currentFrame.alpha == 1 && enabled) {
            Game.currentFrame.fadeTo(0, 0.05f);
            new Thread() {
                @Override
                public void run() {
                    if (goingto == 1) Game.currentFrame.addLayer(ll);
                    if (goingto == 2) Game.currentFrame.addLayer(new JoinLayer());
                    if (goingto == 3) Game.currentFrame.addLayer(new WeaponryLayer(true));

                    goingto = 0;
                }
            }.start();
        }

        if (Game.weapons != null) {
            components.get(0).enabled = Game.weapons.length() > 0;
            components.get(1).enabled = Game.weapons.length() > 0;
        }

        enabled = Game.currentGame.getActiveLayer().equals(this);
    }

    @Override
    public void init() {
        ll = new LobbyLayer();
        Game.pullMoney();
        Game.pullWeapons();

        MenuButton start = new MenuButton("startGame", "Create Game", 0);
        start.addClickEvent(new ClickEvent() {
            @Override
            public void trigger() {
                goingto = 1;
                Game.currentFrame.fadeTo(1, 0.05f);
            }
        });
        components.add(start);
        MenuButton joingame = new MenuButton("joinGame", "Join Game", 1);
        joingame.addClickEvent(new ClickEvent() {
            @Override
            public void trigger() {
                goingto = 2;
                Game.currentFrame.fadeTo(1, 0.05f);
            }
        });
        components.add(joingame);
        MenuButton wpn = new MenuButton("weaponry", "Weaponry", 2);
        wpn.addClickEvent(new ClickEvent() {
            @Override
            public void trigger() {
                goingto = 3;
                Game.currentFrame.fadeTo(1, 0.05f);
            }
        });
        components.add(wpn);
        MenuButton opt = new MenuButton("options", "Options", 3);
        opt.addClickEvent(new ClickEvent() {
            @Override
            public void trigger() {
                Game.currentGame.addLayer(new SettingsLayer());
            }
        });
        components.add(opt);
        MenuButton end = new MenuButton("endGame", "Exit Game", 4);
        end.addClickEvent(new ClickEvent() {
            @Override
            public void trigger() {
                System.exit(0);
            }
        });
        components.add(end);
    }

    @Override
    public void onPacketReceived(Packet p, InetAddress ip, int port) {
        ll.onPacketReceived(p, ip, port);
    }
}


text:
'use strict';

module.exports = {

    init: function (fncs, app) {

        var acl = fncs.acl(),
            passport = fncs.passport(),
            controller = require('../controllers/UserController');

        app.get('/user/get', /* passport.authenticate('local', { failureRedirect: '/login' }), acl.middleware(), */ controller.renderGetUsers);

    }

};


text:
layout: default
disqus: false
archive: false
post_class: post-template
---

        Home

{{ page.title }}

                <time class="post-date" datetime="{{ page.date | date:"%Y-%m-%d" }}">{{ page.date | date_to_string }}</time>
                {% if page.categories.size > 0 %}
                    {{ page.categories | array_to_sentence_string | prepend: 'on ' }}
                {% endif %}

            {{content}}

        {% if page.archive %}

Archive

                {% for post in site.posts %}
                    {% if post.published %}

{{ post.date | date_to_string }}  {{ post.title }}

                    {% endif %}
                {% endfor %}

        {% endif %}

            {% include share.html %}

            {% include disqus.html %}


text: basic css cool stuff


text:
wslay is a callback based WebSocket Client and Server library written in C, it doesn't come with a event loop or does I/O operations on its own. https://github.com/tatsuhiro-t/wslay

The following callbacks are exposed in this wrapper

```ruby
wslay_callbacks = Wslay::Event::Callbacks.new

wslay_callbacks.recv_callback do |buf, len|
  # when wslay wants to read data
  # buf is a cptr, if your I/O gem can write to a C pointer you have to write at most len bytes into it
  # and return the bytes written
  # or else return a mruby String or a object which can be converted into a String via to_str
  # and be up to len bytes long
  # the I/O object must be in non blocking mode and raise EAGAIN/EWOULDBLOCK when there is nothing to read
end

wslay_callbacks.on_msg_recv_callback do |msg|
  # when a WebSocket msg is fully recieved this callback is called
  # you get a Wslay::Event::OnMsgRecvArg Struct back with the following fields
  # :rsv => reserved field from WebSocket spec, there are Wslay.get_rsv1/2/3 helper methods
  # :opcode => :continuation_frame, :text_frame, :binary_frame, :connection_close, :ping or
  # :pong, Wslay.is_ctrl_frame? helper method is provided too
  # :msg => the message revieced
  # :status_code => :normal_closure, :going_away, :protocol_error, :unsupported_data, :no_status_rcvd,
  # :abnormal_closure, :invalid_frame_payload_data, :policy_violation, :message_too_big, :mandatory_ext,
  # :internal_server_error, :tls_handshake
  # to_str => returns the message revieced
end

wslay_callbacks.send_callback |buf|
  # when there is data to send, you have to return the bytes send here
  # the I/O object must be in non blocking mode and raise EAGAIN/EWOULDBLOCK when sending would block
end
```

How to setup
```ruby
client = Wslay::Event::Client.new wslay_callbacks
```

To queue a message for sending
```ruby
client.queue_msg("hello world", #optional :opcode)
```

To queue a close message
```ruby
client.queue_close(:status_code, #optional reason)
```

For a fully working example: https://github.com/Asmod4n/mruby-websockets/blob/master/mrblib/client.rb

Acknowledgements
================
This is using code from https://github.com/tatsuhiro-t/wslay

The MIT License

Copyright (c) 2011, 2012, 2015 Tatsuhiro Tsujikawa

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package org.zstack.test.securitygroup;

import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.header.vm.VmNicVO;
import org.zstack.network.securitygroup.SecurityGroupInventory;
import org.zstack.network.securitygroup.SecurityGroupRuleTO;
import org.zstack.simulator.SimulatorSecurityGroupBackend;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.concurrent.TimeUnit;

/**
 * @author frank
 * @condition 1. create a security group: sg and attach to l3network
 * 2. create vm1 and vm1Nic1 to sg
 * 3. stop vm
 * 4. remove vm1Nic1 from sg
 * @test confirm after removing nic, rules for vm1Nic1 were removed
 */
public class TestRemoveVmNicFromSecurityGroupOnVmStopped {
    static CLogger logger = Utils.getLogger(TestRemoveVmNicFromSecurityGroupOnVmStopped.class);
    static Deployer deployer;
    static Api api;
    static ComponentLoader loader;
    static DatabaseFacade dbf;
    static SimulatorSecurityGroupBackend sbkd;

    @BeforeClass
    public static void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/securityGroup/TestApplySeurityGroupRulesToVmOnSimulator.xml", con);
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        dbf = loader.getComponent(DatabaseFacade.class);
        sbkd = loader.getComponent(SimulatorSecurityGroupBackend.class);
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        SecurityGroupInventory scinv = deployer.securityGroups.get("test");
        VmInstanceInventory vm1 = deployer.vms.get("TestVm");
        L3NetworkInventory l3nw1 = deployer.l3Networks.get("TestL3Network1");
        VmNicInventory vm1Nic1 = SecurityGroupTestValidator.getVmNicOnSpecificL3Network(vm1.getVmNics(), l3nw1.getUuid());

        api.addVmNicToSecurityGroup(scinv.getUuid(), vm1Nic1.getUuid());

        TimeUnit.MILLISECONDS.sleep(500);
        String nicname = dbf.findByUuid(vm1Nic1.getUuid(), VmNicVO.class).getInternalName();
        SecurityGroupRuleTO vm1Nic1TO = sbkd.getRulesOnHost(vm1.getHostUuid(), nicname);
        SecurityGroupTestValidator.validate(vm1Nic1TO, scinv.getRules());

        api.stopVmInstance(vm1.getUuid());
        api.removeVmNicFromSecurityGroup(scinv.getUuid(), vm1Nic1.getUuid());
        vm1Nic1TO = sbkd.getRulesOnHost(vm1.getHostUuid(), nicname);
        Assert.assertTrue(vm1Nic1TO.getRules().isEmpty());
    }
}


text:
package com.google.api.client.googleapis.json;

import com.google.api.client.googleapis.json.GoogleJsonErrorTest.ErrorTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.Json;
import com.google.api.client.testing.http.HttpTesting;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import java.io.InputStream;
import junit.framework.TestCase;

/**
 * Tests {@link GoogleJsonResponseException}.
 *
 * @author Yaniv Inbar
 */
public class GoogleJsonResponseExceptionTest extends TestCase {

  public void testFrom_noDetails() throws Exception {
    HttpTransport transport = new MockHttpTransport();
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("200"));
  }

  public void testFrom_withDetails() throws Exception {
    HttpTransport transport = new ErrorTransport();
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertEquals(
        com.google.api.client.googleapis.json.GoogleJsonErrorTest.ERROR,
        com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY.toString(
            ge.getDetails()));
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_detailsMissingContent() throws Exception {
    HttpTransport transport = new ErrorTransport(null, Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_detailsArbitraryJsonContent() throws Exception {
    HttpTransport transport = new ErrorTransport("{\"foo\":\"bar\"}", Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_detailsArbitraryXmlContent() throws Exception {
    HttpTransport transport = new ErrorTransport("<foo>", "application/atom+xml; charset=utf-8");
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
    assertTrue(ge.getMessage().contains("<foo>"));
  }

  public void testFrom_errorNoContentButWithJsonContentType() throws Exception {
    HttpTransport transport = new ErrorTransport("", Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_errorEmptyContentButWithJsonContentType() throws Exception {
    HttpTransport transport = new ErrorTransport(null, Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_detailsErrorObject() throws Exception {
    HttpTransport transport =
        new ErrorTransport(
            "{\"error\": {\"message\": \"invalid_token\"}, \"error_description\": \"Invalid value\"}",
            Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNotNull(ge.getDetails());
    assertEquals("invalid_token", ge.getDetails().getMessage());
    assertTrue(ge.getMessage().contains("403"));
  }

  public void testFrom_detailsErrorString() throws Exception {
    HttpTransport transport =
        new ErrorTransport(
            "{\"error\": \"invalid_token\", \"error_description\": \"Invalid value\"}",
            Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().contains("403"));
    assertTrue(ge.getMessage().contains("invalid_token"));
  }

  public void testFrom_detailsNoErrorField() throws Exception {
    HttpTransport transport =
        new ErrorTransport("{\"error_description\": \"Invalid value\"}", Json.MEDIA_TYPE);
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage().startsWith("403"));
  }

  public void testFrom_detailsWithInvalidParameter() throws Exception {
    String DETAILS_ERROR =
        "{"
            + "\"code\":400,"
            + "\"details\":[{"
            + "\"@type\":\"type.googleapis.com/google.dataflow.v1beta3.InvalidTemplateParameters\","
            + "\"parameterViolations\":[{"
            + "\"description\":\"Parameter didn't match regex '^[0-9a-zA-Z_]+$'\","
            + "\"parameter\":\"safeBrowsingApiKey\""
            + "}]},{"
            + "\"@type\":\"type.googleapis.com/google.rpc.DebugInfo\","
            + "\"detail\":\"test detail\"}],"
            + "\"message\":\"The template parameters are invalid.\","
            + "\"status\":\"INVALID_ARGUMENT\""
            + "}";
    InputStream errorContent =
        com.google.api.client.googleapis.json.GoogleJsonErrorTest.class.getResourceAsStream(
            "error.json");
    HttpTransport transport =
        new ErrorTransport(
            new MockLowLevelHttpResponse()
                .setContent(errorContent)
                .setContentType(Json.MEDIA_TYPE)
                .setStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN));
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge =
        GoogleJsonResponseException.from(
            com.google.api.client.googleapis.json.GoogleJsonErrorTest.FACTORY, response);
    assertNotNull(ge.getDetails().getDetails());
  }
}


text:
Simple system intel tool for eve online.

[Demo](http://demo.ffevo.net/)

#### Data Sources
+ [crest](https://developers.eveonline.com/)
+ [zkillboard](https://github.com/zKillboard/zKillboard/wiki)
+ [evemaps](http://evemaps.dotlan.net)
+ [fuzzworks](https://www.fuzzwork.co.uk/tools/api-map-data/)
+ [eve central](https://eve-central.com/home/develop.html)

#### System Requirements
+ nginx
+ php 5
+ curl
+ [composer](https://getcomposer.org/download/)

#### Installation
These instructions assume an unconfigured debian based linux system

Install nginx, php and git

```sudo apt-get install nginx php5-fpm php5-curl git```

Clone Copilot

```cd /var/www/```

```git clone https://github.com/RZN-FFEvo/CoPilot.git```

```cd CoPilot```

Install Composer using the command line option:

<https://getcomposer.org/download/>

Set up composer

```sudo php composer.phar -d=./core install```

Create the cache directory (because i'm bad at git)

```sudo mkdir core/cache```

Set file permissions

```sudo chmod -R 0755 core/cache```

Set file owner

```sudo chown -R www-data ./```

Create and edit the config.

Note: this version does not require app keys from cpp as a did not have time to finish the authenticated crest features.

```mv core/config.php.dist core/config.php```

I like nano, use what you like

```nano core/config.php```

Change "baseURL" to your url. "Ctrl + o" saves, "Ctrl + x" quits

Time to configure nginx.

Copy the example configuration:

```sudo cp copilot.nginx.conf /etc/nginx/sites-available/copilot.conf```

Edit it:

```sudo nano /etc/nginx/sites-available/copilot.conf```

if you are using a domain, change "server_name" to your domain name

make sure "root" is the path to CoPilot/public

save "Ctrl + o", quit "Ctrl + x"

symlink our new config so nginx will load it

 ```sudo ln -s /etc/nginx/sites-available/copilot.conf /etc/nginx/sites-enabled/copilot.conf```

 you can use the command "sudo nginx -t" to check your configuration

restart nginx

```sudo service nginx restart```

restart php

```sudo service php5-fpm restart```

You should be able to access the site now.

If you get an error message check the error log:

```tail /var/log/nginx/error.log```


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_61b.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-61b.tmpl.cpp
*/
/*
 * @description
 * CWE: 36 Absolute Path Traversal
 * BadSource: file Read input from a file
 * GoodSource: Full path and file name
 * Sinks: fopen
 *    BadSink : Open the file named in data using fopen()
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#ifdef _WIN32
#define FOPEN _wfopen
#else
#define FOPEN fopen
#endif

namespace CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_61
{

#ifndef OMITBAD

wchar_t * badSource(wchar_t * data)
{
    {
        /* Read input from a file */
        size_t dataLen = wcslen(data);
        FILE * pFile;
        /* if there is room in data, attempt to read the input from a file */
        if (FILENAME_MAX-dataLen > 1)
        {
            pFile = fopen(FILENAME, "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read data from a file */
                if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
                {
                    printLine("fgetws() failed");
                    /* Restore NUL terminator if fgetws fails */
                    data[dataLen] = L'\0';
                }
                fclose(pFile);
            }
        }
    }
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
wchar_t * goodG2BSource(wchar_t * data)
{
#ifdef _WIN32
    /* FIX: Use a fixed, full path and file name */
    wcscat(data, L"c:\\temp\\file.txt");
#else
    /* FIX: Use a fixed, full path and file name */
    wcscat(data, L"/tmp/file.txt");
#endif
    return data;
}

#endif /* OMITGOOD */

} /* close namespace */


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('transactions', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='transaction',
            name='response',
            field=models.CharField(default=b'', max_length=4, null=True, blank=True),
        ),
    ]


text: vue dev workflow


text:
import logging
import unittest

import ddt
from sqlalchemy import (  # noqa: F401
    and_,
    between,
    select,
    not_,
)

from tests import db
from tests.db import foo, bar, wumbo
from sqlitis.convert import to_sqla

LOG = logging.getLogger(__name__)
TABLES = {"foo": foo, "bar": bar, "wumbo": wumbo}

@ddt.ddt
class TestFunctional(unittest.TestCase):
    def setUp(self):
        super(TestFunctional, self).setUp()
        self.engine = db.connect()

    @ddt.file_data("data.yaml")
    def test_select(self, sql, data=None, output=None, **kwargs):
        if not data or not output:
            self.skipTest("No functional test specified for this SQL query")

        self._prepare_data(data)
        if not isinstance(sql, list):
            sql = [sql]
        for s in sql:
            self._run(s, output)

    def _prepare_data(self, data):
        LOG.debug("Preparing test data")
        for table_name, values in data.items():
            LOG.debug("  insert into %s values %s", table_name, values)
            table = TABLES[table_name]
            self.engine.execute(table.insert(), values)

    def _run(self, sql, output):
        LOG.debug("sql: '%s'", sql)

        sqla = eval(to_sqla(sql))
        result = self.engine.execute(sqla)
        rows = [list(x) for x in result.fetchall()]
        self.assertEqual(rows, output)


text:
import sys
import six
from django.core.exceptions import ValidationError
from ..models import Driver, Competition, Team, Season, Circuit
from ..models import TeamSeason, Seat, GrandPrix, Race, Result, ContenderSeason, CompetitionTeam

def retro_encode(text):
    if sys.version_info < (3, 0):
        try:
            return text.encode('utf-8')
        except UnicodeDecodeError:
            return text
    else:
        return text

class CommonCreateTestCase(object):
    def set_test_create(self, model, **kwargs):
        return model.objects.create(**kwargs)

class CommonDriverTestCase(CommonCreateTestCase):
    def get_test_driver(self, **kwargs):
        defaults = {
            'last_name': u'García',
            'first_name': u'Juan'
        }
        defaults.update(**kwargs)
        return self.set_test_create(model=Driver, **defaults)

    def get_test_driver_2(self):
        kwargs = {
            'last_name': u'López',
            'first_name': u'Jaime'
        }
        return self.get_test_driver(**kwargs)

class CommonCompetitionTestCase(CommonCreateTestCase):
    def get_test_competition(self, **kwargs):
        defaults = {
            'name': u'Competición A',
            'full_name': u'Competición ABC'
        }
        defaults.update(**kwargs)
        return self.set_test_create(model=Competition, **defaults)

    def get_test_competition_2(self):
        kwargs = {
            'name': u'Competición B',
            'full_name': u'Competición BDF'
        }
        return self.get_test_competition(**kwargs)

class CommonTeamTestCase(CommonCompetitionTestCase):
    def get_test_team(self, **kwargs):
        defaults = {
            'name': u'Escudería Tec Auto',
            'full_name': u'Escudería Tec Auto'
        }
        defaults.update(**kwargs)
        return self.set_test_create(model=Team, **defaults)

    def get_test_team_2(self):
        kwargs = {
            'name': u'D27R',
            'full_name': u'Driver 27 Racing Team'
        }
        return self.get_test_team(**kwargs)

    def get_test_competition_team(self, **kwargs):
        defaults = {}
        defaults.update(**kwargs)
        if 'competition' not in defaults:
            defaults['competition'] = self.get_test_competition()
        if 'team' not in defaults:
            defaults['team'] = self.get_test_team()
        return self.set_test_create(model=CompetitionTeam, **defaults)

class CommonSeasonTestCase(CommonCompetitionTestCase):
    def get_test_season(self, **kwargs):
        defaults = {
            'year': 2016,
            'punctuation': u'F1-25'
        }
        defaults.update(**kwargs)
        if 'competition' not in defaults:
            defaults['competition'] = self.get_test_competition()
        return self.set_test_create(model=Season, **defaults)

class CommonTeamSeasonTestCase(CommonTeamTestCase, CommonSeasonTestCase):
    pass

class CommonSeatTestCase(CommonDriverTestCase, CommonTeamTestCase):
    def get_test_seat(self, **kwargs):
        defaults = {}
        defaults.update(**kwargs)
        if 'driver' not in defaults:
            defaults['driver'] = self.get_test_driver()
        if 'team' not in defaults:
            defaults['team'] = self.get_test_team()
        return self.set_test_create(model=Seat, **defaults)

    def get_test_seat_teammate(self, seat_a):
        driver = self.get_test_driver_2()
        team = seat_a.team
        seat_args = {'driver': driver, 'team': team}
        return self.get_test_seat(**seat_args)

    def get_test_seat_same_driver_other_team(self, seat_a):
        driver = seat_a.driver
        team = self.get_test_team_2()
        seat_args = {'driver': driver, 'team': team}
        return self.get_test_seat(**seat_args)

class CommonRaceTestCase(CommonSeasonTestCase):
    def get_test_race(self, **kwargs):
        defaults = {'round': 1}
        defaults.update(**kwargs)
        if 'season' not in defaults:
            defaults['season'] = self.get_test_season()
        return self.set_test_create(model=Race, **defaults)

    def get_test_circuit(self, **kwargs):
        defaults = {
            'name': u'Autódromo de Jacarepaguá',
            'city': u'Jacarepaguá',
            'opened_in': 1978
        }
        defaults.update(**kwargs)
        return self.set_test_create(model=Circuit, **defaults)

    def get_test_grandprix(self, **kwargs):
        defaults = {'name': u'Grande Prêmio do Brasil'}
        defaults.update(**kwargs)
        return self.set_test_create(model=GrandPrix, **defaults)

class CommonResultTestCase(CommonSeatTestCase, CommonRaceTestCase):
    def get_test_result(self, **kwargs):
        defaults = {}
        defaults.update(**kwargs)
        if 'seat' not in defaults:
            defaults['seat'] = self.get_test_seat()
        if 'race' not in defaults:
            defaults['race'] = self.get_test_race()
        return self.set_test_create(model=Result, **defaults)


text:
package org.elasticsearch.gradle.precommit;

import org.apache.commons.codec.binary.Hex;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.file.FileCollection;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * A task to check licenses for dependencies.
 *
 * There are two parts to the check:
 *

 *
LICENSE and NOTICE files

 *
SHA checksums for each dependency jar

 *

 *
 * The directory to find the license and sha files in defaults to the dir @{code licenses}
 * in the project directory for this task. You can override this directory:
 *

 *   dependencyLicenses {
 *     licensesDir = getProject().file("mybetterlicensedir")
 *   }
 *

 *
 * The jar files to check default to the dependencies from the default configuration. You
 * can override this, for example, to only check compile dependencies:
 *

 *   dependencyLicenses {
 *     dependencies = getProject().configurations.compile
 *   }
 *

 *
 * Every jar must have a {@code .sha1} file in the licenses dir. These can be managed
 * automatically using the {@code updateShas} helper task that is created along
 * with this task. It will add {@code .sha1} files for new jars that are in dependencies
 * and remove old {@code .sha1} files that are no longer needed.
 *
 * Every jar must also have a LICENSE and NOTICE file. However, multiple jars can share
 * LICENSE and NOTICE files by mapping a pattern to the same name.
 *

 *   dependencyLicenses {
 *     mapping from: /lucene-.*/, to: "lucene"
 *   }
 *

 */
public class DependencyLicensesTask extends DefaultTask {

    private final Pattern regex = Pattern.compile("-v?\\d+.*");

    private final Logger logger = Logging.getLogger(getClass());

    private static final String SHA_EXTENSION = ".sha1";

    // TODO: we should be able to default this to eg compile deps, but we need to move the licenses
    // check from distribution to core (ie this should only be run on java projects)
    /** A collection of jar files that should be checked. */
    private FileCollection dependencies;

    /** The directory to find the license and sha files in. */
    private File licensesDir = new File(getProject().getProjectDir(), "licenses");

    /** A map of patterns to prefix, used to find the LICENSE and NOTICE file. */
    private Map<String, String> mappings = new LinkedHashMap<>();

    /** Names of dependencies whose shas should not exist. */
    private Set<String> ignoreShas = new HashSet<>();

    /**
     * Add a mapping from a regex pattern for the jar name, to a prefix to find
     * the LICENSE and NOTICE file for that jar.
     */
    public void mapping(Map<String, String> props) {
        String from = props.remove("from");
        if (from == null) {
            throw new InvalidUserDataException("Missing \"from\" setting for license name mapping");
        }
        String to = props.remove("to");
        if (to == null) {
            throw new InvalidUserDataException("Missing \"to\" setting for license name mapping");
        }
        if (props.isEmpty() == false) {
            throw new InvalidUserDataException("Unknown properties for mapping on dependencyLicenses: " + props.keySet());
        }
        mappings.put(from, to);
    }

    @InputFiles
    public FileCollection getDependencies() {
        return dependencies;
    }

    public void setDependencies(FileCollection dependencies) {
        this.dependencies = dependencies;
    }

    @Optional
    @InputDirectory
    public File getLicensesDir() {
        if (licensesDir.exists()) {
            return licensesDir;
        }

        return null;
    }

    public void setLicensesDir(File licensesDir) {
        this.licensesDir = licensesDir;
    }

    /**
     * Add a rule which will skip SHA checking for the given dependency name. This should be used for
     * locally build dependencies, which cause the sha to change constantly.
     */
    public void ignoreSha(String dep) {
        ignoreShas.add(dep);
    }

    @TaskAction
    public void checkDependencies() throws IOException, NoSuchAlgorithmException {
        if (dependencies == null) {
            throw new GradleException("No dependencies variable defined.");
        }

        if (dependencies.isEmpty()) {
            if (licensesDir.exists()) {
                throw new GradleException("Licenses dir " + licensesDir + " exists, but there are no dependencies");
            }
            return; // no dependencies to check
        } else if (licensesDir.exists() == false) {
            throw new GradleException("Licences dir " + licensesDir + " does not exist, but there are dependencies");
        }

        Map<String, Boolean> licenses = new HashMap<>();
        Map<String, Boolean> notices = new HashMap<>();
        Set<File> shaFiles = new HashSet<>();

        for (File file : licensesDir.listFiles()) {
            String name = file.getName();
            if (name.endsWith(SHA_EXTENSION)) {
                shaFiles.add(file);
            } else if (name.endsWith("-LICENSE") || name.endsWith("-LICENSE.txt")) {
                // TODO: why do we support suffix of LICENSE *and* LICENSE.txt??
                licenses.put(name, false);
            } else if (name.contains("-NOTICE") || name.contains("-NOTICE.txt")) {
                notices.put(name, false);
            }
        }

        checkDependencies(licenses, notices, shaFiles);

        licenses.forEach((item, exists) -> failIfAnyMissing(item, exists, "license"));

        notices.forEach((item, exists) -> failIfAnyMissing(item, exists, "notice"));

        if (shaFiles.isEmpty() == false) {
            throw new GradleException("Unused sha files found: \n" + joinFilenames(shaFiles));
        }
    }

    private void failIfAnyMissing(String item, Boolean exists, String type) {
        if (exists == false) {
            throw new GradleException("Unused " + type + " " + item);
        }
    }

    private void checkDependencies(Map<String, Boolean> licenses, Map<String, Boolean> notices, Set<File> shaFiles)
        throws NoSuchAlgorithmException, IOException {
        for (File dependency : dependencies) {
            String jarName = dependency.getName();
            String depName = regex.matcher(jarName).replaceFirst("");

            validateSha(shaFiles, dependency, jarName, depName);

            String dependencyName = getDependencyName(mappings, depName);
            logger.info("mapped dependency name {} to {} for license/notice check", depName, dependencyName);
            checkFile(dependencyName, jarName, licenses, "LICENSE");
            checkFile(dependencyName, jarName, notices, "NOTICE");
        }
    }

    private void validateSha(Set<File> shaFiles, File dependency, String jarName, String depName) throws NoSuchAlgorithmException,
        IOException {
        if (ignoreShas.contains(depName)) {
            // local deps should not have sha files!
            if (getShaFile(jarName).exists()) {
                throw new GradleException("SHA file " + getShaFile(jarName) + " exists for ignored dependency " + depName);
            }
        } else {
            logger.info("Checking sha for {}", jarName);
            checkSha(dependency, jarName, shaFiles);
        }
    }

    private String joinFilenames(Set<File> shaFiles) {
        List<String> names = shaFiles.stream().map(File::getName).collect(Collectors.toList());
        return String.join("\n", names);
    }

    public static String getDependencyName(Map<String, String> mappings, String dependencyName) {
        // order is the same for keys and values iteration since we use a linked hashmap
        List<String> mapped = new ArrayList<>(mappings.values());
        Pattern mappingsPattern = Pattern.compile("(" + String.join(")|(", mappings.keySet()) + ")");
        Matcher match = mappingsPattern.matcher(dependencyName);
        if (match.matches()) {
            int i = 0;
            while (i < match.groupCount() && match.group(i + 1) == null) {
                ++i;
            }
            return mapped.get(i);
        }
        return dependencyName;
    }

    private void checkSha(File jar, String jarName, Set<File> shaFiles) throws NoSuchAlgorithmException, IOException {
        File shaFile = getShaFile(jarName);
        if (shaFile.exists() == false) {
            throw new GradleException("Missing SHA for " + jarName + ". Run \"gradle updateSHAs\" to create them");
        }

        // TODO: shouldn't have to trim, sha files should not have trailing newline
        byte[] fileBytes = Files.readAllBytes(shaFile.toPath());
        String expectedSha = new String(fileBytes, StandardCharsets.UTF_8).trim();

        String sha = getSha1(jar);

        if (expectedSha.equals(sha) == false) {
            final String exceptionMessage = String.format(
                Locale.ROOT,
                "SHA has changed! Expected %s for %s but got %s."
                    + "\nThis usually indicates a corrupt dependency cache or artifacts changed upstream."
                    + "\nEither wipe your cache, fix the upstream artifact, or delete %s and run updateShas",
                expectedSha,
                jarName,
                sha,
                shaFile
            );

            throw new GradleException(exceptionMessage);
        }
        shaFiles.remove(shaFile);
    }

    private void checkFile(String name, String jarName, Map<String, Boolean> counters, String type) {
        String fileName = getFileName(name, counters, type);

        if (counters.containsKey(fileName) == false) {
            throw new GradleException("Missing " + type + " for " + jarName + ", expected in " + fileName);
        }

        counters.put(fileName, true);
    }

    private String getFileName(String name, Map<String, ?> counters, String type) {
        String fileName = name + "-" + type;

        if (counters.containsKey(fileName) == false) {
            // try the other suffix...TODO: get rid of this, just support ending in .txt
            return fileName + ".txt";
        }

        return fileName;
    }

    @Input
    public LinkedHashMap<String, String> getMappings() {
        return new LinkedHashMap<>(mappings);
    }

    File getShaFile(String jarName) {
        return new File(licensesDir, jarName + SHA_EXTENSION);
    }

    @Internal
    Set<File> getShaFiles() {
        File[] array = licensesDir.listFiles();
        if (array == null) {
            throw new GradleException("\"" + licensesDir.getPath() + "\" isn't a valid directory");
        }

        return Arrays.stream(array).filter(file -> file.getName().endsWith(SHA_EXTENSION)).collect(Collectors.toSet());
    }

    String getSha1(File file) throws IOException, NoSuchAlgorithmException {
        byte[] bytes = Files.readAllBytes(file.toPath());

        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        char[] encoded = Hex.encodeHex(digest.digest(bytes));
        return String.copyValueOf(encoded);
    }

}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.logging;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.testing.drivers.Browser.HTMLUNIT;
import static org.openqa.selenium.testing.drivers.Browser.IE;
import static org.openqa.selenium.testing.drivers.Browser.FIREFOX;
import static org.openqa.selenium.testing.drivers.Browser.SAFARI;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JupiterTestBase;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;

@Ignore(HTMLUNIT)
@Ignore(IE)
@Ignore(FIREFOX)
@Ignore(SAFARI)
class GetLogsTest extends JupiterTestBase {

  private WebDriver localDriver;

  @AfterEach
  public void quitDriver() {
    if (localDriver != null) {
      localDriver.quit();
      localDriver = null;
    }
  }

  @Test
  void logBufferShouldBeResetAfterEachGetLogCall() {
    driver.get(pages.errorsPage);
    driver.findElement(By.cssSelector("input")).click();

    LogEntries firstEntries = driver.manage().logs().get(LogType.BROWSER);
    assertThat(firstEntries.getAll()).isNotEmpty();
    assertThat(driver.manage().logs().get(LogType.BROWSER).getAll()).isEmpty();

    driver.findElement(By.cssSelector("input")).click();
    LogEntries secondEntries = driver.manage().logs().get(LogType.BROWSER);
    assertThat(secondEntries.getAll()).isNotEmpty();
    assertThat(hasOverlappingLogEntries(firstEntries, secondEntries))
        .describedAs("There should be no overlapping log entries in consecutive get log calls")
        .isFalse();
  }

  @Test
  void differentLogsShouldNotContainTheSameLogEntries() {
    driver.get(pages.errorsPage);
    driver.findElement(By.cssSelector("input")).click();

    Map<String, LogEntries> logTypeToEntriesMap = new HashMap<>();
    Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypes) {
      logTypeToEntriesMap.put(logType, driver.manage().logs().get(logType));
    }

    for (Map.Entry<String, LogEntries> entry : logTypeToEntriesMap.entrySet()) {
      for (Map.Entry<String, LogEntries> nested : logTypeToEntriesMap.entrySet()) {
        if (!entry.getKey().equals(nested.getKey())) {
          assertThat(hasOverlappingLogEntries(entry.getValue(), nested.getValue()))
            .describedAs("Two different log types (%s, %s) should not  contain the same log entries", entry.getKey(), nested.getKey())
            .isFalse();
        }
      }
    }
  }

  /**
   * Checks if there are overlapping entries in the given logs.
   *
   * @param firstLog The first log.
   * @param secondLog The second log.
   * @return true if an overlapping entry is discovered, otherwise false.
   */
  private static boolean hasOverlappingLogEntries(LogEntries firstLog, LogEntries secondLog) {
    for (LogEntry firstEntry : firstLog) {
      for (LogEntry secondEntry : secondLog) {
        if (firstEntry.getLevel().getName().equals(secondEntry.getLevel().getName()) &&
            firstEntry.getMessage().equals(secondEntry.getMessage()) &&
            firstEntry.getTimestamp() == secondEntry.getTimestamp()) {
          return true;
        }
      }
    }
    return false;
  }

  @Test
  void turningOffLogShouldMeanNoLogMessages() {
    Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();
    for (String logType : logTypes) {
      createWebDriverWithLogging(logType, Level.OFF);
      LogEntries entries = localDriver.manage().logs().get(logType);
      assertThat(entries.getAll())
          .describedAs("There should be no log entries for log type %s when logging is turned off.", logType)
          .isEmpty();
      quitDriver();
    }
  }

  private void createWebDriverWithLogging(String logType, Level logLevel) {
    LoggingPreferences loggingPrefs = new LoggingPreferences();
    loggingPrefs.enable(logType, logLevel);
    Capabilities caps = new ImmutableCapabilities(CapabilityType.LOGGING_PREFS, loggingPrefs);
    localDriver = new WebDriverBuilder().get(caps);
    localDriver.get(pages.errorsPage);
    localDriver.findElement(By.cssSelector("input")).click();
  }
}


text:
package com.navercorp.pinpoint.profiler.context;

import org.junit.Before;

/**
 * @author emeroad
 * @author jaehong.kim
 */
public class DefaultCallStackTest extends CallStackTest {

    private Span span;
    private SpanEvent spanEvent;

    @Before
    public void before() {
        span = new Span();
        spanEvent = new SpanEvent(span);
    }

    @Override
    public CallStack newCallStack() {
        return new DefaultCallStack(span);
    }

    @Override
    public CallStack newCallStack(int depth) {
        return new DefaultCallStack(span, depth);
    }

    @Override
    public Span getSpan() {
        return span;
    }

    @Override
    public SpanEvent getSpanEvent() {
        return spanEvent;
    }
}


text:
package jp.co.opentone.bsol.framework.web.extension.jsf.listener;

import java.util.Map;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.PreRenderViewEvent;
import javax.faces.event.SystemEvent;

import org.apache.commons.lang.StringUtils;

import jp.co.opentone.bsol.framework.web.view.ViewConst;
import jp.co.opentone.bsol.framework.web.view.listener.ExtendedActionListener;

/**
 * PreRenderイベントリスナです.
 * <p>
 * 各画面のPreRenderイベントリスナが登録されている場合はそれを呼び出します.
 * @author opentone
 */
public class PreRenderViewListener extends ExtendedSystemEventListener {

    /**
     * PreRenderViewListener設定のプリフィックス.
     */
    private static final String PROP_PRERENDER_PREFIX = "prerender";

    /**
     * 管理画面のデフォルトPreRenderリスナの設定キー名.
     */
    private static final String PRERENDER_DEFAULT_KEY = "prerender.default";

    @Override
    public void processEvent(SystemEvent event) throws AbortProcessingException {
        if (event instanceof PreRenderViewEvent) {
            UIViewRoot viewRoot = getUIViewRoot(event);
            if (null != viewRoot && StringUtils.isNotEmpty(viewRoot.getViewId())) {
                ExtendedActionListener listener
                    = createActionEventListener(event, PROP_PRERENDER_PREFIX);
                if (null == listener) {
                    listener = createActionEventListener(PRERENDER_DEFAULT_KEY);
                }
                if (null != listener) {
                    ActionEvent ae = new ActionEvent(viewRoot);
                    listener.processAction(ae);
                    // 画面表示キー値、メッセージの設定
                    //merActionListener.setViewMessage();
                    String pageIdParameter = getPageIdParameter();
                    if (StringUtils.isNotEmpty(pageIdParameter)) {
                        // 画面リダイレクト処理前のエラーメッセージ設定
                        listener.addViewMessage(pageIdParameter);
                        FacesContext fc = FacesContext.getCurrentInstance();
                        Flash f = fc.getExternalContext().getFlash();
                        f.clear();
                    }
                    listener.setViewMessage();
                } else {
                    // デフォルトPreRenderも存在しない場合は処理エラーとする.
                    throw new AbortProcessingException(
                            String.format("Can't create PreRenderViewListener. for viewId=[%s]",
                                    getViewId(event)));
                }
            }
        }
    }

    /**
     * msgIdパラメータを取得します.
     * @return msgIdパラメータ
     */
    private String getPageIdParameter() {
        FacesContext fc = FacesContext.getCurrentInstance();
        Map<String, String> paramMap = fc.getExternalContext().getRequestParameterMap();
        return paramMap.get(ViewConst.PARAM_NAME_MSG_ID);
    }
}


text:
import gzip
import io
import json

from django.db.models import Q
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.http import HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.gzip import gzip_page
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .. import error_constants
from .utils import get_device_info
from kolibri.core.content.models import ChannelMetadata
from kolibri.core.content.models import ContentNode
from kolibri.core.content.models import LocalFile
from kolibri.core.content.serializers import PublicChannelSerializer
from kolibri.core.content.utils.file_availability import generate_checksum_integer_mask
from kolibri.core.device.utils import allow_peer_unlisted_channel_import

class InfoViewSet(viewsets.ViewSet):
    """
    An equivalent endpoint in studio which allows kolibri devices to know
    if this device can serve content.
    Spec doc: https://docs.google.com/document/d/1XKXQe25sf9Tht6uIXvqb3T40KeY3BLkkexcV08wvR9M/edit#
    """

    def list(self, request):
        """Returns metadata information about the device"""

        return Response(get_device_info())

def _get_channel_list(version, params, identifier=None):
    if version == "v1":
        return _get_channel_list_v1(params, identifier=identifier)
    else:
        raise LookupError()

def _get_channel_list_v1(params, identifier=None):
    keyword = params.get("keyword", "").strip()
    language_id = params.get("language", "").strip()

    channels = None
    if identifier:
        channels = ChannelMetadata.objects.filter(pk=identifier)
    else:
        channels = ChannelMetadata.objects.all()

    if keyword != "":
        channels = channels.filter(
            Q(name__icontains=keyword) | Q(description__icontains=keyword)
        )

    if language_id != "":
        matching_tree_ids = (
            ContentNode.objects.prefetch_related("files")
            .filter(
                Q(lang__id__icontains=language_id)
                | Q(files__lang__id__icontains=language_id)
            )
            .values_list("tree_id", flat=True)
        )
        channels = channels.filter(
            Q(root__lang__id__icontains=language_id)
            | Q(root__tree_id__in=matching_tree_ids)
        )

    if not allow_peer_unlisted_channel_import():
        channels = channels.exclude(public=False)

    return channels.filter(root__available=True).distinct()

@api_view(["GET"])
def get_public_channel_list(request, version):
    """ Endpoint: /public/<version>/channels/?=<query params> """
    try:
        channel_list = _get_channel_list(version, request.query_params)
    except LookupError:
        return HttpResponseNotFound(
            json.dumps({"id": error_constants.NOT_FOUND, "metadata": {"view": ""}}),
            content_type="application/json",
        )
    return HttpResponse(
        json.dumps(PublicChannelSerializer(channel_list, many=True).data),
        content_type="application/json",
    )

@api_view(["GET"])
def get_public_channel_lookup(request, version, identifier):
    """ Endpoint: /public/<version>/channels/lookup/<identifier> """
    try:
        channel_list = _get_channel_list(
            version,
            request.query_params,
            identifier=identifier.strip().replace("-", ""),
        )
    except LookupError:
        return HttpResponseNotFound(
            json.dumps({"id": error_constants.NOT_FOUND, "metadata": {"view": ""}}),
            content_type="application/json",
        )

    if not channel_list.exists():
        return HttpResponseNotFound(
            json.dumps({"id": error_constants.NOT_FOUND, "metadata": {"view": ""}}),
            content_type="application/json",
        )
    return HttpResponse(
        json.dumps(PublicChannelSerializer(channel_list, many=True).data),
        content_type="application/json",
    )

@csrf_exempt
@gzip_page
def get_public_file_checksums(request, version):
    """ Endpoint: /public/<version>/file_checksums/ """
    if version == "v1":
        if request.content_type == "application/json":
            data = request.body
        elif request.content_type == "application/gzip":
            with gzip.GzipFile(fileobj=io.BytesIO(request.body)) as f:
                data = f.read()
        else:
            return HttpResponseBadRequest("POST body must be either json or gzip")
        checksums = json.loads(data.decode("utf-8"))
        available_checksums = set(
            LocalFile.objects.filter(available=True)
            .filter_by_uuids(checksums)
            .values_list("id", flat=True)
            .distinct()
        )
        return HttpResponse(
            generate_checksum_integer_mask(checksums, available_checksums),
            content_type="application/octet-stream",
        )
    return HttpResponseNotFound(
        json.dumps({"id": error_constants.NOT_FOUND, "metadata": {"view": ""}}),
        content_type="application/json",
    )


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_TOURNAMENTS_BEGIN

/// <summary>
/// Represents details of the team participating in the tournament.
/// </summary>
public ref class TeamSummary sealed
{
public:
    /// <summary>
    /// The ID of the team. It is an opaque string specified by the tournament organizer.
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ(Id, id);

    /// <summary>
    /// The state of the team.
    /// </summary>
    DEFINE_PROP_GET_ENUM_OBJ(TeamState, state, Microsoft::Xbox::Services::Tournaments::TeamState);

    /// <summary>
    /// The team's final rank within the tournament, if it is available. If missing, the rank is not available.
    /// </summary>
    DEFINE_PROP_GET_OBJ(Ranking, ranking, uint64);

internal:
    TeamSummary(
        _In_ xbox::services::tournaments::team_summary cppObj
        );

    const xbox::services::tournaments::team_summary& GetCppObj() const;

private:
    xbox::services::tournaments::team_summary m_cppObj;
};

NAMESPACE_MICROSOFT_XBOX_SERVICES_TOURNAMENTS_END


text:
/*
 *    Includes declarations that are needed by the splash2 apps to run
 *    using pthreads.
 */

#ifndef __CONFIG_H_
#define __CONFIG_H_

#define MAX_THREADS   256

#endif // __CONFIG_H_


text:
<!doctype html>
<html>
<head>
  <link rel="style/css" href="assets/style.css?bust" />
</head>
<body>
  <img src="assets/image.png" />
  <script src="assets/script.js?bust"></script>
</body>
</html>


text:
package com.xruby.compiler.codedom;

public class ENDBlock extends Statement {

    private CompoundStatement cs_;

    public ENDBlock(CompoundStatement cs) {
        cs_ = cs;
    }

    public void accept(CodeVisitor visitor) {
        if (null != cs_) {
            cs_.accept(visitor);
        }
    }

}


text:
#ifndef Fennel_LcsClusterNodeWriter_Included
#define Fennel_LcsClusterNodeWriter_Included

#include "fennel/lcs/LcsClusterAccessBase.h"
#include "fennel/lcs/LcsBitOps.h"
#include "fennel/lcs/LcsClusterDump.h"
#include "fennel/btree/BTreeWriter.h"
#include "fennel/tuple/TupleData.h"
#include "fennel/tuple/UnalignedAttributeAccessor.h"
#include <boost/scoped_array.hpp>

FENNEL_BEGIN_NAMESPACE

const int LcsMaxRollBack = 8;
const int LcsMaxLeftOver = 7;
const int LcsMaxSzLeftError = 4;

enum ForceMode { none = 0, fixed = 1, variable = 2 };

/**
 * Constructs a cluster page, managing the amount of space currently in use
 * on the page and determining the offsets where different elements are to
 * be stored
 */
class FENNEL_LCS_EXPORT LcsClusterNodeWriter
    : public LcsClusterAccessBase, public TraceSource
{
private:
    /**
     * Writes btree corresponding to cluster
     */
    SharedBTreeWriter bTreeWriter;

    /**
     * Accessor for scratch segments
     */
    SegmentAccessor scratchAccessor;

    /**
     * Lock on scratch page
     */
    ClusterPageLock bufferLock;

    /**
     * Cluster page header
     */
    PLcsClusterNode pHdr;

    /**
     * Size of the cluster page header
     */
    uint hdrSize;

    /**
     * Cluster page to be written
     */
    PBuffer pIndexBlock;

    /**
     * Array of pointers to temporary blocks, 1 block for each column cluster
     */
    PBuffer *pBlock;

    /**
     * Size of the cluster page
     */
    uint szBlock;

    /**
     * Minimum size left on the page
     */
    int minSzLeft;

    /**
     * Batch directories for the batches currently being constructed,
     * one per cluster column
     */
    boost::scoped_array<LcsBatchDir> batchDirs;

    /**
     * Temporary storage for values, used for fixed mode batches; one per
     * cluster column
     */
    boost::scoped_array<PBuffer> pValBank;

    /**
     * First offset in the bank for each column in the cluster
     * value bank
     */
    boost::scoped_array<uint16_t> oValBank;

    /**
     * Start of each cluster column in the value bank
     */
    boost::scoped_array<uint16_t> valBankStart;

    /**
     * Offsets to the batch directories on the temporary pages,
     * one per cluster column
     */
    boost::scoped_array<uint16_t> batchOffset;

    /**
     * Count of the number of batches in the temporary pages, one per
     * cluster column
     */
    boost::scoped_array<uint> batchCount;

    /**
     * Number of bytes left on the page
     */
    int szLeft;

    /**
     * Number of bits required to store the value codes for each column
     * in the cluster, for the batches currently being constructed
     */
    boost::scoped_array<uint> nBits;

    /**
     * Number of values that will cause the next nBit change for the column
     * in the cluster
     */
    boost::scoped_array<uint> nextWidthChange;

    /**
     * Indicates whether temporary arrays have already been allocated
     */
    bool arraysAllocated;

    /**
     * Set when the mode of a batch should be forced to a particular value
     */
    boost::scoped_array<ForceMode> bForceMode;

    /**
     * Number of times force mode has been used for each cluster column
     */
    boost::scoped_array<uint> forceModeCount;

    /**
     * Max value size encountered thus far for each cluster column
     */
    boost::scoped_array<uint> maxValueSize;

    /**
     * Accessors for reading unaligned values.
     */
    boost::scoped_array<UnalignedAttributeAccessor> attrAccessors;

    /**
     * Cluster dump
     */
    SharedLcsClusterDump clusterDump;

    /**
     * Tuple descriptor of the columns being loaded
     */
    TupleDescriptor colTupleDesc;

    /**
     * Associates an offset with an address, determining whether a value is
     * stored in the temporary block or the temporary value bank
     *
     * @param lastValOffset offset of the last value for this particular column
     *
     * @param pValBank buffer storing values in the value bank
     *
     * @param oValBank offset of first value for column in the value bank
     *
     * @param pBlock temporary block for column
     *
     * @param f desired offset
     *
     * @return address corresponding to offset
     */
    PBuffer valueSource(
        uint16_t lastValOffset, PBuffer pValBank, uint16_t oValBank,
        PBuffer pBlock, uint16_t f)
    {
        // if value not in back use
        if (f < lastValOffset) {
            return pValBank + f - oValBank;
        } else {
            return pBlock + f;
        }
    }

    /**
     * Moves all cluster data from cluster page to temporary storage
     *
     * @return number of rows currently on page
     */
    RecordNum moveFromIndexToTemp();

    /**
     * Moves all cluster data from temporary storage to the actual
     * cluster page
     */
    void moveFromTempToIndex();

    /**
     * Allocates temporary arrays used during cluster writes
     */
    void allocArrays();

    /**
     * Rounds a 32-bit value to a boundary of 8
     *
     * @param val value to be rounded
     */
    inline uint32_t round8Boundary(uint32_t val)
    {
        return val & 0xfffffff8;
    }

    /**
     * Rounds a 32-bit value to a boundary of 8 if it is > 8
     *
     * @param val value to be rounded
     */
    inline uint32_t roundIf8Boundary(uint32_t val)
    {
        if (val > 8) {
            return round8Boundary(val);
        }
    }

public:
    explicit LcsClusterNodeWriter(
        BTreeDescriptor const &treeDescriptorInit,
        SegmentAccessor const &accessorInit,
        TupleDescriptor const &colTupleDescInit,
        SharedTraceTarget pTraceTargetInit,
        std::string nameInit);

    ~LcsClusterNodeWriter();

    /**
     * Gets the last cluster page
     *
     * @param pBlock output param returning the cluster page
     *
     * @param firstRid output param returning first rid stored on cluster page
     *
     * @return true if cluster is non-empty
     */
    bool getLastClusterPageForWrite(PLcsClusterNode &pBlock, LcsRid &firstRid);

    /**
     * Allocates a new cluster page
     *
     * @param firstRid first rid to be stored on cluster page
     *
     * @return page allocated
     */
    PLcsClusterNode allocateClusterPage(LcsRid firstRid);

    /**
     * Initializes object with parameters relevant to the cluster page that
     * will be written
     *
     * @param nColumns number of columns in the cluster
     *
     * @param indexBlock pointer to the cluster page to be written
     *
     * @param pBlock array of pointers to temporary pages to be used while
     * writing this cluster page
     *
     * @param szBlock size of cluster page, reflecting max amount of space
     * available to write cluster data
     */
    void init(uint nColumns, PBuffer indexBlock, PBuffer *pBlock, uint szBlock);

    void close();

    /**
     * Prepares a cluster page as a new one
     *
     * @param startRID first RID on the page
     */
    void openNew(LcsRid startRID);

    /**
     * Prepares an existing cluster page for appending new data, and determines
     * whether the page is already full and cannot accomodate any more data.
     *
     *
     * @param nValOffsets pointer to output array reflecting the number of
     * values currently in each column on this page
     *
     * @param lastValOffsets pointer to output array reflecting the offset of
     * the last value currently on the page for each cluster column
     *
     * @param nrows returns number of rows currently on page
     *
     * @return true if the page is already full
     */
    bool openAppend(
        uint *nValOffsets, uint16_t *lastValOffsets, RecordNum &nrows);

    /**
     * Returns parameters describing the last batch for a given column
     *
     * @param column the column to be described
     *
     * @param dRow output parameter returning the number of rows over
     * the multiple of 8 boundary
     *
     * @param recSize output parameter returning the record size for the
     * batch
     */
    void describeLastBatch(uint column, uint &dRow, uint &recSize);

    /**
     * Returns the offset of the next value in a batch
     *
     * @param column column we want the value for
     *
     * @param thisVal offset of the value currently positioned at
     */
    uint16_t getNextVal(uint column, uint16_t thisVal);

    /**
     * Rolls back the last 8 value (or less) from a batch
     *
     * @param column column to be rolled back
     *
     * @param pVal buffer where the rolled back values will be copied;
     * the buffer is assumed to be fixedRec * (nRows % 8) in size, as
     * determined by the last call to describeLastBatch
     */
    void rollBackLastBatch(uint column, PBuffer pVal);

    /**
     * Returns true if the batch is not being forced to compress mode
     *
     * @param column column being described
     */
    inline bool noCompressMode(uint column) const
    {
        return bForceMode[column] == fixed
            || bForceMode[column] == variable;
    };

    /**
     * Translates an offset for a column to the pointer to the actual value
     *
     * @param column offset corresponds to this column
     *
     * @param offset offset to be translated
     *
     * @return pointer to value
     */
    inline PBuffer getOffsetPtr(uint column, uint16_t offset)
    {
        return pBlock[column] + offset;
    };

    /**
     * Adds a value to the page, in the case where the value already exists
     * in the column
     *
     * @param column column corresponding to the value being added
     *
     * @param bFirstTimeInBatch true if this is the first time the value
     * is encountered for this batch
     *
     * @return true if there is enough room in the page for the value
     */
    bool addValue(uint column, bool bFirstTimeInBatch);

    /**
     * Adds a new value to the page.  In the case of compressed or variable
     * mode, adds the value to the bottom of the page.  In the case of
     * fixed mode, adds the value to the "value bank".
     *
     * @param column column corresponding to the value being added
     *
     * @param pVal value to be added
     *
     * @param oVal returns the offset where the value has been added
     *
     * @return true if there is enough room in the page for the value
     */
    bool addValue(uint column, PBuffer pVal, uint16_t *oVal);

    /**
     * Undoes the last value added to the current batch for a column
     *
     * @param column column corresponding to the value to be undone
     *
     * @param pVal value to be undone
     *
     * @param bFirstInBatch true if the value being undone is the first
     * such value for the batch
     */
    void undoValue(uint column, PBuffer pVal, bool bFirstInBatch);

    /**
     * Writes a compressed mode batch into the temporary cluster page for
     * a column.  Only a multiple of 8 rows is written, if this is not the
     * last batch in the cluster.
     *
     * Excess rows are written into a temporary buffer.  If this is the last
     * batch in the load, then it is ok to have < 8 rows, as the next load
     * will roll it back to fill it up with more rows.
     *
     * Note that it is assumed that the caller has already copied the
     * key offsets for this batch into the cluster page.  This call will
     * only copy the bit vectors and batch directory corresponding to this
     * batch
     *
     * @param column column corresponding to the batch
     *
     * @param pRows array mapping rows to key offsets
     *
     * @param pBuf temporary buffer where excess row values will be copied;
     * assumed to be (nRow % 8)*fixedRec big
     */
    void putCompressedBatch(uint column, PBuffer pRows, PBuffer pBuf);

    /**
     * Writes a fixed or variable mode batch into a temporary cluster page for
     * a column.  Only a multiple of 8 rows is written, if this is not the
     * last batch in the cluster.
     *
     * Excess rows are written into a temporary buffer.  If this is the last
     * batch in the load, then it is ok to have < 8 rows, as the next load
     * will roll it back to fill it up with more rows.
     *
     * In the variable mode case, the key offsets are written to the batch
     * area on the page.  In the fixed mode case, the values themselves are
     * written to the batch area.  In both cases, the batch directory is
     * also written out.
     *
     * @param column column corresponding to the batch
     *
     * @param pRows array of offsets to values
     *
     * @param pBuf temporary buffer where excess row values will be copied;
     * assumed to be (nRow % 8)*fixedRec big
     */
    void putFixedVarBatch(uint column, uint16_t *pRows, PBuffer pBuf);

    /**
     * Determines which compression mode to use for a batch
     *
     * @param column column for which compression mode is being determined
     *
     * @param fixedSize size of record in the case of fixed size compression
     *
     * @param nRows number of rows in the batch
     *
     * @param pValOffset returns a pointer to the offset of the start of
     * the batch
     *
     * @param compressionMode returns the chosen compression mode
     */
    void pickCompressionMode(
        uint column, uint fixedSize, uint nRows,
        uint16_t **pValOffset,
        LcsBatchMode &compressionMode);

    /**
     * Returns true if there is no space left in the cluster page
     */
    bool isEndOfBlock()
    {
        uint col;
        int valueSizeNeeded;

        for (valueSizeNeeded = 0, col = 0; col < nClusterCols; col++) {
            valueSizeNeeded += batchDirs[col].recSize * LcsMaxLeftOver;
        }

        return szLeft <= (minSzLeft + valueSizeNeeded);
    }

    /**
     * Done with the current cluster page.  Moves all data from temporary
     * pages into the real cluster page
     */
    void endBlock()
    {
        moveFromTempToIndex();
    }
};

FENNEL_END_NAMESPACE

#endif

// End LcsClusterNodeWriter.h


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Threading;

namespace UniRx.Tests
{
    [TestClass]
    public class SubjectTests
    {
        [TestMethod]
        public void Subject()
        {
            // OnCompletedPattern
            {
                var subject = new Subject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(1, 10, 100, 1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(4);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new Subject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(4);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }

        [TestMethod]
        public void SubjectSubscribeTest()
        {
            var subject = new Subject<int>();
            var listA = new List<int>();
            var listB = new List<int>();
            var listC = new List<int>();
            subject.HasObservers.IsFalse();

            var listASubscription = subject.Subscribe(x => listA.Add(x));
            subject.HasObservers.IsTrue();
            subject.OnNext(1);
            listA[0].Is(1);

            var listBSubscription = subject.Subscribe(x => listB.Add(x));
            subject.HasObservers.IsTrue();
            subject.OnNext(2);
            listA[1].Is(2);
            listB[0].Is(2);

            var listCSubscription = subject.Subscribe(x => listC.Add(x));
            subject.HasObservers.IsTrue();
            subject.OnNext(3);
            listA[2].Is(3);
            listB[1].Is(3);
            listC[0].Is(3);

            listASubscription.Dispose();
            subject.HasObservers.IsTrue();
            subject.OnNext(4);
            listA.Count.Is(3);
            listB[2].Is(4);
            listC[1].Is(4);

            listCSubscription.Dispose();
            subject.HasObservers.IsTrue();
            subject.OnNext(5);
            listC.Count.Is(2);
            listB[3].Is(5);

            listBSubscription.Dispose();
            subject.HasObservers.IsFalse();
            subject.OnNext(6);
            listB.Count.Is(4);

            var listD = new List<int>();
            var listE = new List<int>();

            var listDSubscription = subject.Subscribe(x => listD.Add(x));
            subject.HasObservers.IsTrue();
            subject.OnNext(1);
            listD[0].Is(1);

            var listESubscription = subject.Subscribe(x => listE.Add(x));
            subject.HasObservers.IsTrue();
            subject.OnNext(2);
            listD[1].Is(2);
            listE[0].Is(2);

            subject.Dispose();

            AssertEx.Throws<ObjectDisposedException>(() => subject.OnNext(0));
            AssertEx.Throws<ObjectDisposedException>(() => subject.OnError(new Exception()));
            AssertEx.Throws<ObjectDisposedException>(() => subject.OnCompleted());
        }

        [TestMethod]
        public void AsyncSubjectTest()
        {
            // OnCompletedPattern
            {
                var subject = new AsyncSubject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Count.Is(0);

                subject.OnCompleted();
                onNext.Is(1000);
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(1);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1000, 1000);
                exception.Count.Is(0);
                onCompletedCallCount.Is(2);
            }

            // OnErrorPattern
            {
                var subject = new AsyncSubject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Count.Is(0);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(0);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(2);
                onCompletedCallCount.Is(0);
            }
        }

        [TestMethod]
        public void BehaviorSubject()
        {
            // OnCompletedPattern
            {
                var subject = new BehaviorSubject<int>(3333);

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                onNext.Is(3333);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);

                onNext.Is(3333, 1, 10, 100, 1000);

                // re subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(1);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new BehaviorSubject<int>(3333);

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(3333, 1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(5);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Count.Is(0);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }

        [TestMethod]
        public void ReplaySubject()
        {
            // OnCompletedPattern
            {
                var subject = new ReplaySubject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(1, 10, 100, 1000);

                // replay subscription
                onNext.Clear();
                _.Dispose();
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1, 10, 100, 1000);

                subject.OnCompleted();
                onCompletedCallCount.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(4);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);

                // ++subscription
                onNext.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1, 10, 100, 1000);
                exception.Count.Is(0);
                onCompletedCallCount.Is(1);
            }

            // OnErrorPattern
            {
                var subject = new ReplaySubject<int>();

                var onNext = new List<int>();
                var exception = new List<Exception>();
                int onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                subject.OnNext(1000);
                onNext.Is(1, 10, 100, 1000);

                subject.OnError(new Exception());
                exception.Count.Is(1);

                subject.OnNext(1);
                subject.OnNext(10);
                subject.OnNext(100);
                onNext.Count.Is(4);

                subject.OnCompleted();
                subject.OnError(new Exception());
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);

                // ++subscription
                onNext.Clear();
                exception.Clear();
                onCompletedCallCount = 0;
                subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
                onNext.Is(1, 10, 100, 1000);
                exception.Count.Is(1);
                onCompletedCallCount.Is(0);
            }
        }

        public void ReplaySubjectBufferReplay()
        {
            var subject = new ReplaySubject<int>(bufferSize: 3);

            var onNext = new List<int>();
            var exception = new List<Exception>();
            int onCompletedCallCount = 0;
            var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

            subject.OnNext(1);
            subject.OnNext(10);
            subject.OnNext(100);
            subject.OnNext(1000);
            subject.OnNext(10000);
            onNext.Is(100, 1000, 10000);  // cut 1, 10

            // replay subscription
            onNext.Clear();
            _.Dispose();
            subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
            onNext.Is(100, 1000, 10000);

            subject.OnNext(20000);
            onNext.Is(1000, 10000, 20000);

            subject.OnCompleted();
            onCompletedCallCount.Is(1);
        }

        [TestMethod]
        public void ReplaySubjectWindowReplay()
        {
            var subject = new ReplaySubject<int>(window: TimeSpan.FromMilliseconds(700));

            var onNext = new List<int>();
            var exception = new List<Exception>();
            int onCompletedCallCount = 0;
            var _ = subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);

            subject.OnNext(1); // 0
            Thread.Sleep(TimeSpan.FromMilliseconds(300));

            subject.OnNext(10); // 300
            Thread.Sleep(TimeSpan.FromMilliseconds(300));

            subject.OnNext(100); // 600
            Thread.Sleep(TimeSpan.FromMilliseconds(300));

            _.Dispose();
            onNext.Clear();
            subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
            onNext.Is(10, 100);

            subject.OnNext(1000); // 900
            Thread.Sleep(TimeSpan.FromMilliseconds(300));

            _.Dispose();
            onNext.Clear();
            subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
            onNext.Is(100, 1000);

            subject.OnNext(10000); // 1200
            Thread.Sleep(TimeSpan.FromMilliseconds(500));

            subject.OnNext(2); // 1500
            Thread.Sleep(TimeSpan.FromMilliseconds(10));

            subject.OnNext(20); // 1800
            Thread.Sleep(TimeSpan.FromMilliseconds(10));

            _.Dispose();
            onNext.Clear();
            subject.Subscribe(x => onNext.Add(x), x => exception.Add(x), () => onCompletedCallCount++);
            onNext.Is(10000, 2, 20);
        }
    }
}