text:
require 'spec_helper'
require 'stringio'

describe NyanCatFormatter do

  before do
    rspec_bin = $0.split('/').last
    @output = StringIO.new
    if rspec_bin == 'rspec'
      @formatter = NyanCatFormatter.new(@output)
      @example = RSpec::Core::ExampleGroup.describe.example
    else
      formatter_options = OpenStruct.new(:colour => true, :dry_run => false, :autospec => nil)
      @formatter = NyanCatFormatter.new(formatter_options, @output)
      @example = Spec::Example::ExampleProxy.new("should pass")
      @formatter.instance_variable_set(:@example_group, OpenStruct.new(:description => "group"))
    end
    @formatter.start(2)
    sleep(0.1)  # Just to slow it down a little :-)
  end

  describe 'passed, pending and failed' do

    before do
      @formatter.stub!(:tick)
    end

    describe 'example_passed' do

      it 'should call the increment method' do
        @formatter.should_receive :tick
        @formatter.example_passed(@example)
      end

      it 'should relax Nyan Cat' do
        @formatter.example_passed(@example)
        @formatter.nyan_cat.should == [
          '_,------,   ',
          '_|  /\_/\ ',
          '~|_( ^ .^)  ',
          ' ""  "" '
        ].join("\n")
      end

      it 'should update the scoreboard' do
        @formatter.scoreboard.size.should == 4
      end

    end

    describe 'example_pending' do

      it 'should call the tick method' do
        @formatter.should_receive :tick
        @formatter.example_pending(@example)
      end

      it 'should increment the pending count' do
        lambda { @formatter.example_pending(@example)}.
          should change(@formatter, :pending_count).by(1)
      end

      it 'should alert Nyan Cat' do
        @formatter.example_pending(@example)
        @formatter.nyan_cat.should == [
          '_,------,   ',
          '_|  /\_/\ ',
          '~|_( o .o)  ',
          ' ""  "" '
        ].join("\n")
      end

    end

    describe 'example_failed' do

      it 'should call the increment method' do
        @formatter.should_receive :tick
        @formatter.example_failed(@example)
      end

      it 'should increment the failure count' do
        lambda { @formatter.example_failed(@example)}.
          should change(@formatter, :failure_count).by(1)
      end

      it 'should alert Nyan Cat' do
        @formatter.example_failed(@example)
        @formatter.nyan_cat.should == [
          '_,------,   ',
          '_|  /\_/\ ',
          '~|_( o .o)  ',
          ' ""  "" '
        ].join("\n")
      end

      it 'should kill nyan if the specs are finished' do
        @formatter.example_failed(@example)
        @formatter.stub(:finished?).and_return(true)
        @formatter.nyan_cat.should == [
          '_,------,   ',
          '_|  /\_/\ ',
          '~|_( x .x)  ',
          ' ""  "" '
        ].join("\n")
      end

    end
  end

  describe 'tick' do

    before do
      @formatter.stub!(:current).and_return(1)
      @formatter.stub!(:example_count).and_return(2)
      @formatter.tick
    end

    it 'should increment the current' do
      @formatter.current.should == 1
    end

    it 'should store the marks in an array' do
      @formatter.example_results.should include('=')
    end

  end

  describe 'rainbowify' do

    it 'should increment the color index count' do
      lambda { @formatter.rainbowify('=') }.should change(@formatter, :color_index).by(1)
    end

  end

  describe 'highlight' do

    it 'should rainbowify passing examples' do
      @formatter.highlight('=').should == "\e[38;5;154m-\e[0m"
    end

    it 'should mark failing examples as red' do
      @formatter.highlight('*').should == "\e[31m*\e[0m"
    end

    it 'should mark pending examples as yellow' do
      @formatter.highlight('!').should == "\e[33m!\e[0m"
    end

  end

  describe 'start' do

    it 'should set the total amount of specs' do
      @formatter.example_count.should == 2
    end

    it 'should set the current to 0' do
      @formatter.current.should == 0
    end

  end

  describe "#format_duration" do
    it "should return just seconds for sub 60 seconds" do
      @formatter.format_duration(5.3).should eq("5.3 seconds")
    end

    it "should remove that extra zero if it is not needed" do
      @formatter.format_duration(1.0).should eq("1 second")
    end

    it "should plurlaize seconds" do
      @formatter.format_duration(1.1).should eq("1.1 seconds")
    end

    it "add a minute if it is just over 60 seconds" do
      @formatter.format_duration(63.2543456456).should eq("1 minute and 3.25 seconds")
    end

    it "should pluralize minutes" do
      @formatter.format_duration(987.34).should eq("16 minutes and 27.34 seconds")
    end
  end

  describe "example width" do
    [15, 36, 60].each do |n|
      context "for #{n} examples" do
        before { @formatter.start(n) }

        [0.25, 0.5, 0.75].each do |p|
          i = (n * p).to_i
          before { i.times { @formatter.tick } }

          context "when in example #{i}" do
            it "should return 1 as the example width" do
              @formatter.example_width.should == 1
            end
          end
        end
      end
    end
  end
end


text:
<div class="scene-ripples-wrapper" #wrapper
  matRipple
  [matRippleDisabled]="true">
</div>
<button mat-raised-button color="primary" id="scene-ripples-button" #button
        matRipple
        [matRippleDisabled]="true">RIPPLES</button>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0f0f0">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/app_bar"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/app_bar"
        android:paddingTop="10dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/rl"
            android:background="#f0f0f0">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:minHeight="150dp"
                android:contentDescription="@null"
                android:src="@drawable/icon"
                android:id="@+id/imageView_add_student"
                android:layout_marginBottom="20dp" />

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view0"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="10dp"
                android:layout_below="@+id/imageView_add_student"
                card_view:cardCornerRadius="2dp"
                card_view:cardElevation="1dp"
                card_view:cardUseCompatPadding="true"
                card_view:contentPadding="10dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_name"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <EditText
                            android:id="@+id/edit_name"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Name"
                            android:maxLines="1"
                            android:singleLine="true"/>
                        <requestFocus></requestFocus>
                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_surname"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/input_name">
                        <EditText
                            android:id="@+id/edit_surname"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Surname"
                            android:maxLines="1"
                            android:singleLine="true"/>
                    </android.support.design.widget.TextInputLayout>
                </RelativeLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_marginLeft="5dp"
                android:layout_below="@+id/card_view0"
                card_view:cardCornerRadius="2dp"
                card_view:cardElevation="1dp"
                card_view:cardUseCompatPadding="true"
                card_view:contentPadding="10dp">
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_email"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <EditText
                            android:id="@+id/edit_email"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="E-mail"
                            android:maxLines="1"
                            android:singleLine="true"
                            android:inputType="textEmailAddress" />
                    </android.support.design.widget.TextInputLayout>
                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_phone"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/input_email">
                        <EditText
                            android:id="@+id/edit_phone"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Mobile"
                            android:maxLines="1"
                            android:singleLine="true"
                            android:inputType="phone" />
                    </android.support.design.widget.TextInputLayout>
                </RelativeLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginBottom="10dp"
                android:layout_below="@+id/card_view1"
                card_view:cardCornerRadius="2dp"
                card_view:cardElevation="1dp"
                card_view:cardUseCompatPadding="true"
                card_view:contentPadding="10dp">
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_speciality"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">
                        <EditText
                            android:id="@+id/edit_speciality"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Speciality"
                            android:maxLines="1"
                            android:singleLine="true"/>
                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:id="@+id/input_place"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/input_speciality">
                        <EditText
                            android:id="@+id/edit_place"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Place of study"
                            android:maxLines="1"
                            android:singleLine="true"/>
                    </android.support.design.widget.TextInputLayout>

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_below="@id/input_place"
                        android:layout_marginTop="5dp">
                        <TextView
                            android:id="@+id/set_location"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:text="@string/location"
                            android:layout_centerHorizontal="true"
                            android:drawableLeft="@drawable/ic_place_black_24dp"
                            android:textSize="20sp" />
                    </RelativeLayout>

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_below="@id/input_place">
                        <ImageView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:scaleType="centerCrop"
                            android:id="@+id/static_map"
                            android:adjustViewBounds="true" />
                    </RelativeLayout>

                </RelativeLayout>
            </android.support.v7.widget.CardView>
        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/layout_progress"
        android:background="#78ffffff">

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </FrameLayout>

</RelativeLayout>


text:
package process;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import ij.IJ;
import io.AffineImglib2IO;
import net.imglib2.exception.ImgLibException;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.img.imageplus.FloatImagePlus;
import net.imglib2.img.imageplus.ImagePlusImgs;
import net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.realtransform.RealViews;
import net.imglib2.realtransform.ants.ANTSLoadAffine;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Intervals;
import net.imglib2.view.RandomAccessibleOnRealRandomAccessible;
import net.imglib2.view.Views;
import transforms.AffineHelper;
import util.RenderUtil;

public class RenderAffineSequence
{

	public static void main( String[] args ) throws IOException, ImgLibException
	{
		final String outF = args[ 0 ];
		final String inF = args[ 1 ];

		String[] xfmFileList = new String[ args.length - 2 ];
		int j = 0;
		for( int i = 2; i < args.length; i++ )
			xfmFileList[ j++ ] = args[ i ];

		ArrayList< AffineTransform3D > xfmList = loadAffines( xfmFileList );
		AffineTransform3D totalXfm = new AffineTransform3D();
		AffineTransform3D totalXfmInv = new AffineTransform3D();
		for( AffineTransform3D xfm : xfmList )
		{
			totalXfm.concatenate( xfm );
			totalXfmInv.preConcatenate( xfm.inverse());
		}

		Img< FloatType > baseImg = ImageJFunctions.wrap( IJ.openImage( inF ));
		FloatImagePlus< FloatType > result = ImagePlusImgs.floats(
				Intervals.dimensionsAsLongArray( baseImg ) );

		RandomAccessibleOnRealRandomAccessible< FloatType > imgXfm =
			Views.raster(
				RealViews.affine(
						Views.interpolate( Views.extendZero( baseImg ), new NLinearInterpolatorFactory<FloatType>() ),
						totalXfmInv ));

		RenderUtil.copyToImageStack( imgXfm, result, 8 );

		System.out.println( "writing" );
		IJ.save( result.getImagePlus(), outF );
	}

	public static ArrayList<AffineTransform3D> loadAffines( String[] xfmFileList ) throws IOException
	{
		ArrayList< AffineTransform3D > xfmList = new ArrayList< AffineTransform3D >();
		for( String f : xfmFileList )
		{
			if( f.endsWith( "mat" ))
			{
				xfmList.add( ANTSLoadAffine.loadAffine( f ));
			}
			else if( f.endsWith( "txt" ))
			{
				xfmList.add( AffineHelper.to3D(
						AffineImglib2IO.readXfm( 3, new File( f ))));
			}
			else
			{
				System.err.println( "Error reading: " + f );
				return null;
			}
		}
		return xfmList;
	}

}


text:
package co.cask.coopr.shell.command;

import co.cask.common.cli.Arguments;
import co.cask.coopr.client.AdminClient;
import co.cask.coopr.shell.CLIConfig;
import co.cask.coopr.shell.util.CliUtil;
import com.google.inject.Inject;

import java.io.PrintStream;

/**
 * Lists all hardware types.
 */
public class ListHardwareTypesCommand extends AbstractAuthCommand {

  private final AdminClient adminClient;

  @Inject
  private ListHardwareTypesCommand(AdminClient adminClient, CLIConfig cliConfig) {
    super(cliConfig);
    this.adminClient = adminClient;
  }

  @Override
  public void perform(Arguments arguments, PrintStream printStream) throws Exception {
    printStream.print(CliUtil.getPrettyJson(adminClient.getAllHardwareTypes()));
  }

  @Override
  public String getPattern() {
    return "list hardware types";
  }

  @Override
  public String getDescription() {
    return "List all hardware types";
  }
}


text:
import datetime
from django.utils import timezone
from django.db import models

class Event(models.Model):
    event_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.event_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    event = models.ForeignKey(Event)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):
	return self.choice_text


text:
using Shouldly.Tests.TestHelpers;

namespace Shouldly.Tests.ShouldBeUnique
{
    public class ObjectArrayScenario : ShouldlyShouldTestScenario
    {
        protected override string ChuckedAWobblyErrorMessage
        {
            get
            {
                return "new object[] { 1, 2, 3, 4, 2 } should be unique but [2] was duplicated";
            }
        }

        protected override void ShouldThrowAWobbly()
        {
            new object[] { 1, 2, 3, 4, 2 }.ShouldBeUnique();
        }

        protected override void ShouldPass()
        {
            new object[] { 1, 2, 3, 4, 7 }.ShouldBeUnique();
        }
    }
}


text:
Raceme.js
=============

[![Build Status](https://travis-ci.org/aie0/racemejs.svg?branch=master)](https://travis-ci.org/aie0/racemejs)

JavaScript clustering algorithms framework

***Roadmap:***
- Column family store adapter (Cassandra)
- Graph store adapter (Neo4j)
- Document store adapted (MongoDB)
- K-Medoids clustering algorithm
- Fuzzy C-Means Algorithm
- Code refactoring, full documentation and wiki setup
- Official release
- Performance improvement and algorithms comparison
- Girvan-Newman Betweenness Clustering Algorithm
- Agglomerative Genetic Algorithm for Clustering in Social Networks
- A Genetic Algorithm for Community Detection in Social Networks
- Genetic-based Communities Finding Algorithm using Clustering Coefficient
- Genetic clustering of social networks using random walks

All the explanation and based literature can be found in *articles* folder.

changelog
---------

* _0.4_  - Key-value store adapter (Redis)
* _0.3_  - Support for large graphs
* _0.2_  - K-Means clustering algorithm
* _0.1_  - Euclidian/Manhattan/Ward's method distance measurement


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import sys
import os

extra = {}
if sys.version_info >= (3,):
    extra['use_2to3'] = True
setup(name='Code2pdf',
      version='1.1.0',
      install_requires=[
          r for r in open('requirements.txt', 'r').read().split('\n') if r],
      author='Tushar Gautam',
      author_email='tushar.rishav@gmail.com',
      packages=['Code2pdf', ],
      entry_points={
          'console_scripts': ['code2pdf=Code2pdf:main'],
      },
      license='GNU General Public License v3 (GPLv3)',
      url='https://github.com/tushar-rishav/code2pdf/',
      description="Converts given source code into pdf file with syntax \
                    highlighting, line numbers and much more",
      long_description=open('README').read(),
      keywords=['pdf', 'markup',
                'formatting', 'convert code to pdf', 'python'],
      classifiers=[
          'Operating System :: POSIX :: Linux',
          'Programming Language :: Python',
          'Programming Language :: Python :: 3',
          'Topic :: System :: Monitoring'
      ],
      )


text:
@*
 * Copyright 2021 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

@import iht.constants._
@import iht.models._
@import iht.models.application.exemptions._
@import iht.utils.CommonHelper._
@import iht.config.AppConfig

@this(
    appConfig: AppConfig,
    form: FormWithCSRF,
    errorSummary: ihtHelpers.custom.error_summary,
    ihtMainTemplateApplication: iht_main_template_application,
    inputWithHelp: ihtHelpers.standard.input_with_help
)

@(qualifyingBodyNameForm: Form[QualifyingBody],
rd: RegistrationDetails,
submitUrl: Call,
cancelUrl: Call)(implicit request:Request[_], messages: Messages)

@ihtMainTemplateApplication(
    title = "",
    browserTitle = Some(Messages("page.iht.application.exemptions.qualifyingBody.name.browserTitle")),
    cancelUrl = Some(addFragmentIdentifier(cancelUrl, Some(appConfig.ExemptionsOtherNameID))),
    cancelLabel = Some(Messages("iht.estateReport.exemptions.qualifyingBodies.returnToAssetsLeftToQualifyingBody")),
    isFullWidth=false
){
@errorSummary(qualifyingBodyNameForm)
@form(action = submitUrl,'autoComplete -> "off") {

    @inputWithHelp(qualifyingBodyNameForm("name"),
    '_maxlength -> appConfig.validationMaxLengthQualifyingBodyName,
    '_divClass -> "form-group ",
    '_inputClass -> "form-control",
    '_label -> Html(Messages("page.iht.application.exemptions.qualifyingBody.name.sectionTitle")),
    '_legendIsHeading -> true,
    '_headingClass -> "heading-large"
    )

    <div id="action-button" class="form-group">
        <button class="button" id="save-continue" name="action" value="save">@Messages("iht.saveAndContinue")</button>
    </div>

}
}


text:
package com.tinycore.lifecompile.activities;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tinycore.lifecompile.R;
import com.tinycore.lifecompile.models.Note;
import com.tinycore.lifecompile.models.Tag;
import com.tinycore.lifecompile.network.LifeCompileServiceHelper;
import com.tinycore.lifecompile.services.LifeCompileService;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EditItemActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private LifeCompileService _lifcompileService;
    private int _noteId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_item);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        _lifcompileService = LifeCompileServiceHelper.GetService();
        _noteId = getIntent().getExtras().getInt("id");

        final TextView contentTextView = (TextView) this.findViewById(R.id.editTextNoteContent);
        final TextView tagsTextView = (TextView) this.findViewById(R.id.editTextNoteTags);

        final Call<Note> addNoteCall = _lifcompileService.getNote(_noteId);
        final Context context = this;

        addNoteCall.enqueue(new Callback<Note>() {

            @Override
            public void onResponse(Call<Note> call, Response<Note> response) {
                Log.d("Login", response.toString());

                if (response.isSuccessful()) {
                    Note note = response.body();
                    contentTextView.setText(note.Content);

                    StringBuilder sb = new StringBuilder();
                    String delim = "";
                    for (Tag i : note.TagsFull) {
                        sb.append(i.Name).append(delim);
                        delim = ",";
                    }

                    if(sb.length() > 0)
                        sb.substring(0, sb.length() -1);

                    tagsTextView.setText(sb.toString());
                } else {
                    ResponseBody errorBody = response.errorBody();
                    Log.d("Edit Note", errorBody.toString());
                    Toast.makeText(context, errorBody.toString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Note> call, Throwable t) {
                Log.d("Edit Note Failed", t.getMessage());
                Toast.makeText(context, "Failure! " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void saveClick(View view) {
        TextView contentTextView = (TextView) this.findViewById(R.id.editTextNoteContent);
        TextView tagsTextView = (TextView) this.findViewById(R.id.editTextNoteTags);

        final Call<Note> addNoteCall = _lifcompileService.updateNote(_noteId, contentTextView.getText().toString(), tagsTextView.getText().toString());
        final Context context = this;

        addNoteCall.enqueue(new Callback<Note>() {

            @Override
            public void onResponse(Call<Note> call, Response<Note> response) {
                Log.d("Login", response.toString());

                if (response.isSuccessful()) {
                    finish();
                } else {
                    ResponseBody errorBody = response.errorBody();
                    Log.d("Login", errorBody.toString());
                    Toast.makeText(context, errorBody.toString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Note> call, Throwable t) {
                Log.d("Login Failed", t.getMessage());
                Toast.makeText(context, "Failure! " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void cancelClick(View view) {
        finish();
    }
}


text:
layout: post
title: "J'accuse...!"
excerpt: "Global"
categories: global
comments: false
share: true
---

![](http://gijonlinenews.com/wp-content/uploads/2017/06/Accusation-1.jpg)

Seemingly every day this past month, some famous man has been accused of 'inappropriate behavior' in the workplace. And even though not all have been dismissed from their high-profile job (although most have), all of the accused have a black stain on their public record.

Far left proponents, such as SJW (social justice warriors) are celebrating this new revolution because of the thought that this is a cleansing of predatory behavior and a new day will come where women and men will be treated as equals. Far right proponents, such as Breitbart readers, are rejoicing as well because the majority of these names are part of the 'mainstream media' and the claim that liberalism harbors perverse ideas feels more vindicated in their eyes.

First off, I am glad to see something that is bringing together these otherwise diametrically opposed groups. A common enemy is something that always bring people together.

But that is sort secondary to all of this.

My main point is that I want to warn everyone that all of this may not be going the way you want.

I know the SJWs out there think this is a step in the right direction. And in some ways it is. I mean having your old smelly boss lord over you with primal lust must not make for the best work environment. But there are two things to be aware of:

1. Accusations are not necessarily facts

I am not going to squawk about the whole idea of due process; that is more of an official law-of-the-land thing. But it is true that when someone accuses someone else of something such as 'inappropriate behavior', well, it may not be true. What is 'inappropriate behavior'? Is it someone forcing their tongue down your throat? Is is insisting on going out with them alone because a promotion is in the balance? Or is it someone asking you out that you simply don't find attractive? Or maybe your boss looked at you in a way that you found odd, but was completely misinterpreted by you? And how many are accusing the accused? I don't know. Maybe all of these 'inappropriate behaviors' we are hearing about are not only true but are egregious in nature.

But maybe not.

We are getting dangerously close in creating a world where allegations are fact. This is not a good thing. I suggest having a skeptical mind about some things before conforming to the mob mentality.

2. False equivalencies

The alt right is bathing in this flawed logic. Headlines likening Al Franken, Matt Lauer, Garrison Keilor, etc to a sexual predator are teeming on the Breitbart site (of course headlines like 'Falsely Accused Roy Moore' also pepper their front page, but I digress).

But this is simply not the case. There is a huge difference between 'predator' and 'jerk'.

For example:

- Picture of a fake boob grab while a woman is sleeping - jerk

- Possibly squeezing a tush during a photo - ehh jerk, maybe nothing

- Asking a woman to watch you jerk off - jerk

- Forcing yourself upon multiple interns via walking in naked and having porn on in the background - predator

- Saying to someone their job is on the line if they don't have sex with you - predator

- Hitting on dozens of underage girls, 'dating' them, stripping them down, and kissing them against their will - predator

In other words:

Jerk = Al Franken, Louie CK

Predator = Roy Moore, Roger Ailes, Harvey Weinstein

We all have bullied around by jerks, whether it be in an uncomfortable way like a tush grab or being inappropriately teases at work or simply being pushed around by a bouncer at a club. The reality is that jerks are all around us and we have to get over some of their jerk-like tendencies. The question is: does a jerk deserve to lose their entire livelihood?

Being a victim of predatory behavior is an entirely different thing. Let's avoid confusing the two.

But here is a possible reality of the after-effect of all of these allegations. All of this may not result in social justice for all. There is a very good chance that this 'movement' will make male bosses be more hesitant in hiring a woman, going on business trips with her, or affording her the possibility of promotion. Why bother with the possibility of having her accuse you of something and killing your career?

I know, I know. Totally unfair in the eye of a SJW. 'Why is it always the woman's fault? Why can't men control themselves? Oh is it always a woman tempting the man? This goes back to Lilith and Adam, and it is just exhausting.'

Maybe so. But if everyone is so ready to declare all of these types of allegations fact instantly, how do you honestly like a male in power is going to respond.

So my advice to all...............

![](https://i.pinimg.com/originals/71/bd/8d/71bd8d56d5ed8bab3b8fd05605d81ca6.jpg)


text: TVZ projekt za .NET MVC


text:
module RailsEmailPreview
  class DeliveryHandler
    def initialize(mail, headers)
      @mail = mail
      @mail.headers(headers)
      @mail.delivery_handler = self
    end

    attr_accessor :mail

    def deliver_mail(mail)
      yield
    end
  end
end


text:
package org.apache.tamaya.core.internal.converters;

import org.apache.tamaya.Configuration;
import org.junit.Test;

import java.util.Currency;
import org.apache.tamaya.ConfigException;
import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.spi.ConversionContext;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests the default converter for currencies.
 */
public class CurrencyConverterTest {

    private static final String BGL = "BGL";
    private static final String CHF = "CHF";
    private static final String EUR = "EUR";
    private static final String JPY = "JPY";

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_CHF() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code1", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(Currency.getInstance(CHF)).isEqualTo(valueRead);
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_CHF1() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code2", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(Currency.getInstance(CHF)).isEqualTo(valueRead);
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_CHF_Whitespace_Before() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code3", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead).isEqualTo(Currency.getInstance(CHF));
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_CHF_Whitespace_After() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code4", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead).isEqualTo(Currency.getInstance(CHF));
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_CHF_Whitespace_Around() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code5", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead).isEqualTo(Currency.getInstance(CHF));
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_Numeric() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code-numeric1", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getNumericCode()).isEqualTo(Currency.getInstance(BGL).getNumericCode());
        valueRead = config.get("tests.converter.currency.code-numeric2", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getNumericCode()).isEqualTo(Currency.getInstance(BGL).getNumericCode());
        valueRead = config.get("tests.converter.currency.code-numeric3", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getNumericCode()).isEqualTo(Currency.getInstance(BGL).getNumericCode());
        valueRead = config.get("tests.converter.currency.code-numeric4", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getNumericCode()).isEqualTo(Currency.getInstance(BGL).getNumericCode());
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_Locale() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code-locale1", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(EUR);
        valueRead = config.get("tests.converter.currency.code-locale2", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(EUR);
        valueRead = config.get("tests.converter.currency.code-locale3", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(EUR);
        valueRead = config.get("tests.converter.currency.code-locale4", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(EUR);
    }

    /**
     * Test conversion. The values are provided by
     * {@link org.apache.tamaya.core.internal.converters.ConverterTestsPropertySource}.
     *
     * @throws Exception
     */
    @Test
    public void testConvert_Currency_Code_Multipart_Locale() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code-locale-twopart", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(JPY);
        valueRead = config.get("tests.converter.currency.code-locale-threepart", Currency.class);
        assertThat(valueRead).isNotNull();
        assertThat(valueRead.getCurrencyCode()).isEqualTo(JPY);
    }

    @Test(expected = ConfigException.class)
    public void testConvert_Currency_Code_Fourpart_Locale_Invalid() throws Exception {
        Configuration config = Configuration.current();
        Currency valueRead = config.get("tests.converter.currency.code-locale-fourpart", Currency.class);
        assertThat(valueRead).isNull();
    }

    @Test(expected = ConfigException.class)
    public void testConvert_CurrencyInvalid() throws ConfigException {
        Configuration config = Configuration.current();
        config.get("tests.converter.currency.invalid", Currency.class);
    }

    @Test
    public void callToConvertAddsMoreSupportedFormatsToTheContext() throws Exception {
        ConversionContext context = new ConversionContext.Builder(TypeLiteral.of(Currency.class)).build();

        CurrencyConverter converter = new CurrencyConverter();
        converter.convert("", context);

        assertThat(context.getSupportedFormats()).contains("<numericValue> (CurrencyConverter)",
                "<locale> (CurrencyConverter)", "<currencyCode>, using Locale.ENGLISH (CurrencyConverter)");
    }

    @Test
    public void testHashCode() {
        CurrencyConverter instance = new CurrencyConverter();
        assertThat(instance.hashCode()).isEqualTo(CurrencyConverter.class.hashCode());
    }

    @Test
    public void testEquality() {
        CurrencyConverter converter = new CurrencyConverter();

        assertThat(converter).isEqualTo(new CurrencyConverter());
        assertThat(converter).isNotEqualTo(new DoubleConverter());
        assertThat(converter).isNotEqualTo(null);
    }
}


text:
/**
	¤DESCRIPTION.

	@param {object} arg {}
	@param {object} [elem=ZABLE.app_elem] Element to build content in
*/
¤NAMESPACE = function(arg, elem) {
	var this_name = '¤NAMESPACE';

	this.arg = arg || {};
	this.elem = elem;

	this.flexlist = new ZABLE.toolkit.Flexlist({
		caller: this,
		container: this.elem || ZABLE.app_elem,
		title: _str(¤TITLE),
		item_headers: [¤ITEM_HEADERS],
		logout_codes: [¤LOGOUT_CODES],
		ws_url: ¤WS_URL,
		ws_command: '¤WS_COMMAND',
		onitemclick: this.get.bind(this),
		onnewclick: this.get().bind(this),
		readonly: ¤READONLY
	});

};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
ShareLinksDTO
</TITLE>

<META NAME="date" CONTENT="2013-05-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      概述
      软件包
    类
      使用
      树
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

com.conlect.oatos.dto.client

类 ShareLinksDTO

java.lang.Object
  com.conlect.oatos.dto.client.ShareLinksDTO

所有已实现的接口:
java.io.Serializable

public class ShareLinksDTO
extends java.lang.Object
implements java.io.Serializable

外链list

作者:

yang

另请参见:
序列化表格

字段摘要

private  java.util.List<ShareLinkDTO>
linkDTOs

private static long
serialVersionUID

构造方法摘要

ShareLinksDTO()

方法摘要

 java.util.List<ShareLinkDTO>
getLinkDTOs()

 void
setLinkDTOs(java.util.List<ShareLinkDTO> linkDTOs)

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细信息

linkDTOs

private java.util.List<ShareLinkDTO> linkDTOs

serialVersionUID

private static final long serialVersionUID

另请参见:
常量字段值

构造方法详细信息

ShareLinksDTO

public ShareLinksDTO()

方法详细信息

getLinkDTOs

public java.util.List<ShareLinkDTO> getLinkDTOs()

setLinkDTOs

public void setLinkDTOs(java.util.List<ShareLinkDTO> linkDTOs)

      概述
      软件包
    类
      使用
      树
      索引
      帮助

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法


text:
extern crate cards;
extern crate libthyme;

use cards::card::{Card, Suit, Value};
use libthyme::score::*;
use libthyme::board::{Position,HPosition,VPosition};
use libthyme::game::MoveType;

#[test]
fn starts_with_0_score() {
    assert_eq!(0, scorer().score(false));
}

#[test]
fn doubles_value_for_lucky_suit() {
    let mut scorer = scorer();
    let play = Play {
        hand: MoveType::ThreeOfAKind,
        cleared_positions: vec![],
        cards: vec![Card { value: Value::King, suit: Suit::Clubs }] };
    let score = scorer.check_play(play.clone());
    scorer.add_play(play);
    assert_eq!(30, score.value);
    assert_eq!(2, score.multiplier);
    assert_eq!(60, scorer.score(false));
}

#[test]
fn awards_30_for_three_of_a_kind() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::ThreeOfAKind));
    scorer.add_play(play(MoveType::ThreeOfAKind));
    assert_eq!(30, score.value);
    assert_eq!(30, scorer.score(false));
}

#[test]
fn awards_20_for_three_card_straight() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::ThreeCardStraight));
    scorer.add_play(play(MoveType::ThreeCardStraight));
    assert_eq!(20, score.value);
    assert_eq!(20, scorer.score(false));
}

#[test]
fn awards_10_for_pair() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::Pair));
    scorer.add_play(play(MoveType::Pair));
    assert_eq!(10, score.value);
    assert_eq!(10, scorer.score(false));
}

#[test]
fn awards_0_for_trash() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::Trash));
    scorer.add_play(play(MoveType::Trash));
    assert_eq!(0, score.value);
    assert_eq!(0, scorer.score(false));
}

#[test]
fn awards_50_for_five_card_straight() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::FiveCardStraight));
    scorer.add_play(play(MoveType::FiveCardStraight));
    assert_eq!(50, score.value);
    assert_eq!(50, scorer.score(false));
}

#[test]
fn awards_70_for_full_house() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::FullHouse));
    scorer.add_play(play(MoveType::FullHouse));
    assert_eq!(70, score.value);
    assert_eq!(70, scorer.score(false));
}

#[test]
fn awards_90_for_flush() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::Flush));
    scorer.add_play(play(MoveType::Flush));
    assert_eq!(90, score.value);
    assert_eq!(90, scorer.score(false));
}

#[test]
fn awards_100_for_four_of_a_kind() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::FourOfAKind));
    scorer.add_play(play(MoveType::FourOfAKind));
    assert_eq!(100, score.value);
    assert_eq!(100, scorer.score(false));
}

#[test]
fn awards_150_for_straight_flush() {
    let mut scorer = scorer();
    let score = scorer.check_play(play(MoveType::StraightFlush));
    scorer.add_play(play(MoveType::StraightFlush));
    assert_eq!(150, score.value);
    assert_eq!(150, scorer.score(false));
}

#[test]
fn formats_scores() {
    assert_eq!("0", scorer().format_as_score(0));
    assert_eq!("10", scorer().format_as_score(10));
}

#[test]
fn awards_150_for_clearing_top_position() {
    let positions = vec![HPosition::Left, HPosition::Center, HPosition::Right];
    for x in positions {
        let scorer = scorer();
        let position = Position { x: x, y: VPosition::Top  };
        assert_eq!(150, scorer.bonus(position));
        assert_eq!(150, scorer.check_play(Play {
            cards: vec![], hand: MoveType::FiveCardStraight, cleared_positions: vec![position]
        }).bonus);
    }
}

#[test]
fn awards_100_for_clearing_middle_position() {
    let positions = vec![HPosition::Left, HPosition::Center, HPosition::Right];
    for x in positions {
        let scorer = scorer();
        let position = Position { x: x, y: VPosition::Middle  };
        assert_eq!(100, scorer.bonus(position));
        assert_eq!(100, scorer.check_play(Play {
            cards: vec![], hand: MoveType::FiveCardStraight, cleared_positions: vec![position]
        }).bonus);
    }
}

#[test]
fn awards_50_for_clearing_bottom_position() {
    let positions = vec![HPosition::Left, HPosition::Center, HPosition::Right];
    for x in positions {
        let scorer = scorer();
        let position = Position { x: x, y: VPosition::Bottom  };
        assert_eq!(50, scorer.bonus(position));
        assert_eq!(50, scorer.check_play(Play {
            cards: vec![], hand: MoveType::FiveCardStraight, cleared_positions: vec![position]
        }).bonus);
    }
}

fn scorer() -> StandardScorer {
    let card = Card { value: Value::Seven, suit: Suit::Clubs };
    return StandardScorer::new(card);
}

fn play(hand: MoveType) -> Play {
    Play { hand: hand, cleared_positions: vec![], cards: vec![] }
}


text:
(function outer(modules, cache, entry) {
  if (typeof Bokeh !== "undefined") {
    for (var name in modules) {
      Bokeh.require.modules[name] = modules[name];
    }

    for (var i = 0; i < entry.length; i++) {
        Bokeh.Models.register_locations(Bokeh.require(entry[i]));
    }
  } else {
    throw new Error("Cannot find Bokeh. You have to load it prior to loading plugins.");
  }
})


text:
package liquibase.changelog;

import liquibase.Contexts;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import liquibase.database.core.H2Database;

import java.util.Arrays;

public class ChangeLogParametersTest {

    @Test
    public void setParameterValue_doubleSet() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters();

        changeLogParameters.set("doubleSet", "originalValue");
        changeLogParameters.set("doubleSet", "newValue");

        assertEquals("re-setting a param should not overwrite the value (like how ant works)", "originalValue", changeLogParameters.getValue("doubleSet"));
    }

    @Test
    public void getParameterValue_systemProperty() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters();

        assertEquals(System.getProperty("user.name"), changeLogParameters.getValue("user.name"));
    }

    @Test
    public void setParameterValue_doubleSetButSecondWrongDatabase() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters(new H2Database());

        changeLogParameters.set("doubleSet", "originalValue", new Contexts(), "baddb");
        changeLogParameters.set("doubleSet", "newValue");

        assertEquals("newValue", changeLogParameters.getValue("doubleSet"));
    }

    @Test
    public void setParameterValue_multiDatabase() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters(new H2Database());

        changeLogParameters.set("doubleSet", "originalValue", new Contexts(), "baddb, h2");

        assertEquals("originalValue", changeLogParameters.getValue("doubleSet"));
    }

    @Test
    public void setParameterValue_rightDBWrongContext() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters(new H2Database());
        changeLogParameters.setContexts(new Contexts("junit"));

        changeLogParameters.set("doubleSet", "originalValue", "anotherContext", "baddb, h2");

        assertNull(changeLogParameters.getValue("doubleSet"));
    }
   @Test
    public void setParameterValue_rightDBRightContext() {
        ChangeLogParameters changeLogParameters = new ChangeLogParameters(new H2Database());
        changeLogParameters.setContexts(new Contexts("junit"));

        changeLogParameters.set("doubleSet", "originalValue", "junit", "baddb, h2");

        assertEquals("originalValue", changeLogParameters.getValue("doubleSet"));
    }
}


text:
using System;
using System.Threading;
using Microsoft.SPOT.Hardware;

namespace Toolbox.NETMF.Hardware
{
    ///
    /// Lots of Leds shield
    ///
    public class LolShield : IDisposable
    {
        #region "Generic stuff"
        /// Width of the LoL Shield
        private int _Width = 14;
        /// Height of the LoL Shield
        private int _Height = 9;

        /// Width of the LoL Shield
        public int Width { get { return this._Width; } }
        /// Height of the LoL Shield
        public int Height { get { return this._Height; } }

        /// Led map; defines the low and high pins for each LED
        private byte[][] _LedMap = new byte[126][] {
            new byte[2] { 11,  3 }, new byte[2] { 11,  4 }, new byte[2] { 11,  5 }, new byte[2] { 11,  6 }, new byte[2] { 11,  7 }, new byte[2] { 11,  8 },
            new byte[2] { 11,  9 }, new byte[2] { 11, 10 }, new byte[2] { 11,  2 }, new byte[2] {  2, 11 }, new byte[2] { 11,  1 }, new byte[2] {  1, 11 },
            new byte[2] { 11,  0 }, new byte[2] {  0, 11 }, new byte[2] { 10,  3 }, new byte[2] { 10,  4 }, new byte[2] { 10,  5 }, new byte[2] { 10,  6 },
            new byte[2] { 10,  7 }, new byte[2] { 10,  8 }, new byte[2] { 10,  9 }, new byte[2] { 10, 11 }, new byte[2] { 10,  2 }, new byte[2] {  2, 10 },
            new byte[2] { 10,  1 }, new byte[2] {  1, 10 }, new byte[2] { 10,  0 }, new byte[2] {  0, 10 }, new byte[2] {  9,  3 }, new byte[2] {  9,  4 },
            new byte[2] {  9,  5 }, new byte[2] {  9,  6 }, new byte[2] {  9,  7 }, new byte[2] {  9,  8 }, new byte[2] {  9, 10 }, new byte[2] {  9, 11 },
            new byte[2] {  9,  2 }, new byte[2] {  2,  9 }, new byte[2] {  9,  1 }, new byte[2] {  1,  9 }, new byte[2] {  9,  0 }, new byte[2] {  0,  9 },
            new byte[2] {  8,  3 }, new byte[2] {  8,  4 }, new byte[2] {  8,  5 }, new byte[2] {  8,  6 }, new byte[2] {  8,  7 }, new byte[2] {  8,  9 },
            new byte[2] {  8, 10 }, new byte[2] {  8, 11 }, new byte[2] {  8,  2 }, new byte[2] {  2,  8 }, new byte[2] {  8,  1 }, new byte[2] {  1,  8 },
            new byte[2] {  8,  0 }, new byte[2] {  0,  8 }, new byte[2] {  7,  3 }, new byte[2] {  7,  4 }, new byte[2] {  7,  5 }, new byte[2] {  7,  6 },
            new byte[2] {  7,  8 }, new byte[2] {  7,  9 }, new byte[2] {  7, 10 }, new byte[2] {  7, 11 }, new byte[2] {  7,  2 }, new byte[2] {  2,  7 },
            new byte[2] {  7,  1 }, new byte[2] {  1,  7 }, new byte[2] {  7,  0 }, new byte[2] {  0,  7 }, new byte[2] {  6,  3 }, new byte[2] {  6,  4 },
            new byte[2] {  6,  5 }, new byte[2] {  6,  7 }, new byte[2] {  6,  8 }, new byte[2] {  6,  9 }, new byte[2] {  6, 10 }, new byte[2] {  6, 11 },
            new byte[2] {  6,  2 }, new byte[2] {  2,  6 }, new byte[2] {  6,  1 }, new byte[2] {  1,  6 }, new byte[2] {  6,  0 }, new byte[2] {  0,  6 },
            new byte[2] {  5,  3 }, new byte[2] {  5,  4 }, new byte[2] {  5,  6 }, new byte[2] {  5,  7 }, new byte[2] {  5,  8 }, new byte[2] {  5,  9 },
            new byte[2] {  5, 10 }, new byte[2] {  5, 11 }, new byte[2] {  5,  2 }, new byte[2] {  2,  5 }, new byte[2] {  5,  1 }, new byte[2] {  1,  5 },
            new byte[2] {  5,  0 }, new byte[2] {  0,  5 }, new byte[2] {  4,  3 }, new byte[2] {  4,  5 }, new byte[2] {  4,  6 }, new byte[2] {  4,  7 },
            new byte[2] {  4,  8 }, new byte[2] {  4,  9 }, new byte[2] {  4, 10 }, new byte[2] {  4, 11 }, new byte[2] {  4,  2 }, new byte[2] {  2,  4 },
            new byte[2] {  4,  1 }, new byte[2] {  1,  4 }, new byte[2] {  4,  0 }, new byte[2] {  0,  4 }, new byte[2] {  3,  4 }, new byte[2] {  3,  5 },
            new byte[2] {  3,  6 }, new byte[2] {  3,  7 }, new byte[2] {  3,  8 }, new byte[2] {  3,  9 }, new byte[2] {  3, 10 }, new byte[2] {  3, 11 },
            new byte[2] {  3,  2 }, new byte[2] {  2,  3 }, new byte[2] {  3,  1 }, new byte[2] {  1,  3 }, new byte[2] {  3,  0 }, new byte[2] {  0,  3 }
        };

        /// This array will contain the grid, from a low to high point of view
        private bool[][] _LowToHigh;

        /// Reference to all pins
        private TristatePort[] _Pin;

        /// Main loop thread
        private Thread _LoopThread;

        /// Defines a new LoL Shield
        /// <param name="CpuPins">An array of all relevant CPU Pins</param>
        public LolShield(Cpu.Pin[] CpuPins)
        {
            // We've got a Led Map. In the future we might make this a second option.
            // The Led Map must have equally or less Leds as the maximum amount that can be charlieplexed with the amount of CpuPins.
            int MaxLeds = CpuPins.Length * CpuPins.Length - CpuPins.Length; // n²-n
            if (MaxLeds < this._LedMap.Length) throw new InvalidOperationException("Can't charlieplex " + this._LedMap.Length.ToString() + " LEDs with only " + CpuPins.Length.ToString() + " CPU pins");

            // Prepaires the LowToHigh array
            this._LowToHigh = new bool[CpuPins.Length][];
            for (int Counter = 0; Counter < this._LowToHigh.Length; ++Counter)
                this._LowToHigh[Counter] = new bool[12] { false, false, false, false, false, false, false, false, false, false, false, false };

            // Makes tristates of all pins
            this._Pin = new TristatePort[CpuPins.Length];
            for (int Counter = 0; Counter < CpuPins.Length; ++Counter)
                this._Pin[Counter] = new TristatePort(CpuPins[Counter], false, false, Port.ResistorMode.Disabled);

            // Creates a new background thread
            this._LoopThread = new Thread(new ThreadStart(this._Loop));
            this._LoopThread.Start();
        }

        ///
        /// Main loop
        ///
        private void _Loop()
        {
            while (true)
            {
                for (int LowPins = 0; LowPins < this._LowToHigh.Length; ++LowPins)
                {
                    // Sets the High pin High and enables it
                    this._SetState(LowPins, true, true);
                    // Sets the required Low pins low and enables it
                    for (int HighPins = 0; HighPins < this._LowToHigh[LowPins].Length; ++HighPins)
                    {
                        if (this._LowToHigh[LowPins][HighPins])
                            this._SetState(HighPins, true, false);
                    }
                    // Sets all pins off again
                    for (int HighPins = 0; HighPins < this._LowToHigh[LowPins].Length; ++HighPins)
                        this._SetState(HighPins, false);
                    this._SetState(LowPins, false);
                }
            }
        }

        ///
        /// Disposes all pins and stops the display cycle
        ///
        public void Dispose()
        {
            this._LoopThread.Abort();
            for (int Counter = 0; Counter < this._Pin.Length; ++Counter)
                this._Pin[Counter].Dispose();
        }
        #endregion

        #region "Get/set pixels"
        ///
        /// Sets a pixel to a specific value
        ///
        /// <param name="Row">The row</param>
        /// <param name="Col">The column</param>
        /// <param name="Value">The new value</param>
        public void Set(int Row, int Col, bool Value)
        {
            this.Set(Row * this._Width + Col, Value);
        }

        ///
        /// Sets a pixel to a specific value
        ///
        /// <param name="PixNo">The index of the pixel</param>
        /// <param name="Value">The new value</param>
        public void Set(int PixNo, bool Value)
        {
            byte[] Pix = this._LedMap[PixNo];
            this._LowToHigh[Pix[0]][Pix[1]] = Value;
        }

        ///
        /// Gets the current value of a specific pixel
        ///
        /// <param name="Row">The row</param>
        /// <param name="Col">The column</param>
        /// <returns>The current value</returns>
        public bool Get(int Row, int Col)
        {
            return this.Get(Row * this._Width + Col);
        }

        ///
        /// Gets the current value of a specific pixel
        ///
        /// <param name="PixNo">The index of the pixel</param>
        /// <returns>The current value</returns>
        public bool Get(int PixNo)
        {
            byte[] Pix = this._LedMap[PixNo];
            return this._LowToHigh[Pix[0]][Pix[1]];
        }

        /// Changes the settings of a specific pin
        /// <param name="PinId">The Id of the pin</param>
        /// <param name="Active">Should be active?</param>
        /// <param name="State">Current state</param>
        private void _SetState(int PinId, bool Active, bool State = false)
        {
            if (Active != this._Pin[PinId].Active)
                this._Pin[PinId].Active = Active;

            if (Active)
                this._Pin[PinId].Write(State);
        }
        #endregion

        #region "Display modifiers"
        ///
        /// Clears the display
        ///
        /// <param name="Value">When true, it will fill the display instead</param>
        public void Clear(bool Value = false)
        {
            for (int PixNo = 0; PixNo < this._LedMap.Length; ++PixNo)
                this.Set(PixNo, Value);
        }

        ///
        /// Inverts the display
        ///
        public void Invert()
        {
            for (int PixNo = 0; PixNo < this._LedMap.Length; ++PixNo)
                this.Set(PixNo, !this.Get(PixNo));
        }

        ///
        /// Draws a horizontal line
        ///
        /// <param name="Row">The row to draw the line in</param>
        /// <param name="Value">The value for the line</param>
        public void HorizontalLine(int Row, bool Value = true)
        {
            for (int Col = 0; Col < this._Width; ++Col)
                this.Set(Row, Col, Value);
        }

        ///
        /// Draws a vertical line
        ///
        /// <param name="Col">The column to draw the line in</param>
        /// <param name="Value">The value for the line</param>
        public void VerticalLine(int Col, bool Value = true)
        {
            for (int Row = 0; Row < this._Height; ++Row)
                this.Set(Row, Col, Value);
        }

        /// Loads a monochrome bitmap onto the LoL Shield
        /// <param name="Bitmap">An array with bits</param>
        public void LoadBitmap(byte[] Bitmap)
        {
            int PixNo = 0;
            int ByteNo = 0;
            while (true)
            {
                for (byte BitMask = 0x80; BitMask > 0; BitMask >>= 1)
                {
                    this.Set(PixNo, (Bitmap[ByteNo] & BitMask) == BitMask);
                    ++PixNo;
                    if (PixNo >= this._LedMap.Length) break;
                }
                ++ByteNo;
                if (ByteNo >= Bitmap.Length) break;
                if (PixNo >= this._LedMap.Length) break;
            }
        }

        ///
        /// Loads a monochrome bitmap onto the LoL Shield
        ///
        /// <param name="Bitmap">An array with bits</param>
        /// <param name="BitmapWidth">The width of the bitmap</param>
        /// <param name="StartLeft">The column from where the bitmap must be read</param>
        /// <param name="StartTop">The row from where the bitmap must be read</param>
        /// <param name="DrawLeft">The first column where we must start displaying</param>
        /// <param name="DrawTop">The first row where we must start displaying</param>
        public void LoadBitmap(byte[] Bitmap, int BitmapWidth, int StartLeft = 0, int StartTop = 0, int DrawLeft = 0, int DrawTop = 0)
        {
            this.LoadBitmap(Bitmap, BitmapWidth, StartLeft, StartTop, DrawLeft, DrawTop, this.Width - DrawLeft, this._Height - DrawTop);
        }

        ///
        /// Loads a monochrome bitmap onto the LoL Shield
        ///
        /// <param name="Bitmap">An array with bits</param>
        /// <param name="BitmapWidth">The width of the bitmap</param>
        /// <param name="StartLeft">The column from where the bitmap must be read</param>
        /// <param name="StartTop">The row from where the bitmap must be read</param>
        /// <param name="DrawLeft">The first column where we must start displaying</param>
        /// <param name="DrawTop">The first row where we must start displaying</param>
        /// <param name="DrawWidth">The amount of columns we must display</param>
        /// <param name="DrawHeight">The amount of rows we must display</param>
        public void LoadBitmap(byte[] Bitmap, int BitmapWidth, int StartLeft, int StartTop, int DrawLeft, int DrawTop, int DrawWidth, int DrawHeight)
        {
            // Loops through all bytes in the bitmap array
            for (int SrcByteNo = 0; SrcByteNo < Bitmap.Length; ++SrcByteNo)
            {
                // Loops through all bits in the current byte
                byte SrcBitNo = 0;
                for (byte BitMask = 0x80; BitMask > 0; BitMask >>= 1)
                {
                    // Getting some info from the current position
                    int SrcPixNo = SrcByteNo * 8 + SrcBitNo;
                    int SrcPixRow = SrcPixNo / BitmapWidth;
                    int SrcPixCol = SrcPixNo - (SrcPixRow * BitmapWidth);
                    // Where should it be placed in the target display?
                    int TgtPixRow = SrcPixRow - StartTop + DrawTop;
                    int TgtPixCol = SrcPixCol - StartLeft + DrawLeft;
                    int TgtPixNo = TgtPixRow * this._Width + TgtPixCol;
                    // Should it be placed?
                    if (
                        TgtPixCol >= 0  // Can't write at negative space
                        && TgtPixRow >= 0  // Can't write at negative space
                        && TgtPixCol < this._Width // Can't write outside the screen
                        && TgtPixRow < this._Height // Can't write outside the screen
                        && TgtPixCol < DrawLeft + DrawWidth
                        && TgtPixRow < DrawTop + DrawHeight
                    )
                    {
                        this.Set(TgtPixNo, (Bitmap[SrcByteNo] & BitMask) == BitMask);
                    }
                    ++SrcBitNo;
                }
            }
        }

        #endregion
    }
}


text:
<?php

namespace UAM\Bundle\AwsBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class UAMAwsExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter(
            'uam_aws.config',
            array_key_exists('config_path', $config)
                ? $config['config_path']
                : $config['config']
        );

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/services'));
        $loader->load('common.yml');
        $loader->load('s3.yml');
        $loader->load('sqs.yml');
    }
}


text:
class Checkstyle < Formula
  desc "Check Java source against a coding standard"
  homepage "https://checkstyle.sourceforge.io/"
  url "https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.10.1/checkstyle-8.10.1-all.jar"
  sha256 "67239ffff8340a6c9266c8c952df1f639491474e48c4183637437f27c35e6066"

  bottle :unneeded

  def install
    libexec.install "checkstyle-#{version}-all.jar"
    bin.write_jar_script libexec/"checkstyle-#{version}-all.jar", "checkstyle"
  end

  test do
    path = testpath/"foo.java"
    path.write "public class Foo{ }\n"

    output = `#{bin}/checkstyle -c /sun_checks.xml #{path}`
    errors = output.lines.select { |line| line.start_with?("[ERROR] #{path}") }
    assert_match "#{path}:1:17: '{' is not preceded with whitespace.", errors.join(" ")
    assert_equal errors.size, $CHILD_STATUS.exitstatus
  end
end


text:
<!DOCTYPE html>

    <title></title>
    <link href="styles.css" rel="stylesheet" />

        Integer number
        <input placeholder="Enter integer" type="text" id="number" />
        Is divisible by 5 and 7 at same time


text:
class Group < ActiveRecord::Base
  has_many :users
  has_many :rights, :class_name => 'GroupForumRight' do
    def readable(options = {})
      f = []
      find_all_by_is_read(true, options).each do |r|
        f << r.forum
      end
      f
    end
  end

  attr_accessible :title
  validates_length_of :title, :in => 3..50

  def to_s
    "#{title}"
  end

  def self.get_cache(id)
    Rails.cache.fetch "Group(#{id})", :expires_in => 1.hour do
      find(id) rescue false
    end
  end

  def self.anonymous
    get_cache(3)
  end

  def readable_forums
    rights.readable
  end

  def has_rights?(forum_id)
    return false unless r = forum_rights(forum_id)
    r.is_moderate or block_given? && yield(r)
  end

  def forum_rights(forum, *args)
    forum_id = forum.is_a?(Forum) ? forum.id : forum
    Rails.cache.fetch "Group(#{id}).Forum(#{forum_id}).rights(#{(updated_at.to_i)})", :expires_in => 10.minutes do
      rights.find_by_forum_id(forum_id, *args) || false
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-2.0.xsd
       ">

    <import resource="quartz_db.xml"/>

    <bean id="dhlite" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="javax.sql.DataSource"/>
    </bean>

    <bean id="dh" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="javax.sql.DataSource"/>
    </bean>

    <bean id="nasa" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="javax.sql.DataSource"/>
    </bean>

    <bean id="executor" class="java.util.concurrent.Executors" factory-method="newCachedThreadPool" destroy-method="shutdownNow"/>

    <bean id="hadesAlfa" class="pl.touk.hades.sql.timemonitoring.SqlTimeBasedHades">
        <constructor-arg name="mainDataSource" ref="dhlite"/>
        <constructor-arg name="failoverDataSource" ref="dh"/>
        <constructor-arg name="mainDsName" value="DHLITE"/>
        <constructor-arg name="failoverDsName" value="DH"/>
    </bean>

    <bean id="hadesBeta" class="pl.touk.hades.sql.timemonitoring.SqlTimeBasedHades">
        <constructor-arg name="mainDataSource" ref="nasa"/>
        <constructor-arg name="failoverDataSource" ref="dh"/>
        <constructor-arg name="mainDsName" value="NASA"/>
        <constructor-arg name="failoverDsName" value="DH"/>
    </bean>

    <util:properties id="hadesProps" location="classpath:integration/quartz.properties"/>

    <bean id="schedulerFactory" class="org.quartz.impl.StdSchedulerFactory">
        <constructor-arg name="props" ref="hadesProps"/>
    </bean>

    <bean id="scheduler" factory-bean="schedulerFactory" factory-method="getScheduler"/>

    <bean id="quartzCluster" factory-bean="scheduler" factory-method="getSchedulerName"/>

    <bean id="hostName" class="pl.touk.hades.HostName" factory-method="get"/>

    <bean id="schedulerInstanceIdHumanReadable" class="java.lang.System" factory-method="getProperty">
        <constructor-arg value="instance.name"/>
    </bean>

    <bean id="repo" class="pl.touk.hades.sql.timemonitoring.QuartzRepoJdbcImpl">
        <constructor-arg name="borrowExistingMatchingResultIfYoungerThanMillis" value="20000"/>
        <constructor-arg name="dataSource"                                      ref="quartzDs"/>
        <constructor-arg name="connTimeoutMillis"                               value="1000"/>
        <constructor-arg name="sqlExecTimeout"                                  value="1"/>
        <constructor-arg name="sqlExecTimeoutForcingPeriodMillis"               value="1000"/>
        <constructor-arg name="externalExecutor"                                ref="executor"/>
        <constructor-arg name="quartzCluster"                                   ref="quartzCluster"/>
        <constructor-arg name="host"                                            ref="hostName"/>
        <constructor-arg name="schedulerInstanceIdHumanReadable"                ref="schedulerInstanceIdHumanReadable"/>
    </bean>

    <bean id="calcAlfa" class="pl.touk.hades.sql.timemonitoring.SqlTimeQuartzCalculatorImpl">
        <constructor-arg name="hades"                             ref="hadesAlfa"/>
        <constructor-arg name="connTimeoutMillis"                 value="1000"/>
        <constructor-arg name="externalExecutor"                  ref="executor"/>
        <constructor-arg name="repo"                              ref="repo"/>
        <constructor-arg name="sql"                               value="SELECT CURRENT_TIMESTAMP"/>
        <constructor-arg name="sqlExecTimeout"                    value="2"/>
        <constructor-arg name="sqlExecTimeoutForcingPeriodMillis" value="2000"/>
    </bean>

    <bean id="calcBeta" class="pl.touk.hades.sql.timemonitoring.SqlTimeQuartzCalculatorImpl">
        <constructor-arg name="hades"                             ref="hadesBeta"/>
        <constructor-arg name="connTimeoutMillis"                 value="1000"/>
        <constructor-arg name="externalExecutor"                  ref="executor"/>
        <constructor-arg name="repo"                              ref="repo"/>
        <constructor-arg name="sql"                               value="SELECT CURRENT_TIMESTAMP"/>
        <constructor-arg name="sqlExecTimeout"                    value="2"/>
        <constructor-arg name="sqlExecTimeoutForcingPeriodMillis" value="2000"/>
    </bean>

    <bean id="cronAlfa" class="pl.touk.hades.StringFactory" />
    <bean id="cronBeta" class="pl.touk.hades.StringFactory" />

    <bean id="monitorAlfa" class="pl.touk.hades.sql.timemonitoring.SqlTimeBasedQuartzMonitor" init-method="init" lazy-init="true">
        <constructor-arg name="hades"                                                   ref="hadesAlfa"/>
        <constructor-arg name="sqlTimeTriggeringFailoverMillis"                         value="600"/>
        <constructor-arg name="sqlTimeTriggeringFailbackMillis"                         value="200"/>
        <constructor-arg name="sqlTimesIncludedInAverage"                               value="5"/>
        <constructor-arg name="exceptionsIgnoredAfterRecovery"                          value="true"/>
        <constructor-arg name="recoveryErasesHistoryIfExceptionsIgnoredAfterRecovery"   value="false"/>
        <constructor-arg name="calc"                                                    ref="calcAlfa"/>
        <constructor-arg name="repo"                                                    ref="repo"/>
        <constructor-arg name="currentToUnusedRatio"                                    value="5"/>
        <constructor-arg name="backOffMultiplier"                                       value="3"/>
        <constructor-arg name="backOffMaxRatio"                                         value="15"/>
        <constructor-arg name="cron"                                                    ref="cronAlfa"/>
        <constructor-arg name="startDelayMillis"                                        value="0"/>
        <constructor-arg name="syncAttemptDelayMillis"                                  value="1000"/>
        <constructor-arg name="scheduler"                                               ref="scheduler"/>
        <constructor-arg name="syncExecutor"                                            ref="executor"/>
        <constructor-arg name="monitoringMethodDurationHistorySize"                     value="5"/>
    </bean>

    <bean id="monitorBeta" class="pl.touk.hades.sql.timemonitoring.SqlTimeBasedQuartzMonitor" init-method="init" lazy-init="true">
        <constructor-arg name="hades"                                                   ref="hadesBeta"/>
        <constructor-arg name="sqlTimeTriggeringFailoverMillis"                         value="600"/>
        <constructor-arg name="sqlTimeTriggeringFailbackMillis"                         value="200"/>
        <constructor-arg name="sqlTimesIncludedInAverage"                               value="5"/>
        <constructor-arg name="exceptionsIgnoredAfterRecovery"                          value="true"/>
        <constructor-arg name="recoveryErasesHistoryIfExceptionsIgnoredAfterRecovery"   value="false"/>
        <constructor-arg name="calc"                                                    ref="calcBeta"/>
        <constructor-arg name="repo"                                                    ref="repo"/>
        <constructor-arg name="currentToUnusedRatio"                                    value="5"/>
        <constructor-arg name="backOffMultiplier"                                       value="3"/>
        <constructor-arg name="backOffMaxRatio"                                         value="15"/>
        <constructor-arg name="cron"                                                    ref="cronBeta"/>
        <constructor-arg name="startDelayMillis"                                        value="0"/>
        <constructor-arg name="syncAttemptDelayMillis"                                  value="1000"/>
        <constructor-arg name="scheduler"                                               ref="scheduler"/>
        <constructor-arg name="syncExecutor"                                            ref="executor"/>
        <constructor-arg name="monitoringMethodDurationHistorySize"                     value="5"/>
    </bean>

</beans>


text:
#pragma once

#include <memory>
#include <string>

#include "envoy/common/pure.h"
#include "envoy/config/typed_config.h"
#include "envoy/http/header_map.h"
#include "envoy/server/factory_context.h"
#include "envoy/upstream/upstream.h"

namespace Envoy {
namespace Http {

/**
 * Interface class for session state. Session state is used to get address of upstream host
 * assigned to the session.
 */
class SessionState {
public:
  virtual ~SessionState() = default;

  /**
   * Get address of upstream host that the current session stuck on.
   *
   * @return absl::optional<absl::string_view> optional upstream address. If there is no available
   * session or no available address, absl::nullopt will be returned.
   */
  virtual absl::optional<absl::string_view> upstreamAddress() const PURE;

  /**
   * Called when a request is completed to update the session state.
   *
   * @param host the upstream host that was finally selected.
   * @param headers the response headers.
   */
  virtual void onUpdate(const Upstream::HostDescription& host, ResponseHeaderMap& headers) PURE;
};

using SessionStatePtr = std::unique_ptr<SessionState>;

/**
 * Interface class for creating session state from request headers.
 */
class SessionStateFactory {
public:
  virtual ~SessionStateFactory() = default;

  /**
   * Create session state from request headers.
   *
   * @param headers request headers.
   */
  virtual SessionStatePtr create(const RequestHeaderMap& headers) const PURE;
};

using SessionStateFactorySharedPtr = std::shared_ptr<SessionStateFactory>;

/*
 * Extension configuration for session state factory.
 */
class SessionStateFactoryConfig : public Envoy::Config::TypedFactory {
public:
  ~SessionStateFactoryConfig() override = default;

  /**
   * Creates a particular session state factory implementation.
   *
   * @param config supplies the configuration for the session state factory extension.
   * @return SessionStateFactorySharedPtr the session state factory.
   */
  virtual SessionStateFactorySharedPtr
  createSessionStateFactory(const Protobuf::Message& config,
                            Server::Configuration::CommonFactoryContext& context) PURE;

  std::string category() const override { return "envoy.http.stateful_session"; }
};

using SessionStateFactoryConfigPtr = std::unique_ptr<SessionStateFactoryConfig>;

} // namespace Http
} // namespace Envoy


text:
class User < ActiveRecord::Base
  has_many :projects
  has_many :ideas
  has_many :managers
  has_many :developers
  has_many :comments
  has_many :issues
  has_many :ideas
end

class Project < ActiveRecord::Base
  belongs_to :user
  belongs_to :member
  has_many :ideas
  has_many :issues
end

class Idea < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

class Issue < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :issue
  belongs_to :user
  belongs_to :member
end

class Dummy < ActiveRecord::Base
end

class Member < ActiveRecord::Base
  belongs_to :user
  has_many :projects
  has_many :comments
end

class Manager < Member
  has_many :developers
end

class Developer < Member
  belongs_to :boss, class_name: "Manager", foreign_key: :custom_boss_id
end


text:
"""
PowerVC Driver Common Exceptions
"""

from powervc.common.gettextutils import _

_FATAL_EXCEPTION_FORMAT_ERRORS = False

class CommonException(Exception):
    """
    PowerVC Driver Common Exception

    To correctly use this class, inherit from it and define a 'message'
    property. That message will get printed with the keyword arguments
    provided to the constructor.
    """
    message = _('An unknown exception occurred')

    def __init__(self, message=None, *args, **kwargs):
        if not message:
            message = self.message
        try:
            message = message % kwargs
        except Exception:
            if _FATAL_EXCEPTION_FORMAT_ERRORS:
                raise
            else:
                # at least get the core message out if something happened
                pass

        super(CommonException, self).__init__(message)

class StorageConnectivityGroupNotFound(CommonException):
    """
    Exception thrown when the PowerVC Storage Connectivity Group specified
    cannot be found.

    :param scg: The PowerVC Storage Connectivity Group name or id
    """
    message = _('The PowerVC Storage Connectivity Group \'%(scg)s\' was not '
                'found.')

class StagingProjectNotFound(CommonException):
    """
    Exception thrown when the staging project specified in the conf cannot be
    found.

    :param name: The name of the staging project which was not found.
    """
    message = _('The staging project \'%(name)s\' was not found.')

class StagingUserNotFound(CommonException):
    """
    Exception thrown when the staging user specified in the conf cannot be
    found.

    :param name: The name of the staging user which was not found.
    """
    message = _('The staging user \'%(name)s\' was not found.')


text:
package bio.terra.service.snapshot.flight.export;

import bio.terra.common.Column;
import bio.terra.service.dataset.Dataset;
import bio.terra.service.dataset.DatasetTable;
import bio.terra.service.resourcemanagement.exception.GoogleResourceException;
import bio.terra.service.snapshot.Snapshot;
import bio.terra.service.snapshot.SnapshotService;
import bio.terra.service.snapshot.SnapshotTable;
import bio.terra.service.snapshot.exception.CorruptMetadataException;
import bio.terra.service.snapshot.exception.SnapshotExportException;
import bio.terra.service.tabulardata.google.bigquery.BigQueryPdao;
import bio.terra.stairway.FlightContext;
import bio.terra.stairway.Step;
import bio.terra.stairway.StepResult;
import bio.terra.stairway.StepStatus;
import bio.terra.stairway.exception.RetryException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

public class SnapshotExportValidatePrimaryKeysStep implements Step {
  private final SnapshotService snapshotService;
  private final UUID snapshotId;

  public SnapshotExportValidatePrimaryKeysStep(SnapshotService snapshotService, UUID snapshotId) {
    this.snapshotService = snapshotService;
    this.snapshotId = snapshotId;
  }

  @Override
  public StepResult doStep(FlightContext context) throws InterruptedException, RetryException {
    Snapshot snapshot = snapshotService.retrieve(snapshotId);
    Dataset dataset = snapshot.getFirstSnapshotSource().getDataset();
    List<SnapshotTable> tables = snapshot.getTables();
    List<String> tablesWithDuplicates =
        tables.stream()
            .map(
                table -> {
                  String tableName = table.getName();
                  DatasetTable datasetTable =
                      dataset
                          .getTableByName(tableName)
                          .orElseThrow(
                              () ->
                                  new CorruptMetadataException(
                                      String.format(
                                          "Could not find '%s' table in the snapshot's dataset",
                                          tableName)));
                  List<Column> primaryKeyColumns = datasetTable.getPrimaryKey();
                  if (primaryKeyColumns.isEmpty()) {
                    return null;
                  }

                  boolean hasDuplicates;
                  try {
                    hasDuplicates =
                        (BigQueryPdao.duplicatePrimaryKeys(snapshot, primaryKeyColumns, tableName)
                                .getTotalRows()
                            > 0);
                  } catch (InterruptedException e) {
                    throw new GoogleResourceException(
                        String.format(
                            "Failed to query BigQuery for duplicate rows in snapshot table '%s'",
                            tableName));
                  }
                  if (hasDuplicates) {
                    return table.getName();
                  } else {
                    return null;
                  }
                })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    if (tablesWithDuplicates.isEmpty()) {
      return StepResult.getStepResultSuccess();
    } else {
      String message = "Validating snapshot primary keys for export failed.";
      int numTables = tablesWithDuplicates.size();
      String tableNames = String.join(", ", tablesWithDuplicates);
      List<String> details =
          List.of(
              String.format(
                  "%d table(s) had rows with duplicate primary keys [%s]. ", numTables, tableNames),
              "To export, please create a new snapshot, ensuring there are no rows with duplicate primary keys.");
      return new StepResult(
          StepStatus.STEP_RESULT_FAILURE_FATAL, new SnapshotExportException(message, details));
    }
  }

  @Override
  public StepResult undoStep(FlightContext context) throws InterruptedException {
    return StepResult.getStepResultSuccess();
  }
}


text:
using FluentAssertions;
using Moq;
using NUnit.Framework;
using System;
using System.Text;
using XSerializer.Encryption;

namespace RockLib.Encryption.XSerializer.Tests
{
    [TestFixture]
    public class SerializingCryptoTests
    {
        private static readonly int _bar = 123;
        private static readonly string _baz = "abc";
        private static readonly double _qux = 543.21;

        private const string FooXmlFormat = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Foo xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Bar>{0}</Bar><Baz>{1}</Baz><Qux>{2}</Qux></Foo>";
        private static readonly string FooXml = string.Format(FooXmlFormat, EncryptRaw(_bar), EncryptRaw(_baz), EncryptRaw(_qux));

        private const string FooJsonFormat = "{{\"Bar\":\"{0}\",\"Baz\":\"{1}\",\"Qux\":\"{2}\"}}";
        private static readonly string FooJson = string.Format(FooJsonFormat, EncryptRaw(_bar), EncryptJsonString(_baz), EncryptRaw(_qux));

        private static readonly Mock<Base64Crypto> _mockCrypto = new Mock<Base64Crypto>() { CallBase = true };

        static SerializingCryptoTests() => Crypto.SetCurrent(_mockCrypto.Object);

        [Test]
        public void TheDefaultEncryptionMechanismHasItsCryptoSetFromCryptoCurrent()
        {
            SerializingCrypto.EncryptionMechanism.Crypto.Should().BeSameAs(Crypto.Current);
        }

        [Test]
        public void ToXmlWithNoKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            SerializingCrypto.ToXml(foo);

            _mockCrypto.Verify(c => c.GetEncryptor(It.Is<string>(o => o == null)), Times.Once());
        }

        [Test]
        public void ToXmlWithKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            var credentialName = "foobar";

            SerializingCrypto.ToXml(foo, credentialName);

            _mockCrypto.Verify(c => c.GetEncryptor(It.Is<string>(o => o == credentialName)), Times.Once());
        }

        [Test]
        public void FromXmlWithNoKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            SerializingCrypto.FromXml<Foo>(FooXml);

            _mockCrypto.Verify(c => c.GetDecryptor(It.Is<string>(o => o == null)), Times.Once());
        }

        [Test]
        public void FromXmlWithKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var credentialName = "foobar";

            SerializingCrypto.FromXml<Foo>(FooXml, credentialName);

            _mockCrypto.Verify(c => c.GetDecryptor(It.Is<string>(o => o == credentialName)), Times.Once());
        }

        [Test]
        public void ToJsonWithNoKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            SerializingCrypto.ToJson(foo);

            _mockCrypto.Verify(c => c.GetEncryptor(It.Is<string>(o => o == null)), Times.Once());
        }

        [Test]
        public void ToJsonWithKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            var credentialName = "foobar";

            SerializingCrypto.ToJson(foo, credentialName);

            _mockCrypto.Verify(c => c.GetEncryptor(It.Is<string>(o => o == credentialName)), Times.Once());
        }

        [Test]
        public void FromJsonWithNoKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            SerializingCrypto.FromJson<Foo>(FooJson);

            _mockCrypto.Verify(c => c.GetDecryptor(It.Is<string>(o => o == null)), Times.Once());
        }

        [Test]
        public void FromJsonWithKeyIdentifierCallsCryptoGetEncryptorOnce()
        {
            _mockCrypto.ResetCalls();

            var credentialName = "foobar";

            SerializingCrypto.FromJson<Foo>(FooJson, credentialName);

            _mockCrypto.Verify(c => c.GetDecryptor(It.Is<string>(o => o == credentialName)), Times.Once());
        }

        [Test]
        public void ToXmlSerializesCorrectly()
        {
            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            var xml = SerializingCrypto.ToXml(foo);
            var expectedXml = string.Format(FooXmlFormat,
                EncryptRaw(foo.Bar), EncryptRaw(foo.Baz), EncryptRaw(foo.Qux));

            xml.Should().Be(expectedXml);
        }

        [Test]
        public void FromXmlDeserializesCorrectly()
        {
            var foo = SerializingCrypto.FromXml<Foo>(FooXml);

            foo.Bar.Should().Be(_bar);
            foo.Baz.Should().Be(_baz);
            foo.Qux.Should().Be(_qux);
        }

        [Test]
        public void ToJsonSerializesCorrectly()
        {
            var foo = new Foo { Bar = _bar, Baz = _baz, Qux = _qux };

            var json = SerializingCrypto.ToJson(foo);
            var expectedJson = string.Format(FooJsonFormat,
                EncryptRaw(foo.Bar), EncryptJsonString(foo.Baz), EncryptRaw(foo.Qux));

            json.Should().Be(expectedJson);
        }

        [Test]
        public void FromJsonDeserializesCorrectly()
        {
            var foo = SerializingCrypto.FromJson<Foo>(FooJson);

            foo.Bar.Should().Be(_bar);
            foo.Baz.Should().Be(_baz);
            foo.Qux.Should().Be(_qux);
        }

        public class Foo
        {
            [Encrypt]
            public int Bar { get; set; }

            [Encrypt]
            public string Baz { get; set; }

            [Encrypt]
            public double Qux { get; set; }
        }

        public class Base64Crypto : ICrypto
        {
            public virtual bool CanDecrypt(string credentialName) => true;
            public virtual bool CanEncrypt(string credentialName) => true;
            public virtual string Decrypt(string cipherText, string credentialName) => Base64.Decrypt(cipherText);
            public virtual byte[] Decrypt(byte[] cipherText, string credentialName) => throw new NotImplementedException();
            public virtual string Encrypt(string plainText, string credentialName) => Base64.Encrypt(plainText);
            public virtual byte[] Encrypt(byte[] plainText, string credentialName) => throw new NotImplementedException();
            public virtual IDecryptor GetDecryptor(string credentialName) => MockDecryptor.Object;
            public virtual IEncryptor GetEncryptor(string credentialName) => MockEncryptor.Object;
            public Mock<Base64Encryptor> MockEncryptor { get; } = new Mock<Base64Encryptor>() { CallBase = true };
            public Mock<Base64Decryptor> MockDecryptor { get; } = new Mock<Base64Decryptor>() { CallBase = true };
        }

        public class Base64Encryptor : IEncryptor
        {
            public void Dispose() { }
            public string Encrypt(string plainText) => Base64.Encrypt(plainText);
            public byte[] Encrypt(byte[] plainText) => throw new NotImplementedException();
        }

        public class Base64Decryptor : IDecryptor
        {
            public void Dispose() { }
            public string Decrypt(string cipherText) => Base64.Decrypt(cipherText);
            public byte[] Decrypt(byte[] cipherText) => throw new NotImplementedException();
        }

        private static class Base64
        {
            public static string Encrypt(string plainText) => Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
            public static string Decrypt(string cipherText) => Encoding.UTF8.GetString(Convert.FromBase64String(cipherText));
        }

        private static string EncryptJsonString(string value) => Base64.Encrypt("\"" + value + "\"");
        private static string EncryptRaw(object value) => Base64.Encrypt(value.ToString());
    }
}