text:
<!DOCTYPE html>

  <meta charset="utf-8">

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

  <title>cortex.built_ins.datasets.imagenet — Cortex2.0  documentation</title>

  <link rel="stylesheet" href="../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />

             Cortex2.0

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

User Documentation

Installation

Getting Started

cortex

Develop

Custom demos

A walkthrough a custom classifier:

Defining losses and results

Visualization

Putting it together

          Cortex2.0

Docs »

Module code »

cortex.built_ins.datasets.imagenet

Source code for cortex.built_ins.datasets.imagenet

'''Handler for imagenet datasets.

'''

from os import path

import torchvision
from torchvision.transforms import transforms

from cortex.plugins import DatasetPlugin, register_data
from cortex.built_ins.datasets.utils import build_transforms

[docs]class ImageFolder(DatasetPlugin):
    sources = ['tiny-imagenet-200', 'imagenet']

[docs]    def handle(self, source, copy_to_local=False, normalize=True,
               tanh_normalization=False, **transform_args):

        Dataset = self.make_indexing(torchvision.datasets.ImageFolder)
        data_path = self.get_path(source)

        train_path = path.join(data_path, 'train')
        test_path = path.join(data_path, 'val')

        if copy_to_local:
            train_path = self.copy_to_local_path(train_path)
            test_path = self.copy_to_local_path(test_path)

        if normalize and isinstance(normalize, bool):
            if tanh_normalization:
                normalize = transforms.Normalize((0.5, 0.5, 0.5),
                                                 (0.5, 0.5, 0.5))
            else:
                normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                 std=[0.229, 0.224, 0.225])

        if source == 'imagenet':
            normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                             std=[0.229, 0.224, 0.225])
            train_transform = transforms.Compose([
                transforms.RandomResizedCrop(224),
                transforms.RandomHorizontalFlip(),
                transforms.ToTensor(),
                normalize,
            ])
            test_transform = transforms.Compose([
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize,
            ])
        else:
            train_transform = build_transforms(
                normalize=normalize, **transform_args)
            test_transform = build_transforms(normalize=normalize)
        train_set = Dataset(root=train_path, transform=train_transform)
        test_set = Dataset(root=test_path, transform=test_transform)
        input_names = ['images', 'targets', 'index']

        dim_c, dim_x, dim_y = train_set[0][0].size()

        print('Computing min / max...')

        img_min = 1000
        img_max = -1000
        for i in range(1000):
            img = train_set[i][0]
            img_min = min(img.min(), img_min)
            img_max = max(img.max(), img_max)

        dim_l = len(train_set.classes)

        dims = dict(x=dim_x, y=dim_y, c=dim_c, labels=dim_l)

        self.add_dataset('train', train_set)
        self.add_dataset('test', test_set)
        self.set_input_names(input_names)
        self.set_dims(**dims)

        self.set_scale((img_min, img_max))
        print('Finished loading dataset')

register_data(ImageFolder)

        © Copyright 2018, MILA.

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


text:
def Polygon2Centerline(TheInPolyFile,TheInPointFile,TheOutFilePath,MaxWidth,AsArcGISTool):
	try:
		import os
		from math import sqrt
		import AnalysisInterface as AnalysisGIS
		import CartographyInterface as CartGIS
		import ManagementInterface as MgmtGIS
		import ShapefileProperties as ShpProp
		from SplitLineModule import SplitLine
		from MessagingModule import MessageSwitch

		### Setup classes, etc.
		# Create instances of classes
		AInterface=AnalysisGIS.AnalysisInterface()
		MgmtInterface=MgmtGIS.ManagementInterface()
		CartInterface=CartGIS.CartographyInterface()

		# Extract just the polygon file name
		TheFileName=os.path.basename(TheInPolyFile)
		if AsArcGISTool==0:
			TheFileName=TheFileName[0:-4]

		#Determine how many input polygon features there are
		NumFeatures=MgmtInterface.CountRows(TheInPolyFile)

		# Check to see if there is other than 1 features and abort if so
		message="Input polygon file has more or less than 1 feature.  Script will abort."
		if NumFeatures!=1:
			MessageSwitch(AsArcGISTool,message)
			x=1/0

		#Determine how many input point features there are
		NumPoints=MgmtInterface.CountRows(TheInPointFile)

		# Check to see if there is other than 4 features and abort if so
		message="Input point file has more or less than 4 points.  Script will abort."
		if NumPoints!=4:
			MessageSwitch(message,AsArcGISTool)
			x=1/0

		# Check to make sure points shapefile has Id field with more than just 0s
		# Get Id field entries
		IdFieldList=ShpProp.ListFromField(TheInPointFile,"Id")
		# Loop through Id field checking entries
		for Id in IdFieldList:
			if ((Id == 0) or (Id == 1) or (Id == 10) or (Id == 11)):
				""
			else:
				message=("Input point file Id field does not contain the "+
				"correct identifying numbers \n"+
				"(0: DS Left, 1: DS Right, 10: US Left, 11: US Right)." +
				"Check Read Me for details.  Script will abort.\n")
				MessageSwitch(message,AsArcGISTool)
				x=1/0

		# Make sure output folder has ending slash
		if TheOutFilePath[-1] != u"/" or TheOutFilePath[-2:-1] != u"\\":
			TheOutFilePath=TheOutFilePath+"/"
		# Check to see if out folder exists, if not create it
		if os.path.isdir(TheOutFilePath)!= True:
			os.mkdir(TheOutFilePath)

		# Create intermediate file folder if it does not exist
		IntermedOutputFolder=TheOutFilePath+"IntermediateFiles/"
		if os.path.isdir(IntermedOutputFolder)!= True:
			os.mkdir(IntermedOutputFolder)

		### Convert polygon to polyline
		# Update user on process
		message="Converting " + TheFileName+ " to polyline..."
		MessageSwitch(AsArcGISTool,message)
		RawPolyline=IntermedOutputFolder+TheFileName+"_rawpolyline.shp"
		MgmtInterface.Polygon2Polyline(TheInPolyFile,RawPolyline,"","ATTRIBUTES")

		### Split the resulting polyline at the corner points
		# Update user on process
		message="Splitting polyline at points..."
		MessageSwitch(AsArcGISTool,message)
		BoundaryRawPolyline=IntermedOutputFolder+TheFileName+"_boundarypolyline.shp"
		MgmtInterface.SplitLineAtPoints(RawPolyline,TheInPointFile,BoundaryRawPolyline,1)

		### Reconnect lines if separated at more than just corners (more than 4 lines): e.g. end of line fell in middle of boundary
		# Determine how many polyline features there are
		NumLines=MgmtInterface.CountRows(BoundaryRawPolyline)
		# Convert to feature layers
		MgmtInterface.CreateLayer(TheInPointFile,"Point_Layer")

		if NumLines>4:
			# Convert to feature layers
			MgmtInterface.CreateLayer(BoundaryRawPolyline,"Polyline_Layer")
			# Create new field in polyline to specify which lines to dissolve
			MgmtInterface.AddField("Polyline_Layer","Dissolve","SHORT","#","#","#")
			# Write fid to new field
			MgmtInterface.WriteField("Polyline_Layer","Dissolve", "[FID]","VB")

			# Select line on left side using points
			# Select left side points
			MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 0 OR \"Id\" = 10")
			# Select lines which intersects left points
			MgmtInterface.SelectUsingLocation("Polyline_Layer","INTERSECT","Point_Layer",0,"NEW_SELECTION")
			# Select right side points
			MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 1 OR \"Id\" = 11")
			# Deselect lines which intersect right side points
			MgmtInterface.SelectUsingLocation("Polyline_Layer","INTERSECT","Point_Layer",0,"REMOVE_FROM_SELECTION")

			# Check to see if more than 1 line - if so write to field for dissolve field calculation
			NumSelected=MgmtInterface.CountRows("Polyline_Layer")
			if NumSelected>1:
				# write consistent ID to Dissolve field
				MgmtInterface.WriteField("Polyline_Layer","Dissolve",5,"VB")

			# Select lines which are on right side using points
			# Select right side points
			MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 1 OR \"Id\" = 11")
			# Select lines which intersects right points
			MgmtInterface.SelectUsingLocation("Polyline_Layer","INTERSECT","Point_Layer",0,"NEW_SELECTION")
			# Select left side points
			MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 0 OR \"Id\" = 10")
			# Deselect lines which intersect left side points
			MgmtInterface.SelectUsingLocation("Polyline_Layer","INTERSECT","Point_Layer",0,"REMOVE_FROM_SELECTION")
			# check to see if more than 1 line - if so dissolve field calculation
			NumSelected=MgmtInterface.CountRows("Polyline_Layer")
			if NumSelected>1:
				# write consistent ID to Dissolve field
				MgmtInterface.WriteField("Polyline_Layer","Dissolve",6,"VB")

			# Unselect all
			MgmtInterface.SelectUsingAttributes("Polyline_Layer","CLEAR_SELECTION","#")
			# Name for merged boundary lines
			MergedBoundaries=IntermedOutputFolder+TheFileName+"_mergedpolyline.shp"
			# Run dissolve to combine any side lines (don't care if multipart)
			MgmtInterface.Dissolve("Polyline_Layer",MergedBoundaries,"Dissolve","#",
				               "MULTI_PART","DISSOLVE_Lines")
		else:
			MergedBoundaries=BoundaryRawPolyline

		### Identify side lines from merged shapefile
		# Convert to feature layer
		MgmtInterface.CreateLayer(MergedBoundaries,"Boundary_Layer")

		# Select line on left side using points
		# Select left side points
		MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 0 OR \"Id\" = 10")
		# Select lines which intersects left points
		MgmtInterface.SelectUsingLocation("Boundary_Layer","INTERSECT","Point_Layer",0,"NEW_SELECTION")
		# Select right side points
		MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 1 OR \"Id\" = 11")
		# Deselect lines which intersect right side points
		MgmtInterface.SelectUsingLocation("Boundary_Layer","INTERSECT","Point_Layer",0,"REMOVE_FROM_SELECTION")
		# Get the FID of the left side line
		LeftLineFID=ShpProp.ListFromField("Boundary_Layer","FID")

		# Select lines which are on right side using points
		# Select right side points
		MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 1 OR \"Id\" = 11")
		# Select lines which intersects right points
		MgmtInterface.SelectUsingLocation("Boundary_Layer","INTERSECT","Point_Layer",0,"NEW_SELECTION")
		# Select left side points
		MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 0 OR \"Id\" = 10")
		# Deselect lines which intersect left side points
		MgmtInterface.SelectUsingLocation("Boundary_Layer","INTERSECT","Point_Layer",0,"REMOVE_FROM_SELECTION")
		# Get the FID of the right side line
		RightLineFID=ShpProp.ListFromField("Boundary_Layer","FID")

		### Select 2 side lines to new shapefile
		# Update user on process
		message="Extracting side lines from converted polyline..."
		MessageSwitch(AsArcGISTool,message)
		# Select 2 side lines
		SQLexp=("\"FID\" = "+format(LeftLineFID[0])+" OR \"FID\" = "+format(RightLineFID[0]))
		MgmtInterface.SelectUsingAttributes("Boundary_Layer","NEW_SELECTION",SQLexp)
		# Final side boundaries name
		FinalBoundaries=IntermedOutputFolder+TheFileName+"_finalsidepolylines.shp"
		# Copy side lines to new shapefile
		MgmtInterface.CopyFeatures("Boundary_Layer",FinalBoundaries)

		### Determine US end line midpoint coordinates for later use to check centerline orientation
		# Switch selection to the end lines
		MgmtInterface.SelectUsingAttributes("Boundary_Layer","SWITCH_SELECTION","")
		# Select US side line by right US point (Point Id=11)
		MgmtInterface.SelectUsingAttributes("Point_Layer","NEW_SELECTION","\"Id\" = 11")
		MgmtInterface.SelectUsingLocation("Boundary_Layer","INTERSECT","Point_Layer",1,"SUBSET_SELECTION")
		# Get US end line FID
		USEndFID=ShpProp.ListFromField("Boundary_Layer","FID")
		# Get coordinates for the end line
		USEndLineCoords=ShpProp.Coordinates("Boundary_Layer")
		# Get rid of top list structure since there's only 1 feature
		USEndLineCoords=USEndLineCoords[0]
		# Separate the coordinates for the first and last points
		USEndLineStart=USEndLineCoords[0]
		USEndLineEnd=USEndLineCoords[-1]
		# Calculate midpoint xy coordinates for end line
		USEndLineMid=((USEndLineStart[0]+USEndLineEnd[0])/2,(USEndLineStart[1]+USEndLineEnd[1])/2)

		### Convert boundary polylines to centerline
		# Update user on process
		message="Converting boundaries to centerline..."
		MessageSwitch(AsArcGISTool,message)
		# centerline name
		CenterlinePolyline=IntermedOutputFolder+TheFileName+"_centerlinepolyline.shp"
		CartInterface.Centerline(FinalBoundaries,CenterlinePolyline,MaxWidth*1.2,0)
		# Clean up attribute table
		MgmtInterface.DeleteField(CenterlinePolyline,"LnType")
		MgmtInterface.DeleteField(CenterlinePolyline,"LeftLn_FID")
		MgmtInterface.DeleteField(CenterlinePolyline,"RightLn_FI")

		### Check to see if any part of centerline is still on top of boundary line
		### by looking for near to boundary
		AInterface.Near(CenterlinePolyline,FinalBoundaries,MaxWidth*.01,"NO_LOCATION","NO_ANGLE")
		# Look in added NEAR_FID field for anything other than -1 (-1 means not near)
		NearFID=ShpProp.ListFromField(CenterlinePolyline,"NEAR_FID")
		#Create empty list for FIDs
		OverlapFID=[]
		#create counter for row
		i=0
		for FID in NearFID:
			if FID <> -1:
				OverlapFID=OverlapFID+[i]
			i+=1
		# if there is feature overlap between centerline and boundary,
		#  tell user which features overlap and abort process
		if len(OverlapFID)>0:
			message="Aborting: Centerline features overlap boundary: FIDs: "+format(OverlapFID)
			MessageSwitch(message,AsArcGISTool)
			x=1/0

		# Clean up attribute table
		MgmtInterface.DeleteField(CenterlinePolyline,"NEAR_FID")
		MgmtInterface.DeleteField(CenterlinePolyline,"NEAR_DIST")

		### Determine if centerline is oriented appropriately
		# Get centerline coordinates
		CenterlineCoords=ShpProp.Coordinates(CenterlinePolyline)
		# Get rid of top list structure since there's only 1 feature
		CenterlineCoords=CenterlineCoords[0]
		# Separate the coordinates for the end points
		CenterlineStartCoords=CenterlineCoords[0]
		CenterlineEndCoords=CenterlineCoords[-1]
		# Get distance between centerline start and us end line midpoint
		CenterlineStart2USEndlineMid=sqrt(
			(CenterlineStartCoords[0]-USEndLineMid[0])**2+
			(CenterlineStartCoords[1]-USEndLineMid[1])**2)
		# Get distance between centerline end and us end line midpoint
		CenterlineEnd2USEndlineMid=sqrt(
			(CenterlineStartCoords[0]-USEndLineMid[0])**2+
			(CenterlineStartCoords[1]-USEndLineMid[1])**2)
		# Check to see which centerline end is closer to US end line
		if CenterlineStart2USEndlineMid < CenterlineEnd2USEndlineMid:
			FlipCenterline=0
		else:
			FlipCenterline=1

		return([CenterlinePolyline]+[FlipCenterline])

	#Print out error from Python
	except Exception, err: # an error occurred (probably in arcGIS)
		raise RuntimeError("** Error: Polygon2Centerline Failed ("+str(err)+")") #raise "grabs" error for use in higher level

redpajama_set_name: RedPajamaGithub


text:
#include <errno.h>

#include <onyx/compiler.h>
#include <onyx/cpu.h>
#include <onyx/mutex.h>
#include <onyx/panic.h>
#include <onyx/scheduler.h>
#include <onyx/scoped_lock.h>
#include <onyx/task_switching.h>
#include <onyx/thread.h>

static unsigned long thread_to_lock_word(thread *t)
{
    return (unsigned long) t ^ 1;
}

static thread *lock_word_to_thread(unsigned long word)
{
    return (thread *) (word ^ 1);
}

thread *mutex_owner(mutex *mtx)
{
    auto counter = read_once(mtx->counter);
    return (counter == 0 ? nullptr : lock_word_to_thread(counter));
}

static void mutex_prepare_sleep(struct mutex *mtx, int state)
{
    scoped_lock g{mtx->llock};

    thread *t = get_current_thread();

    set_current_state(state);

    list_add_tail(&t->wait_list_head, &mtx->thread_list);
}

static void mutex_dequeue_thread(mutex *mtx, thread *thr)
{
    scoped_lock g{mtx->llock};
    list_remove(&thr->wait_list_head);
}

bool __mutex_trylock(mutex *lock)
{
    unsigned long expected = 0;
    auto word = thread_to_lock_word(get_current_thread());
    return __atomic_compare_exchange_n(&lock->counter, &expected, word, false, __ATOMIC_ACQUIRE,
                                       __ATOMIC_RELAXED);
}

bool mutex_optimistic_spin(mutex *lock)
{
    /* The algorithm goes like this: Try to always fetch the owner thread,
     * and if there's none try to acquire the lock. If in fact there is a thread,
     * check if it's on the same CPU; if so, give up, if not, try to get the lock
     * until we run out of budget. If the thread changes from under us, give up too.
     */
    thread *last_thread = nullptr;
    for (int i = 0; i < 500; i++)
    {
        auto thread = mutex_owner(lock);

        if (!thread)
            return __mutex_trylock(lock);

        if (last_thread && thread != last_thread)
            return false;

        if (thread->cpu == get_cpu_nr())
            return false;

        last_thread = thread;

        cpu_relax();
    }

    return false;
}

bool mutex_trylock(mutex *lock)
{
    return __mutex_trylock(lock) || mutex_optimistic_spin(lock);
}

static void commit_sleep(void)
{
    sched_yield();
}

int mutex_lock_slow_path(struct mutex *mutex, int state)
{
    int ret = 0;
    bool signals_allowed = state == THREAD_INTERRUPTIBLE;

    struct thread *current = get_current_thread();

    mutex_prepare_sleep(mutex, state);

    while (!mutex_trylock(mutex))
    {
        if (signals_allowed && signal_is_pending())
        {
            ret = -EINTR;
            break;
        }

        auto owner = mutex_owner(mutex);

        assert(owner != current);

        commit_sleep();

        mutex_dequeue_thread(mutex, current);

        mutex_prepare_sleep(mutex, state);
    }

    set_current_state(THREAD_RUNNABLE);

    mutex_dequeue_thread(mutex, current);

    return ret;
}

static inline void mutex_postlock(mutex *mtx)
{
}

void must_not_sleep()
{
    if (sched_is_preemption_disabled())
    {
        halt();
        panic("Mutexes may not be used under disabled preemption");
    }
}

int __mutex_lock(struct mutex *mutex, int state)
{
    // must_not_sleep();
    int ret = 0;
    if (!mutex_trylock(mutex)) [[unlikely]]
        ret = mutex_lock_slow_path(mutex, state);

    if (ret >= 0) [[likely]]
    {
        mutex_postlock(mutex);
    }

    return ret;
}

void mutex_lock(struct mutex *mutex)
{
    __mutex_lock(mutex, THREAD_UNINTERRUPTIBLE);
}

int mutex_lock_interruptible(struct mutex *mutex)
{
    return __mutex_lock(mutex, THREAD_INTERRUPTIBLE);
}

void mutex_unlock(struct mutex *mutex)
{
    __atomic_store_n(&mutex->counter, 0, __ATOMIC_RELEASE);

    scoped_lock g{mutex->llock};

    if (!list_is_empty(&mutex->thread_list))
    {
        struct list_head *l = list_first_element(&mutex->thread_list);
        assert(l != &mutex->thread_list);
        struct thread *t = container_of(l, struct thread, wait_list_head);

        thread_wake_up(t);
    }
}

bool mutex_holds_lock(struct mutex *m)
{
    return m->counter && mutex_owner(m) == get_current_thread();
}

#ifdef CONFIG_KTEST_MUTEX

#include <stdio.h>

#include <onyx/clock.h>
#include <onyx/cpu.h>
#include <onyx/scoped_lock.h>

#include <libtest/libtest.h>

static DECLARE_MUTEX(mtx) = {};

static volatile unsigned long counter = 0;

static unsigned int mtx_completed = 0;
static thread *to_wake_up = nullptr;

void mutex_thread_entry(void *arg)
{
    bool incs = (unsigned int) (unsigned long) arg % 2;
    for (long i = 0; i < 0xffffff; i++)
    {
        {
            scoped_mutex g{mtx};

            if (incs)
                counter = counter + 1;
            else
                counter = counter - 1;
        }

        for (int i = 0; i < 1; i++)
            cpu_relax();

        // sched_sleep(10);
    }

    mtx_completed++;

    thread_wake_up(to_wake_up);

    thread_exit();
}

bool mutex_test(void)
{
    counter = 0;
    mtx_completed = 0;
    to_wake_up = get_current_thread();
    auto clock = get_main_clock();

    auto t0 = clock->get_ns();

    mutex_init(&mtx);

    for (unsigned int i = 0; i < 4; i++)
    {
        auto thread =
            sched_create_thread(mutex_thread_entry, THREAD_KERNEL, (void *) (unsigned long) i);

        assert(thread != nullptr);

        sched_start_thread(thread);
    }

    sched_block(get_current_thread());

    while (mtx_completed != 4)
        cpu_relax();

    auto t1 = clock->get_ns();

    printk("mutex test completed in %lu ns\n", t1 - t0);

    return counter == 0;
}

DECLARE_TEST(mutex_test, 4);

#endif


text:
package nl.jft.logic.participant.impl;

import nl.jft.common.rating.Rating;
import nl.jft.logic.LogicConstants;
import nl.jft.logic.util.builder.ObjectBuilder;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.*;

/**
 * @author Lesley
 * @author Oscar de Leeuw
 */
public class TeamTest {
    @Rule
    public final ExpectedException expectedException = ExpectedException.none();

    @Test
    public void construct_nullTeamName_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withTeamName(null).build();
    }

    @Test
    public void construct_emptyTeamName_throwsException() {
        expectedException.expect(IllegalArgumentException.class);

        Team team = ObjectBuilder.team().withTeamName("").build();
    }

    @Test
    public void construct_nullRating_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withRating(null).build();
    }

    @Test
    public void construct_nullFirstUser_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withFirstUser(null).build();
    }

    @Test
    public void construct_nullSecondUser_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withSecondUser(null).build();
    }

    @Test
    public void construct_sameUsers_throwsException() {
        expectedException.expect(IllegalArgumentException.class);

        User user1 = ObjectBuilder.user().build();
        User user2 = ObjectBuilder.user().build();

        Team team = ObjectBuilder.team().withFirstUser(user1).withSecondUser(user2).build();
    }

    @Test
    public void construct2_nullTeamName_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withTeamName(null).build2();
    }

    @Test
    public void construct2_emptyTeamName_throwsException() {
        expectedException.expect(IllegalArgumentException.class);

        Team team = ObjectBuilder.team().withTeamName("").build2();
    }

    @Test
    public void construct2_nullRating_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withRating(null).build2();
    }

    @Test
    public void construct2_nullFirstUser_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withFirstUser(null).build2();
    }

    @Test
    public void construct2_nullSecondUser_throwsException() {
        expectedException.expect(NullPointerException.class);

        Team team = ObjectBuilder.team().withSecondUser(null).build2();
    }

    @Test
    public void construct2_sameUsers_throwsException() {
        expectedException.expect(IllegalArgumentException.class);

        User user1 = ObjectBuilder.user().build();
        User user2 = ObjectBuilder.user().build();

        Team team = ObjectBuilder.team().withFirstUser(user1).withSecondUser(user2).build2();
    }

    @Test
    public void equals_sameObjects_returnsTrue() {
        Team team1 = ObjectBuilder.team().build2();
        Team team2 = ObjectBuilder.team().build2();

        boolean result = team1.equals(team2);
        assertTrue(result);
    }

    @Test
    public void equals_otherInstance_returnsFalse() {
        Team team1 = ObjectBuilder.team().build();
        Team team2 = null;

        boolean result = team1.equals(team2);
        assertFalse(result);
    }

    @Test
    public void equals_differentIds_returnsFalse() {
        Team team1 = ObjectBuilder.team().withId(1).build();
        Team team2 = ObjectBuilder.team().withId(2).build();

        boolean result = team1.equals(team2);
        assertFalse(result);
    }

    @Test
    public void equals_differentTeamNames_returnsFalse() {
        Team team1 = ObjectBuilder.team().withTeamName("team1").build();
        Team team2 = ObjectBuilder.team().withTeamName("team2").build();

        boolean result = team1.equals(team2);
        assertFalse(result);
    }

    @Test
    public void equals_differentFirstUser_returnsFalse() {
        User user1 = ObjectBuilder.user().withUsername("user1").build();
        User user2 = ObjectBuilder.user().withUsername("user2").build();
        User user3 = ObjectBuilder.user().withUsername("user3").build();

        Team team1 = ObjectBuilder.team().withFirstUser(user1).withSecondUser(user3).build();
        Team team2 = ObjectBuilder.team().withFirstUser(user2).withSecondUser(user3).build();

        boolean result = team1.equals(team2);
        assertFalse(result);
    }

    @Test
    public void equals_differentSecondUser_returnsFalse() {
        User user1 = ObjectBuilder.user().withUsername("user1").build();
        User user2 = ObjectBuilder.user().withUsername("user2").build();
        User user3 = ObjectBuilder.user().withUsername("user3").build();

        Team team1 = ObjectBuilder.team().withFirstUser(user1).withSecondUser(user2).build();
        Team team2 = ObjectBuilder.team().withFirstUser(user1).withSecondUser(user3).build();

        boolean result = team1.equals(team2);
        assertFalse(result);
    }

    @Test
    public void hashCode_whenCalled_returnsHashCode() {
        Team team1 = ObjectBuilder.team().build();
        Team team2 = ObjectBuilder.team().build();

        boolean result = team1.hashCode() == team2.hashCode();
        assertTrue(result);
    }

    @Test
    public void getName_withDefaultName_returnsName() {
        Team team = ObjectBuilder.team().withTeamName("name").build();

        String expected = "name";
        String actual = team.getName();

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getId_withDefaultId_returnsId() {
        Team team = ObjectBuilder.team().withId(LogicConstants.INTERNAL_ID).build();

        int expected = LogicConstants.INTERNAL_ID;
        int actual = team.getId();

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getRating_whenCalled_returnsRating() {
        Team team = ObjectBuilder.team().withRating(ObjectBuilder.Rating.glickoRating().build()).build();

        Rating expected = ObjectBuilder.Rating.glickoRating().build();
        Rating actual = team.getRating();

        assertEquals(expected, actual);
    }

}


text:
from os import getenv
from opentmi_client import OpenTmiClient

client = OpenTmiClient(port=3000)
client.login(username=getenv('USERNAME'), password=getenv('PASSWORD'))


text:
<?php

if (!defined('WPO_VERSION')) die('No direct access allowed');

require_once 'class-wp-optimize-htaccess.php';

/**
 * Class WP_Optimize_Browser_Cache
 */
class WP_Optimize_Browser_Cache {

	private $_htaccess = null;

	private $_options = null;

	private $_wp_optimize = null;

	/**
	 * Browser cache section in htaccess will wrapped with this comment
	 *
	 * @var string
	 */
	private $_htaccess_section_comment = 'WP-Optimize Browser Cache';

	/**
	 * WP_Optimize_Browser_Cache constructor.
	 */
	public function __construct() {
		$this->_wp_optimize = WP_Optimize();

		$this->_htaccess = new WP_Optimize_Htaccess();

		$this->_options = $this->_wp_optimize->get_options();
	}

	/***
	 * Check headers for Cache-Control and Etag. And if they are exist return true.
	 *
	 * @return bool|WP_Error
	 */
	public function is_cache_enabled() {
		$style = get_template_directory_uri() . '/style.css';

		$response = wp_remote_get($style, array('timeout' => 15));

		if (is_a($response, 'WP_Error')) return $response;

		$headers = wp_remote_retrieve_headers($response);

		if (is_a($headers, 'Requests_Utility_CaseInsensitiveDictionary')) {
			$headers = $headers->getAll();
		}

		if (false === array_key_exists('etag', $headers) && array_key_exists('cache-control', $headers)) {
			return true;
		}

		if ($this->is_browser_cache_section_exists() && !$this->_wp_optimize->is_apache_module_loaded(array('mod_expires', 'mod_headers'))) {
			return new WP_Error('Browser cache', __('We successfully updated your .htaccess file. But it seems one of Apache modules - mod_expires or mod_headers is not active.', 'wp-optimize'));
		}

		return false;
	}

	/**
	 * Enable browser cache - add settings into .htaccess.
	 *
	 * @param string $expiry_time
	 */
	public function enable($expiry_time = '1 month') {
		$this->_htaccess->update_commented_section($this->prepare_browser_cache_section($expiry_time), $this->_htaccess_section_comment);
		$this->_htaccess->write_file();
	}

	/**
	 * Disable cache - remove settings from .htaccess added in enable() function.
	 */
	public function disable() {
		$this->_htaccess->remove_commented_section($this->_htaccess_section_comment);
		$this->_htaccess->write_file();
	}

	/**
	 * Check if section with browser cache settings already exists.
	 */
	public function is_browser_cache_section_exists() {
		return $this->_htaccess->is_commented_section_exists($this->_htaccess_section_comment);
	}

	/**
	 * Handle for enable_browser_cache command used in WP_Optimize_Commands.
	 *
	 * @param array $params - ['browser_cache_expire' => '1 month 15 days 2 hours' || '' - for disable cache]
	 * @return array
	 */
	public function enable_browser_cache_command_handler($params) {
		$expire_days = isset($params['browser_cache_expire_days']) ? $params['browser_cache_expire_days'] : '';
		$expire_hours = isset($params['browser_cache_expire_hours']) ? $params['browser_cache_expire_hours'] : '';

		$current_expire_days = $this->_options->get_option('browser_cache_expire_days', '');
		$current_expire_hours = $this->_options->get_option('browser_cache_expire_hours', '');

		$section_updated = false;

		$expiry_time = $this->prepare_interval($expire_days, $expire_hours);

		$enable = ('' == $expiry_time) ? false : true;

		/**
		 * If we don't need to do anything in .htaccess then return message.
		 */
		if ($enable == $this->_htaccess->is_commented_section_exists() && $expire_days == $current_expire_days && $expire_hours == $current_expire_hours) {
			$message = __('Browser static caching settings already exists in the .htaccess file', 'wp-optimize');

			return array(
				'success' => true,
				'enabled' => $enable,
				'message' => $message,
			);
		}

		if ($this->_htaccess->is_writable()) {
			// update commented section

			if ($enable) {
				$this->enable($expiry_time);
			} else {
				$this->disable();
			}

			// read updated file.
			$this->_htaccess->read_file();
			// check if section added or removed successfully.
			$section_exists = $this->_htaccess->is_commented_section_exists();
			// set correct $section-updated flag.
			$section_updated = $enable === $section_exists;
		}

		if ($section_updated) {
			$enabled = $this->is_cache_enabled();

			// save $expire value to options.
			$this->_options->update_option('browser_cache_expire_days', $expire_days);
			$this->_options->update_option('browser_cache_expire_hours', $expire_hours);

			if (is_wp_error($enabled)) {
				return array(
					'success' => true,
					'enabled' => $enabled,
					'error_message' => $enabled->get_error_message(),
				);
			} else {
				return array(
					'success' => true,
					'enabled' => $enabled,
					'message' => __('We successfully updated your .htaccess file.', 'wp-optimize'),
				);
			}
		} else {
			$cache_section = $this->prepare_browser_cache_section($expiry_time);

			if ($enable) {
				$message = sprintf(__('We can\'t update your %s file. Please try to add following lines manually:', 'wp-optimize'), $this->_htaccess->get_filename());
				$output = htmlentities($this->_htaccess->get_section_begin_comment() . PHP_EOL .
						  join(PHP_EOL, $this->_htaccess->get_flat_array($cache_section)).
						  PHP_EOL . $this->_htaccess->get_section_end_comment());
			} else {
				$message = sprintf(__('We can\'t update your %s file. Please try to remove following lines manually:', 'wp-optimize'), $this->_htaccess->get_filename());
				$output = htmlentities($this->_htaccess->get_section_begin_comment() . PHP_EOL .
					' ... ... ... '.
					PHP_EOL . $this->_htaccess->get_section_end_comment());
			}

			return array(
				'success' => false,
				'enabled' => $this->is_cache_enabled(),
				'error_message' => $message,
				'output' => $output,
			);
		}
	}

	/**
	 * Use $days an $hours values to build correct time interval as a string like '2 days 3 hours' or empty string if date is empty.
	 *
	 * @param int $days
	 * @param int $hours
	 * @return string
	 */
	private function prepare_interval($days, $hours) {

		$days = floor($days);
		$hours = floor($hours);

		if (0 == $days && 0 == $hours) {
			return '';
		}

		$parts = array();

		// if hours value more than one day then fix it.
		$days += floor($hours / 24);
		$hours = $hours % 24;

		$years = floor($days / 365);
		$days = $days % 365;
		$months = floor($days / 30);
		$days = $days % 30;

		if ($years > 0) {
			$parts[] = $years . ($years > 1 ? ' years' : ' year');
		}

		if ($months > 0) {
			$parts[] = $months . ($months > 1 ? ' months' : ' month');
		}

		if ($days > 0) {
			$parts[] = $days . ($days > 1 ? ' days' : ' day');
		}

		if ($hours > 0) {
			$parts[] = $hours . ($hours > 1 ? ' hours' : ' hour');
		}

		return join(' ', $parts);
	}

	/**
	 * Build browser cache section array.
	 *
	 * @param string $expire - value like - 1 day 12 hours 15 minutes
	 * @return array
	 */
	public function prepare_browser_cache_section($expire) {
		return array(
			array(
				'<IfModule mod_expires.c>',
				'ExpiresActive On',
				'ExpiresByType text/css "access '.$expire.'"',
				'ExpiresByType text/html "access '.$expire.'"',
				'ExpiresByType image/gif "access '.$expire.'"',
				'ExpiresByType image/png "access '.$expire.'"',
				'ExpiresByType image/jpg "access '.$expire.'"',
				'ExpiresByType image/jpeg "access '.$expire.'"',
				'ExpiresByType image/webp "access '.$expire.'"',
				'ExpiresByType image/x-icon "access '.$expire.'"',
				'ExpiresByType application/pdf "access '.$expire.'"',
				'ExpiresByType application/javascript "access '.$expire.'"',
				'ExpiresByType text/x-javascript "access '.$expire.'"',
				'ExpiresByType application/x-shockwave-flash "access '.$expire.'"',
				'ExpiresDefault "access '.$expire.'"',
				'</IfModule>',
			),
			'',
			array(
				'<IfModule mod_headers.c>',
				array(
					'<filesMatch "\.(ico|jpe?g|png|gif|webp|swf)$">',
					'Header set Cache-Control "public"',
					'</filesMatch>',
				),
				array(
					'<filesMatch "\.(css)$">',
					'Header set Cache-Control "public"',
					'</filesMatch>',
				),
				array(
					'<filesMatch "\.(js)$">',
					'Header set Cache-Control "private"',
					'</filesMatch>',
				),
				array(
					'<filesMatch "\.(x?html?|php)$">',
					'Header set Cache-Control "private, must-revalidate"',
					'</filesMatch>',
				),
				'</IfModule>',
			),
			'',
			'#Disable ETag',
			'FileETag None',
		);
	}
}


text:
var chai = require('chai');
var expect = chai.expect;
var request = require('supertest');

var app;
function validation(req, res) {
  req.sanitizeBody('testparam').whitelist(['a', 'b', 'c']);
  res.send({ body: req.body });
}

function pass(body) {
  expect(body).to.have.deep.property('body.testparam', 'abc');
}
function fail(body) {
  expect(body).to.not.have.property('body', 'testparam');
}

function postRoute(path, data, test, done) {
  request(app)
    .post(path)
    .send(data)
    .end(function(err, res) {
      test(res.body);
      done();
    });
}

// This before() is required in each set of tests in
// order to use a new validation function in each file
before(function() {
  delete require.cache[require.resolve('./helpers/app')];
  app = require('./helpers/app')(validation);
});

describe('#sanitizeBody', function() {
  describe('POST tests', function() {
    it('should return property and sanitized value when body param is present', function(done) {
      postRoute('/', { testparam: '   abcdf    ' }, pass, done);
    });

    it('should not return property when body param is missing', function(done) {
      postRoute('/', null, fail, done);
    });

  });
});


text:
{% extends "admin/base_site.html" %}
{% comment %}

   Copyright 2015, Institute for Systems Biology

   Licensed 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.

{% endcomment %}

{% load i18n %}

{% block breadcrumbs %}

{% trans 'Home' %}
› {% trans 'Password reset' %}

{% endblock %}

{% block title %}{{ title }}{% endblock %}
{% block content_title %}
{{ title }}
{% endblock %}

{% block content %}

{% trans "Your password has been set.  You may go ahead and log in now." %}

{% trans 'Log in' %}

{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="支付"
            android:textColor="@color/black"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/ib_close"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:padding="4dp"
            android:scaleType="centerInside"
            android:src="@drawable/icon_close" />

        <Button
            android:id="@+id/btn_pwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:text="使用密码"
            android:textColor="@color/blue" />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/light_gray" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="验证指纹支付"
        android:textColor="@color/dark_gray"
        android:textSize="20sp" />

</LinearLayout>


text:
ROOT = ../../../..

DIR = Pegasus/ProviderManager2/CMPIR

include $(ROOT)/mak/config.mak

ifeq ($(PEGASUS_PLATFORM),ZOS_ZSERIES_IBM)
    CXX = cc
    FLAGS += -W"c,SSCOMM"
endif
EXTRA_INCLUDES = $(SYS_INCLUDES)

LOCAL_DEFINES = -DPEGASUS_SERVER_INTERNAL -DPEGASUS_INTERNALONLY -DPEGASUS_CMPI_PROXY_INTERNAl

LIBRARY = CMPIRProxyProvider

LIBRARIES = \
   CMPIProviderManager

SOURCES = \
   proxy_comm.c \
   proxy_provider.c \
   namespace_resolver.c \
   ticket.c \
   tool.c

include $(ROOT)/mak/library.mak


text:
package com.heliosapm.jmx.alarm;

/**
 *
Title: AlarmState

 *
Description: Enumerates the possible states of an alarm

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.jmx.alarm.AlarmState

 * Open / Closed / Paused / NoData
 */

public enum AlarmState {
	INIT,
	OK,
	WARN,
	CRITICAL,
	PAUSED,
	NODATA;
}


text:
package net.krotscheck.jersey2.configuration;

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;

/**
 * This is the central configuration feature for the jersey2 toolkit. It reads
 * any jersey2-toolkit.properties configuration file found in your war file.
 * The contents of this file should contain whatever configuration options
 * are appropriate for the features you've enabled.
 *
 * @author Michael Krotscheck
 */
public final class ConfigurationFeature implements Feature {

    /**
     * Register the ConfigurationFeature with the current application context.
     *
     * @param context The application context.
     * @return Always true.
     */
    @Override
    public boolean configure(final FeatureContext context) {
        context.register(new Jersey2ToolkitConfig.Binder());
        return true;
    }
}


text:
require "sso_push_client"

class PermissionUpdater < PushUserUpdatesJob
  def perform(uid, application_id)
    user = User.find_by(uid: uid)
    application = ::Doorkeeper::Application.find_by(id: application_id)
    # It's possible they've been deleted between when the job was scheduled and run.
    return if user.nil? || application.nil?

    api = SSOPushClient.new(application)
    presenter = UserOAuthPresenter.new(user, application)
    api.update_user(user.uid, presenter.as_hash)

    user.permissions_synced!(application)
  end
end


text:
@protocol TSCH3DChartElementSceneObjectSeriesDelegate
- (void)didGenerateShaderEffectsForSeriesAtIndex:(const tvec2_3b141483 *)arg1 effects:(id)arg2 sceneObject:(id)arg3 pipeline:(id)arg4;
- (_Bool)willProcessSeries:(id)arg1 sceneObject:(id)arg2 pipeline:(id)arg3;
@end


text:
package org.ebookdroid.core.curl;
import org.ebookdroid.R;
import org.ebookdroid.core.Page;
import org.ebookdroid.core.SinglePageDocumentView;
import org.ebookdroid.core.ViewState;
import org.ebookdroid.core.bitmaps.BitmapManager;
import org.ebookdroid.core.bitmaps.BitmapRef;
import org.ebookdroid.core.models.DocumentModel;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public abstract class AbstractPageAnimator extends SinglePageView implements PageAnimator {

    /** Fixed update time used to create a smooth curl animation */
    protected int mUpdateRate;
    /** Handler used to auto flip time based */
    protected FlipAnimationHandler mAnimationHandler;
    /** Point used to move */
    protected Vector2D mMovement;
    /** Defines the flip direction that is currently considered */
    protected boolean bFlipRight;
    /** If TRUE we are currently auto-flipping */
    protected boolean bFlipping;
    /** Used to control touch input blocking */
    protected boolean bBlockTouchInput = false;
    /** Enable input after the next draw event */
    protected boolean bEnableInputAfterDraw = false;
    protected Vector2D mA = new Vector2D(0, 0);
    /** The initial offset for x and y axis movements */
    protected int mInitialEdgeOffset;
    /** The finger position */
    protected Vector2D mFinger;
    /** Movement point form the last frame */
    protected Vector2D mOldMovement;
    /** TRUE if the user moves the pages */
    protected boolean bUserMoves;

    protected BitmapRef foreBitmap;
    protected int foreBitmapIndex = -1;

    protected BitmapRef backBitmap;
    protected int backBitmapIndex = -1;

    protected Bitmap arrowsBitmap;

    protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public AbstractPageAnimator(final PageAnimationType type, final SinglePageDocumentView singlePageDocumentView) {
        super(type, singlePageDocumentView);
    }

    @Override
    public void init() {
        super.init();
        arrowsBitmap = BitmapFactory.decodeResource(view.getBase().getContext().getResources(), R.drawable.arrows);

        mMovement = new Vector2D(0, 0);
        mFinger = new Vector2D(0, 0);
        mOldMovement = new Vector2D(0, 0);

        // Create our curl animation handler
        mAnimationHandler = new FlipAnimationHandler(this);

        // Set the default props
        mUpdateRate = 5;
    }

    @Override
    public final boolean isPageVisible(final Page page, final ViewState viewState) {
        final int pageIndex = page.index.viewIndex;
        return pageIndex == this.foreIndex || pageIndex == this.backIndex;
    }

    /**
     * Swap to next view
     */
    protected ViewState nextView(final ViewState viewState) {
        final DocumentModel dm = view.getBase().getDocumentModel();
        if (dm == null) {
            return viewState;
        }

        foreIndex = viewState.currentIndex;
        if (foreIndex >= dm.getPageCount()) {
            foreIndex = 0;
        }
        backIndex = foreIndex + 1;
        if (backIndex >= dm.getPageCount()) {
            backIndex = 0;
        }

        return view.invalidatePages(viewState, dm.getPageObject(foreIndex), dm.getPageObject(backIndex));
    }

    /**
     * Swap to previous view
     */
    protected ViewState previousView(final ViewState viewState) {
        final DocumentModel dm = view.getBase().getDocumentModel();
        if (dm == null) {
            return viewState;
        }

        backIndex = viewState.currentIndex;
        foreIndex = backIndex - 1;
        if (foreIndex < 0) {
            foreIndex = dm.getPageCount() - 1;
        }

        return view.invalidatePages(viewState, dm.getPageObject(foreIndex), dm.getPageObject(backIndex));
    }

    /**
     * Execute a step of the flip animation
     */
    @Override
    public synchronized void FlipAnimationStep() {
        if (!bFlipping) {
            return;
        }

        // System.out.println("FAS start");
        final int width = view.getWidth();

        // No input when flipping
        bBlockTouchInput = true;

        // Handle speed
        float curlSpeed = width / 5;
        if (!bFlipRight) {
            curlSpeed *= -1;
        }

        // Move us
        mMovement.x += curlSpeed;
        mMovement = fixMovement(mMovement, false);

        // Create values

        lock.writeLock().lock();
        try {
            updateValues();

            if (mA.x < getLeftBound()) {
                mA.x = getLeftBound() - 1;
            }

            if (mA.x > width - 1) {
                mA.x = width;
            }
        } finally {
            lock.writeLock().unlock();
        }
        // Check for endings :D
        if (mA.x <= getLeftBound() || mA.x >= width - 1) {
            bFlipping = false;
            // System.out.println("FAS end");
            if (bFlipRight) {
                view.goToPageImpl(backIndex);
                foreIndex = backIndex;
            } else {
                view.goToPageImpl(foreIndex);
            }

            // Create values
            lock.writeLock().lock();
            try {
                resetClipEdge();
                updateValues();
            } finally {
                lock.writeLock().unlock();
            }

            // Enable touch input after the next draw event
            bEnableInputAfterDraw = true;
        } else {
            mAnimationHandler.sleep(mUpdateRate);
        }

        // Force a new draw call
        view.redrawView();
    }

    protected float getLeftBound() {
        return 1;
    }

    protected abstract void resetClipEdge();

    protected abstract Vector2D fixMovement(Vector2D point, final boolean bMaintainMoveDir);

    protected abstract void drawBackground(final Canvas canvas, final ViewState viewState);

    protected abstract void drawForeground(final Canvas canvas, final ViewState viewState);

    protected abstract void drawExtraObjects(final Canvas canvas, final ViewState viewState);

    /**
     * Update points values values.
     */
    protected abstract void updateValues();

    /**
     * @see org.ebookdroid.core.curl.PageAnimator#onDraw(android.graphics.Canvas)
     */
    @Override
    public final synchronized void draw(final Canvas canvas, final ViewState viewState) {
        if (!enabled()) {
            BitmapManager.release(foreBitmap);
            BitmapManager.release(backBitmap);

            foreBitmap = null;
            backBitmap = null;

            super.draw(canvas, viewState);
            return;
        }

        // We need to initialize all size data when we first draw the view
        if (!isViewDrawn()) {
            setViewDrawn(true);
            onFirstDrawEvent(canvas, viewState);
        }

        canvas.drawColor(Color.BLACK);

        // Draw our elements
        lock.readLock().lock();
        try {
            drawInternal(canvas, viewState);
            drawExtraObjects(canvas, viewState);
        } finally {
            lock.readLock().unlock();
        }

        // Check if we can re-enable input
        if (bEnableInputAfterDraw) {
            bBlockTouchInput = false;
            bEnableInputAfterDraw = false;
        }
    }

    protected void drawInternal(Canvas canvas, ViewState viewState) {
        drawForeground(canvas, viewState);
        if (foreIndex != backIndex) {
            drawBackground(canvas, viewState);
        }
    }

    protected abstract void onFirstDrawEvent(Canvas canvas, final ViewState viewState);

    @Override
    public boolean enabled() {
        return view.getScrollLimits().width() <= 0;
    }

    @Override
    public final boolean onTouchEvent(final MotionEvent event) {
        if (!bBlockTouchInput) {

            // Get our finger position
            mFinger.x = event.getX();
            mFinger.y = event.getY();
            final int width = view.getWidth();

            ViewState viewState = new ViewState(view);

            // Depending on the action do what we need to
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mOldMovement.x = mFinger.x;
                    mOldMovement.y = mFinger.y;
                    bUserMoves = false;
                    return false;
                case MotionEvent.ACTION_UP:
                    if (bUserMoves) {
                        bUserMoves = false;
                        bFlipping = true;
                        FlipAnimationStep();
                    } else {
                        return false;
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    if ((mFinger.distanceSquared(mOldMovement) > 625)) {
                        if (!bUserMoves) {
                            // If we moved over the half of the display flip to next
                            if (mOldMovement.x > (width >> 1)) {
                                mMovement.x = mInitialEdgeOffset;
                                mMovement.y = mInitialEdgeOffset;

                                // Set the right movement flag
                                bFlipRight = true;
                                viewState = nextView(viewState);

                            } else {
                                // Set the left movement flag
                                bFlipRight = false;

                                // go to next previous page
                                viewState = previousView(viewState);

                                // Set new movement
                                mMovement.x = getInitialXForBackFlip(width);
                                mMovement.y = mInitialEdgeOffset;
                            }
                        }
                        bUserMoves = true;
                    } else {
                        if (!bUserMoves) {
                            break;
                        }
                    }

                    // Get movement
                    mMovement.x -= mFinger.x - mOldMovement.x;
                    mMovement.y -= mFinger.y - mOldMovement.y;
                    mMovement = fixMovement(mMovement, true);

                    // Make sure the y value get's locked at a nice level
                    if (mMovement.y <= 1) {
                        mMovement.y = 1;
                    }

                    // Get movement direction
                    if (mFinger.x < mOldMovement.x) {
                        bFlipRight = true;
                    } else {
                        bFlipRight = false;
                    }

                    // Save old movement values
                    mOldMovement.x = mFinger.x;
                    mOldMovement.y = mFinger.y;

                    // Force a new draw call
                    lock.writeLock().lock();
                    try {
                        updateValues();
                    } finally {
                        lock.writeLock().unlock();
                    }
                    view.redrawView(viewState);
                    return !bUserMoves;
            }

        }

        // TODO: Only consume event if we need to.
        return true;
    }

    protected int getInitialXForBackFlip(final int width) {
        return width;
    }

    @Override
    public void pageUpdated(int viewIndex) {
        if (foreBitmapIndex == viewIndex) {
            foreBitmapIndex = -1;
        }
        if (backBitmapIndex == viewIndex) {
            backBitmapIndex = -1;
        }
    }

    @Override
    public void animate(int direction) {
        resetClipEdge();
        mMovement = new Vector2D(direction < 0 ? 7 * view.getWidth() / 8 : view.getWidth() / 8, mInitialEdgeOffset);
        bFlipping = true;
        bFlipRight = direction > 0;
        ViewState viewState = new ViewState(view);
        if (bFlipRight) {
            nextView(viewState);
        } else {
            previousView(viewState);
        }

        bUserMoves = false;
        FlipAnimationStep();

    }

}


text:
'use strict'

// Node Modules
const path = require('path')

// Dependency Modules
const program = require('commander')
const init = require('../init')

// Local Modules
const pkg = require(path.resolve(__dirname, '../package.json'))

program
  .version(pkg.version)
  .usage('[options] <file ...>')
  .option('-s, --safe', '.env.example is also output for use with dotenv-safe')
  .option('-c, --comments', 'include comments when parsing for environment variables')
  .option('-i, --ignore <patterns>', 'files to ignore as part of file patterns; overrides default (\'node_modules/**,test/**\')', 'node_modules/**,test/**')
  .option('-o, --output [level]', 'set the console output level [normal] (silent|normal|verbose)', /^(silent|normal|verbose)$/i, 'normal')
  .option('-O, --file-output [level]', 'set the file output level [normal] (minimal|normal|verbose)', /^(minimal|normal|verbose)$/i, 'normal')
  .option('--filename [name]', 'chose the name of the output file [.env]', '.env')
  .option('--safe-filename [name]', 'chose the name of the safe output file [.env.example]', '.env.example')
  .parse(process.argv)

// TODO: possible future features
// .option('--merge', 'Merge new files with specified existing file')

init(program)


text:
package com.morgan.client.common;

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

import com.google.inject.BindingAnnotation;

/**
 * Common binding annotations used in the client.
 *
 * @author mark@mark-morgan.net (Mark Morgan)
 */
public final class CommonBindingAnnotations {

  private CommonBindingAnnotations() {
    // Do not instantiate
  }

  /**
   * An annotation representing the "default" version of something.
   *
   * @author mark@mark-morgan.net (Mark Morgan)
   */
  @BindingAnnotation
  @Retention(RetentionPolicy.RUNTIME)
  @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  public @interface Default {
  }

  @BindingAnnotation
  @Retention(RetentionPolicy.RUNTIME)
  @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  public @interface PagePresenters {
  }
}


text:
                ×

Edit Events

            <form method="post" role="form" action="<?php echo base_url('index.php/admin/events_edit') ?>" enctype="multipart/form-data">

                <input type="text" name="id_otsukaresama" value="<?php echo $id_otsukaresama; ?>">
                <input type="text" name="id" id="input-edit-id" >

                            Gambar

                        <input name="url" type="file" id="exampleInputFile">
                        <input type="text" name="old_url" id="input-edit-url" >

                    Close
                    <button type="submit" class="btn btn-warning">Edit</button>

            </form>


text:
var inherit = require('./util/inherit.js').inherit;
var NixBlock = require('./NixBlock.js').NixBlock;
var nijs = require('../nijs.js');

/**
 * Creates a new NixWith instance.
 *
 * @class NixWith
 * @extends NixBlock
 * @classdesc Captures the abstract syntax of a Nix with block importing
 * variables of the attribute set parameter into the lexical scope of the body
 *
 * @constructor
 * @param {Object} args Arguments to this function
 * @param {Object} args.withExpr An expression yielding an attribute set
 * @param {Object} args.body Body of the let block containing an arbitrary expression in which the members of the attribute set are imported
 */
function NixWith(args) {
    this.withExpr = args.withExpr;
    this.body = args.body;
}

/* NixWith inherits from NixBlock */
inherit(NixBlock, NixWith);

/**
 * @see NixObject#toNixExpr
 */
NixWith.prototype.toNixExpr = function(indentLevel, format) {
    return "with "+nijs.jsToIndentedNix(this.withExpr, indentLevel, format)+";\n\n"+
        nijs.generateIndentation(indentLevel, format) + nijs.jsToIndentedNix(this.body, indentLevel, format);
};

exports.NixWith = NixWith;


text:
package math.doubleV;

public interface AxisDependency {
	default void emancipate() {};
	default void axisSlipWarning(AbstractAxes globalPriorToSlipping, AbstractAxes globalAfterSlipping, AbstractAxes thisAxis) {};
	default void axisSlipCompletionNotice(AbstractAxes globalPriorToSlipping, AbstractAxes globalAfterSlipping, AbstractAxes thisAxis) {};
	default void  parentChangeWarning(AbstractAxes warningBy, AbstractAxes oldParent, AbstractAxes intendedParent, Object requestedBy) {};
	default void parentChangeCompletionNotice(AbstractAxes warningBy, AbstractAxes oldParent, AbstractAxes intendedParent, Object requestedBy) {};
	default void markDirty() {};
	default void markDependentsDirty() {};
	public AbstractAxes getParentAxes();
}


text:
<?php

/**
 * config controller
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Webshopapps_Matrixrate_System_ConfigController extends Mage_Adminhtml_Controller_Action
{

/**
     * Export shipping table rates in csv format
     *
     */
    public function exportmatrixrateAction()
    {
        $fileName   = 'matrixrates.csv';
        /** @var $gridBlock Mage_Adminhtml_Block_Shipping_Carrier_Tablerate_Grid */
        $gridBlock  = $this->getLayout()->createBlock('matrixrate_adminhtml/shipping_carrier_matrixrate_grid');
        $website    = Mage::app()->getWebsite($this->getRequest()->getParam('website'));
        if ($this->getRequest()->getParam('conditionName')) {
            $conditionName = $this->getRequest()->getParam('conditionName');
        } else {
            $conditionName = $website->getConfig('carriers/matrixrate/condition_name');
        }
        $gridBlock->setWebsiteId($website->getId())->setConditionName($conditionName);
        $content    = $gridBlock->getCsvFile();
        $this->_prepareDownloadResponse($fileName, $content);
    }

    protected function _isAllowed()
    {
        return true;
    }

}


text:
using namespace Lucene;

BOOST_FIXTURE_TEST_SUITE(IndexWriterDeleteTest, LuceneTestFixture)

DECLARE_SHARED_PTR(FailOnlyOnDeleteFlush)

class FailOnlyOnDeleteFlush : public MockDirectoryFailure
{
public:
    FailOnlyOnDeleteFlush()
    {
        sawMaybe = false;
        failed = false;
    }

    virtual ~FailOnlyOnDeleteFlush()
    {
    }

public:
    bool sawMaybe;
    bool failed;

public:
    virtual MockDirectoryFailurePtr reset()
    {
        sawMaybe = false;
        failed = false;
        return shared_from_this();
    }

    virtual void eval(MockRAMDirectoryPtr dir)
    {
        if (sawMaybe && !failed)
        {
            if (!TestPoint::getTestPoint(L"applyDeletes"))
            {
                // Only fail once we are no longer in applyDeletes
                failed = true;
                boost::throw_exception(IOException(L"fail after applyDeletes"));
            }
        }
        if (!failed)
        {
            if (TestPoint::getTestPoint(L"applyDeletes"))
                sawMaybe = true;
        }
    }
};

DECLARE_SHARED_PTR(FailOnlyOnAdd)

class FailOnlyOnAdd : public MockDirectoryFailure
{
public:
    FailOnlyOnAdd()
    {
        failed = false;
    }

    virtual ~FailOnlyOnAdd()
    {
    }

public:
    bool failed;

public:
    virtual MockDirectoryFailurePtr reset()
    {
        failed = false;
        return shared_from_this();
    }

    virtual void eval(MockRAMDirectoryPtr dir)
    {
        if (!failed)
        {
            failed = true;
            boost::throw_exception(IOException(L"fail in add doc"));
        }
    }
};

static int32_t getHitCount(DirectoryPtr dir, TermPtr term)
{
    IndexSearcherPtr searcher = newLucene<IndexSearcher>(dir, true);
    int32_t hitCount = searcher->search(newLucene<TermQuery>(term), FilterPtr(), 1000)->totalHits;
    searcher->close();
    return hitCount;
}

static void addDoc(IndexWriterPtr modifier, int32_t id, int32_t value)
{
    DocumentPtr doc = newLucene<Document>();
    doc->add(newLucene<Field>(L"content", L"aaa", Field::STORE_NO, Field::INDEX_ANALYZED));
    doc->add(newLucene<Field>(L"id", StringUtils::toString(id), Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
    doc->add(newLucene<Field>(L"value", StringUtils::toString(value), Field::STORE_NO, Field::INDEX_NOT_ANALYZED));
    modifier->addDocument(doc);
}

static void updateDoc(IndexWriterPtr modifier, int32_t id, int32_t value)
{
    DocumentPtr doc = newLucene<Document>();
    doc->add(newLucene<Field>(L"content", L"aaa", Field::STORE_NO, Field::INDEX_ANALYZED));
    doc->add(newLucene<Field>(L"id", StringUtils::toString(id), Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
    doc->add(newLucene<Field>(L"value", StringUtils::toString(value), Field::STORE_NO, Field::INDEX_NOT_ANALYZED));
    modifier->updateDocument(newLucene<Term>(L"id", StringUtils::toString(id)), doc);
}

static void checkNoUnreferencedFiles(DirectoryPtr dir)
{
    HashSet<String> _startFiles = dir->listAll();
    SegmentInfosPtr infos = newLucene<SegmentInfos>();
    infos->read(dir);
    IndexFileDeleterPtr deleter = newLucene<IndexFileDeleter>(dir, newLucene<KeepOnlyLastCommitDeletionPolicy>(), infos, InfoStreamPtr(), DocumentsWriterPtr(), HashSet<String>());
    HashSet<String> _endFiles = dir->listAll();

    Collection<String> startFiles = Collection<String>::newInstance(_startFiles.begin(), _startFiles.end());
    Collection<String> endFiles = Collection<String>::newInstance(_endFiles.begin(), _endFiles.end());

    std::sort(startFiles.begin(), startFiles.end());
    std::sort(endFiles.begin(), endFiles.end());

    BOOST_CHECK(startFiles.equals(endFiles));
}

BOOST_AUTO_TEST_CASE(testSimpleCase)
{
    Collection<String> keywords = newCollection<String>(L"1", L"2");
    Collection<String> unindexed = newCollection<String>(L"Netherlands", L"Italy");
    Collection<String> unstored = newCollection<String>(L"Amsterdam has lots of bridges", L"Venice has lots of canals");
    Collection<String> text = newCollection<String>(L"Amsterdam", L"Venice");

    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setUseCompoundFile(true);
    modifier->setMaxBufferedDeleteTerms(1);

    for (int32_t i = 0; i < keywords.size(); ++i)
    {
        DocumentPtr doc = newLucene<Document>();
        doc->add(newLucene<Field>(L"id", keywords[i], Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
        doc->add(newLucene<Field>(L"country", unindexed[i], Field::STORE_YES, Field::INDEX_NO));
        doc->add(newLucene<Field>(L"contents", unstored[i], Field::STORE_NO, Field::INDEX_ANALYZED));
        doc->add(newLucene<Field>(L"city", text[i], Field::STORE_YES, Field::INDEX_ANALYZED));
        modifier->addDocument(doc);
    }
    modifier->optimize();
    modifier->commit();

    TermPtr term = newLucene<Term>(L"city", L"Amsterdam");
    int32_t hitCount = getHitCount(dir, term);
    BOOST_CHECK_EQUAL(1, hitCount);
    modifier->deleteDocuments(term);
    modifier->commit();
    hitCount = getHitCount(dir, term);
    BOOST_CHECK_EQUAL(0, hitCount);

    modifier->close();
    dir->close();
}

/// test when delete terms only apply to disk segments
BOOST_AUTO_TEST_CASE(testNonRAMDelete)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(2);
    modifier->setMaxBufferedDeleteTerms(2);

    int32_t id = 0;
    int32_t value = 100;

    for (int32_t i = 0; i < 7; ++i)
        addDoc(modifier, ++id, value);
    modifier->commit();

    BOOST_CHECK_EQUAL(0, modifier->getNumBufferedDocuments());
    BOOST_CHECK(0 < modifier->getSegmentCount());

    modifier->commit();

    IndexReaderPtr reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    modifier->deleteDocuments(newLucene<Term>(L"value", StringUtils::toString(value)));

    modifier->commit();

    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(0, reader->numDocs());
    reader->close();
    modifier->close();
    dir->close();
}

BOOST_AUTO_TEST_CASE(testMaxBufferedDeletes)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr writer = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);
    writer->setMaxBufferedDeleteTerms(1);
    writer->deleteDocuments(newLucene<Term>(L"foobar", L"1"));
    writer->deleteDocuments(newLucene<Term>(L"foobar", L"1"));
    writer->deleteDocuments(newLucene<Term>(L"foobar", L"1"));
    BOOST_CHECK_EQUAL(3, writer->getFlushDeletesCount());
    writer->close();
    dir->close();
}

/// test when delete terms only apply to ram segments
BOOST_AUTO_TEST_CASE(testRAMDeletes)
{
    for (int32_t t = 0; t < 2; ++t)
    {
        DirectoryPtr dir = newLucene<MockRAMDirectory>();
        IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

        modifier->setMaxBufferedDocs(4);
        modifier->setMaxBufferedDeleteTerms(4);

        int32_t id = 0;
        int32_t value = 100;

        addDoc(modifier, ++id, value);
        if (t == 0)
            modifier->deleteDocuments(newLucene<Term>(L"value", StringUtils::toString(value)));
        else
            modifier->deleteDocuments(newLucene<TermQuery>(newLucene<Term>(L"value", StringUtils::toString(value))));
        addDoc(modifier, ++id, value);
        if (t == 0)
        {
            modifier->deleteDocuments(newLucene<Term>(L"value", StringUtils::toString(value)));
            BOOST_CHECK_EQUAL(2, modifier->getNumBufferedDeleteTerms());
            BOOST_CHECK_EQUAL(1, modifier->getBufferedDeleteTermsSize());
        }
        else
            modifier->deleteDocuments(newLucene<TermQuery>(newLucene<Term>(L"value", StringUtils::toString(value))));

        addDoc(modifier, ++id, value);
        BOOST_CHECK_EQUAL(0, modifier->getSegmentCount());
        modifier->commit();

        modifier->commit();

        IndexReaderPtr reader = IndexReader::open(dir, true);
        BOOST_CHECK_EQUAL(1, reader->numDocs());

        int32_t hitCount = getHitCount(dir, newLucene<Term>(L"id", StringUtils::toString(id)));
        BOOST_CHECK_EQUAL(1, hitCount);
        reader->close();
        modifier->close();
        dir->close();
    }
}

/// test when delete terms apply to both disk and ram segments
BOOST_AUTO_TEST_CASE(testBothDeletes)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(100);
    modifier->setMaxBufferedDeleteTerms(100);

    int32_t id = 0;
    int32_t value = 100;
    for (int32_t i = 0; i < 5; ++i)
        addDoc(modifier, ++id, value);

    value = 200;
    for (int32_t i = 0; i < 5; ++i)
        addDoc(modifier, ++id, value);

    modifier->commit();

    for (int32_t i = 0; i < 5; ++i)
        addDoc(modifier, ++id, value);

    modifier->deleteDocuments(newLucene<Term>(L"value", StringUtils::toString(value)));

    modifier->commit();

    IndexReaderPtr reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(5, reader->numDocs());
    modifier->close();
    reader->close();
}

/// test that batched delete terms are flushed together
BOOST_AUTO_TEST_CASE(testBatchDeletes)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(100);
    modifier->setMaxBufferedDeleteTerms(100);

    int32_t id = 0;
    int32_t value = 100;
    for (int32_t i = 0; i < 7; ++i)
        addDoc(modifier, ++id, value);
    modifier->commit();

    IndexReaderPtr reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    id = 0;
    modifier->deleteDocuments(newLucene<Term>(L"id", StringUtils::toString(++id)));
    modifier->deleteDocuments(newLucene<Term>(L"id", StringUtils::toString(++id)));

    modifier->commit();

    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(5, reader->numDocs());
    reader->close();

    Collection<TermPtr> terms = Collection<TermPtr>::newInstance(3);
    for (int32_t i = 0; i < terms.size(); ++i)
        terms[i] = newLucene<Term>(L"id", StringUtils::toString(++id));

    modifier->deleteDocuments(terms);
    modifier->commit();
    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(2, reader->numDocs());
    reader->close();

    modifier->close();
    dir->close();
}

BOOST_AUTO_TEST_CASE(testDeleteAll)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(2);
    modifier->setMaxBufferedDeleteTerms(2);

    int32_t id = 0;
    int32_t value = 100;
    for (int32_t i = 0; i < 7; ++i)
        addDoc(modifier, ++id, value);
    modifier->commit();

    IndexReaderPtr reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    // Add 1 doc (so we will have something buffered)
    addDoc(modifier, 99, value);

    // Delete all
    modifier->deleteAll();

    // Delete all shouldn't be on disk yet
    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    // Add a doc and update a doc (after the deleteAll, before the commit)
    addDoc(modifier, 101, value);
    updateDoc(modifier, 102, value);

    // commit the delete all
    modifier->commit();

    // Validate there are no docs left
    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(2, reader->numDocs());
    reader->close();

    modifier->close();
    dir->close();
}

BOOST_AUTO_TEST_CASE(testDeleteAllRollback)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(2);
    modifier->setMaxBufferedDeleteTerms(2);

    int32_t id = 0;
    int32_t value = 100;
    for (int32_t i = 0; i < 7; ++i)
        addDoc(modifier, ++id, value);
    modifier->commit();

    addDoc(modifier, 99, value);

    IndexReaderPtr reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    // Delete all
    modifier->deleteAll();

    // Roll it back
    modifier->rollback();
    modifier->close();

    // Validate that the docs are still there
    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    dir->close();
}

/// test deleteAll() with near real-time reader
BOOST_AUTO_TEST_CASE(testDeleteAllNRT)
{
    DirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setMaxBufferedDocs(2);
    modifier->setMaxBufferedDeleteTerms(2);

    int32_t id = 0;
    int32_t value = 100;
    for (int32_t i = 0; i < 7; ++i)
        addDoc(modifier, ++id, value);
    modifier->commit();

    IndexReaderPtr reader = modifier->getReader();
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    addDoc(modifier, ++id, value);
    addDoc(modifier, ++id, value);

    // Delete all
    modifier->deleteAll();

    reader = modifier->getReader();
    BOOST_CHECK_EQUAL(0, reader->numDocs());
    reader->close();

    // Roll it back
    modifier->rollback();
    modifier->close();

    // Validate that the docs are still there
    reader = IndexReader::open(dir, true);
    BOOST_CHECK_EQUAL(7, reader->numDocs());
    reader->close();

    dir->close();
}

/// Make sure if modifier tries to commit but hits disk full that modifier
/// remains consistent and usable.
static void testOperationsOnDiskFull(bool updates)
{
    TermPtr searchTerm = newLucene<Term>(L"content", L"aaa");
    int32_t START_COUNT = 157;
    int32_t END_COUNT = 144;

    // First build up a starting index
    RAMDirectoryPtr startDir = newLucene<MockRAMDirectory>();
    IndexWriterPtr writer = newLucene<IndexWriter>(startDir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);
    for (int32_t i = 0; i < 157; ++i)
    {
        DocumentPtr doc = newLucene<Document>();
        doc->add(newLucene<Field>(L"id", StringUtils::toString(i), Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
        doc->add(newLucene<Field>(L"content", L"aaa " + StringUtils::toString(i), Field::STORE_NO, Field::INDEX_ANALYZED));
        writer->addDocument(doc);
    }
    writer->close();

    int64_t diskUsage = startDir->sizeInBytes();
    int64_t diskFree = diskUsage + 10;

    LuceneException err;

    bool done = false;

    // Iterate with ever increasing free disk space
    while (!done)
    {
        MockRAMDirectoryPtr dir = newLucene<MockRAMDirectory>(startDir);

        // If IndexReader hits disk full, it can write to the same files again.
        dir->setPreventDoubleWrite(false);

        IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), IndexWriter::MaxFieldLengthUNLIMITED);

        modifier->setMaxBufferedDocs(1000); // use flush or close
        modifier->setMaxBufferedDeleteTerms(1000); // use flush or close

        // For each disk size, first try to commit against dir that will hit random IOExceptions and
        // disk full; after, give it infinite disk space and turn off random IOExceptions and
        // retry with same reader
        bool success = false;

        for (int32_t x = 0; x < 2; ++x)
        {
            double rate = 0.1;
            double diskRatio = ((double)diskFree) / (double)diskUsage;
            int64_t thisDiskFree = 0;
            String testName;

            if (x == 0)
            {
                thisDiskFree = diskFree;
                if (diskRatio >= 2.0)
                    rate /= 2;
                if (diskRatio >= 4.0)
                    rate /= 2;
                if (diskRatio >= 6.0)
                    rate = 0.0;
                testName = L"disk full during reader.close() @ " + StringUtils::toString(thisDiskFree) + L" bytes";
            }
            else
            {
                thisDiskFree = 0;
                rate = 0.0;
                testName = L"reader re-use after disk full";
            }

            dir->setMaxSizeInBytes(thisDiskFree);
            dir->setRandomIOExceptionRate(rate, diskFree);

            try
            {
                if (x == 0)
                {
                    int32_t docId = 12;
                    for (int32_t i = 0; i < 13; ++i)
                    {
                        if (updates)
                        {
                            DocumentPtr doc = newLucene<Document>();
                            doc->add(newLucene<Field>(L"id", StringUtils::toString(i), Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
                            doc->add(newLucene<Field>(L"content", L"bbb " + StringUtils::toString(i), Field::STORE_NO, Field::INDEX_ANALYZED));
                            modifier->updateDocument(newLucene<Term>(L"id", StringUtils::toString(docId)), doc);
                        }
                        else // deletes
                            modifier->deleteDocuments(newLucene<Term>(L"id", StringUtils::toString(docId)));
                        docId += 12;
                    }
                }
                modifier->close();
                success = true;
                if (x == 0)
                    done = true;
            }
            catch (IOException& e)
            {
                err = e;
                if (x == 1)
                    BOOST_FAIL(testName << " hit IOException after disk space was freed up");
            }

            // If the close() succeeded, make sure there are no unreferenced files.
            if (success)
            {
                checkIndex(dir);
                checkNoUnreferencedFiles(dir);
            }

            // Finally, verify index is not corrupt, and, if we succeeded, we see all docs changed, and if
            // we failed, we see either all docs or no docs changed (transactional semantics):
            IndexReaderPtr newReader;

            try
            {
                newReader = IndexReader::open(dir, true);
            }
            catch (IOException& e)
            {
                BOOST_FAIL(testName << ":exception when creating IndexReader after disk full during close:" << e.getError());
            }

            IndexSearcherPtr searcher = newLucene<IndexSearcher>(newReader);
            Collection<ScoreDocPtr> hits;
            BOOST_CHECK_NO_THROW(hits = searcher->search(newLucene<TermQuery>(searchTerm), FilterPtr(), 1000)->scoreDocs);
            int32_t result2 = hits.size();
            if (success)
            {
                if (x == 0 && result2 != END_COUNT)
                    BOOST_FAIL(testName << ": method did not throw exception but hits.size() for search on term 'aaa' is " << result2 << " instead of expected " << END_COUNT);
                else if (x == 1 && result2 != START_COUNT && result2 != END_COUNT)
                {
                    // It's possible that the first exception was "recoverable" wrt pending deletes, in which
                    // case the pending deletes are retained and then re-flushing (with plenty of disk space)
                    // will succeed in flushing the deletes
                    BOOST_FAIL(testName << ": method did not throw exception but hits.size() for search on term 'aaa' is " << result2 << " instead of expected " << START_COUNT << " or " << END_COUNT);
                }
            }
            else
            {
                // On hitting exception we still may have added all docs
                if (result2 != START_COUNT && result2 != END_COUNT)
                    BOOST_FAIL(testName << ": method did throw exception but hits.size() for search on term 'aaa' is " << result2 << " instead of expected " << START_COUNT << " or " << END_COUNT);
            }

            searcher->close();
            newReader->close();

            if (result2 == END_COUNT)
                break;
        }

        dir->close();

        // Try again with 10 more bytes of free space
        diskFree += 10;
    }

    startDir->close();
}

BOOST_AUTO_TEST_CASE(testDeletesOnDiskFull)
{
    testOperationsOnDiskFull(false);
}

BOOST_AUTO_TEST_CASE(testUpdatesOnDiskFull)
{
    testOperationsOnDiskFull(true);
}

/// This test tests that buffered deletes are cleared when an Exception is hit during flush.
BOOST_AUTO_TEST_CASE(testErrorAfterApplyDeletes)
{
    Collection<String> keywords = newCollection<String>(L"1", L"2");
    Collection<String> unindexed = newCollection<String>(L"Netherlands", L"Italy");
    Collection<String> unstored = newCollection<String>(L"Amsterdam has lots of bridges", L"Venice has lots of canals");
    Collection<String> text = newCollection<String>(L"Amsterdam", L"Venice");

    MockRAMDirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    modifier->setUseCompoundFile(true);
    modifier->setMaxBufferedDeleteTerms(2);

    FailOnlyOnDeleteFlushPtr failure = newLucene<FailOnlyOnDeleteFlush>();
    dir->failOn(failure->reset());

    for (int32_t i = 0; i < keywords.size(); ++i)
    {
        DocumentPtr doc = newLucene<Document>();
        doc->add(newLucene<Field>(L"id", keywords[i], Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
        doc->add(newLucene<Field>(L"country", unindexed[i], Field::STORE_YES, Field::INDEX_NO));
        doc->add(newLucene<Field>(L"contents", unstored[i], Field::STORE_NO, Field::INDEX_ANALYZED));
        doc->add(newLucene<Field>(L"city", text[i], Field::STORE_YES, Field::INDEX_ANALYZED));
        modifier->addDocument(doc);
    }

    modifier->optimize();
    modifier->commit();

    TermPtr term = newLucene<Term>(L"city", L"Amsterdam");
    int32_t hitCount = getHitCount(dir, term);
    BOOST_CHECK_EQUAL(1, hitCount);

    modifier->deleteDocuments(term);

    DocumentPtr doc = newLucene<Document>();
    modifier->addDocument(doc);

    // The failure object will fail on the first write after the del file gets created when
    // processing the buffered delete

    // In the ac case, this will be when writing the new segments files so we really don't
    // need the new doc, but it's harmless

    // In the !ac case, a new segments file won't be created but in this case, creation of
    // the cfs file happens next so we need the doc (to test that it's okay that we don't
    // lose deletes if failing while creating the cfs file)

    BOOST_CHECK_EXCEPTION(modifier->commit(), IOException, check_exception(LuceneException::IO));

    // The commit above failed, so we need to retry it (which will succeed, because the
    // failure is a one-shot)

    modifier->commit();
    hitCount = getHitCount(dir, term);

    // Make sure the delete was successfully flushed
    BOOST_CHECK_EQUAL(0, hitCount);

    modifier->close();
    dir->close();
}

/// This test tests that the files created by the docs writer before a segment is written are
/// cleaned up if there's an i/o error
BOOST_AUTO_TEST_CASE(testErrorInDocsWriterAdd)
{
    Collection<String> keywords = newCollection<String>(L"1", L"2");
    Collection<String> unindexed = newCollection<String>(L"Netherlands", L"Italy");
    Collection<String> unstored = newCollection<String>(L"Amsterdam has lots of bridges", L"Venice has lots of canals");
    Collection<String> text = newCollection<String>(L"Amsterdam", L"Venice");

    MockRAMDirectoryPtr dir = newLucene<MockRAMDirectory>();
    IndexWriterPtr modifier = newLucene<IndexWriter>(dir, newLucene<WhitespaceAnalyzer>(), true, IndexWriter::MaxFieldLengthUNLIMITED);

    FailOnlyOnAddPtr failure = newLucene<FailOnlyOnAdd>();
    dir->failOn(failure->reset());

    for (int32_t i = 0; i < keywords.size(); ++i)
    {
        DocumentPtr doc = newLucene<Document>();
        doc->add(newLucene<Field>(L"id", keywords[i], Field::STORE_YES, Field::INDEX_NOT_ANALYZED));
        doc->add(newLucene<Field>(L"country", unindexed[i], Field::STORE_YES, Field::INDEX_NO));
        doc->add(newLucene<Field>(L"contents", unstored[i], Field::STORE_NO, Field::INDEX_ANALYZED));
        doc->add(newLucene<Field>(L"city", text[i], Field::STORE_YES, Field::INDEX_ANALYZED));

        try
        {
            modifier->addDocument(doc);
        }
        catch (IOException&)
        {
            break;
        }
    }

    checkNoUnreferencedFiles(dir);

    modifier->close();
    dir->close();
}

BOOST_AUTO_TEST_SUITE_END()


text:
package org.hibernate.jpamodelgen.model;

import java.util.List;
import javax.lang.model.element.TypeElement;

/**
 * @author Hardy Ferentschik
 */
public interface MetaEntity extends ImportContext {
	String getSimpleName();

	String getQualifiedName();

	String getPackageName();

	List<MetaAttribute> getMembers();

	String generateImports();

	String importType(String fqcn);

	String staticImport(String fqcn, String member);

	TypeElement getTypeElement();

	boolean isMetaComplete();
}


text:
using Cosmos.TestRunner;

namespace Cosmos.Compiler.Tests.SimpleWriteLine.Kernel
{
    public static class TestTryFinally
    {
        public static void Execute()
        {
            ClearToggles();

            // test the normal flow, no explicit return, no return value
            TestNormalFlowNoReturnValue();

            Assert.IsTrue(mWasBeforeTry, "NormalFlowNoReturnValue.WasBeforeTry");
            Assert.IsTrue(mWasInTry, "NormalFlowNoReturnValue.WasInTry");
            Assert.IsTrue(mWasInFinally, "NormalFlowNoReturnValue.WasInFinally");
            Assert.IsTrue(mWasAfterFinally, "NormalFlowNoReturnValue.WasAfterFinally");

            ClearToggles();
            TestExplicitReturnNoReturnValue();

            Assert.IsTrue(mWasBeforeTry, "ExplicitReturnNoReturnValue.WasBeforeTry");
            Assert.IsTrue(mWasInTry, "ExplicitReturnNoReturnValue.WasInTry");
            Assert.IsTrue(mWasInFinally, "ExplicitReturnNoReturnValue.WasInFinally");
            Assert.IsFalse(mWasAfterFinally, "ExplicitReturnNoReturnValue.WasAfterFinally");
        }

        private static bool mWasBeforeTry;
        private static bool mWasInTry;
        private static bool mWasInFinally;
        private static bool mWasAfterFinally;

        private static void ClearToggles()
        {
            mWasBeforeTry = false;
            mWasInTry = false;
            mWasInFinally = false;
            mWasAfterFinally = false;
        }

        private static void TestNormalFlowNoReturnValue()
        {
            mWasBeforeTry = true;
            try
            {
                mWasInTry = true;
            }
            finally
            {
                mWasInFinally = true;
            }
            mWasAfterFinally = true;
        }

        private static void TestExplicitReturnNoReturnValue()
        {
            mWasBeforeTry = true;
            try
            {
                mWasInTry = true;
                return;
            }
            finally
            {
                mWasInFinally = true;
            }
            mWasAfterFinally = true;
        }
    }
}


text:
{% extends "base_site.html" %}

{% block title %}Meetings{% endblock %}

{% block extrahead %}{{ block.super }}

{% endblock %}

{% block breadcrumbs %}{{ block.super }}
  » Meetings
  » {{ meeting.number }}
  » Select Group
{% endblock %}

{% block content %}

IETF {{ meeting.number }} - Schedule Sessions

The lists below contain those groups which have submitted a session request.  Select a
      group to schedule sessions.  (Proposed Working Groups are in the BOFs list).

Select this link to View Agenda

        <form class="internal-form" action="" method="post">
          Working Groups
          {{ group_form.group }}
          <input type="submit" name="submit" value="Select" />
        </form>
        <form class="internal-form" action="" method="post">
          BOFs
          {{ bof_form.group }}
          <input type="submit" name="submit" value="Select" />
        </form>
        <form class="internal-form" action="" method="post">
          IRTF
          {{ irtf_form.group }}
          <input type="submit" name="submit" value="Select" />
        </form>

<button onclick="window.location='../'">Back</button>

Scheduled Sessions

          {% for group in scheduled_groups %}

{{ group.acronym }}

          {% endfor %}

{% endblock %}

{% block footer-extras %}
  {% include "includes/meetings_footer.html" %}
{% endblock %}


text:
require 'riot_lol_api/models/leveltips'
require 'riot_lol_api/models/images'
require 'riot_lol_api/models/vars'
require 'riot_lol_api/models/altimages'

module RiotLolApi
  module Model
    class Spell
      include RiotLolApi::Concern::Init
    end
  end
end


text:
"use strict";

var _buildChartConfig = require("./buildChartConfig");

var _fixtures = require("../fixtures");

describe('buildChartConfig', function () {
  it('normalizes chart type strings', function () {
    var lineConfig = (0, _buildChartConfig.buildChartConfig)({
      config: {
        type: 'looker_line'
      }
    });
    expect(lineConfig.type).toEqual('line');
    var barConfig = (0, _buildChartConfig.buildChartConfig)({
      config: {
        type: 'looker_bar'
      }
    });
    expect(barConfig.type).toEqual('bar');
    var scatterConfig = (0, _buildChartConfig.buildChartConfig)({
      config: {
        type: 'looker_scatter'
      }
    });
    expect(scatterConfig.type).toEqual('scatter');
  });
  it('removes unsupported config values from final output', function () {
    var config = (0, _buildChartConfig.buildChartConfig)({
      config: {
        defaults_version: 2
      }
    });
    expect(config.defaults_version).toEqual(undefined);
  });
  it('passes through deeply nested user overrides', function () {
    var config = (0, _buildChartConfig.buildChartConfig)({
      config: {
        type: 'line',
        series: {
          'orders.count': {
            color: '#FF5733',
            label: 'TEST LABEL'
          }
        }
      },
      data: _fixtures.mockData,
      fields: _fixtures.mockFields
    });
    expect(config.series['orders.count']).toEqual({
      color: '#FF5733',
      label: 'TEST LABEL',
      line_width: 3,
      shape: 'circle',
      style: 'filled',
      value_format: '0,0.[00]',
      visible: true
    });
  });
  it('sets bar default values', function () {
    var config = (0, _buildChartConfig.buildChartConfig)({
      config: {
        type: 'bar'
      },
      data: _fixtures.mockData,
      fields: _fixtures.mockFields
    });
    expect(config.positioning).toEqual('grouped');
  });
});
//# sourceMappingURL=buildChartConfig.spec.js.map