text:
import pygame
import monorail.koon.gui as gui
import monorail.koon.gfx as gfx
from monorail.koon.input import *
from monorail.koon.geo import Vec2D, Rectangle

def setup_module( cls ):
    pygame.init()

def teardown_module( cls ):
    pygame.quit()

class TestGuiState:

    def test_get_interactive_components_should_return_all_and_no_more( self ):
        """Given a hierarchy of components
        when asked for all interactive components
        then all and no more are returned"""
        # Given
        root = gui.Component()
        child1 = gui.Component()
        child2 = gui.InteractiveComponent( Rectangle(0,0,0,0) )
        child11 = gui.Component()
        child12 = gui.InteractiveComponent( Rectangle(0,0,0,0) )
        child21 = gui.InteractiveComponent( Rectangle(0,0,0,0) )
        child22 = gui.Component()
        child222 = gui.InteractiveComponent( Rectangle(0,0,0,0) )

        root.add_subcomponent( child1 )
        root.add_subcomponent( child2 )
        child1.add_subcomponent( child11 )
        child1.add_subcomponent( child12 )
        child2.add_subcomponent( child21 )
        child2.add_subcomponent( child22 )
        child22.add_subcomponent( child222 )

        # When
        interactives = gui.GuiState._get_interactive_components( root )

        # Then
        assert len( interactives ) == 4
        assert root     not in interactives
        assert child1   not in interactives
        assert child2       in interactives
        assert child11  not in interactives
        assert child12      in interactives
        assert child21      in interactives
        assert child22  not in interactives
        assert child222     in interactives

    def test_mouse_move_over_should_activate_component( self ):
        # Given
        gui_state = gui.GuiState()
        userinput = UserInput()
        userinput.mouse.feed_pos( Vec2D( 50, 150 ) )

        component = gui.InteractiveComponent( Rectangle( 100, 100, 100, 100 ) )

        assert gui_state.get_active() <> component

        # When
        userinput.update()
        userinput.mouse.feed_pos( Vec2D( 150, 150 ) )
        gui_state.update( userinput, component )

        # Then
        assert gui_state.get_active() == component

    def test_mouse_still_over_shouldnt_activate_component( self ):
        # Given
        gui_state = gui.GuiState()
        userinput = UserInput()
        userinput.mouse.feed_pos( Vec2D( 150, 150 ) )

        component1 = gui.InteractiveComponent( Rectangle( 100, 100, 100, 100 ) )
        component = gui.InteractiveComponent( Rectangle( 100, 100, 100, 100 ) )

        base = gui.Component()
        base.add_subcomponent(component1)
        base.add_subcomponent(component)

        assert gui_state.get_active() <> component

        # When
        userinput.update()
        userinput.mouse.feed_pos( Vec2D( 150, 150 ) )
        gui_state.update( userinput, base )

        # Then
        assert gui_state.get_active() <> component

    def test_mouse_move_over_shouldnt_activate_nonhard_component( self ):
        # Given
        gui_state = gui.GuiState()
        userinput = UserInput()
        userinput.mouse.feed_pos( Vec2D( 50, 150 ) )

        component = gui.InteractiveComponent( Rectangle( 100, 100, 100, 100 ) )

        hardcomp = gui.InteractiveComponent( Rectangle( 100, 300, 100, 100 ) )
        hardcomp.lock_input( True )

        base = gui.Component()
        base.add_subcomponent( component )
        base.add_subcomponent( hardcomp )

        gui_state.set_active( hardcomp )

        assert gui_state.get_active() <> component
        assert gui_state.get_active() == hardcomp

        # When
        userinput.update()
        userinput.mouse.feed_pos( Vec2D( 150, 150 ) )
        gui_state.update( userinput, base )

        # Then
        assert gui_state.get_active() <> component
        assert gui_state.get_active() == hardcomp

class TestComponent:

    def test_subs( self ):
        comp = gui.Component()

    def test_should_call_subs_tick( self ):
        """Given a derived Component and subcomponent
            when tick is called on parent
            then tick is also called on subcomponent."""
        class Child (gui.Component):
            def __init__( self ):
                gui.Component.__init__( self )
                self.tick_cnt = 0

            def tick( self, userinput, guistate ):
                gui.Component.tick( self, None, None )
                self.tick_cnt += 1

        # Given
        top = Child()
        sub1 = Child()
        sub2 = Child()
        sub1sub = Child()
        top.add_subcomponent( sub1 )
        top.add_subcomponent( sub2 )
        sub1.add_subcomponent( sub1sub )
        assert top.tick_cnt == 0
        assert sub1.tick_cnt == 0
        assert sub2.tick_cnt == 0
        assert sub1sub.tick_cnt == 0

        # When
        top.tick( None, None )

        # Then
        assert sub1.tick_cnt == 1
        assert sub2.tick_cnt == 1
        assert sub1sub.tick_cnt == 1

    def test_should_call_subs_draw( self ):
        """Given a derived Component and subcomponent
            when draw is called on parent
            then draw is also called on subcomponent."""
        class Child (gui.Component):
            def __init__( self ):
                gui.Component.__init__( self )
                self.draw_cnt = 0

            def draw( self, surface, interpol, time_sec ):
                gui.Component.draw( self, surface, interpol, time_sec )
                self.draw_cnt += 1

        # Given
        top = Child()
        sub1 = Child()
        sub2 = Child()
        sub1sub = Child()
        top.add_subcomponent( sub1 )
        top.add_subcomponent( sub2 )
        sub1.add_subcomponent( sub1sub )
        assert top.draw_cnt == 0
        assert sub1.draw_cnt == 0
        assert sub2.draw_cnt == 0
        assert sub1sub.draw_cnt == 0

        # When
        top.draw( None, 0, 0 )

        # Then
        assert sub1.draw_cnt == 1
        assert sub2.draw_cnt == 1
        assert sub1sub.draw_cnt == 1

class TestButton:

    def test_init( self ):
        button = gui.Button()

    def test_clicked_when_mousepress_inside( self ):
        """Given a button
            when mouse clicks inside
            then button should return clicked state"""
        # Given
        button = gui.Button( Rectangle( 100, 100 , 50, 50 ) )
        userinput = UserInput()
        guistate = gui.GuiState()
        assert not button.went_down()

        # When
        userinput.mouse.feed_pos( Vec2D(110,110) )
        userinput.mouse.feed_down( Mouse.LEFT )
        button.tick( userinput, guistate )

        # Then
        assert button.went_down()

    def test_not_clicked_when_mousepress_outside( self ):
        """Given a button
            when mouse clicks outside
            then button shouldn't return clicked state"""
        # Given
        button = gui.Button( Rectangle( 100, 100 , 50, 50 ) )
        userinput = UserInput()
        guistate = gui.GuiState()
        assert not button.went_down()

        # When
        userinput.mouse.feed_pos( Vec2D(110,90) )
        userinput.mouse.feed_down( Mouse.LEFT )
        button.tick( userinput, guistate )

        # Then
        assert not button.went_down()

    def test_not_clicked_when_mouserelease_inside( self ):
        """Given a button
            when mouse is released inside
            then button shouldn't return clicked state"""
        # Given
        button = gui.Button( Rectangle( 100, 100 , 50, 50 ) )
        userinput = UserInput()
        guistate = gui.GuiState()
        assert not button.went_down()

        # When
        userinput.mouse.feed_pos( Vec2D(110,90) )
        userinput.mouse.feed_down( Mouse.LEFT )
        userinput.update()
        userinput.mouse.feed_up( Mouse.LEFT )
        button.tick( userinput, guistate )

        # Then
        assert not button.went_down()

    def test_clicked_when_enter_activated( self ):
        """Given an active button
            when enter is pressed
            then button should return clicked state"""
        pass

    def test_not_clicked_when_enter_non_activated( self ):
        """Given a non-active button
            when enter is pressed
            then button shouldn't return clicked state"""
        pass

class TestImageButton:

    def test_init( self ):
        surface = gfx.Surface( (10, 10 * 4) )

        sprite = gfx.SpriteFilm( surface )
        sprite.set_div( 1, 4 )
        assert sprite.width == 10 and sprite.height == 10

        button = gui.ImageButton(sprite)

    def test_draw( self ):
        surface = gfx.Surface( (10, 10 * 3) )

        sprite = gfx.SpriteFilm( surface )
        sprite.set_div( 1, 3 )
        assert sprite.width == 10 and sprite.height == 10

        button = gui.ImageButton(sprite)

        background = gfx.Surface((100,100))

        button.draw( background, 0, 0 )

class TestCheckbox:
    def test_init( self ):
        checkbox = gui.Checkbox()

    def test_init_selected( self ):
        checkbox = gui.Checkbox()
        assert not checkbox.is_selected()

        checkbox = gui.Checkbox( selected = True )
        assert checkbox.is_selected()

    def test_clicked_when_mousepress_inside( self ):
        # Given
        checkbox = gui.Checkbox( Rectangle( 100, 100 , 50, 50 ), False )
        userinput = UserInput()
        guistate = gui.GuiState()
        assert not checkbox.is_selected()

        # When
        userinput.mouse.feed_pos( Vec2D(110,110) )
        userinput.mouse.feed_down( Mouse.LEFT )
        checkbox.tick( userinput, guistate )

        # Then
        assert checkbox.went_down()
        assert checkbox.is_selected()

        # And when
        checkbox.tick( userinput, guistate )

        # Then
        assert not checkbox.is_selected()

class TestImageCheckbox:
    pass

class TestRadiobuttons:

    def test_init( self ):
        radiobuttons = gui.Radiobuttons()

    def test_add( self ):
        # Given
        rb = gui.Radiobuttons()
        checkbox1 = gui.Checkbox()
        checkbox2 = gui.Checkbox()

        # When
        rb.append( checkbox1 )
        rb.append( checkbox2 )

        # Then
        assert len( rb ) == 2
        assert rb[0] is checkbox1
        assert rb[1] is checkbox2

    def test_only_one_selected( self ):
        # Given
        rb = gui.Radiobuttons()
        rb.append( gui.Checkbox( Rectangle( 100, 100 , 50, 50 ), False ) )
        rb.append( gui.Checkbox( Rectangle( 100, 200 , 50, 50 ), False ) )
        rb.append( gui.Checkbox( Rectangle( 100, 300 , 50, 50 ), False ) )
        userinput = UserInput()
        guistate = gui.GuiState()

        # When select checkbox 0
        userinput.mouse.feed_pos( Vec2D(110,110) )
        userinput.mouse.feed_down( Mouse.LEFT )
        rb.tick( userinput, guistate )

        # Then
        assert rb[0].is_selected()
        assert not rb[1].is_selected()
        assert not rb[2].is_selected()
        assert rb.get_selected() is rb[0]
        assert rb.get_selected_index() == 0

        # And when select checkbox 2
        userinput.mouse.feed_pos( Vec2D(110,310) )
        userinput.mouse.feed_down( Mouse.LEFT )
        rb.tick( userinput, guistate )

        # Then
        assert not rb[0].is_selected()
        assert not rb[1].is_selected()
        assert rb[2].is_selected()
        assert rb.get_selected() is rb[2]
        assert rb.get_selected_index() == 2

        # And when select checkbox 1
        userinput.mouse.feed_pos( Vec2D(110,210) )
        userinput.mouse.feed_down( Mouse.LEFT )
        rb.tick( userinput, guistate )

        # Then
        assert not rb[0].is_selected()
        assert rb[1].is_selected()
        assert not rb[2].is_selected()
        assert rb.get_selected() is rb[1]
        assert rb.get_selected_index() == 1

class TestTextField:

    def test_get_text_returns_set_text( self ):
        """Given a TextField
            when a text is set
            then that text can be retrieved"""
        # Given
        textfield = gui.TextField( Rectangle( 100, 100, 50, 50 ), gfx.Font() )
        TEST_TEXT = "Testing 1 2 3"

        # When
        textfield.text = TEST_TEXT

        # Then
        assert textfield.text == TEST_TEXT

    def test_active_receives_input_chars( self ):
        """Given an active TextField
            when keys are pressed
            then the text is entered"""
        # Given
        textfield = gui.TextField( Rectangle( 100, 100, 50, 50 ), gfx.Font() )
        userinput = UserInput()
        guistate = gui.GuiState()
        guistate.set_active( textfield )

        # When
        # loop 1
        userinput.key.feed_char( "A" )
        textfield.tick( userinput, guistate )
        userinput.update()
        userinput.key.feed_char( "b" )
        textfield.tick( userinput, guistate )
        userinput.update()

        # Then
        assert textfield.text == "Ab"

    def test_non_active_receives_no_input( self ):
        """Given an non-active TextField
            when keys are pressed
            then the text isn't entered"""
        # Given
        textfield = gui.TextField( Rectangle( 100, 100, 50, 50 ), gfx.Font() )
        userinput = UserInput()
        guistate = gui.GuiState()
        guistate.set_active( None )

        # When
        # loop 1
        userinput.key.feed_char( "A" )
        textfield.tick( userinput, guistate )
        userinput.update()
        userinput.key.feed_char( "b" )
        textfield.tick( userinput, guistate )
        userinput.update()

        # Then
        assert textfield.text == ""

class TestSlider:

    def test_init( self ):
        slider = gui.Slider()


text:
package ecrpublic

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/ecrpublic/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Create or updates the catalog data for a public registry.
func (c *Client) PutRegistryCatalogData(ctx context.Context, params *PutRegistryCatalogDataInput, optFns ...func(*Options)) (*PutRegistryCatalogDataOutput, error) {
	if params == nil {
		params = &PutRegistryCatalogDataInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "PutRegistryCatalogData", params, optFns, c.addOperationPutRegistryCatalogDataMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*PutRegistryCatalogDataOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type PutRegistryCatalogDataInput struct {

	// The display name for a public registry. The display name is shown as the
	// repository author in the Amazon ECR Public Gallery. The registry display name is
	// only publicly visible in the Amazon ECR Public Gallery for verified accounts.
	DisplayName *string

	noSmithyDocumentSerde
}

type PutRegistryCatalogDataOutput struct {

	// The catalog data for the public registry.
	//
	// This member is required.
	RegistryCatalogData *types.RegistryCatalogData

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationPutRegistryCatalogDataMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutRegistryCatalogData{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutRegistryCatalogData{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutRegistryCatalogData(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opPutRegistryCatalogData(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ecr-public",
		OperationName: "PutRegistryCatalogData",
	}
}

redpajama_set_name: RedPajamaGithub


text:
class ExamController < ApplicationController
  def show
    @test = Test.find(params[:id])
    @questions = @test.questions
    @question = @questions.find_by_position(params[:question_id])
  end

  def check
    test = Test.find(params[:exam][:test_id])
    #question = test.questions.find(params[:exam][:question_id])
    #question = params[:exam][:question_id]
    #answer = params[:exam][:options]
    #next_question =
    #format.html { redirect_to "exam/#{test_question_path(@question.test, @question.position)}", notice: 'Вопрос обновлен.' }

  end
end


text:
package org.ragudosa;

import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;

public class PhotoImporter {

    private static final Logger logger = LogManager.getLogger(PhotoImporter.class);
    private String source;
    private String destination;

    public static void main(String[] args) {

        try {
            new PhotoImporter().run(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void run(String[] args) throws IOException {

        Options options = createParameters();

        // create the parser
        CommandLineParser parser = new DefaultParser();

        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);

            if (line.hasOption("help")) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("photoimporter", options);
            }

            this.source = line.getOptionValue("source-folder");

            this.destination = line.getOptionValue("destination-folder");
            boolean deleteSourceFolder = line.hasOption("deleteSourceFolder");
            copyFiles(deleteSourceFolder);
            deleteEmptyFolders(deleteSourceFolder);

        } catch (ParseException exp) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("photoimporter", options);
        }

    }

    private void deleteEmptyFolders(Boolean deleteFolders) throws IOException {
        Files.walk(Paths.get(this.source)).forEach(filePath -> {
            if (Files.isDirectory(filePath, LinkOption.NOFOLLOW_LINKS)) {

                File directory = filePath.toFile();
                if (deleteFolders) {
                    if (directory.list().length == 0) {
                        directory.delete();
                    }
                }
            }
        });
    }

    private void copyFiles(Boolean deleteSourceFolder) throws IOException {

        Files.walk(Paths.get(this.source)).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                try {
                    File jpegFile = filePath.toFile();
                    processFile(filePath, jpegFile);

                    if (deleteSourceFolder) {
                        deleteFile(jpegFile);
                    }

                } catch (ImageProcessingException | IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void processFile(Path filePath, File jpegFile) throws ImageProcessingException, IOException {

        Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);

        // obtain the Exif directory
        ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);

        if (directory == null) {
            logger.warn("File " + jpegFile.getAbsolutePath() + " skipped, no EXIF metadata found");
            return;
        }

        // query the tag's value
        Date date = directory.getDateOriginal();

        if (date != null) {
            copyFile(this.destination, filePath, jpegFile, date);

        } else {
            logger.warn("File " + jpegFile.getAbsolutePath() + " skipped, missing original date");
        }
    }

    private void deleteFile(File fileToDelete) throws IOException {
        if (!fileToDelete.isDirectory()) {
            fileToDelete.delete();
            logger.info("Deleted " + fileToDelete.getAbsolutePath());
        }
    }

    private Options createParameters() {
        Option help = new Option("help", "print this message");
        Option version = new Option("version", "print the version information and exit");
        Option deleteSourceFolder = new Option("deleteSourceFolder", "Deletes the source files");

        Option source = Option.builder("s").argName("folder").hasArg().desc("Source folder to process")
                .longOpt("source-folder").required().build();

        Option destination = Option.builder("d").argName("folder").hasArg()
                .desc("Where to copy the pictures specified in source").longOpt("destination-folder").required()
                .build();

        Options options = new Options();

        options.addOption(help);
        options.addOption(version);
        options.addOption(source);
        options.addOption(destination);
        options.addOption(deleteSourceFolder);

        return options;
    }

    private void copyFile(String destination, Path filePath, File jpegFile, Date date) throws IOException {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
        String day = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH));

        String newJpegName = new SimpleDateFormat("yyMMdd_hhmmss").format(date) + ".jpg";

        Path destinationPath = Paths.get(destination, year, month, day);
        File destinationFolder = new File(destinationPath.toString());
        destinationFolder.mkdirs();

        destinationPath = Paths.get(destination, year, month, day, newJpegName);

        Files.copy(filePath, destinationPath, REPLACE_EXISTING, COPY_ATTRIBUTES);
        logger.info(filePath.toString() + " -> " + destinationPath.toString());
    }
}


text:
package org.apache.hadoop.hbase.regionserver;

import static org.mockito.Mockito.verify;

import java.io.IOException;

import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.Action;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MultiRequest;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.RegionAction;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.RpcController;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.ServiceException;

/**
 * Tests logging of large batch commands via Multi. Tests are fast, but uses a mini-cluster (to test
 * via "Multi" commands) so classified as MediumTests
 */
@Category(MediumTests.class)
public class TestMultiLogThreshold {

  private static RSRpcServices SERVICES;

  private static HBaseTestingUtility TEST_UTIL;
  private static Configuration CONF;
  private static final byte[] TEST_FAM = Bytes.toBytes("fam");
  private static RSRpcServices.LogDelegate LD;
  private static HRegionServer RS;
  private static int THRESHOLD;

  @BeforeClass
  public static void setup() throws Exception {
    final TableName tableName = TableName.valueOf("tableName");
    TEST_UTIL = HBaseTestingUtility.createLocalHTU();
    CONF = TEST_UTIL.getConfiguration();
    THRESHOLD = CONF.getInt(RSRpcServices.BATCH_ROWS_THRESHOLD_NAME,
      RSRpcServices.BATCH_ROWS_THRESHOLD_DEFAULT);
    TEST_UTIL.startMiniCluster();
    TEST_UTIL.createTable(tableName, TEST_FAM);
    RS = TEST_UTIL.getRSForFirstRegionInTable(tableName);
  }

  @Before
  public void setupTest() throws Exception {
    LD = Mockito.mock(RSRpcServices.LogDelegate.class);
    SERVICES = new RSRpcServices(RS, LD);
  }

  private enum ActionType {
    REGION_ACTIONS, ACTIONS;
  }

  /**
   * Sends a multi request with a certain amount of rows, will populate Multi command with either
   * "rows" number of RegionActions with one Action each or one RegionAction with "rows" number of
   * Actions
   */
  private void sendMultiRequest(int rows, ActionType actionType) throws ServiceException {
    RpcController rpcc = Mockito.mock(RpcController.class);
    MultiRequest.Builder builder = MultiRequest.newBuilder();
    int numRAs = 1;
    int numAs = 1;
    switch (actionType) {
    case REGION_ACTIONS:
      numRAs = rows;
      break;
    case ACTIONS:
      numAs = rows;
      break;
    }
    for (int i = 0; i < numRAs; i++) {
      RegionAction.Builder rab = RegionAction.newBuilder();
      rab.setRegion(RequestConverter.buildRegionSpecifier(
        HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME,
        new String("someStuff" + i).getBytes()));
      for (int j = 0; j < numAs; j++) {
        Action.Builder ab = Action.newBuilder();
        rab.addAction(ab.build());
      }
      builder.addRegionAction(rab.build());
    }
    try {
      SERVICES.multi(rpcc, builder.build());
    } catch (ClassCastException e) {
      // swallow expected exception due to mocked RpcController
    }
  }

  @Test
  public void testMultiLogThresholdRegionActions() throws ServiceException, IOException {
    sendMultiRequest(THRESHOLD + 1, ActionType.REGION_ACTIONS);
    verify(LD, Mockito.times(1)).logBatchWarning(Mockito.anyInt(), Mockito.anyInt());
  }

  @Test
  public void testMultiNoLogThresholdRegionActions() throws ServiceException, IOException {
    sendMultiRequest(THRESHOLD, ActionType.REGION_ACTIONS);
    verify(LD, Mockito.never()).logBatchWarning(Mockito.anyInt(), Mockito.anyInt());
  }

  @Test
  public void testMultiLogThresholdActions() throws ServiceException, IOException {
    sendMultiRequest(THRESHOLD + 1, ActionType.ACTIONS);
    verify(LD, Mockito.times(1)).logBatchWarning(Mockito.anyInt(), Mockito.anyInt());
  }

  @Test
  public void testMultiNoLogThresholdAction() throws ServiceException, IOException {
    sendMultiRequest(THRESHOLD, ActionType.ACTIONS);
    verify(LD, Mockito.never()).logBatchWarning(Mockito.anyInt(), Mockito.anyInt());
  }

}


text:
package com.imu.csbookstore.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.imu.csbookstore.javabean.BookClass;
import com.imu.csbookstore.util.DBPoolUtil;

public class BookClassDao {
	public boolean addBookClass(BookClass bookclass) throws Exception {
		Connection conn = DBPoolUtil.getConnection();
		String sql = "insert into tb_bookclass (class_name) values(?)";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, bookclass.getClass_name());
		pstmt.executeUpdate();
		DBPoolUtil.closeConnection(conn);
		return true;
	}

	public boolean deleteBookClassByBookClassId(int class_id) throws Exception {

		Connection conn = DBPoolUtil.getConnection();
		String sql = "delete from tb_bookclass where class_id=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, class_id);
		pstmt.executeUpdate();
		DBPoolUtil.closeConnection(conn);
		return true;
	}

	public boolean modifyBookClass(BookClass bookclass) throws Exception {
		Connection conn = DBPoolUtil.getConnection();
		String sql = "update tb_bookclass set class_name=? where class_id=?";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, bookclass.getClass_name());
		pstmt.setInt(2, bookclass.getClass_id());
		pstmt.executeUpdate();
		DBPoolUtil.closeConnection(conn);
		return true;
	}

	public List ListAllBookClasses() throws Exception {
		List bookclass = new ArrayList();
		Connection conn = DBPoolUtil.getConnection();
		Statement stmt;
		String sql = "select * from tb_bookclass";
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet result = pstmt.executeQuery(sql);

		while (result.next()) {
			BookClass u = new BookClass();
			u.setClass_id(result.getInt("class_id"));
			u.setClass_name(result.getString("class_name"));
			bookclass.add(u);
		}
		DBPoolUtil.closeConnection(conn);
		return bookclass;
	}

	public String getClassNameByClassId(int class_id) throws Exception {
		String class_name = "";
		Connection conn = DBPoolUtil.getConnection();
		Statement stmt;
		String sql = "select * from tb_bookclass where class_id=" + class_id;
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet result = pstmt.executeQuery(sql);

		if (result.next()) {
			class_name = result.getString("class_name");
		}
		DBPoolUtil.closeConnection(conn);
		return class_name;
	}
}


text:
<?xml version="1.0"?>
<launch>
  <arg name="surfacing_mode_str" value="true" />
  <arg name="mesh_cad_str" value="plane/plane_defect.ply" />

  <group ns="bezier_application__">
    <include file="$(find bezier_application)/launch/fanuc_m20ia.launch">
      <arg name="sim" value="false" />
      <arg name="robot_ip" value="127.0.0.1" />
      <arg name="mesh_cad" value="$(arg mesh_cad_str)" />
      <arg name="surfacing_mode" value="$(arg surfacing_mode_str)" />
    </include>
  </group>
</launch>


text:
import java.util.*;
public class Solution {
    public List<String[]> result = new ArrayList<String[]>();
    public List<String[]> solveNQueens(int n) {
        List<Integer> array = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            array.add(i+1);
        }
        List<Integer> curr = new ArrayList<Integer>();
        this.dfs(curr, array);
        return this.result;
    }

    public void dfs (List<Integer> curr, List<Integer> array) {
        if (array.size() == 0) {
            this.result.add(this.construct(curr));
            return;
        }
        for (int i = 0; i < array.size(); i++) {
            if (this.check(curr, array.get(i)) == true) {
                List<Integer> copyCurr = new ArrayList<Integer>(curr);
                copyCurr.add(array.get(i));
                List<Integer> arrayCopy = new ArrayList<Integer>(array);
                arrayCopy.remove(i);
                dfs(copyCurr, arrayCopy);
            }
        }
    }

    public boolean check (List<Integer> curr, int newValue) {
        for (int i = 0; i < curr.size(); i++) {
            if (Math.abs(newValue-curr.get(i)) == Math.abs(curr.size()-i)) {
                return false;
            }
        }
        return true;
    }

    public String[] construct (List<Integer> curr) {
        String[] r = new String[curr.size()];
        for (int i = 0; i < curr.size(); i++) {
            StringBuilder sb = new StringBuilder(curr.size());
            for (int j = 0; j < curr.size(); j++) {
                if ((j + 1) == curr.get(i)) {
                    sb.append('Q');
                } else {
                    sb.append('.');
                }
            }
            r[i] = sb.toString();
        }
        return r;
    }

    public static void main (String args[]) {
        Solution sol = new Solution();
        int n = 2;
        List<String[]> result = sol.solveNQueens(n);
        for (int i = 0; i < result.size(); i++) {
            for (int j = 0; j < n; j++) {
                System.out.println(result.get(i)[j]);
            }
        }
    }
}


text:
package io.druid.segment.filter;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.metamx.common.Pair;
import io.druid.data.input.InputRow;
import io.druid.data.input.impl.DimensionsSpec;
import io.druid.data.input.impl.InputRowParser;
import io.druid.data.input.impl.MapInputRowParser;
import io.druid.data.input.impl.TimeAndDimsParseSpec;
import io.druid.data.input.impl.TimestampSpec;
import io.druid.query.extraction.ExtractionFn;
import io.druid.query.extraction.JavaScriptExtractionFn;
import io.druid.query.filter.BoundDimFilter;
import io.druid.query.filter.DimFilter;
import io.druid.query.filter.Filter;
import io.druid.query.filter.InDimFilter;
import io.druid.segment.IndexBuilder;
import io.druid.segment.StorageAdapter;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RunWith(Parameterized.class)
public class InFilterTest extends BaseFilterTest
{
  private static final String TIMESTAMP_COLUMN = "timestamp";

  private static final InputRowParser<Map<String, Object>> PARSER = new MapInputRowParser(
      new TimeAndDimsParseSpec(
          new TimestampSpec(TIMESTAMP_COLUMN, "iso", new DateTime("2000")),
          new DimensionsSpec(null, null, null)
      )
  );

  private static final List<InputRow> ROWS = ImmutableList.of(
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "a", "dim1", "", "dim2", ImmutableList.of("a", "b"))),
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "b", "dim1", "10", "dim2", ImmutableList.of())),
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "c", "dim1", "2", "dim2", ImmutableList.of(""))),
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "d", "dim1", "1", "dim2", ImmutableList.of("a"))),
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "e", "dim1", "def", "dim2", ImmutableList.of("c"))),
      PARSER.parse(ImmutableMap.<String, Object>of("dim0", "f", "dim1", "abc"))
  );

  @Parameterized.Parameters(name = "{0}")
  public static Collection<Object[]> constructorFeeder() throws IOException
  {
    return makeConstructors();
  }

  public InFilterTest(
      String testName,
      IndexBuilder indexBuilder,
      Function<IndexBuilder, Pair<StorageAdapter, Closeable>> finisher,
      boolean optimize
  )
  {
    super(ROWS, indexBuilder, finisher, optimize);
  }

  @Before
  public void setUp() throws IOException
  {
    final Pair<StorageAdapter, Closeable> pair = finisher.apply(
        indexBuilder.tmpDir(temporaryFolder.newFolder()).add(ROWS)
    );
    this.adapter = pair.lhs;
    this.closeable = pair.rhs;
  }

  @Test
  public void testSingleValueStringColumnWithoutNulls()
  {
    assertFilterMatches(
        toInFilter("dim0", null),
        ImmutableList.<String>of()
    );

    assertFilterMatches(
        toInFilter("dim0", "", ""),
        ImmutableList.<String>of()
    );

    assertFilterMatches(
        toInFilter("dim0", "a", "c"),
        ImmutableList.of("a", "c")
    );

    assertFilterMatches(
        toInFilter("dim0", "e", "x"),
        ImmutableList.of("e")
    );
  }

  @Test
  public void testSingleValueStringColumnWithNulls()
  {
    assertFilterMatches(
        toInFilter("dim1", null, ""),
        ImmutableList.of("a")
    );

    assertFilterMatches(
        toInFilter("dim1", ""),
        ImmutableList.of("a")
    );

    assertFilterMatches(
        toInFilter("dim1", null, "10", "abc"),
        ImmutableList.of("a", "b", "f")
    );

    assertFilterMatches(
        toInFilter("dim1", "-1", "ab", "de"),
        ImmutableList.<String>of()
    );
  }

  @Test
  public void testMultiValueStringColumn()
  {
    assertFilterMatches(
        toInFilter("dim2", null),
        ImmutableList.of("b", "c", "f")
    );

    assertFilterMatches(
        toInFilter("dim2", "", (String)null),
        ImmutableList.of("b", "c", "f")
    );

    assertFilterMatches(
        toInFilter("dim2", null, "a"),
        ImmutableList.of("a", "b", "c", "d", "f")

    );

    assertFilterMatches(
        toInFilter("dim2", null, "b"),
        ImmutableList.of("a", "b", "c", "f")

    );

    assertFilterMatches(
        toInFilter("dim2", "c"),
        ImmutableList.of("e")
    );

    assertFilterMatches(
        toInFilter("dim2", "d"),
        ImmutableList.<String>of()
    );
  }

  @Test
  public void testMissingColumn()
  {
    assertFilterMatches(
        toInFilter("dim3", null, (String)null),
        ImmutableList.of("a", "b", "c", "d", "e", "f")
    );

    assertFilterMatches(
        toInFilter("dim3", ""),
        ImmutableList.of("a", "b", "c", "d", "e", "f")
    );

    assertFilterMatches(
        toInFilter("dim3", null, "a"),
        ImmutableList.of("a", "b", "c", "d", "e", "f")
    );

    assertFilterMatches(
        toInFilter("dim3", "a"),
        ImmutableList.<String>of()
    );

    assertFilterMatches(
        toInFilter("dim3", "b"),
        ImmutableList.<String>of()
    );

    assertFilterMatches(
        toInFilter("dim3", "c"),
        ImmutableList.<String>of()
    );
  }

  @Test
  public void testMatchWithExtractionFn()
  {
    String extractionJsFn = "function(str) { return 'super-' + str; }";
    ExtractionFn superFn = new JavaScriptExtractionFn(extractionJsFn, false);

    String nullJsFn = "function(str) { if (str === null) { return 'YES'; } else { return 'NO';} }";
    ExtractionFn yesNullFn = new JavaScriptExtractionFn(nullJsFn, false);

    assertFilterMatches(
        toInFilterWithFn("dim2", superFn, "super-null", "super-a", "super-b"),
        ImmutableList.of("a", "b", "c", "d", "f")
    );

    assertFilterMatches(
        toInFilterWithFn("dim2", yesNullFn, "YES"),
        ImmutableList.of("b", "c", "f")
    );

    assertFilterMatches(
        toInFilterWithFn("dim1", superFn, "super-null", "super-10", "super-def"),
        ImmutableList.of("a", "b", "e")
    );

    assertFilterMatches(
        toInFilterWithFn("dim3", yesNullFn, "NO"),
        ImmutableList.<String>of()
    );

    assertFilterMatches(
        toInFilterWithFn("dim3", yesNullFn, "YES"),
        ImmutableList.of("a", "b", "c", "d", "e", "f")
    );

    assertFilterMatches(
        toInFilterWithFn("dim1", yesNullFn, "NO"),
        ImmutableList.of("b", "c", "d", "e", "f")
    );
  }

  private DimFilter toInFilter(String dim, String value, String... values)
  {
    return new InDimFilter(dim, Lists.asList(value, values), null);
  }

  private DimFilter toInFilterWithFn(String dim, ExtractionFn fn, String value, String... values)
  {
    return new InDimFilter(dim, Lists.asList(value, values), fn);
  }

  private void assertFilterMatches(
      final DimFilter filter,
      final List<String> expectedRows
  )
  {
    Assert.assertEquals(filter.toString(), expectedRows, selectColumnValuesMatchingFilter(filter, "dim0"));
    Assert.assertEquals(filter.toString(), expectedRows.size(), selectCountUsingFilteredAggregator(filter));
  }
}


text:
namespace bart {

namespace formulation {

namespace angular {

template <int dim>
class SelfAdjointAngularFlux : public SelfAdjointAngularFluxI<dim> {
 public:

  SelfAdjointAngularFlux(
      std::shared_ptr<domain::finite_element::FiniteElementI<dim>>,
      std::shared_ptr<data::cross_sections::CrossSectionsI>,
      std::shared_ptr<quadrature::QuadratureSetI<dim>>);

  void Initialize(const domain::CellPtr<dim>&) override;

  // Fill functions

  void FillBoundaryBilinearTerm(
      FullMatrix &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const domain::FaceIndex face_number,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number) override;

  auto FillReflectiveBoundaryLinearTerm(
      Vector &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      domain::FaceIndex face_number,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const dealii::Vector<double>& incoming_flux) -> double override;

  void FillCellCollisionTerm(
      FullMatrix &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const system::EnergyGroup group_number) override;

  auto FillCellFissionSourceTerm(
      Vector &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number,
      const double k_eff,
      const system::moments::MomentVector &in_group_moment,
      const system::moments::MomentsMap &group_moments) -> double override;

  void FillCellFixedSourceTerm(
      Vector &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number) override;

  auto FillCellScatteringSourceTerm(
      Vector &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number,
      const system::moments::MomentVector &in_group_moment,
      const system::moments::MomentsMap &group_moments) -> double override;

  void FillCellStreamingTerm(
      FullMatrix &to_fill,
      const domain::CellPtr<dim> &cell_ptr,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number) override;

  // Getters for pre-calculated values
  std::vector<double> OmegaDotGradient(int cell_quadrature_point,
                                       quadrature::QuadraturePointIndex) const;
  FullMatrix OmegaDotGradientSquared(int cell_quadrature_point,
                                     quadrature::QuadraturePointIndex) const;
  // Dependency getters
  domain::finite_element::FiniteElementI<dim>* finite_element_ptr() const {
    return finite_element_ptr_.get(); }
  data::cross_sections::CrossSectionsI* cross_sections_ptr() const {
    return cross_sections_ptr_.get(); }
  quadrature::QuadratureSetI<dim>* quadrature_set_ptr() const {
    return quadrature_set_ptr_.get(); }

  std::map<int, FullMatrix> shape_squared() const {
    return shape_squared_; }

  bool is_initialized() const { return is_initialized_; }

 protected:
  // Validation Functions
  void ValidateMatrixSizeAndSetCell(const domain::CellPtr<dim>& cell_ptr,
                                    const FullMatrix& matrix_to_validate,
                                    std::string called_function_name) {
    ValidateAndSetCell(cell_ptr, called_function_name);
    ValidateMatrixSize(matrix_to_validate, called_function_name);
  }
  void ValidateVectorSizeAndSetCell(const domain::CellPtr<dim>& cell_ptr,
                                    const Vector& vector_to_validate,
                                    std::string called_function_name) {
    ValidateAndSetCell(cell_ptr, called_function_name);
    ValidateVectorSize(vector_to_validate, called_function_name);
  }
  void ValidateAndSetCell(const domain::CellPtr<dim>& cell_ptr,
                          std::string function_name);
  void ValidateMatrixSize(const FullMatrix&, std::string called_function_name);
  void ValidateVectorSize(const Vector&, std::string called_function_name);
  void VerifyInitialized(std::string called_function_name);

  // Combined implementation functions
  auto FillCellSourceTerm(
      Vector& to_fill,
      const int material_id,
      const std::shared_ptr<quadrature::QuadraturePointI<dim>> quadrature_point,
      const system::EnergyGroup group_number,
      std::vector<double> source) -> double;

  // Dependencies
  std::shared_ptr<domain::finite_element::FiniteElementI<dim>> finite_element_ptr_;
  std::shared_ptr<data::cross_sections::CrossSectionsI> cross_sections_ptr_;
  std::shared_ptr<quadrature::QuadratureSetI<dim>> quadrature_set_ptr_;
  // Geometric properties
  const int cell_degrees_of_freedom_ = 0; //!< Degrees of freedom per cell
  const int cell_quadrature_points_ = 0; //!< Quadrature points per cell
  const int face_quadrature_points_ = 0; //!< Quadrature points per face
  // Precalculated matrices and vectors
  using CellQuadratureIndex = int;
  using AngleIndex = int;
  std::map<std::pair<CellQuadratureIndex, AngleIndex>,
           dealii::Vector<double>> omega_dot_gradient_;
  std::map<std::pair<CellQuadratureIndex, AngleIndex>,
           FullMatrix> omega_dot_gradient_squared_;
  std::map<CellQuadratureIndex, FullMatrix> shape_squared_ = {};
  bool is_initialized_ = false;
};

} // namespace angular

} // namespace formulation

} //namespace bart

#endif //BART_SRC_FORMULATION_ANGULAR_SELF_ADJOINT_ANGULAR_FLUX_H_


text:
/**
 * Contains Rust Iterator enumerate equivalent implementation.
 *
 * enumerate function:
 * https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.enumerate
 *
 * Enumerate struct: https://doc.rust-lang.org/std/iter/struct.Enumerate.html
 *
 * @author Chen Weiguang
 * @version 0.1.0
 */

#pragma once

#include "option.h"
#include "traits.h"
#include "util.h"

#include <type_traits>
#include <utility>

namespace rustfp {

// declaration section

/**
 * impl<I> Iterator for Enumerate<I>
 * where
 *     I: Iterator,
 * type Item = (usize, <I as Iterator>::Item)
 */
template <class Self>
class Enumerate {
public:
    /**
     * Type alias to rustfp Iter type.
     */
    using I = Self;

    /**
     * Item type to generate.
     */
    using Item = std::pair<size_t, typename Self::Item>;

    /**
     * Takes in both the moved rustfp Iter instance and
     * and function type F instance.
     * @tparam Selfx Forwarded type of Self, rustfp Iter type
     * @param self rustfp Iter instance
     */
    template <class Selfx>
    explicit Enumerate(Selfx &&self);

    /**
     * Generates the next value of enumerate operation.
     * @return Some(Item) if there is a next value to generate,
     * otherwise None.
     */
    auto next() -> Option<Item>;

private:
    Self self;
    size_t index;
};

class EnumerateOp {
public:
    template <class Self>
    auto operator()(Self &&self) && -> Enumerate<Self>;
};

/**
 * fn enumerate(self) -> Enumerate<Self>
 */
auto enumerate() -> EnumerateOp;

// implementation section

template <class Self>
template <class Selfx>
Enumerate<Self>::Enumerate(Selfx &&self)
    : self(std::forward<Selfx>(self)), index(0) {
}

template <class Iterator>
auto Enumerate<Iterator>::next() -> Option<Item> {
    return self.next().map([this](auto &&value) {
        return std::pair<size_t, typename Iterator::Item>(
            index++, std::forward<typename Iterator::Item>(value));
    });
}

template <class Self>
auto EnumerateOp::operator()(Self &&self) && -> Enumerate<Self> {
    static_assert(
        !std::is_lvalue_reference<Self>::value,
        "enumerate can only take rvalue ref object with Iterator traits");

    return Enumerate<Self>(std::move(self));
}

inline auto enumerate() -> EnumerateOp {
    return EnumerateOp();
}
} // namespace rustfp


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Shared;

#nullable disable

namespace Microsoft.Build.Evaluation
{
    /// <summary>
    /// Evaluates as boolean and evaluates children as boolean, numeric, or string.
    /// Order in which comparisons are attempted is numeric, boolean, then string.
    /// Updates conditioned properties table.
    /// </summary>
    internal abstract class MultipleComparisonNode : OperatorExpressionNode
    {
        private bool _conditionedPropertiesUpdated = false;

        /// <summary>
        /// Compare numbers
        /// </summary>
        protected abstract bool Compare(double left, double right);

        /// <summary>
        /// Compare booleans
        /// </summary>
        protected abstract bool Compare(bool left, bool right);

        /// <summary>
        /// Compare strings
        /// </summary>
        protected abstract bool Compare(string left, string right);

        /// <summary>
        /// Evaluates as boolean and evaluates children as boolean, numeric, or string.
        /// Order in which comparisons are attempted is numeric, boolean, then string.
        /// Updates conditioned properties table.
        /// </summary>
        internal override bool BoolEvaluate(ConditionEvaluator.IConditionEvaluationState state, LoggingContext loggingContext)
        {
            ProjectErrorUtilities.VerifyThrowInvalidProject
                (LeftChild != null && RightChild != null,
                 state.ElementLocation,
                 "IllFormedCondition",
                 state.Condition);

            // It's sometimes possible to bail out of expansion early if we just need to know whether
            // the result is empty string.
            // If at least one of the left or the right hand side will evaluate to empty,
            // and we know which do, then we already have enough information to evaluate this expression.
            // That means we don't have to fully expand a condition like " '@(X)' == '' "
            // which is a performance advantage if @(X) is a huge item list.
            bool leftEmpty = LeftChild.EvaluatesToEmpty(state, loggingContext);
            bool rightEmpty = RightChild.EvaluatesToEmpty(state, loggingContext);
            if (leftEmpty || rightEmpty)
            {
                UpdateConditionedProperties(state);

                return Compare(leftEmpty, rightEmpty);
            }
            else if (LeftChild.TryNumericEvaluate(state, out double leftNumericValue) && RightChild.TryNumericEvaluate(state, out double rightNumericValue))
            {
                // The left child evaluating to a number and the right child not evaluating to a number
                // is insufficient to say they are not equal because $(MSBuildToolsVersion) evaluates to
                // the string "Current" most of the time but when doing numeric comparisons, is treated
                // as a version and returns "17.0" (or whatever the current tools version is). This means
                // that if '$(MSBuildToolsVersion)' is "equal" to BOTH '17.0' and 'Current' (if 'Current'
                // is 17.0).
                return Compare(leftNumericValue, rightNumericValue);
            }
            else if (LeftChild.TryBoolEvaluate(state, out bool leftBoolValue, loggingContext) && RightChild.TryBoolEvaluate(state, out bool rightBoolValue, loggingContext))
            {
                return Compare(leftBoolValue, rightBoolValue);
            }

            string leftExpandedValue = LeftChild.GetExpandedValue(state, loggingContext);
            string rightExpandedValue = RightChild.GetExpandedValue(state, loggingContext);

            ProjectErrorUtilities.VerifyThrowInvalidProject
                (leftExpandedValue != null && rightExpandedValue != null,
                    state.ElementLocation,
                    "IllFormedCondition",
                    state.Condition);

            UpdateConditionedProperties(state);

            return Compare(leftExpandedValue, rightExpandedValue);
        }

        /// <summary>
        /// Reset temporary state
        /// </summary>
        internal override void ResetState()
        {
            base.ResetState();
            _conditionedPropertiesUpdated = false;
        }

        /// <summary>
        /// Updates the conditioned properties table if it hasn't already been done.
        /// </summary>
        private void UpdateConditionedProperties(ConditionEvaluator.IConditionEvaluationState state)
        {
            if (!_conditionedPropertiesUpdated && state.ConditionedPropertiesInProject != null)
            {
                string leftUnexpandedValue = LeftChild.GetUnexpandedValue(state);
                string rightUnexpandedValue = RightChild.GetUnexpandedValue(state);

                if (leftUnexpandedValue != null)
                {
                    ConditionEvaluator.UpdateConditionedPropertiesTable
                        (state.ConditionedPropertiesInProject,
                         leftUnexpandedValue,
                         RightChild.GetExpandedValue(state));
                }

                if (rightUnexpandedValue != null)
                {
                    ConditionEvaluator.UpdateConditionedPropertiesTable
                        (state.ConditionedPropertiesInProject,
                         rightUnexpandedValue,
                         LeftChild.GetExpandedValue(state));
                }

                _conditionedPropertiesUpdated = true;
            }
        }
    }
}


text:
package com.aishang.app.data.model;

/**
 * Created by song on 2016/3/30.
 */
public class JNewsHitsResult {
  private String result;

  public String getResult() {
    return result;
  }

  public void setResult(String result) {
    this.result = result;
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>My Polls</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="/public/css/main.css" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Voting App

Home

My Polls

Sign out

Hello {{displayName}}!

Below is a list of all your polls. Select a poll to view its summary, or delete it.

        Click here to create a new poll

			POLLS CREATED: {{mypolls.length}}
			Loading data

				{{data.description}}


text:
require 'spec_helper'

describe Todo do
  let(:issue) { create(:issue) }

  describe 'relationships' do
    it { is_expected.to belong_to(:author).class_name("User") }
    it { is_expected.to belong_to(:note) }
    it { is_expected.to belong_to(:project) }
    it { is_expected.to belong_to(:target).touch(true) }
    it { is_expected.to belong_to(:user) }
  end

  describe 'respond to' do
    it { is_expected.to respond_to(:author_name) }
    it { is_expected.to respond_to(:author_email) }
  end

  describe 'validations' do
    it { is_expected.to validate_presence_of(:action) }
    it { is_expected.to validate_presence_of(:target_type) }
    it { is_expected.to validate_presence_of(:user) }

    context 'for commits' do
      subject { described_class.new(target_type: 'Commit') }

      it { is_expected.to validate_presence_of(:commit_id) }
      it { is_expected.not_to validate_presence_of(:target_id) }
    end

    context 'for issuables' do
      subject { described_class.new(target: issue) }

      it { is_expected.to validate_presence_of(:target_id) }
      it { is_expected.not_to validate_presence_of(:commit_id) }
    end
  end

  describe '#body' do
    before do
      subject.target = build(:issue, title: 'Bugfix')
    end

    it 'returns target title when note is blank' do
      subject.note = nil

      expect(subject.body).to eq 'Bugfix'
    end

    it 'returns note when note is present' do
      subject.note = build(:note, note: 'quick fix')

      expect(subject.body).to eq 'quick fix'
    end
  end

  describe '#done' do
    it 'changes state to done' do
      todo = create(:todo, state: :pending)
      expect { todo.done }.to change(todo, :state).from('pending').to('done')
    end

    it 'does not raise error when is already done' do
      todo = create(:todo, state: :done)
      expect { todo.done }.not_to raise_error
    end
  end

  describe '#for_commit?' do
    it 'returns true when target is a commit' do
      subject.target_type = 'Commit'
      expect(subject.for_commit?).to eq true
    end

    it 'returns false when target is an issuable' do
      subject.target_type = 'Issue'
      expect(subject.for_commit?).to eq false
    end
  end

  describe '#target' do
    context 'for commits' do
      let(:project) { create(:project, :repository) }
      let(:commit) { project.commit }

      it 'returns an instance of Commit when exists' do
        subject.project = project
        subject.target_type = 'Commit'
        subject.commit_id = commit.id

        expect(subject.target).to be_a(Commit)
        expect(subject.target).to eq commit
      end

      it 'returns nil when does not exists' do
        subject.project = project
        subject.target_type = 'Commit'
        subject.commit_id = 'xxxx'

        expect(subject.target).to be_nil
      end
    end

    it 'returns the issuable for issuables' do
      subject.target_id = issue.id
      subject.target_type = issue.class.name
      expect(subject.target).to eq issue
    end
  end

  describe '#target_reference' do
    it 'returns commit full reference with short id' do
      project = create(:project, :repository)
      commit = project.commit

      subject.project = project
      subject.target_type = 'Commit'
      subject.commit_id = commit.id

      expect(subject.target_reference).to eq commit.reference_link_text(full: true)
    end

    it 'returns full reference for issuables' do
      subject.target = issue
      expect(subject.target_reference).to eq issue.to_reference(full: true)
    end
  end

  describe '#self_added?' do
    let(:user_1) { build(:user) }

    before do
      subject.user = user_1
    end

    it 'is true when the user is the author' do
      subject.author = user_1

      expect(subject).to be_self_added
    end

    it 'is false when the user is not the author' do
      subject.author = build(:user)

      expect(subject).not_to be_self_added
    end
  end

  describe '#self_assigned?' do
    let(:user_1) { build(:user) }

    before do
      subject.user = user_1
      subject.author = user_1
      subject.action = Todo::ASSIGNED
    end

    it 'is true when todo is ASSIGNED and self_added' do
      expect(subject).to be_self_assigned
    end

    it 'is false when the todo is not ASSIGNED' do
      subject.action = Todo::MENTIONED

      expect(subject).not_to be_self_assigned
    end

    it 'is false when todo is not self_added' do
      subject.author = build(:user)

      expect(subject).not_to be_self_assigned
    end
  end
end


text:
Rumbster is a fake smtp server for email testing in Ruby.
Rumbster was developed to as a way to acceptance test email sending applications.

[![Build Status](https://secure.travis-ci.org/aesterline/rumbster.png)](http://travis-ci.org/aesterline/rumbster)

## Requirements

* Ruby 1.8.7 or later (may work with earlier versions)

## Usage

A good source for usage information is the unit tests in the
test directory.   Below is an example of the usage.

```ruby
 class TestEmails < Test::Unit::TestCase
   def setup
     @rumbster = Rumbster.new(port)
     @message_observer = MailMessageObserver.new

     @rumbster.add_observer @message_observer
     @rumbster.add_observer FileMessageObserver.new('some/directory')

     @rumbster.start
   end

   def teardown
     @rumbster.stop
   end

   def test_email_is_sent
     send_email
     assert_equal 1, @message_observer.messages.size
     assert_equal 'junk@junk.com', @message_observer.messages.first.to
   end
 end
```

## Contributing to rumbster

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2011 Adam Esterline. See LICENSE.txt for
further details.


text:
static const char *colorStrings[nColors] = {
	[colorBackground] = colorBackgroundString,
	[colorMessage] = "#000000",
	[colorHighlight] = "#FF0000",
	[colorAction] = "#0000FF",
	[colorServerCommand] = "#91640A",
	[colorChannelCommand] = "#960096",
	[colorYourNick] = "#000001",
	[colorTimestamp] = "#709070",
	[colorHyperlink] = "#0000FF",
	[colorBacklog] = "#AAAAAA",
	[colorBackgroundAlt] = "#EDF4F9",
	[colorTabDefault] = "#000000",		// TODO especially this one
	[colorTabChannelMessage] = "#008000",
	[colorTabQueryMessage] = "#800000",
	[colorTabHighlight] = "#FF0000",
	[colorTabChannelEvent] = "#008000",
	[colorTabApplicationEvent] = "#C3C300",
};

GdkRGBA colors[nColors];

static const char *nickColorStrings[nNickColors] = {
	"#E90E7F",	"#8E55E9",	"#B30E0E",	"#18B33C",
	"#58ADB3",	"#9E54B3",	"#B39875",	"#3176B3",
};

GdkRGBA nickColors[nNickColors];

static const char *formattedColorStrings[nFormattedColors] = {
	"#FFFFFF",	"#000000",	"#000080",	"#008000",
	"#FF0000",	"#A52A2A",	"#800080",	"#FF8000",
	"#808000",	"#00FF00",	"#008080",	"#00FFFF",
	"#0000FF",	"#FFC0CB",	"#A0A0A0",	"#C0C0C0",
};

GdkRGBA formattedColors[nFormattedColors];

void initColors(void)
{
	int i;
	GdkRGBA rgba;
	GError *err = NULL;

	for (i = 0; i < nColors; i++) {
		// TODO verify that missing values are NULL and then check for them
		// TODO standardize "(no reason specified)" error text
		if (gdk_rgba_parse(&rgba, colorStrings[i]) == FALSE)
			g_error("error parsing color %d (no reason specified)", i);
		colors[i] = rgba;
	}
	for (i = 0; i < nNickColors; i++) {
		if (gdk_rgba_parse(&rgba, nickColorStrings[i]) == FALSE)
			g_error("error parsing nick color %d (no reason specified)", i);
		nickColors[i] = rgba;
	}
	for (i = 0; i < nFormattedColors; i++) {
		if (gdk_rgba_parse(&rgba, formattedColorStrings[i]) == FALSE)
			g_error("error parsing formatted color %d (no reason specified)", i);
		formattedColors[i] = rgba;
	}
}

static const char *chatBackgroundCSS =
	"GtkTextView {\n"
	"	background-color: " colorBackgroundString ";\n"
	"}\n";

void applyChatBackgroundColor(GtkWidget *chat)
{
	GtkStyleContext *context;
	GtkCssProvider *provider;
	GError *err = NULL;

	context = gtk_widget_get_style_context(chat);
	provider = gtk_css_provider_new();
	if (gtk_css_provider_load_from_data(provider, chatBackgroundCSS, -1, &err) == FALSE)
		g_error("error loading chat area background CSS: %s", err->message);
	gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER);
}


text:
package bitbucket

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/drone/drone/model"
	"github.com/drone/drone/remote"
	"github.com/drone/drone/remote/bitbucket/internal"
	"github.com/drone/drone/shared/httputil"

	"golang.org/x/oauth2"
)

// Bitbucket cloud endpoints.
const (
	DefaultAPI = "https://api.bitbucket.org"
	DefaultURL = "https://bitbucket.org"
)

type config struct {
	API    string
	URL    string
	Client string
	Secret string
}

// New returns a new remote Configuration for integrating with the Bitbucket
// repository hosting service at https://bitbucket.org
func New(client, secret string) remote.Remote {
	return &config{
		API:    DefaultAPI,
		URL:    DefaultURL,
		Client: client,
		Secret: secret,
	}
}

// Login authenticates an account with Bitbucket using the oauth2 protocol. The
// Bitbucket account details are returned when the user is successfully authenticated.
func (c *config) Login(w http.ResponseWriter, r *http.Request) (*model.User, error) {
	redirect := httputil.GetURL(r)
	config := c.newConfig(redirect)

	code := r.FormValue("code")
	if len(code) == 0 {
		http.Redirect(w, r, config.AuthCodeURL("drone"), http.StatusSeeOther)
		return nil, nil
	}

	token, err := config.Exchange(oauth2.NoContext, code)
	if err != nil {
		return nil, err
	}

	client := internal.NewClient(c.API, config.Client(oauth2.NoContext, token))
	curr, err := client.FindCurrent()
	if err != nil {
		return nil, err
	}
	return convertUser(curr, token), nil
}

// Auth uses the Bitbucket oauth2 access token and refresh token to authenticate
// a session and return the Bitbucket account login.
func (c *config) Auth(token, secret string) (string, error) {
	client := c.newClientToken(token, secret)
	user, err := client.FindCurrent()
	if err != nil {
		return "", err
	}
	return user.Login, nil
}

// Refresh refreshes the Bitbucket oauth2 access token. If the token is
// refreshed the user is updated and a true value is returned.
func (c *config) Refresh(user *model.User) (bool, error) {
	config := c.newConfig("")
	source := config.TokenSource(
		oauth2.NoContext, &oauth2.Token{RefreshToken: user.Secret})

	token, err := source.Token()
	if err != nil || len(token.AccessToken) == 0 {
		return false, err
	}

	user.Token = token.AccessToken
	user.Secret = token.RefreshToken
	user.Expiry = token.Expiry.UTC().Unix()
	return true, nil
}

// Teams returns a list of all team membership for the Bitbucket account.
func (c *config) Teams(u *model.User) ([]*model.Team, error) {
	opts := &internal.ListTeamOpts{
		PageLen: 100,
		Role:    "member",
	}
	resp, err := c.newClient(u).ListTeams(opts)
	if err != nil {
		return nil, err
	}
	return convertTeamList(resp.Values), nil
}

// TeamPerm is not supported by the Bitbucket driver.
func (c *config) TeamPerm(u *model.User, org string) (*model.Perm, error) {
	return nil, nil
}

// Repo returns the named Bitbucket repository.
func (c *config) Repo(u *model.User, owner, name string) (*model.Repo, error) {
	repo, err := c.newClient(u).FindRepo(owner, name)
	if err != nil {
		return nil, err
	}
	return convertRepo(repo), nil
}

// Repos returns a list of all repositories for Bitbucket account, including
// organization repositories.
func (c *config) Repos(u *model.User) ([]*model.RepoLite, error) {
	client := c.newClient(u)

	var all []*model.RepoLite

	accounts := []string{u.Login}
	resp, err := client.ListTeams(&internal.ListTeamOpts{
		PageLen: 100,
		Role:    "member",
	})
	if err != nil {
		return all, err
	}
	for _, team := range resp.Values {
		accounts = append(accounts, team.Login)
	}

	for _, account := range accounts {
		repos, err := client.ListReposAll(account)
		if err != nil {
			return all, err
		}
		for _, repo := range repos {
			all = append(all, convertRepoLite(repo))
		}
	}
	return all, nil
}

// Perm returns the user permissions for the named repository. Because Bitbucket
// does not have an endpoint to access user permissions, we attempt to fetch
// the repository hook list, which is restricted to administrators to calculate
// administrative access to a repository.
func (c *config) Perm(u *model.User, owner, name string) (*model.Perm, error) {
	client := c.newClient(u)

	perms := new(model.Perm)
	_, err := client.FindRepo(owner, name)
	if err != nil {
		return perms, err
	}

	_, err = client.ListHooks(owner, name, &internal.ListOpts{})
	if err == nil {
		perms.Push = true
		perms.Admin = true
	}
	perms.Pull = true
	return perms, nil
}

// File fetches the file from the Bitbucket repository and returns its contents.
func (c *config) File(u *model.User, r *model.Repo, b *model.Build, f string) ([]byte, error) {
	config, err := c.newClient(u).FindSource(r.Owner, r.Name, b.Commit, f)
	if err != nil {
		return nil, err
	}
	return []byte(config.Data), err
}

// Status creates a build status for the Bitbucket commit.
func (c *config) Status(u *model.User, r *model.Repo, b *model.Build, link string) error {
	status := internal.BuildStatus{
		State: convertStatus(b.Status),
		Desc:  convertDesc(b.Status),
		Key:   "Drone",
		Url:   link,
	}
	return c.newClient(u).CreateStatus(r.Owner, r.Name, b.Commit, &status)
}

// Activate activates the repository by registering repository push hooks with
// the Bitbucket repository. Prior to registering hook, previously created hooks
// are deleted.
func (c *config) Activate(u *model.User, r *model.Repo, link string) error {
	rawurl, err := url.Parse(link)
	if err != nil {
		return err
	}
	c.Deactivate(u, r, link)

	return c.newClient(u).CreateHook(r.Owner, r.Name, &internal.Hook{
		Active: true,
		Desc:   rawurl.Host,
		Events: []string{"repo:push"},
		Url:    link,
	})
}

// Deactivate deactives the repository be removing repository push hooks from
// the Bitbucket repository.
func (c *config) Deactivate(u *model.User, r *model.Repo, link string) error {
	client := c.newClient(u)

	hooks, err := client.ListHooks(r.Owner, r.Name, &internal.ListOpts{})
	if err != nil {
		return err
	}
	hook := matchingHooks(hooks.Values, link)
	if hook != nil {
		return client.DeleteHook(r.Owner, r.Name, hook.Uuid)
	}
	return nil
}

// Netrc returns a netrc file capable of authenticating Bitbucket requests and
// cloning Bitbucket repositories.
func (c *config) Netrc(u *model.User, r *model.Repo) (*model.Netrc, error) {
	return &model.Netrc{
		Machine:  "bitbucket.org",
		Login:    "x-token-auth",
		Password: u.Token,
	}, nil
}

// Hook parses the incoming Bitbucket hook and returns the Repository and
// Build details. If the hook is unsupported nil values are returned.
func (c *config) Hook(r *http.Request) (*model.Repo, *model.Build, error) {
	return parseHook(r)
}

// helper function to return the bitbucket oauth2 client
func (c *config) newClient(u *model.User) *internal.Client {
	return c.newClientToken(u.Token, u.Secret)
}

// helper function to return the bitbucket oauth2 client
func (c *config) newClientToken(token, secret string) *internal.Client {
	return internal.NewClientToken(
		c.API,
		c.Client,
		c.Secret,
		&oauth2.Token{
			AccessToken:  token,
			RefreshToken: secret,
		},
	)
}

// helper function to return the bitbucket oauth2 config
func (c *config) newConfig(redirect string) *oauth2.Config {
	return &oauth2.Config{
		ClientID:     c.Client,
		ClientSecret: c.Secret,
		Endpoint: oauth2.Endpoint{
			AuthURL:  fmt.Sprintf("%s/site/oauth2/authorize", c.URL),
			TokenURL: fmt.Sprintf("%s/site/oauth2/access_token", c.URL),
		},
		RedirectURL: fmt.Sprintf("%s/authorize", redirect),
	}
}

// helper function to return matching hooks.
func matchingHooks(hooks []*internal.Hook, rawurl string) *internal.Hook {
	link, err := url.Parse(rawurl)
	if err != nil {
		return nil
	}
	for _, hook := range hooks {
		hookurl, err := url.Parse(hook.Url)
		if err == nil && hookurl.Host == link.Host {
			return hook
		}
	}
	return nil
}


text:
var winston = require('winston');

function Mediator(logger) {

	this.logger = logger;
	this.layers;

	this.launch = function() {
		this.layers.data.init();
		this.layers.internet.init();
		this.layers.domain.init();
	}

	this.validateSecret = function(siteKey, siteSecret) {
		// Always validated straight in data layer
		return this.layers.data.validateSecret(siteKey, siteSecret);
	}

	this.registerLayers = function(layers) {
		this.layers = layers;
	}

	this.sendMsgToUserName = function(msgObj, toUserName) {
		this.logInfo('Msg to: ' + toUserName + " | Contents: " + JSON.stringify(msgObj));
		this.layers.internet.msgToSocket(msgObj, toUserName);

	}

	this.msgFromSocket = function(fromUserName, toSite, isEntrepreneur, msgObj) {
		this.logInfo('Msg from: ' + fromUserName + " | Contents: " + JSON.stringify(msgObj));
		msgObj.from = fromUserName;
		return this.layers.domain.gateway({tag: 'msgFromUser', siteKey: toSite, from: fromUserName, isEntrepreneur: isEntrepreneur, msgObj: msgObj});

	}

	// Logging facade
	this.logInfo = function(msg) {
		this.logger.log('info', msg);
	}

	this.logWarning = function(msg) {
		this.logger.log('warn', msg);
	}

	this.logError = function(msg, isFatal) {
		this.logger.log('error', msg);
		if (isFatal) {
			// We are fucked.
			this.prepareForControlledShutDown();
		}
	}

	this.prepareForControlledShutDown = function() {
		// Do something
		// Must be everything in sync because we throw soon
		// But then again, at this point doing in sync makes no difference anyway
		// as we are going down.
	}

	this.needSiteKeysFromDisk = function() {
		return this.layers.data.needSiteKeysFromDisk();

	}

	this.needRoutingDataFromDisk = function() {

	}

	this.userJoined = function(userID, siteKey, isEntrepreneur) {
		return this.layers.domain.gateway({tag: 'userJoined', from: userID, siteKey: siteKey, isEntrepreneur: isEntrepreneur});

	}
	this.userDisconnected = function(userID, siteKey, isEntrepreneur) {
		return this.layers.domain.gateway({tag: 'userLeft', from: userID, siteKey: siteKey, isEntrepreneur: isEntrepreneur});
	}

}

module.exports = function(logger, testMode) {
	logger = logger || winston;
	var mediator = new Mediator(logger);

	if (testMode) {
		// Monkey patch like hell some suitable methods
		mediator.needSiteKeysFromDisk = needSiteKeysFromDiskFake;
		mediator.needRoutingDataFromDisk = needRoutingDataFromDiskFake;

	}

	return mediator;
}

function needSiteKeysFromDiskFake() {
	return ['aaa1', 'bbb2', 'ccc3', 'ddd4'];
}
function needRoutingDataFromDiskFake() {
	return [];

}


text:
<?php

declare(strict_types=1);

namespace Sabre\DAV\Locks;

use Sabre\DAV;
use Sabre\HTTP;

require_once 'Sabre/HTTP/ResponseMock.php';
require_once 'Sabre/TestUtil.php';

class MSWordTest extends \PHPUnit\Framework\TestCase
{
    public function tearDown()
    {
        \Sabre\TestUtil::clearTempDir();
    }

    public function testLockEtc()
    {
        mkdir(SABRE_TEMPDIR.'/mstest');
        $tree = new DAV\FS\Directory(SABRE_TEMPDIR.'/mstest');

        $server = new DAV\Server($tree);
        $server->debugExceptions = true;
        $locksBackend = new Backend\File(SABRE_TEMPDIR.'/locksdb');
        $locksPlugin = new Plugin($locksBackend);
        $server->addPlugin($locksPlugin);

        $response1 = new HTTP\ResponseMock();

        $server->httpRequest = $this->getLockRequest();
        $server->httpResponse = $response1;
        $server->sapi = new HTTP\SapiMock();
        $server->exec();

        $this->assertEquals(201, $server->httpResponse->getStatus(), 'Full response body:'.$response1->getBodyAsString());
        $this->assertTrue((bool) $server->httpResponse->getHeaders('Lock-Token'));
        $lockToken = $server->httpResponse->getHeader('Lock-Token');

        //sleep(10);

        $response2 = new HTTP\ResponseMock();

        $server->httpRequest = $this->getLockRequest2();
        $server->httpResponse = $response2;
        $server->exec();

        $this->assertEquals(201, $server->httpResponse->status);
        $this->assertTrue((bool) $server->httpResponse->getHeaders('Lock-Token'));

        //sleep(10);

        $response3 = new HTTP\ResponseMock();
        $server->httpRequest = $this->getPutRequest($lockToken);
        $server->httpResponse = $response3;
        $server->exec();

        $this->assertEquals(204, $server->httpResponse->status);
    }

    public function getLockRequest()
    {
        $request = HTTP\Sapi::createFromServerArray([
           'REQUEST_METHOD' => 'LOCK',
           'HTTP_CONTENT_TYPE' => 'application/xml',
           'HTTP_TIMEOUT' => 'Second-3600',
           'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx',
        ]);

        $request->setBody('<D:lockinfo xmlns:D="DAV:">
    <D:lockscope>
        <D:exclusive />
    </D:lockscope>
    <D:locktype>
        <D:write />
    </D:locktype>
    <D:owner>
        <D:href>PC-Vista\User</D:href>
    </D:owner>
</D:lockinfo>');

        return $request;
    }

    public function getLockRequest2()
    {
        $request = HTTP\Sapi::createFromServerArray([
           'REQUEST_METHOD' => 'LOCK',
           'HTTP_CONTENT_TYPE' => 'application/xml',
           'HTTP_TIMEOUT' => 'Second-3600',
           'REQUEST_URI' => '/~$Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx',
        ]);

        $request->setBody('<D:lockinfo xmlns:D="DAV:">
    <D:lockscope>
        <D:exclusive />
    </D:lockscope>
    <D:locktype>
        <D:write />
    </D:locktype>
    <D:owner>
        <D:href>PC-Vista\User</D:href>
    </D:owner>
</D:lockinfo>');

        return $request;
    }

    public function getPutRequest($lockToken)
    {
        $request = HTTP\Sapi::createFromServerArray([
           'REQUEST_METHOD' => 'PUT',
           'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx',
           'HTTP_IF' => 'If: ('.$lockToken.')',
        ]);
        $request->setBody('FAKE BODY');

        return $request;
    }
}


text:
$(document).ready(function() {
    make_active($("#id_employee_profile_account_menu"));
});


text:
// CLASS HEADER
#include <dali/public-api/object/object-registry.h>

// INTERNAL INCLUDES
#include <dali/internal/event/common/object-registry-impl.h>

namespace Dali
{

ObjectRegistry::ObjectRegistry()
{
}

ObjectRegistry::~ObjectRegistry()
{
}

ObjectRegistry::ObjectRegistry(const ObjectRegistry& copy)
: BaseHandle(copy)
{
}

ObjectRegistry& ObjectRegistry::operator=(const ObjectRegistry& rhs)
{
  BaseHandle::operator=(rhs);
  return *this;
}

ObjectRegistry::ObjectCreatedSignalType& ObjectRegistry::ObjectCreatedSignal()
{
  return GetImplementation(*this).ObjectCreatedSignal();
}

ObjectRegistry::ObjectDestroyedSignalType& ObjectRegistry::ObjectDestroyedSignal()
{
  return GetImplementation(*this).ObjectDestroyedSignal();
}

ObjectRegistry::ObjectRegistry(Internal::ObjectRegistry* internal)
: BaseHandle(internal)
{
}

} // namespace Dali


text:
package com.intellij.codeInspection.dataFlow;

import com.intellij.codeInsight.NullableNotNullManager;
import com.intellij.codeInspection.dataFlow.instructions.Instruction;
import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction;
import com.intellij.codeInspection.dataFlow.instructions.ReturnInstruction;
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

public class DfaPsiUtil {

  public static boolean isFinalField(PsiVariable var) {
    return var.hasModifierProperty(PsiModifier.FINAL) && !var.hasModifierProperty(PsiModifier.TRANSIENT) && var instanceof PsiField;
  }

  static PsiElement getEnclosingCodeBlock(final PsiVariable variable, final PsiElement context) {
    PsiElement codeBlock;
    if (variable instanceof PsiParameter) {
      codeBlock = ((PsiParameter)variable).getDeclarationScope();
      if (codeBlock instanceof PsiMethod) {
        codeBlock = ((PsiMethod)codeBlock).getBody();
      }
    }
    else if (variable instanceof PsiLocalVariable) {
      codeBlock = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class);
    }
    else {
      codeBlock = getTopmostBlockInSameClass(context);
    }
    while (codeBlock != null) {
      PsiAnonymousClass anon = PsiTreeUtil.getParentOfType(codeBlock, PsiAnonymousClass.class);
      if (anon == null) break;
      codeBlock = PsiTreeUtil.getParentOfType(anon, PsiCodeBlock.class);
    }
    return codeBlock;
  }

  @NotNull
  public static Nullness getElementNullability(@Nullable PsiType resultType, @Nullable PsiModifierListOwner owner) {
    if (owner == null) {
      return Nullness.UNKNOWN;
    }

    if (owner instanceof PsiEnumConstant) {
      return Nullness.NOT_NULL;
    }

    if (resultType != null) {
      NullableNotNullManager nnn = NullableNotNullManager.getInstance(owner.getProject());
      for (PsiAnnotation annotation : resultType.getAnnotations()) {
        if (!annotation.isValid()) {
          PsiUtilCore.ensureValid(owner);
          PsiUtil.ensureValidType(resultType, owner + " of " + owner.getClass());
          PsiUtilCore.ensureValid(annotation); //should fail
        }
        String qualifiedName = annotation.getQualifiedName();
        if (nnn.getNullables().contains(qualifiedName)) {
          return Nullness.NULLABLE;
        }
        if (nnn.getNotNulls().contains(qualifiedName)) {
          return Nullness.NOT_NULL;
        }
      }
    }

    if (NullableNotNullManager.isNullable(owner)) {
      return Nullness.NULLABLE;
    }
    if (NullableNotNullManager.isNotNull(owner)) {
      return Nullness.NOT_NULL;
    }

    return Nullness.UNKNOWN;
  }

  public static boolean isInitializedNotNull(PsiField field) {
    PsiClass containingClass = field.getContainingClass();
    if (containingClass == null) return false;

    PsiMethod[] constructors = containingClass.getConstructors();
    if (constructors.length == 0) return false;

    for (PsiMethod method : constructors) {
      if (!getNotNullInitializedFields(method, containingClass).contains(field)) {
        return false;
      }
    }
    return true;
  }

  private static Set<PsiField> getNotNullInitializedFields(final PsiMethod constructor, final PsiClass containingClass) {
    if (!constructor.getLanguage().isKindOf(JavaLanguage.INSTANCE)) return Collections.emptySet();

    final PsiCodeBlock body = constructor.getBody();
    if (body == null) return Collections.emptySet();

    return CachedValuesManager.getCachedValue(constructor, new CachedValueProvider<Set<PsiField>>() {
      @Nullable
      @Override
      public Result<Set<PsiField>> compute() {
        final PsiCodeBlock body = constructor.getBody();
        final Map<PsiField, Boolean> map = ContainerUtil.newHashMap();
        final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner(false, false) {

          private boolean isCallExposingNonInitializedFields(Instruction instruction) {
            if (!(instruction instanceof MethodCallInstruction) ||
                ((MethodCallInstruction)instruction).getMethodType() != MethodCallInstruction.MethodType.REGULAR_METHOD_CALL) {
              return false;
            }

            PsiCallExpression call = ((MethodCallInstruction)instruction).getCallExpression();
            if (call == null) return false;

            if (call instanceof PsiMethodCallExpression &&
                DfaValueFactory.isEffectivelyUnqualified(((PsiMethodCallExpression)call).getMethodExpression())) {
              return true;
            }

            PsiExpressionList argumentList = call.getArgumentList();
            if (argumentList != null) {
              for (PsiExpression expression : argumentList.getExpressions()) {
                if (expression instanceof PsiThisExpression) return true;
              }
            }

            return false;
          }

          @Override
          protected DfaInstructionState[] acceptInstruction(InstructionVisitor visitor, DfaInstructionState instructionState) {
            Instruction instruction = instructionState.getInstruction();
            if (isCallExposingNonInitializedFields(instruction) ||
                instruction instanceof ReturnInstruction && !((ReturnInstruction)instruction).isViaException()) {
              for (PsiField field : containingClass.getFields()) {
                if (!instructionState.getMemoryState().isNotNull(getFactory().getVarFactory().createVariableValue(field, false))) {
                  map.put(field, false);
                } else if (!map.containsKey(field)) {
                  map.put(field, true);
                }
              }
              return DfaInstructionState.EMPTY_ARRAY;
            }
            return super.acceptInstruction(visitor, instructionState);
          }
        };
        final RunnerResult rc = dfaRunner.analyzeMethod(body, new StandardInstructionVisitor());
        Set<PsiField> notNullFields = ContainerUtil.newHashSet();
        if (rc == RunnerResult.OK) {
          for (PsiField field : map.keySet()) {
            if (map.get(field)) {
              notNullFields.add(field);
            }
          }
        }
        return Result.create(notNullFields, constructor, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
      }
    });
  }

  public static List<PsiExpression> findAllConstructorInitializers(PsiField field) {
    final List<PsiExpression> result = ContainerUtil.createLockFreeCopyOnWriteList();
    ContainerUtil.addIfNotNull(result, field.getInitializer());

    final PsiClass containingClass = field.getContainingClass();
    if (containingClass != null && !(containingClass instanceof PsiCompiledElement)) {
      result.addAll(getAllConstructorFieldInitializers(containingClass).get(field));
    }
    return result;
  }

  private static MultiMap<PsiField, PsiExpression> getAllConstructorFieldInitializers(final PsiClass psiClass) {
    if (psiClass instanceof PsiCompiledElement) {
      //noinspection unchecked
      return MultiMap.EMPTY;
    }

    return CachedValuesManager.getCachedValue(psiClass, new CachedValueProvider<MultiMap<PsiField, PsiExpression>>() {
      @Nullable
      @Override
      public Result<MultiMap<PsiField, PsiExpression>> compute() {
        final Set<String> fieldNames = ContainerUtil.newHashSet();
        for (PsiField field : psiClass.getFields()) {
          ContainerUtil.addIfNotNull(fieldNames, field.getName());
        }

        final MultiMap<PsiField, PsiExpression> result = new MultiMap<PsiField, PsiExpression>();
        JavaRecursiveElementWalkingVisitor visitor = new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitAssignmentExpression(PsiAssignmentExpression assignment) {
            super.visitAssignmentExpression(assignment);
            PsiExpression lExpression = assignment.getLExpression();
            PsiExpression rExpression = assignment.getRExpression();
            if (rExpression != null &&
                lExpression instanceof PsiReferenceExpression &&
                fieldNames.contains(((PsiReferenceExpression)lExpression).getReferenceName())) {
              PsiElement target = ((PsiReferenceExpression)lExpression).resolve();
              if (target instanceof PsiField && ((PsiField)target).getContainingClass() == psiClass) {
                result.putValue((PsiField)target, rExpression);
              }
            }
          }
        };

        for (PsiMethod constructor : psiClass.getConstructors()) {
          if (constructor.getLanguage().isKindOf(JavaLanguage.INSTANCE)) {
            constructor.accept(visitor);
          }
        }

        return Result.create(result, psiClass);
      }
    });
  }

  @Nullable
  public static PsiCodeBlock getTopmostBlockInSameClass(@NotNull PsiElement position) {
    PsiCodeBlock block = PsiTreeUtil.getParentOfType(position, PsiCodeBlock.class, false, PsiMember.class, PsiFile.class);
    if (block == null) {
      return null;
    }

    PsiCodeBlock lastBlock = block;
    while (true) {
      block = PsiTreeUtil.getParentOfType(block, PsiCodeBlock.class, true, PsiMember.class, PsiFile.class);
      if (block == null) {
        return lastBlock;
      }
      lastBlock = block;
    }
  }

  @NotNull
  public static Collection<PsiExpression> getVariableAssignmentsInFile(@NotNull PsiVariable psiVariable,
                                                                       final boolean literalsOnly,
                                                                       final PsiElement place) {
    final Ref<Boolean> modificationRef = Ref.create(Boolean.FALSE);
    final PsiCodeBlock codeBlock = place == null? null : getTopmostBlockInSameClass(place);
    final int placeOffset = codeBlock != null? place.getTextRange().getStartOffset() : 0;
    List<PsiExpression> list = ContainerUtil.mapNotNull(
      ReferencesSearch.search(psiVariable, new LocalSearchScope(new PsiElement[] {psiVariable.getContainingFile()}, null, true)).findAll(),
      new NullableFunction<PsiReference, PsiExpression>() {
        @Override
        public PsiExpression fun(final PsiReference psiReference) {
          if (modificationRef.get()) return null;
          final PsiElement parent = psiReference.getElement().getParent();
          if (parent instanceof PsiAssignmentExpression) {
            final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent;
            final IElementType operation = assignmentExpression.getOperationTokenType();
            if (assignmentExpression.getLExpression() == psiReference) {
              if (JavaTokenType.EQ.equals(operation)) {
                final PsiExpression rValue = assignmentExpression.getRExpression();
                if (!literalsOnly || allOperandsAreLiterals(rValue)) {
                  // if there's a codeBlock omit the values assigned later
                  if (codeBlock != null && PsiTreeUtil.isAncestor(codeBlock, parent, true)
                      && placeOffset < parent.getTextRange().getStartOffset()) {
                    return null;
                  }
                  return rValue;
                }
                else {
                  modificationRef.set(Boolean.TRUE);
                }
              }
              else if (JavaTokenType.PLUSEQ.equals(operation)) {
                modificationRef.set(Boolean.TRUE);
              }
            }
          }
          return null;
        }
      });
    if (modificationRef.get()) return Collections.emptyList();
    PsiExpression initializer = psiVariable.getInitializer();
    if (initializer != null && (!literalsOnly || allOperandsAreLiterals(initializer))) {
      list = ContainerUtil.concat(list, Collections.singletonList(initializer));
    }
    return list;
  }

  public static boolean allOperandsAreLiterals(@Nullable final PsiExpression expression) {
    if (expression == null) return false;
    if (expression instanceof PsiLiteralExpression) return true;
    if (expression instanceof PsiPolyadicExpression) {
      Stack<PsiExpression> stack = new Stack<PsiExpression>();
      stack.add(expression);
      while (!stack.isEmpty()) {
        PsiExpression psiExpression = stack.pop();
        if (psiExpression instanceof PsiPolyadicExpression) {
          PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)psiExpression;
          for (PsiExpression op : binaryExpression.getOperands()) {
            stack.push(op);
          }
        }
        else if (!(psiExpression instanceof PsiLiteralExpression)) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
}