text:
require 'spec_helper'

describe Fitgem::Client do
  before(:each) do
    @client = Fitgem::Client.new({
      :consumer_key => '12345',
      :consumer_secret => '67890'
    })
  end

  describe "#construct_date_range_fragment" do
    it 'should format the correct URI fragment based on a base date and end date' do
      frag = @client.construct_date_range_fragment({:base_date => '2011-03-07', :end_date => '2011-03-14'})
      expect(frag).to eq 'date/2011-03-07/2011-03-14'
    end

    it 'should format the correct URI fragment based on a base date and period' do
      frag = @client.construct_date_range_fragment({:base_date => '2011-03-07', :period => '7d'})
      expect(frag).to eq 'date/2011-03-07/7d'
    end

    it 'should raise an error unless there is a base date AND either a period or an end date' do
      expect {
        @client.construct_date_range_fragment({:base_date => '2011-03-07'})
      }.to raise_error(Fitgem::InvalidTimeRange)

      expect {
        @client.construct_date_range_fragment({:period => '1y'})
      }.to raise_error(Fitgem::InvalidTimeRange)

      expect {
        @client.construct_date_range_fragment({:end_date => '2011-03-07', :period => '7d'})
      }.to raise_error(Fitgem::InvalidTimeRange)
    end

    it 'formats DateTime objects to the required date format' do
      span_start = DateTime.new(1997, 4, 18, 9, 30, 30)
      span_end = DateTime.new(1999, 10, 3, 15, 30, 30)
      frag = @client.construct_date_range_fragment base_date: span_start, end_date: span_end
      expect(frag).to eq 'date/1997-04-18/1999-10-03'
    end
  end

  describe "#format_date" do
    it "accepts DateTime objects" do
      date = DateTime.strptime('2011-03-19','%Y-%m-%d')
      expect(@client.format_date(date)).to eq '2011-03-19'
    end

    it "accepts strings in YYYY-MM-DD format" do
      expect(@client.format_date('2011-03-19')).to eq '2011-03-19'
    end

    it "accepts the string 'today' to denote the current date" do
      today = Date.today.strftime("%Y-%m-%d")
      expect(@client.format_date('today')).to eq today
    end

    it "accepts the string 'yesterday' to denote the day previous to today" do
      yesterday = (Date.today-1).strftime("%Y-%m-%d")
      expect(@client.format_date('yesterday')).to eq yesterday
    end

    it "rejects strings that are not in YYY-MM-DD format" do
      date = "2011-3-2"
      expect {
        @client.format_date(date)
      }.to raise_error Fitgem::InvalidDateArgument, "Invalid date (2011-3-2), must be in yyyy-MM-dd format"
    end

    it "rejects strings are formatted correctly but include non-numeric elements" do
      date = "2011-aa-20"
      expect {
        @client.format_date(date)
      }.to raise_error Fitgem::InvalidDateArgument, "Invalid date (2011-aa-20), must be in yyyy-MM-dd format"
    end

    it "rejects arguments that are not a Date, Time, DateTime, or String" do
      date = 200
      expect {
        @client.format_date(date)
      }.to raise_error Fitgem::InvalidDateArgument, "Date used must be a date/time object or a string in the format YYYY-MM-DD; supplied argument is a Fixnum"
    end
  end

  describe "#format_time" do
    context "without a timezone" do
      it "accepts DateTime objects" do
        time = DateTime.parse("3rd Feb 2001 04:05:06 PM")
        expect(@client.format_time(time)).to eq "16:05"
      end

      it "accepts Time objects" do
        time = Time.mktime 2012, 1, 20, 13, 33, 30
        expect(@client.format_time(time)).to eq "13:33"
      end

      it "accepts the string 'now' to denote the current localtime" do
        now = DateTime.now
        expect(@client.format_time('now')).to eq now.strftime("%H:%M")
      end

      it "accepts strings in HH:mm format" do
        time = "04:20"
        expect(@client.format_time(time)).to eq "04:20"
      end
    end

    context "with a timezone" do
      it "accepts DateTime objects" do
        time = DateTime.parse("3rd Feb 2001 04:05:06 PM UTC")
        expect(@client.format_time(time, include_timezone: true)).to eq "16:05+00:00"
      end

      it "accepts Time objects" do
        time = Time.new 2012, 1, 20, 13, 33, 30, "+00:00"
        expect(@client.format_time(time, include_timezone: true)).to eq "13:33+00:00"
      end

      it "accepts the string 'now' to denote the current localtime" do
        now = DateTime.now
        expect(@client.format_time('now', include_timezone: true)).to eq now.strftime("%H:%M%:z")
      end

      it "accepts strings in HH:mm format" do
        datetime = DateTime.parse("26th Apr 2000 09:27:00 +08:00")
        allow(DateTime).to receive(:now).and_return datetime

        time = "04:20"
        expect(@client.format_time(time, include_timezone: true)).to eq "04:20+08:00"
      end
    end

    it "rejects Date objects" do
      date = Date.today
      expect {
        @client.format_time(date)
      }.to raise_error Fitgem::InvalidTimeArgument
    end

    it "rejects strings that are not in HH:mm format" do
      time = "4:20pm"
      expect {
        @client.format_time(time)
      }.to raise_error Fitgem::InvalidTimeArgument
    end

    it "rejects strings that are formatted correctly but include non-numeric elements" do
      time = "4a:33"
      expect {
        @client.format_time(time)
      }.to raise_error Fitgem::InvalidTimeArgument
    end

    it "rejects arguments that do not conform to accepted types" do
      expect {
        @client.format_time(200)
      }.to raise_error Fitgem::InvalidTimeArgument
    end
  end

  describe "#label_for_measurement" do
    it "accepts the supported Fitgem::ApiUnitSystem values" do
      @client.api_unit_system = Fitgem::ApiUnitSystem.US
      @client.label_for_measurement :duration, false
      @client.api_unit_system = Fitgem::ApiUnitSystem.UK
      @client.label_for_measurement :duration, false
      @client.api_unit_system = Fitgem::ApiUnitSystem.METRIC
      @client.label_for_measurement :duration, false
    end

    it "raises an InvalidUnitSystem error if the Fitgem::Client.api_unit_system value is invalid" do
      expect {
        @client.api_unit_system = "something else entirely"
        @client.label_for_measurement :duration, false
      }.to raise_error Fitgem::InvalidUnitSystem
    end

    it "accepts the supported values for the measurement_type parameter" do
      @client.label_for_measurement :duration, false
      @client.label_for_measurement :distance, false
      @client.label_for_measurement :elevation, false
      @client.label_for_measurement :height, false
      @client.label_for_measurement :weight, false
      @client.label_for_measurement :measurements, false
      @client.label_for_measurement :liquids, false
      @client.label_for_measurement :blood_glucose, false
    end

    it "raises an InvalidMeasurementType error if the measurement_type parameter is invalid" do
      expect {
        @client.label_for_measurement :homina, false
      }.to raise_error Fitgem::InvalidMeasurementType
    end

    it "returns the correct values when the unit system is Fitgem::ApiUnitSystem.US" do
      @client.api_unit_system = Fitgem::ApiUnitSystem.US
      expect(@client.label_for_measurement(:duration, false)).to eq "milliseconds"
      expect(@client.label_for_measurement(:distance, false)).to eq "miles"
      expect(@client.label_for_measurement(:elevation, false)).to eq "feet"
      expect(@client.label_for_measurement(:height, false)).to eq "inches"
      expect(@client.label_for_measurement(:weight, false)).to eq "pounds"
      expect(@client.label_for_measurement(:measurements, false)).to eq "inches"
      expect(@client.label_for_measurement(:liquids, false)).to eq "fl oz"
      expect(@client.label_for_measurement(:blood_glucose, false)).to eq "mg/dL"
    end

    it "returns the correct values when the unit system is Fitgem::ApiUnitSystem.UK" do
      @client.api_unit_system = Fitgem::ApiUnitSystem.UK
      expect(@client.label_for_measurement(:duration, false)).to eq "milliseconds"
      expect(@client.label_for_measurement(:distance, false)).to eq "kilometers"
      expect(@client.label_for_measurement(:elevation, false)).to eq "meters"
      expect(@client.label_for_measurement(:height, false)).to eq "centimeters"
      expect(@client.label_for_measurement(:weight, false)).to eq "stone"
      expect(@client.label_for_measurement(:measurements, false)).to eq "centimeters"
      expect(@client.label_for_measurement(:liquids, false)).to eq "mL"
      expect(@client.label_for_measurement(:blood_glucose, false)).to eq "mmol/l"
    end

    it "returns the correct values when the unit system is Fitgem::ApiUnitSystem.METRIC" do
      @client.api_unit_system = Fitgem::ApiUnitSystem.METRIC
      expect(@client.label_for_measurement(:duration, false)).to eq "milliseconds"
      expect(@client.label_for_measurement(:distance, false)).to eq "kilometers"
      expect(@client.label_for_measurement(:elevation, false)).to eq "meters"
      expect(@client.label_for_measurement(:height, false)).to eq "centimeters"
      expect(@client.label_for_measurement(:weight, false)).to eq "kilograms"
      expect(@client.label_for_measurement(:measurements, false)).to eq "centimeters"
      expect(@client.label_for_measurement(:liquids, false)).to eq "mL"
      expect(@client.label_for_measurement(:blood_glucose, false)).to eq "mmol/l"
    end

    context "when respecting the user's unit measurement preferences" do
      before(:each) do
        allow(@client).to receive(:connected?).and_return(true)
        allow(@client).to receive(:user_info).and_return({"user" => {"distanceUnit"=>"en_GB", "glucoseUnit"=>"en_GB", "heightUnit"=>"en_GB", "waterUnit"=>"METRIC", "weightUnit"=>"en_GB"}})
      end

      it "returns the correct overridden measurement label" do
        @client.api_unit_system = Fitgem::ApiUnitSystem.US
        expect(@client.label_for_measurement(:distance)).to eq "kilometers"
      end
    end
  end
end


text:
package javaposse.jobdsl.plugin.actions;

import hudson.model.Run;
import jenkins.model.RunAction2;
import jenkins.tasks.SimpleBuildStep;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public abstract class GeneratedObjectsRunAction<T> implements RunAction2, SimpleBuildStep.LastBuildAction {
    private final Set<T> modifiedObjects;
    protected transient Run owner;

    GeneratedObjectsRunAction(Collection<T> modifiedObjects) {
        this.modifiedObjects = new LinkedHashSet<>(modifiedObjects);
    }

    @Override
    public String getIconFileName() {
        return null;
    }

    @Override
    public String getDisplayName() {
        return null;
    }

    @Override
    public String getUrlName() {
        return null;
    }

    @Override
    public void onLoad(Run<?, ?> run) {
        onAttached(run);
    }

    @Override
    public void onAttached(Run run) {
        owner = run;
    }

    @SuppressWarnings("ConstantConditions") // modifiedObjects can be null when this is deserialized by XStream
    public Collection<T> getModifiedObjects() {
        return modifiedObjects == null ? null : new TreeSet<>(modifiedObjects);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\v1\models\Recommendations */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'userid')->textInput() ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'kindid')->textInput() ?>

    <?= $form->field($model, 'location')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'sellerphone')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'reason')->textInput(['maxlength' => true]) ?>

    <?//= $form->field($model, 'created_at')->textInput() ?>

    <?//= $form->field($model, 'pictures')->textInput(['maxlength' => true]) ?>

    <?//= $form->field($model, 'longitude')->textInput() ?>

    <?//= $form->field($model, 'latitude')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? '创建' : '更新', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
var tessel = require('tessel');
var climatelib = require('climate-si7005');

var climate = climatelib.use(tessel.port['A']);

climate.on('ready', function() {
    console.log('Connected to si7005');

    // Loop forever
    setImmediate(function loop() {
        climate.readTemperature('f', function (err, temp) {
            climate.readHumidity(function (err, humid) {
                console.log('Degrees:', temp.toFixed(4) + 'F', 'Humidity:', humid.toFixed(4) + '%RH');
                setTimeout(loop, 300);
            });
        });
    });
});

climate.on('error', function(err) {
    console.log('error connecting module', err);
});


text:
$(document).ready(function(){
    'use strict';

    var getQuote = function() {
        var promise = $.ajax({url: 'quote.php', dataType: 'json'});
        var textEl = $('#text');

        promise.done(function(data) {
                textEl.fadeOut(function() {
                    $(this).text(data.quote).fadeIn();
                });
            })
            //textEl.text(data.quote);})
            .fail(function(jqXHR, textStatus, errorThrown) {
                textEl.text('Något gick fel i Ajax-anropet');
        });
    };

    $("[type='button']").click(getQuote).trigger('click');

});


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dcd2a8d2"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 顶栏 -->
    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#383737"
        android:gravity="center"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <Button
                android:id="@+id/back"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/back" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:gravity="center">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="修改信息"
                android:textColor="#FFF"
                android:textSize="30dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </LinearLayout>
    </LinearLayout>
    <!-- body-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignParentBottom="true">
]
        \
        <TableLayout
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:shrinkColumns="0,1,2"
            android:stretchColumns="0,1,2">

            <TableRow
                android:layout_margin="10dp">
                <TextView
                    android:gravity="center"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:text="住址:"
                    android:textSize="20dp"
                    />
                <EditText
                    android:id="@+id/setdizhi"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3"
                    android:inputType="text"
                    android:hint="请确认地址"></EditText>
            </TableRow>
            <TableRow
                android:layout_marginTop="20dp">
                <Button
                    android:id="@+id/queren"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_span="2"
                    android:text="确认" />

            </TableRow>
        </TableLayout>
    </LinearLayout>

</RelativeLayout>


text:
Spells take 10ft less movement Speed to cast.

Using the Enineer Skill requires 5ft less movement Speed.


text:
#ifndef __FIFO_H__
#define __FIFO_H__

#include <stdint.h>
#include <stdbool.h>

/** @addtogroup FIFO
  * @{
  */

#pragma pack(push,4)

/// Header defining a circular fifo memory block.
typedef struct __CFIFO_Header {
	volatile int32_t PutIdx;	//!< Index to start of empty data block
	volatile int32_t GetIdx;	//!< Index to start of used data block
	int32_t MaxIdxCnt;			//!< Max block count
	bool bBlocking;          	//!< False to push out when FIFO is full (drop)
	uint32_t DropCnt;           //!< Count dropped block
	uint32_t BlkSize;			//!< Block size in bytes
	uint32_t MemSize;			//!< Total FIFO memory size allocated
	uint8_t *pMemStart;			//!< Start of FIFO data memory
} CFIFOHDR;

#pragma pack(pop)

/// @brief	CFIFO handle.
///
/// This handle is used for all CFIFO function calls. It is the pointer to to CFIFO memory block.
///
typedef CFIFOHDR* HCFIFO;

/// This macro calculates total memory require in bytes including header for byte based FIFO.
#define CFIFO_MEMSIZE(FSIZE)					((FSIZE) + sizeof(CFIFOHDR))

/// This macro calculates total memory require in bytes including header for block based FIFO.
#define CFIFO_TOTAL_MEMSIZE(NbBlk, BlkSize)		((NbBlk) * (BlkSize) + sizeof(CFIFOHDR))

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief	Initialize FIFO.
 *
 * This function must be called first to initialize FIFO before any other functions
 * can be used.
 *
 * @param	pMemBlk 		: Pointer to memory block to be used for FIFO
 * @param	TotalMemSize	: Total memory size in byte
 * @param	BlkSize 		: Block size in bytes
 * @param   bBlocking  		: Behavior when FIFO is full.\n
 *                    			false - Old data will be pushed out to make place
 *                            			for new data.\n
 *                    			true  - New data will not be pushed in
 *
 * 	@return CFifo Handle
 */
HCFIFO const CFifoInit(uint8_t * const pMemBlk, uint32_t TotalMemSize, uint32_t BlkSize, bool bBlocking);

/**
 * @brief	Retrieve FIFO data by returning pointer to FIFO memory block for reading.
 *
 * This function returns a direct pointer to FIFO memory to quickly retrieve data.
 * User must ensure to transfer data quickly to avoid data being overwritten by a
 * new FIFO put. This is to allows FIFO handling within interrupt.
 *
 * @param	hFifo : CFIFO handle
 *
 * @return	Pointer to the FIFO buffer.
 */
uint8_t *CFifoGet(HCFIFO const hFifo);

/**
 * @brief	Retrieve FIFO data in multiple blocks by returning pointer to FIFO memory blocks
 * for reading.
 *
 * This function returns a direct pointer to FIFO memory to quickly retrieve data.
 * User must ensure to transfer data quickly to avoid data being overwritten by a
 * new FIFO put. This is to allows FIFO handling within interrupt.
 *
 * @param	hFifo : CFIFO handle
 * @param	pCnt  : Number of block to get\n
 * 					On return number of blocks available to read
 *
 * @return	Pointer to first FIFO block. Blocks are consecutive.
 */
uint8_t *CFifoGetMultiple(HCFIFO const hFifo, int *pCnt);

/**
 * @brief	Insert FIFO data by returning pointer to FIFO memory block for writing.
 *
 * @param	hFifo : CFIFO handle
 *
 * @return pointer to the inserted FIFO buffer.
 */
uint8_t *CFifoPut(HCFIFO const hFifo);

/**
 * @brief	Insert multiple FIFO blocks by returning pointer to memory blocks for writing.
 *
 * @param	hFifo : CFIFO handle
 * @param	pCnt  : Number of block to put\n
 * 					On return pCnt contains the number of blocks available for writing
 *
 * @return	pointer to the first FIFO block. Blocks are consecutive.
 */
uint8_t *CFifoPutMultiple(HCFIFO const hFifo, int *pCnt);

/**
 * @brief	Retrieve FIFO data into provided buffer
 *
 * @param	hFifo : CFIFO handle
 * @param	pBuff : Pointer to buffer container for returned data
 * @param	BuffLen : Size of container in bytes
 *
 * @return	Number of bytes copied into pBuff
 */
int CFifoPop(HCFIFO const hFifo, uint8_t *pBuff, int BuffLen);

/**
 * @brief	Insert FIFO data with provided data
 *
 * @param	hFifo : CFIFO handle
 * @param	pData : Pointer to data to be inserted
 * @param	DataLen : Size of data in bytes
 *
 * @return	Number of bytes inserted into FIFO
 */
int CFifoPush(HCFIFO const hFifo, uint8_t *pData, int DataLen);

/**
 * @brief	Reset FIFO
 *
 * @param	hFifo : CFIFO handle
 */
void CFifoFlush(HCFIFO const hFifo);

/**
 * @brief	Get available blocks in FIFO
 *
 * @param	hFifo : CFIFO handle
 *
 * @return	Number of FIFO block available for writing
 */
int CFifoAvail(HCFIFO const hFifo);

/**
 * @brief	Get number of used blocks
 *
 * @param	hFifo : CFIFO handle
 *
 * @return	Number of FIFO block used
 */
int CFifoUsed(HCFIFO const hFifo);

/**
 * @brief	Get block size
 *
 * @param	hFifo : CFIFO handle
 *
 * @return	Block size in bytes
 */
static inline uint32_t CFifoBlockSize(HCFIFO const hFifo) { return hFifo->BlkSize; }

#ifdef __cplusplus
}
#endif

/** @} end group FIFO */

#endif // __FIFO_H__


text:
package alluxio.master.file.meta;

import alluxio.master.file.options.CreateFileOptions;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for {@link TtlBucket}.
 */
public class TtlBucketTest {
  private TtlBucket mBucket;

  /**
   * Sets up a new {@link TtlBucket} before a test runs.
   */
  @Before
  public void before() {
    mBucket = new TtlBucket(0);
  }

  /**
   * Tests the different interval methods.
   */
  @Test
  public void interval() {
    for (long i = 0; i < 10; i++) {
      mBucket = new TtlBucket(i);
      Assert.assertEquals(mBucket.getTtlIntervalEndTimeMs(), mBucket.getTtlIntervalStartTimeMs()
          + TtlBucket.getTtlIntervalMs());
    }
  }

  /**
   * Tests the {@link TtlBucket#compareTo(TtlBucket)} method with the
   * {@link TtlBucket#getTtlIntervalStartTimeMs()} method.
   */
  @Test
  public void compareIntervalStartTime() {
    for (long i = 0; i < 10; i++) {
      for (long j = i + 1; j < 10; j++) {
        TtlBucket bucket1 = new TtlBucket(i);
        Assert.assertEquals(i, bucket1.getTtlIntervalStartTimeMs());

        TtlBucket bucket2 = new TtlBucket(j);
        Assert.assertEquals(j, bucket2.getTtlIntervalStartTimeMs());

        Assert.assertEquals(-1, bucket1.compareTo(bucket2));
        Assert.assertEquals(1, bucket2.compareTo(bucket1));

        TtlBucket bucket3 = new TtlBucket(i);
        Assert.assertEquals(i, bucket3.getTtlIntervalStartTimeMs());

        Assert.assertEquals(0, bucket1.compareTo(bucket3));
      }
    }
  }

  /**
   * Tests the {@link TtlBucket#addFile(InodeFile)} and {@link TtlBucket#removeFile(InodeFile)}
   * methods.
   */
  @Test
  public void addAndRemoveFile() {
    InodeFile mFileTtl1 =
        InodeFile.create(0, 0, "test1", 0, CreateFileOptions.defaults().setTtl(1));
    InodeFile mFileTtl2 =
        InodeFile.create(1, 0, "test1", 0, CreateFileOptions.defaults().setTtl(2));
    Assert.assertTrue(mBucket.getFiles().isEmpty());

    mBucket.addFile(mFileTtl1);
    Assert.assertEquals(1, mBucket.getFiles().size());

    // The same file, won't be added.
    mBucket.addFile(mFileTtl1);
    Assert.assertEquals(1, mBucket.getFiles().size());

    // Different file, will be added.
    mBucket.addFile(mFileTtl2);
    Assert.assertEquals(2, mBucket.getFiles().size());

    // Remove files;
    mBucket.removeFile(mFileTtl1);
    Assert.assertEquals(1, mBucket.getFiles().size());
    Assert.assertTrue(mBucket.getFiles().contains(mFileTtl2));
    mBucket.removeFile(mFileTtl2);
    Assert.assertEquals(0, mBucket.getFiles().size());
  }

  /**
   * Tests the {@link TtlBucket#compareTo(TtlBucket)} method.
   */
  @Test
  public void compareTo() {
    TtlBucket firstBucket = new TtlBucket(0);
    TtlBucket secondBucket = new TtlBucket(0);
    TtlBucket thirdBucket = new TtlBucket(1);
    TtlBucket fourthBucket = new TtlBucket(2);

    Assert.assertEquals(0, firstBucket.compareTo(firstBucket));
    Assert.assertEquals(0, firstBucket.compareTo(secondBucket));
    Assert.assertEquals(0, secondBucket.compareTo(firstBucket));
    Assert.assertEquals(-1, firstBucket.compareTo(thirdBucket));
    Assert.assertEquals(1, fourthBucket.compareTo(firstBucket));
  }

  /**
   * Tests the {@link TtlBucket#equals(Object)} method.
   */
  @Test
  public void equals() {
    TtlBucket firstBucket = new TtlBucket(0);
    TtlBucket secondBucket = new TtlBucket(0);
    TtlBucket thirdBucket = new TtlBucket(1);

    Assert.assertNotEquals(firstBucket, null);
    Assert.assertEquals(firstBucket, firstBucket);
    Assert.assertEquals(firstBucket, secondBucket);
    Assert.assertEquals(secondBucket, firstBucket);
    Assert.assertNotEquals(firstBucket, thirdBucket);
  }

  /**
   * Tests the {@link TtlBucket#hashCode()} method.
   */
  @Test
  public void hashCodeTest() {
    TtlBucket firstBucket = new TtlBucket(0);
    TtlBucket secondBucket = new TtlBucket(0);
    TtlBucket thirdBucket = new TtlBucket(1);

    Assert.assertEquals(firstBucket.hashCode(), firstBucket.hashCode());
    Assert.assertEquals(firstBucket.hashCode(), secondBucket.hashCode());
    Assert.assertNotEquals(firstBucket.hashCode(), thirdBucket.hashCode());
  }
}


text:
package com.siondream.libgdxjam.overlap.plugins;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.utils.ObjectMap;
import com.siondream.libgdxjam.ecs.components.environment.DoorComponent;
import com.siondream.libgdxjam.overlap.OverlapScene;

public class DoorPlugin implements OverlapLoaderPlugin
{

	@Override
	public void load(OverlapScene scene, Entity entity,
			ObjectMap<String, String> map)
	{
		DoorComponent door = new DoorComponent();
		door.isOpen = false;
		door.id = Integer.parseInt(map.get("doorId", "0"));

		entity.add(door);
	}

}


text:
using System;
using RestRPC.Framework.Plugins;

namespace RestRPC.Service.Plugins
{
    class PrintToScreen : Plugin
    {
        public override object Respond(object[] args)
        {
            foreach (object arg in args)
            {
                Console.Write(arg.ToString());
            }
            Console.Write(Environment.NewLine);

            // Return true so that our client will be notified that the operation succeeded
            return true;
        }
    }
}


text:
package com.shaunchurch.androidpickings.example;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module
public class VehicleModule {

    @Provides @Singleton
    Motor provideMotor(){
        return new Motor();
    }

    @Provides @Singleton
    Vehicle provideVehicle(){
        return new Vehicle(new Motor());
    }

}


text:
namespace GammaJul.ReSharper.EnhancedTooltip.Presentation {

	public enum HighlighterIdSource {
		ReSharper,
		VisualStudio16, // VS 2019
		VisualStudio14, // VS 2015
		VisualStudioLegacy
	}

}


text:
package com.intuso.housemate.client.v1_0.real.impl.type;

import com.google.inject.Inject;
import com.intuso.housemate.client.v1_0.real.impl.ChildUtil;
import com.intuso.housemate.client.v1_0.real.impl.ioc.Type;
import com.intuso.utilities.collection.ManagedCollectionFactory;
import org.slf4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: tomc
 * Date: 01/05/14
 * Time: 08:51
 * To change this template use File | Settings | File Templates.
 */
public class EmailType extends RealRegexType {

    public final static String ID = "email";
    public final static String NAME = "Email";
    public final static String DESCRIPTION = "Email address of the form <username>@<host>";
    public final static String REGEX = ".+@.+\\..+";

    /**
     * @param managedCollectionFactory
     */
    @Inject
    public EmailType(@Type Logger logger,
                     ManagedCollectionFactory managedCollectionFactory) {
        super(ChildUtil.logger(logger, ID), ID, NAME, DESCRIPTION, REGEX, managedCollectionFactory);
    }
}


text:
package com.jivesoftware.os.miru.reco.plugins.uniques;

import com.jivesoftware.os.miru.plugin.partition.MiruPartitionUnavailableException;
import com.jivesoftware.os.miru.plugin.solution.MiruRequest;
import com.jivesoftware.os.miru.plugin.solution.MiruResponse;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.routing.bird.shared.ResponseHelper;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import static com.jivesoftware.os.miru.reco.plugins.uniques.UniquesConstants.CUSTOM_QUERY_ENDPOINT;
import static com.jivesoftware.os.miru.reco.plugins.uniques.UniquesConstants.UNIQUES_PREFIX;

@Singleton
@Path(UNIQUES_PREFIX)
public class UniquesEndpoints {

    private static final MetricLogger log = MetricLoggerFactory.getLogger();

    private final UniquesInjectable injectable;
    private final ResponseHelper responseHelper = ResponseHelper.INSTANCE;

    public UniquesEndpoints(@Context UniquesInjectable injectable) {
        this.injectable = injectable;
    }

    @POST
    @Path(CUSTOM_QUERY_ENDPOINT)
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response gatherUniques(MiruRequest<UniquesQuery> request) {
        try {
            long t = System.currentTimeMillis();
            MiruResponse<UniquesAnswer> response = injectable.gatherUniques(request);

            if (response.answer != null) {
                log.info("gatherUniques {}:{} in {}ms for tenant {}",
                        request.query.gatherUniquesForField,
                        response.answer.uniques,
                        System.currentTimeMillis() - t,
                        request.tenantId);
            } else {
                log.warn("gatherUniques: no answer for tenant {}", request.tenantId);
            }

            return responseHelper.jsonResponse(response);
        } catch (MiruPartitionUnavailableException | InterruptedException e) {
            return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Unavailable " + e.getMessage()).build();
        } catch (Exception e) {
            log.error("Failed to gather uniques.", e);
            return Response.serverError().build();
        }
    }

}


text:
<?php
namespace Directorzone\Model;

use Netsensia\Model\DatabaseTableModel;

class UserMessage extends DatabaseTableModel
{
    public function __construct()
    {
        $this->setTableName('usermessage');

        parent::__construct();

    }

    public function init($id = null)
    {
        $this->setPrimaryKey(array("usermessageid" => $id));
        if ($id != null) {
            $this->load();
        }
        return $this;
    }

    public function getUserMessageId()
    {
        $primaryKey = $this->getPrimaryKey();
        return $primaryKey['usermessageid'];
    }
}


text:
<?php

// Require the base class.
require_once __DIR__ . "/../BaseExample.php";

// Require the necessary utility class.
require_once __DIR__ . "/Utils/DateUtils.php";

/**
 * This example creates an insertion order under the given Display & Video 360
 * campaign.
 */
class CreateInsertionOrder extends BaseExample
{
    /**
     * (non-PHPdoc)
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters(): array
    {
        return array(
            array(
                'name' => 'advertiser_id',
                'display' => 'Advertiser ID',
                'required' => true
            ),
            array(
                'name' => 'campaign_id',
                'display' => 'Campaign ID',
                'required' => true
            ),
            array(
                'name' => 'display_name',
                'display' => 'Display Name',
                'required' => true
            )
        );
    }

    /**
     * (non-PHPdoc)
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $advertiserId = $values['advertiser_id'];
        $campaignId = $values['campaign_id'];
        $displayName = $values['display_name'];

        $insertionOrder = new Google_Service_DisplayVideo_InsertionOrder();
        $insertionOrder->setCampaignId($campaignId);
        $insertionOrder->setDisplayName($displayName);
        $insertionOrder->setEntityStatus('ENTITY_STATUS_DRAFT');

        $pacing = new Google_Service_DisplayVideo_Pacing();
        $pacing->setPacingPeriod('PACING_PERIOD_DAILY');
        $pacing->setPacingType('PACING_TYPE_EVEN');
        $pacing->setDailyMaxMicros(10000);
        $insertionOrder->setPacing($pacing);

        $frequencyCap = new Google_Service_DisplayVideo_FrequencyCap();
        $frequencyCap->setMaxImpressions(10);
        $frequencyCap->setTimeUnit('TIME_UNIT_DAYS');
        $frequencyCap->setTimeUnitCount(1);
        $insertionOrder->setFrequencyCap($frequencyCap);

        $performanceGoal = new Google_Service_DisplayVideo_PerformanceGoal();
        $performanceGoal->setPerformanceGoalType('PERFORMANCE_GOAL_TYPE_CPC');
        $performanceGoal->setPerformanceGoalAmountMicros(1000000);
        $insertionOrder->setPerformanceGoal($performanceGoal);

        $budget = new Google_Service_DisplayVideo_InsertionOrderBudget();
        $budget->setBudgetUnit('BUDGET_UNIT_CURRENCY');

        $budgetSegment =
            new Google_Service_DisplayVideo_InsertionOrderBudgetSegment();
        $budgetSegment->setBudgetAmountMicros(100000);
        $budgetSegment->setDateRange(DateUtils::createFutureDateRange());
        $budget->setBudgetSegments(array($budgetSegment));

        $insertionOrder->setBudget($budget);

        // Call the API, creating the insertion order under the advertiser and
        // campaign given.
        try {
            $result = $this->service->advertisers_insertionOrders->create(
                $advertiserId,
                $insertionOrder
            );
        } catch (\Exception $e) {
            $this->renderError($e);
            return;
        }

        printf('
Insertion Order %s was created.
', $result['name']);
    }

    /**
     * (non-PHPdoc)
     * @see BaseExample::getName()
     */
    public function getName(): string
    {
        return 'Create Insertion Order';
    }
}


text:
title: Made with love, tears, and bootstrap
banner: /img/banners/holyrood-park.jpg
---

I've rebuilt this site with a fresh new look for the summer browsing season.
Out with the old, in with the new. There was nothing inherently wrong about the
previous design, but I did have a few gripes. Chiefly, it was designed with a
"500px should be enough for anyone" attitude, which meant that on anything
except a 2013-resolution laptop display, the site was either too sparse or
poorly scaled:

![]({{ '/img/2017/revamp-old-site-home.png' | relative_url }})

A few days ago when I had a moment to burn I fired up
[Balsamiq](https://balsamiq.com/) and mocked up a tweaked design. First,
replacing the fixed-width content block with something that will scale, and
secondly ensure that the header doesn't become too unwieldy when squished down
to single column view on a phone:

However, I quickly realized that when you change one thing, you may as well go
ahead and tick all of the things off the wish list. So starting from a blank
slate I roughly sketched up a new design, doubling down on a complete overhaul
and opting for "hero image" branding:

I preferred that. The oversize banner would allow me to add a bit of visual
interest beyond that same repeated mugshot, and I have a stockpile of holiday
snaps that I've been trying to find a purpose for. However, as with any first
effort, it had some problems I needed to work through.

First among them was that the title was left floating in the top of the page,
and when compressed down to single column width would awkwardly sandwich my
name between the headline and the content. Also, right-side navigation is in-
vogue. Let's iterate:

Better. We'll put the title in the same block as the page content, and use the
floating text over the image as the site's navigation bar. I prefer this as it
adds emphasis to the two most important links on my site: my resume and
portfolio, which were a little under-emphasized in the old layout. Let's switch
to [OmniGraffle](https://www.omnigroup.com/omnigraffle/) for a high-fidelity
mockup:

![]({{ '/img/2017/revamp-mockup-home.png' | relative_url }})

After spending an hour or so on minor tweaks, I was happy and ready to
implement. I grabbed a copy of [Bootstrap](https://getbootstrap.com/) for the
scaffolding, then spent a couple of days building up a living implementation of
the mockups. The finished product is pretty true to the design that I  mocked
up, albeit with minor tweaks. Some side by side comparisons of OmniGraffle
mockup (left) and the actual site (right):

![]({{ '/img/2017/revamp-cv.png' | relative_url }})

![]({{ '/img/2017/revamp-blog.png' | relative_url }})

![]({{ '/img/2017/revamp-portfolio.png' | relative_url }})

Normally if I'm building a site I reach first for my text editor, and figure
out the design on-the-fly, so working towards a preconceived plan was a
refreshing change, and allowed me to focus more on the minor details. Not since
making [jusselme.com](http://barthelemyjusselme.com) in 2012 have I spent so
long iterating and refining the details, a few of which I particularly like
are:

* subtle animations: the right column acts as a navigation bar when the banner
  image is out of view. There's also a parallax behind the hero image because,
  you know, that's what all the kids are doing.
* more templating: all of the content for the resume and portfolio are stored
  in a single JSON file, programatically instantiated to generate the HTML.
  Additionally, all the links within the site are now generated by Jekyll,
  which allows me to do things like set a `baseurl` for hosting a staging site.
* page scaling: The transition from ultra large to tiny displays is incremental
  and fully accounted for. There are a number of small adjustments that page
  size is responsible for. E.g. dates next to titles "hang right" on desktop,
  but on narrow displays where real estate is limited, they slip under the
  title to make the most of limited screen width.

![]({{ '/img/2017/revamp-mobile.png' | relative_url }})

I'm pretty happy with this new design, and if it holds up like the previous
one, then it should comfortably see me through to the end of the decade. If you
find a bug or would like to suggest a change please do [let me know](https://github.com/ChrisCummins/chriscummins.github.io/issues). And of
course, as always, the source code for this design is [free software](https://tldrlegal.com/license/mit-license).


text:
module.exports = function stdin(callback, notBlankMessage) {
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.once('data', function (data) {
    process.stdin.pause();
    data = data.toString().trim();
    if (data == '' && notBlankMessage) {
      console.log(notBlankMessage);
      stdin(callback, notBlankMessage);
    } else {
      callback(data);
    }
  });
};


text:
package org.apache.ws.scout.registry.qa;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.xml.registry.BulkResponse;
import javax.xml.registry.BusinessQueryManager;
import javax.xml.registry.FindQualifier;
import javax.xml.registry.JAXRException;
import javax.xml.registry.JAXRResponse;
import javax.xml.registry.RegistryService;
import javax.xml.registry.infomodel.Association;
import javax.xml.registry.infomodel.Concept;
import javax.xml.registry.infomodel.Key;
import javax.xml.registry.infomodel.Organization;
import javax.xml.registry.infomodel.RegistryObject;

import junit.framework.JUnit4TestAdapter;

import org.apache.ws.scout.BaseTestCase;
import org.apache.ws.scout.Creator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests Publish, Delete (and indirectly, find) for associations.
 *
 * You can comment out the deletion portion and use Open source UDDI Browser
 * <http://www.uddibrowser.org> to check your intermediate results.
 *
 * Based on query/publish tests written by Anil
 * Saldhana.
 *
 * @author Deepak Bhole
 * @author Anil Saldhana
 *
 * @since Sep 27, 2005
 */
public class JAXR030AssociationsTest extends BaseTestCase {

	private BusinessQueryManager bqm = null;

	String associationType = "AssociationType/RelatedTo";
	private static String tempSrcOrgName = "Apache Source Org -- APACHE SCOUT TEST";
	private static String tempTgtOrgName = "Apache Target Org -- APACHE SCOUT TEST";

	private Organization sOrg=null;
	private Organization tOrg=null;

    @Before
	public void setUp() {
		super.setUp();
	}

    @After
	public void tearDown() {
		super.tearDown();
	}

	/**
	 * Tests publishing and deleting of associations.
	 *
	 * Do not break this into testPublish(), testDelete(), etc. Order is
	 * important, and not all jvms can guarantee order since the JUnit framework
	 * uses getMethods() to gather test methods, and getMethods() does not
	 * guarantee order.
	 */
    @Test
	public void testPublishFindAndDeleteAssociation() {
		login();

		try {

			RegistryService rs = connection.getRegistryService();
			bqm = rs.getBusinessQueryManager();
			blm = rs.getBusinessLifeCycleManager();

			//deleting any pre-exisiting organizations
			ArrayList<Organization> orgs = findTempOrgs();
			for (Organization organization : orgs) {
				Collection<Key> keys = new ArrayList<Key>();
				keys.add(organization.getKey());
				blm.deleteOrganizations(keys);
			}

            Creator creator = new Creator(blm);

			System.out.println("\nCreating temporary organizations...\n");
            Organization org1 = creator.createOrganization(tempSrcOrgName);
            Organization org2 = creator.createOrganization(tempTgtOrgName);
            Collection<Organization> organizations = new ArrayList<Organization>();
            organizations.add(org1);
            organizations.add(org2);
            blm.saveOrganizations(organizations);

			System.out.println("\nSearching for newly created organizations...\n");
			ArrayList<Organization> newOrgs = findTempOrgs();
                        Assert.assertEquals(2, newOrgs.size());
			sOrg = newOrgs.get(0);
			tOrg = newOrgs.get(1);

			System.out.println("\nCreating association...\n");
			createAssociation(sOrg, tOrg);

			// All created ... now try to delete.
			String associationID = findAndDeleteAssociation();

			//Let us look for associations now
			BulkResponse associationResp =
				bqm.findCallerAssociations(null, Boolean.TRUE, Boolean.TRUE, null);

			if(associationResp.getExceptions() != null)
			{
				System.out.println(associationResp.getExceptions());
				fail("Association lookup failed");
			}
			else
			{
				Collection retAssocs = associationResp.getCollection();
                if (retAssocs.size() == 0)
                {
                    //Pass
                } else
                {
                   Iterator iterAss = retAssocs.iterator();
                   while(iterAss.hasNext())
                   {
                      Association assc = (Association) iterAss.next();
                      if(assc.getKey().getId().equals(associationID)) {
                    	  System.out.println("found: " + associationID);
                          fail("Deleted Association found");
                      }
                   }
                }
			}

		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	private void createAssociation(Organization sOrg, Organization tOrg)
			throws JAXRException {

		Concept type = bqm.findConceptByPath(associationType);
		Association association = blm.createAssociation(tOrg, type);
		sOrg.addAssociation(association);

		ArrayList<Association> associations = new ArrayList<Association>();
		associations.add(association);

		BulkResponse br = blm.saveAssociations(associations, true);
		if (br.getStatus() == JAXRResponse.STATUS_SUCCESS) {
			System.out.println("Association Saved");
			Collection coll = br.getCollection();
			Iterator iter = coll.iterator();
			while (iter.hasNext()) {
				System.out.println("Saved Key=" + iter.next());
			}// end while
		} else {
			System.err.println("JAXRExceptions " + "occurred during save:");
			Collection exceptions = br.getExceptions();
			Iterator iter = exceptions.iterator();
			while (iter.hasNext()) {
				Exception e = (Exception) iter.next();
				System.err.println(e.toString());
			}
            deleteTempOrgs();
		}
	}

	private String findAndDeleteAssociation() throws JAXRException {

		String id = null;

		String sOrgID = sOrg.getKey().getId();
		String tOrgID = tOrg.getKey().getId();

		Collection<String> findQualifiers = new ArrayList<String>();
		findQualifiers.add(FindQualifier.SORT_BY_NAME_ASC);

		Concept type = bqm.findConceptByPath(associationType);
		ArrayList<Concept> conceptTypes = new ArrayList<Concept>(1);
		conceptTypes.add(type);

		BulkResponse br = bqm.findAssociations(findQualifiers, sOrgID, tOrgID,
				conceptTypes);
		Collection associations = br.getCollection();

		if (associations == null) {
			System.out.println("\n-- Matched 0 orgs");
            fail("Expected 1 association");

		} else {
			System.out.println("\n-- Matched " + associations.size()
					+ " associations --\n");
            assertEquals(1,associations.size());

			// then step through them
			for (Iterator conceptIter = associations.iterator(); conceptIter
					.hasNext();) {
				Association a = (Association) conceptIter.next();

				System.out.println("Id: " + a.getKey().getId());
				System.out.println("Name: " + a.getName().getValue());

				// Print spacer between messages
				System.out.println(" --- ");

				id = a.getKey().getId();
				deleteAssociation(a.getKey());

				System.out.println("\n ============================== \n");
			}
		}
		return id;
	}

	private void deleteAssociation(Key key) throws JAXRException {

		String id = key.getId();

		System.out.println("\nDeleting association with id " + id + "\n");

		Collection<Key> keys = new ArrayList<Key>();
		keys.add(key);
		BulkResponse response = blm.deleteAssociations(keys);

        assertEquals(BulkResponse.STATUS_SUCCESS, response.getStatus());
		Collection exceptions = response.getExceptions();
		if (exceptions == null) {
			Collection retKeys = response.getCollection();
			Iterator keyIter = retKeys.iterator();
			javax.xml.registry.infomodel.Key orgKey = null;
			if (keyIter.hasNext()) {
				orgKey = (javax.xml.registry.infomodel.Key) keyIter.next();
				id = orgKey.getId();
				System.out
						.println("Association with ID=" + id + " was deleted");
			}
		}
	}

	private ArrayList<Organization> findTempOrgs() throws JAXRException {

		ArrayList<Organization> toReturn = new ArrayList<Organization>();

		// Define find qualifiers and name patterns
		Collection<String> findQualifiers = new ArrayList<String>();
		findQualifiers.add(FindQualifier.SORT_BY_NAME_ASC);
		Collection<String> namePatterns = new ArrayList<String>();
		if ("3.0".equals(uddiversion)) {
			namePatterns.add(tempSrcOrgName);
			namePatterns.add(tempTgtOrgName);
		} else {
			namePatterns.add("%" + tempSrcOrgName + "%");
			namePatterns.add("%" + tempTgtOrgName + "%");
		}
		// Find based upon qualifier type and values
		System.out.println("\n-- searching the registry --\n");
		BulkResponse response = bqm.findOrganizations(findQualifiers,
				namePatterns, null, null, null, null);

		// check how many organisation we have matched
		Collection orgs = response.getCollection();
		if (orgs == null) {
			System.out.println("\n-- Matched 0 orgs");

		} else {
			System.out.println("\n-- Matched " + orgs.size()
					+ " organisations --\n");

			// then step through them
			for (Iterator orgIter = orgs.iterator(); orgIter.hasNext();) {
				Organization org = (Organization) orgIter.next();

				System.out.println("Org name: " + getName(org));
				System.out.println("Org description: " + getDescription(org));
				System.out.println("Org key id: " + getKey(org));

				if (getName(org).indexOf(tempSrcOrgName) > -1) {
					toReturn.add(0, org);
				} else {
					toReturn.add(1, org);
				}

				// Print spacer between organizations
				System.out.println("\n ============================== \n");
			}
		}// end else

		return toReturn;
	}

	private void deleteTempOrgs() {

		try {

			Key sOrgKey = sOrg.getKey();
			Key tOrgKey = tOrg.getKey();

			System.out.println("\nDeleting temporary organizations with ids "
					+ sOrgKey + " and " + tOrgKey + "\n");

			Collection<Key> keys = new ArrayList<Key>();
			keys.add(sOrgKey);
			keys.add(tOrgKey);
			BulkResponse response = blm.deleteOrganizations(keys);

			Collection exceptions = response.getExceptions();
			if (exceptions == null) {
				Collection retKeys = response.getCollection();
				Iterator keyIter = retKeys.iterator();
				Key orgKey = null;
				while (keyIter.hasNext()) {
					orgKey = (javax.xml.registry.infomodel.Key) keyIter.next();
					String id = orgKey.getId();
					System.out.println("Organization with ID=" + id
							+ " was deleted");
				}
			}
		} catch (JAXRException jaxre) {
			jaxre.printStackTrace();
		}
	}

	private static String getName(RegistryObject ro) throws JAXRException {
		if (ro != null && ro.getName() != null) {
			return ro.getName().getValue();
		}
		return "";
	}

	private static String getDescription(RegistryObject ro)
			throws JAXRException {
		if (ro != null && ro.getDescription() != null) {
			return ro.getDescription().getValue();
		}
		return "";
	}

	private static String getKey(RegistryObject ro) throws JAXRException {
		if (ro != null && ro.getKey() != null) {
			return ro.getKey().getId();
		}
		return "";
	}

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(JAXR030AssociationsTest.class);
    }
}


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

<title>AddServiceController</title>
<meta name="date" content="2015-12-11">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ca.ualberta.cs.xpertsapp.controllers

Class AddServiceController

java.lang.Object

ca.ualberta.cs.xpertsapp.controllers.AddServiceController

public class AddServiceController
extends java.lang.Object

This controller communicates with  AddServiceActivity  and the model

Constructor Summary

Constructors

Constructor and Description

AddServiceController()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addService(android.widget.EditText title,
          android.widget.EditText description,
          Category category,
          android.widget.CheckBox isPrivate,
          java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information and converts it into a Service object in the database

void
cloneService(java.lang.String title,
            java.lang.String description,
            Category category,
            java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information and converts it into a Service object in the database

void
deleteService(java.lang.String id)

This function deletes a selected service

void
editService(android.widget.EditText title,
           android.widget.EditText description,
           Category category,
           android.widget.CheckBox isPrivate,
           java.lang.String id,
           java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information from the  AddServiceActivity  and converts it into a service object in the database

Methods inherited from class java.lang.Object

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

Constructor Detail

AddServiceController

public AddServiceController()

Method Detail

addService

public void addService(android.widget.EditText title,
                       android.widget.EditText description,
                       Category category,
                       android.widget.CheckBox isPrivate,
                       java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information and converts it into a Service object in the database

Parameters:

title - this is the string value of the Service's title passed as a EditText from the AddServiceActivity there are no character restrictions. Ex "Write JavaDoc"

description - this is a description of the service passed as an EditText from the  AddServiceActivity  that a user writes to better describe the service to other users. Ex "I write excellent JavaDoc for java projects. This includes descriptions and examples of different variables and functions. And I don't forget about runime."

category - is the category of a Service. Category objects are used by User's to better focus their search results.Category objects have a string title. Ex "Computers"

isPrivate - is the setting that allows a user to keep a Service unsearchable by other Users. It is passed as a CheckBox from  AddServiceActivity . For example User Bob might want to keep his "Write JavaDoc" private because it is highly in demand. This way he isn't spammed by 301 students but is still able to offer his service to other User's who have a service that he wants.

cloneService

public void cloneService(java.lang.String title,
                         java.lang.String description,
                         Category category,
                         java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information and converts it into a Service object in the database

Parameters:

title - this is the string value of the Service's title passed as a EditText

description - this is a description of the service passed as an EditText

category - is the category of a Service.

editService

public void editService(android.widget.EditText title,
                        android.widget.EditText description,
                        Category category,
                        android.widget.CheckBox isPrivate,
                        java.lang.String id,
                        java.util.List<android.graphics.Bitmap> pictures)

This function takes the inputted information from the  AddServiceActivity  and converts it into a service object in the database

Parameters:

title - see above

description - "" ""

category - "" ""

isPrivate - "" ""

id - this is the existing service ID of the Service which is being edited. This is used to edit information instead of creating a new Service.

deleteService

public void deleteService(java.lang.String id)

This function deletes a selected service

Parameters:

id - This is the service ID of the service which is being deleted

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require 'test_helper'

module Lit
  class LocalesControllerTest < ActionController::TestCase
    setup do
      @routes = Lit::Engine.routes

      Lit.authentication_function = nil
      @locale = Locale.first_or_create(locale: 'en')
    end

    test 'should get index' do
      get :index
      assert_response :success
      assert_not_nil assigns(:locales)
    end

    test 'should hide locale' do
      put :hide, id: @locale, locale: {}, format: :js
      assert assigns(:locale).is_hidden?
    end

    test 'should destroy locale' do
      assert_difference('Locale.count', -1) do
        delete :destroy, id: @locale
      end
    end
  end
end


text:
(function () {
  'use strict';

  angular
    .module('likes.admin')
    .controller('LikesAdminListController', LikesAdminListController);

  LikesAdminListController.$inject = ['LikesService'];

  function LikesAdminListController(LikesService) {
    var vm = this;

    vm.likes = LikesService.query();
  }
}());


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Subscription',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('cpf', models.CharField(max_length=11)),
                ('email', models.EmailField(max_length=75)),
                ('phone', models.CharField(max_length=20)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
            ],
        ),
    ]


text:
appleproject
============

Coding exercises all about apples.


text:
/*
 * Licensed Materials - Property of IBM
 * RMI-IIOP v1.0
 * Copyright IBM Corp. 1998 1999  All Rights Reserved
 *
 */

package org.omg.SendingContext;

/** Defines the base class that represents the Sending Context of a
* request.  The sending context provides access to information about
* the runtime environment of the originator of a GIOP message.  For example,
* when a value type is marshalled on a GIOP Request message, the receiver
* of the value type may need to ask the sender about the CodeBase for the
* implementation of the value type.
*/
public interface RunTime extends RunTimeOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
}


text:
class UpdateBtcTxStatusJob < ApplicationJob
  queue_as :default

  def perform(*_args)
    BtcTx.where(confirmation_status: 'pending').each(&:check_status)
  end
end


text:
namespace trace_api = opentelemetry::trace;
namespace trace_sdk = opentelemetry::sdk::trace;

OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{

std::unique_ptr<trace_api::TracerProvider> TracerProviderFactory::Create(
    std::unique_ptr<SpanProcessor> processor)
{
  auto resource = opentelemetry::sdk::resource::Resource::Create({});
  return Create(std::move(processor), resource);
}

std::unique_ptr<trace_api::TracerProvider> TracerProviderFactory::Create(
    std::unique_ptr<SpanProcessor> processor,
    const opentelemetry::sdk::resource::Resource &resource)
{
  auto sampler = AlwaysOnSamplerFactory::Create();
  return Create(std::move(processor), resource, std::move(sampler));
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::unique_ptr<SpanProcessor> processor,
    const opentelemetry::sdk::resource::Resource &resource,
    std::unique_ptr<Sampler> sampler)
{
  auto id_generator = RandomIdGeneratorFactory::Create();
  return Create(std::move(processor), resource, std::move(sampler), std::move(id_generator));
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::unique_ptr<SpanProcessor> processor,
    const opentelemetry::sdk::resource::Resource &resource,
    std::unique_ptr<Sampler> sampler,
    std::unique_ptr<IdGenerator> id_generator)
{
  std::unique_ptr<trace_api::TracerProvider> provider(new trace_sdk::TracerProvider(
      std::move(processor), resource, std::move(sampler), std::move(id_generator)));
  return provider;
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::vector<std::unique_ptr<SpanProcessor>> &&processors)
{
  auto resource = opentelemetry::sdk::resource::Resource::Create({});
  return Create(std::move(processors), resource);
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::vector<std::unique_ptr<SpanProcessor>> &&processors,
    const opentelemetry::sdk::resource::Resource &resource)
{
  auto sampler = AlwaysOnSamplerFactory::Create();
  return Create(std::move(processors), resource, std::move(sampler));
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::vector<std::unique_ptr<SpanProcessor>> &&processors,
    const opentelemetry::sdk::resource::Resource &resource,
    std::unique_ptr<Sampler> sampler)
{
  auto id_generator = RandomIdGeneratorFactory::Create();
  return Create(std::move(processors), resource, std::move(sampler), std::move(id_generator));
}

std::unique_ptr<opentelemetry::trace::TracerProvider> TracerProviderFactory::Create(
    std::vector<std::unique_ptr<SpanProcessor>> &&processors,
    const opentelemetry::sdk::resource::Resource &resource,
    std::unique_ptr<Sampler> sampler,
    std::unique_ptr<IdGenerator> id_generator)
{
  std::unique_ptr<trace_api::TracerProvider> provider(new trace_sdk::TracerProvider(
      std::move(processors), resource, std::move(sampler), std::move(id_generator)));
  return provider;
}

std::unique_ptr<trace_api::TracerProvider> TracerProviderFactory::Create(
    std::shared_ptr<sdk::trace::TracerContext> context)
{
  std::unique_ptr<trace_api::TracerProvider> provider(new trace_sdk::TracerProvider(context));
  return provider;
}

}  // namespace trace
}  // namespace sdk
OPENTELEMETRY_END_NAMESPACE


text:
// Copyright 2009 Google Inc. All Rights Reserved.

package com.google.test.metric.report.issues;

import com.google.test.metric.CostUtil;

/**
 * a simple class with cost in a setter
 * @author alexeagle@google.com (Alex Eagle)
 */
public class HasSetterCost {
  public void setFoo(int foo) {
    new CostUtil().instanceCost4();
  }
}


text:
#include "third_party/blink/renderer/core/svg/svg_fe_displacement_map_element.h"

#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
#include "third_party/blink/renderer/core/svg/svg_animated_number.h"
#include "third_party/blink/renderer/core/svg/svg_animated_string.h"
#include "third_party/blink/renderer/core/svg/svg_enumeration_map.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"

namespace blink {

template <>
const SVGEnumerationMap& GetEnumerationMap<ChannelSelectorType>() {
  static const SVGEnumerationMap::Entry enum_items[] = {
      {CHANNEL_R, "R"}, {CHANNEL_G, "G"}, {CHANNEL_B, "B"}, {CHANNEL_A, "A"},
  };
  static const SVGEnumerationMap entries(enum_items);
  return entries;
}

SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(Document& document)
    : SVGFilterPrimitiveStandardAttributes(svg_names::kFEDisplacementMapTag,
                                           document),
      scale_(MakeGarbageCollected<SVGAnimatedNumber>(this,
                                                     svg_names::kScaleAttr,
                                                     0.0f)),
      in1_(MakeGarbageCollected<SVGAnimatedString>(this, svg_names::kInAttr)),
      in2_(MakeGarbageCollected<SVGAnimatedString>(this, svg_names::kIn2Attr)),
      x_channel_selector_(
          MakeGarbageCollected<SVGAnimatedEnumeration<ChannelSelectorType>>(
              this,
              svg_names::kXChannelSelectorAttr,
              CHANNEL_A)),
      y_channel_selector_(
          MakeGarbageCollected<SVGAnimatedEnumeration<ChannelSelectorType>>(
              this,
              svg_names::kYChannelSelectorAttr,
              CHANNEL_A)) {
  AddToPropertyMap(scale_);
  AddToPropertyMap(in1_);
  AddToPropertyMap(in2_);
  AddToPropertyMap(x_channel_selector_);
  AddToPropertyMap(y_channel_selector_);
}

void SVGFEDisplacementMapElement::Trace(Visitor* visitor) const {
  visitor->Trace(scale_);
  visitor->Trace(in1_);
  visitor->Trace(in2_);
  visitor->Trace(x_channel_selector_);
  visitor->Trace(y_channel_selector_);
  SVGFilterPrimitiveStandardAttributes::Trace(visitor);
}

bool SVGFEDisplacementMapElement::SetFilterEffectAttribute(
    FilterEffect* effect,
    const QualifiedName& attr_name) {
  FEDisplacementMap* displacement_map = static_cast<FEDisplacementMap*>(effect);
  if (attr_name == svg_names::kXChannelSelectorAttr) {
    return displacement_map->SetXChannelSelector(
        x_channel_selector_->CurrentEnumValue());
  }
  if (attr_name == svg_names::kYChannelSelectorAttr) {
    return displacement_map->SetYChannelSelector(
        y_channel_selector_->CurrentEnumValue());
  }
  if (attr_name == svg_names::kScaleAttr)
    return displacement_map->SetScale(scale_->CurrentValue()->Value());

  return SVGFilterPrimitiveStandardAttributes::SetFilterEffectAttribute(
      effect, attr_name);
}

void SVGFEDisplacementMapElement::SvgAttributeChanged(
    const SvgAttributeChangedParams& params) {
  const QualifiedName& attr_name = params.name;
  if (attr_name == svg_names::kXChannelSelectorAttr ||
      attr_name == svg_names::kYChannelSelectorAttr ||
      attr_name == svg_names::kScaleAttr) {
    SVGElement::InvalidationGuard invalidation_guard(this);
    PrimitiveAttributeChanged(attr_name);
    return;
  }

  if (attr_name == svg_names::kInAttr || attr_name == svg_names::kIn2Attr) {
    SVGElement::InvalidationGuard invalidation_guard(this);
    Invalidate();
    return;
  }

  SVGFilterPrimitiveStandardAttributes::SvgAttributeChanged(params);
}

FilterEffect* SVGFEDisplacementMapElement::Build(
    SVGFilterBuilder* filter_builder,
    Filter* filter) {
  FilterEffect* input1 = filter_builder->GetEffectById(
      AtomicString(in1_->CurrentValue()->Value()));
  FilterEffect* input2 = filter_builder->GetEffectById(
      AtomicString(in2_->CurrentValue()->Value()));
  DCHECK(input1);
  DCHECK(input2);

  auto* effect = MakeGarbageCollected<FEDisplacementMap>(
      filter, x_channel_selector_->CurrentEnumValue(),
      y_channel_selector_->CurrentEnumValue(), scale_->CurrentValue()->Value());
  FilterEffectVector& input_effects = effect->InputEffects();
  input_effects.reserve(2);
  input_effects.push_back(input1);
  input_effects.push_back(input2);
  return effect;
}

}  // namespace blink


text:
package org.apache.beam.runners.spark.translation;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static org.apache.beam.runners.spark.translation.TranslationUtils.avoidRddSerialization;

import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.beam.runners.core.SystemReduceFn;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.metrics.MetricsContainerStepMap;
import org.apache.beam.runners.spark.SparkPipelineOptions;
import org.apache.beam.runners.spark.aggregators.AggregatorsAccumulator;
import org.apache.beam.runners.spark.aggregators.NamedAggregators;
import org.apache.beam.runners.spark.coders.CoderHelpers;
import org.apache.beam.runners.spark.io.SourceRDD;
import org.apache.beam.runners.spark.metrics.MetricsAccumulator;
import org.apache.beam.runners.spark.util.SideInputBroadcast;
import org.apache.beam.sdk.coders.CannotProvideCoderException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.IterableCoder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.CombineWithContext;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.Flatten;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Reshuffle;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature;
import org.apache.beam.sdk.transforms.reflect.DoFnSignatures;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.transforms.windowing.WindowFn;
import org.apache.beam.sdk.util.CombineFnUtil;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.PValue;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.WindowingStrategy;
import org.apache.spark.Accumulator;
import org.apache.spark.HashPartitioner;
import org.apache.spark.Partitioner;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.storage.StorageLevel;

/** Supports translation between a Beam transform, and Spark's operations on RDDs. */
public final class TransformTranslator {

  private TransformTranslator() {}

  private static <T> TransformEvaluator<Flatten.PCollections<T>> flattenPColl() {
    return new TransformEvaluator<Flatten.PCollections<T>>() {
      @SuppressWarnings("unchecked")
      @Override
      public void evaluate(Flatten.PCollections<T> transform, EvaluationContext context) {
        Collection<PValue> pcs = context.getInputs(transform).values();
        JavaRDD<WindowedValue<T>> unionRDD;
        if (pcs.isEmpty()) {
          unionRDD = context.getSparkContext().emptyRDD();
        } else {
          JavaRDD<WindowedValue<T>>[] rdds = new JavaRDD[pcs.size()];
          int index = 0;
          for (PValue pc : pcs) {
            checkArgument(
                pc instanceof PCollection,
                "Flatten had non-PCollection value in input: %s of type %s",
                pc,
                pc.getClass().getSimpleName());
            rdds[index] = ((BoundedDataset<T>) context.borrowDataset(pc)).getRDD();
            index++;
          }
          unionRDD = context.getSparkContext().union(rdds);
        }
        context.putDataset(transform, new BoundedDataset<>(unionRDD));
      }

      @Override
      public String toNativeString() {
        return "sparkContext.union(...)";
      }
    };
  }

  private static <K, V, W extends BoundedWindow> TransformEvaluator<GroupByKey<K, V>> groupByKey() {
    return new TransformEvaluator<GroupByKey<K, V>>() {
      @Override
      public void evaluate(GroupByKey<K, V> transform, EvaluationContext context) {
        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<KV<K, V>>> inRDD =
            ((BoundedDataset<KV<K, V>>) context.borrowDataset(transform)).getRDD();
        @SuppressWarnings("unchecked")
        final KvCoder<K, V> coder = (KvCoder<K, V>) context.getInput(transform).getCoder();
        final Accumulator<NamedAggregators> accum = AggregatorsAccumulator.getInstance();
        @SuppressWarnings("unchecked")
        final WindowingStrategy<?, W> windowingStrategy =
            (WindowingStrategy<?, W>) context.getInput(transform).getWindowingStrategy();
        @SuppressWarnings("unchecked")
        final WindowFn<Object, W> windowFn = (WindowFn<Object, W>) windowingStrategy.getWindowFn();

        // --- coders.
        final Coder<K> keyCoder = coder.getKeyCoder();
        final WindowedValue.WindowedValueCoder<V> wvCoder =
            WindowedValue.FullWindowedValueCoder.of(coder.getValueCoder(), windowFn.windowCoder());

        // --- group by key only.
        Long bundleSize =
            context.getSerializableOptions().get().as(SparkPipelineOptions.class).getBundleSize();
        Partitioner partitioner =
            (bundleSize > 0)
                ? new HashPartitioner(context.getSparkContext().defaultParallelism())
                : null;
        JavaRDD<WindowedValue<KV<K, Iterable<WindowedValue<V>>>>> groupedByKey =
            GroupCombineFunctions.groupByKeyOnly(inRDD, keyCoder, wvCoder, partitioner);

        // --- now group also by window.
        // for batch, GroupAlsoByWindow uses an in-memory StateInternals.
        JavaRDD<WindowedValue<KV<K, Iterable<V>>>> groupedAlsoByWindow =
            groupedByKey.flatMap(
                new SparkGroupAlsoByWindowViaOutputBufferFn<>(
                    windowingStrategy,
                    new TranslationUtils.InMemoryStateInternalsFactory<>(),
                    SystemReduceFn.buffering(coder.getValueCoder()),
                    context.getSerializableOptions(),
                    accum));

        context.putDataset(transform, new BoundedDataset<>(groupedAlsoByWindow));
      }

      @Override
      public String toNativeString() {
        return "groupByKey()";
      }
    };
  }

  private static <K, InputT, OutputT>
      TransformEvaluator<Combine.GroupedValues<K, InputT, OutputT>> combineGrouped() {
    return new TransformEvaluator<Combine.GroupedValues<K, InputT, OutputT>>() {
      @Override
      public void evaluate(
          Combine.GroupedValues<K, InputT, OutputT> transform, EvaluationContext context) {
        @SuppressWarnings("unchecked")
        CombineWithContext.CombineFnWithContext<InputT, ?, OutputT> combineFn =
            (CombineWithContext.CombineFnWithContext<InputT, ?, OutputT>)
                CombineFnUtil.toFnWithContext(transform.getFn());
        final SparkKeyedCombineFn<K, InputT, ?, OutputT> sparkCombineFn =
            new SparkKeyedCombineFn<>(
                combineFn,
                context.getSerializableOptions(),
                TranslationUtils.getSideInputs(transform.getSideInputs(), context),
                context.getInput(transform).getWindowingStrategy());

        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<KV<K, Iterable<InputT>>>> inRDD =
            ((BoundedDataset<KV<K, Iterable<InputT>>>) context.borrowDataset(transform)).getRDD();

        JavaRDD<WindowedValue<KV<K, OutputT>>> outRDD =
            inRDD.map(
                in ->
                    WindowedValue.of(
                        KV.of(in.getValue().getKey(), sparkCombineFn.apply(in)),
                        in.getTimestamp(),
                        in.getWindows(),
                        in.getPane()));
        context.putDataset(transform, new BoundedDataset<>(outRDD));
      }

      @Override
      public String toNativeString() {
        return "map(new <fn>())";
      }
    };
  }

  private static <InputT, AccumT, OutputT>
      TransformEvaluator<Combine.Globally<InputT, OutputT>> combineGlobally() {
    return new TransformEvaluator<Combine.Globally<InputT, OutputT>>() {

      @Override
      public void evaluate(Combine.Globally<InputT, OutputT> transform, EvaluationContext context) {
        final PCollection<InputT> input = context.getInput(transform);
        final Coder<InputT> iCoder = context.getInput(transform).getCoder();
        final Coder<OutputT> oCoder = context.getOutput(transform).getCoder();
        final WindowingStrategy<?, ?> windowingStrategy = input.getWindowingStrategy();
        @SuppressWarnings("unchecked")
        final CombineWithContext.CombineFnWithContext<InputT, AccumT, OutputT> combineFn =
            (CombineWithContext.CombineFnWithContext<InputT, AccumT, OutputT>)
                CombineFnUtil.toFnWithContext(transform.getFn());
        final WindowedValue.FullWindowedValueCoder<OutputT> wvoCoder =
            WindowedValue.FullWindowedValueCoder.of(
                oCoder, windowingStrategy.getWindowFn().windowCoder());
        final boolean hasDefault = transform.isInsertDefault();

        final SparkGlobalCombineFn<InputT, AccumT, OutputT> sparkCombineFn =
            new SparkGlobalCombineFn<>(
                combineFn,
                context.getSerializableOptions(),
                TranslationUtils.getSideInputs(transform.getSideInputs(), context),
                windowingStrategy);
        final Coder<AccumT> aCoder;
        try {
          aCoder = combineFn.getAccumulatorCoder(context.getPipeline().getCoderRegistry(), iCoder);
        } catch (CannotProvideCoderException e) {
          throw new IllegalStateException("Could not determine coder for accumulator", e);
        }

        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<InputT>> inRdd =
            ((BoundedDataset<InputT>) context.borrowDataset(transform)).getRDD();

        JavaRDD<WindowedValue<OutputT>> outRdd;

        Optional<Iterable<WindowedValue<AccumT>>> maybeAccumulated =
            GroupCombineFunctions.combineGlobally(
                inRdd, sparkCombineFn, iCoder, aCoder, windowingStrategy);

        if (maybeAccumulated.isPresent()) {
          Iterable<WindowedValue<OutputT>> output =
              sparkCombineFn.extractOutput(maybeAccumulated.get());
          outRdd =
              context
                  .getSparkContext()
                  .parallelize(CoderHelpers.toByteArrays(output, wvoCoder))
                  .map(CoderHelpers.fromByteFunction(wvoCoder));
        } else {
          // handle empty input RDD, which will naturally skip the entire execution
          // as Spark will not run on empty RDDs.
          JavaSparkContext jsc = new JavaSparkContext(inRdd.context());
          if (hasDefault) {
            OutputT defaultValue = combineFn.defaultValue();
            outRdd =
                jsc.parallelize(Lists.newArrayList(CoderHelpers.toByteArray(defaultValue, oCoder)))
                    .map(CoderHelpers.fromByteFunction(oCoder))
                    .map(WindowingHelpers.windowFunction());
          } else {
            outRdd = jsc.emptyRDD();
          }
        }

        context.putDataset(transform, new BoundedDataset<>(outRdd));
      }

      @Override
      public String toNativeString() {
        return "aggregate(..., new <fn>(), ...)";
      }
    };
  }

  private static <K, InputT, AccumT, OutputT>
      TransformEvaluator<Combine.PerKey<K, InputT, OutputT>> combinePerKey() {
    return new TransformEvaluator<Combine.PerKey<K, InputT, OutputT>>() {
      @Override
      public void evaluate(
          Combine.PerKey<K, InputT, OutputT> transform, EvaluationContext context) {
        final PCollection<KV<K, InputT>> input = context.getInput(transform);
        // serializable arguments to pass.
        @SuppressWarnings("unchecked")
        final KvCoder<K, InputT> inputCoder =
            (KvCoder<K, InputT>) context.getInput(transform).getCoder();
        @SuppressWarnings("unchecked")
        final CombineWithContext.CombineFnWithContext<InputT, AccumT, OutputT> combineFn =
            (CombineWithContext.CombineFnWithContext<InputT, AccumT, OutputT>)
                CombineFnUtil.toFnWithContext(transform.getFn());
        final WindowingStrategy<?, ?> windowingStrategy = input.getWindowingStrategy();
        final Map<TupleTag<?>, KV<WindowingStrategy<?, ?>, SideInputBroadcast<?>>> sideInputs =
            TranslationUtils.getSideInputs(transform.getSideInputs(), context);
        final SparkKeyedCombineFn<K, InputT, AccumT, OutputT> sparkCombineFn =
            new SparkKeyedCombineFn<>(
                combineFn, context.getSerializableOptions(), sideInputs, windowingStrategy);
        final Coder<AccumT> vaCoder;
        try {
          vaCoder =
              combineFn.getAccumulatorCoder(
                  context.getPipeline().getCoderRegistry(), inputCoder.getValueCoder());
        } catch (CannotProvideCoderException e) {
          throw new IllegalStateException("Could not determine coder for accumulator", e);
        }

        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<KV<K, InputT>>> inRdd =
            ((BoundedDataset<KV<K, InputT>>) context.borrowDataset(transform)).getRDD();

        JavaPairRDD<K, Iterable<WindowedValue<KV<K, AccumT>>>> accumulatePerKey =
            GroupCombineFunctions.combinePerKey(
                inRdd,
                sparkCombineFn,
                inputCoder.getKeyCoder(),
                inputCoder.getValueCoder(),
                vaCoder,
                windowingStrategy);

        JavaRDD<WindowedValue<KV<K, OutputT>>> outRdd =
            accumulatePerKey
                .flatMapValues(sparkCombineFn::extractOutput)
                .map(TranslationUtils.fromPairFunction())
                .map(TranslationUtils.toKVByWindowInValue());

        context.putDataset(transform, new BoundedDataset<>(outRdd));
      }

      @Override
      public String toNativeString() {
        return "combineByKey(..., new <fn>(), ...)";
      }
    };
  }

  private static <InputT, OutputT> TransformEvaluator<ParDo.MultiOutput<InputT, OutputT>> parDo() {
    return new TransformEvaluator<ParDo.MultiOutput<InputT, OutputT>>() {
      @Override
      @SuppressWarnings("unchecked")
      public void evaluate(
          ParDo.MultiOutput<InputT, OutputT> transform, EvaluationContext context) {
        String stepName = context.getCurrentTransform().getFullName();
        DoFn<InputT, OutputT> doFn = transform.getFn();
        checkState(
            !DoFnSignatures.signatureForDoFn(doFn).processElement().isSplittable(),
            "Not expected to directly translate splittable DoFn, should have been overridden: %s",
            doFn);
        JavaRDD<WindowedValue<InputT>> inRDD =
            ((BoundedDataset<InputT>) context.borrowDataset(transform)).getRDD();
        WindowingStrategy<?, ?> windowingStrategy =
            context.getInput(transform).getWindowingStrategy();
        Accumulator<MetricsContainerStepMap> metricsAccum = MetricsAccumulator.getInstance();
        Coder<InputT> inputCoder = (Coder<InputT>) context.getInput(transform).getCoder();
        Map<TupleTag<?>, Coder<?>> outputCoders = context.getOutputCoders();
        JavaPairRDD<TupleTag<?>, WindowedValue<?>> all;

        DoFnSignature signature = DoFnSignatures.getSignature(transform.getFn().getClass());
        boolean stateful =
            signature.stateDeclarations().size() > 0 || signature.timerDeclarations().size() > 0;

        MultiDoFnFunction<InputT, OutputT> multiDoFnFunction =
            new MultiDoFnFunction<>(
                metricsAccum,
                stepName,
                doFn,
                context.getSerializableOptions(),
                transform.getMainOutputTag(),
                transform.getAdditionalOutputTags().getAll(),
                inputCoder,
                outputCoders,
                TranslationUtils.getSideInputs(transform.getSideInputs(), context),
                windowingStrategy,
                stateful);

        if (stateful) {
          // Based on the fact that the signature is stateful, DoFnSignatures ensures
          // that it is also keyed
          all =
              statefulParDoTransform(
                  (KvCoder) context.getInput(transform).getCoder(),
                  windowingStrategy.getWindowFn().windowCoder(),
                  (JavaRDD) inRDD,
                  (MultiDoFnFunction) multiDoFnFunction);
        } else {
          all = inRDD.mapPartitionsToPair(multiDoFnFunction);
        }

        Map<TupleTag<?>, PValue> outputs = context.getOutputs(transform);
        if (outputs.size() > 1) {
          StorageLevel level = StorageLevel.fromString(context.storageLevel());
          if (avoidRddSerialization(level)) {
            // if it is memory only reduce the overhead of moving to bytes
            all = all.persist(level);
          } else {
            // Caching can cause Serialization, we need to code to bytes
            // more details in https://issues.apache.org/jira/browse/BEAM-2669
            Map<TupleTag<?>, Coder<WindowedValue<?>>> coderMap =
                TranslationUtils.getTupleTagCoders(outputs);
            all =
                all.mapToPair(TranslationUtils.getTupleTagEncodeFunction(coderMap))
                    .persist(level)
                    .mapToPair(TranslationUtils.getTupleTagDecodeFunction(coderMap));
          }
        }
        for (Map.Entry<TupleTag<?>, PValue> output : outputs.entrySet()) {
          JavaPairRDD<TupleTag<?>, WindowedValue<?>> filtered =
              all.filter(new TranslationUtils.TupleTagFilter(output.getKey()));
          // Object is the best we can do since different outputs can have different tags
          JavaRDD<WindowedValue<Object>> values =
              (JavaRDD<WindowedValue<Object>>) (JavaRDD<?>) filtered.values();
          context.putDataset(output.getValue(), new BoundedDataset<>(values));
        }
      }

      @Override
      public String toNativeString() {
        return "mapPartitions(new <fn>())";
      }
    };
  }

  private static <K, V, OutputT> JavaPairRDD<TupleTag<?>, WindowedValue<?>> statefulParDoTransform(
      KvCoder<K, V> kvCoder,
      Coder<? extends BoundedWindow> windowCoder,
      JavaRDD<WindowedValue<KV<K, V>>> kvInRDD,
      MultiDoFnFunction<KV<K, V>, OutputT> doFnFunction) {
    Coder<K> keyCoder = kvCoder.getKeyCoder();

    final WindowedValue.WindowedValueCoder<V> wvCoder =
        WindowedValue.FullWindowedValueCoder.of(kvCoder.getValueCoder(), windowCoder);

    JavaRDD<WindowedValue<KV<K, Iterable<WindowedValue<V>>>>> groupRDD =
        GroupCombineFunctions.groupByKeyOnly(kvInRDD, keyCoder, wvCoder, null);

    return groupRDD
        .map(
            input -> {
              final K key = input.getValue().getKey();
              Iterable<WindowedValue<V>> value = input.getValue().getValue();
              return FluentIterable.from(value)
                  .transform(
                      windowedValue ->
                          windowedValue.withValue(KV.of(key, windowedValue.getValue())))
                  .iterator();
            })
        .flatMapToPair(doFnFunction);
  }

  private static <T> TransformEvaluator<Read.Bounded<T>> readBounded() {
    return new TransformEvaluator<Read.Bounded<T>>() {
      @Override
      public void evaluate(Read.Bounded<T> transform, EvaluationContext context) {
        String stepName = context.getCurrentTransform().getFullName();
        final JavaSparkContext jsc = context.getSparkContext();
        // create an RDD from a BoundedSource.
        JavaRDD<WindowedValue<T>> input =
            new SourceRDD.Bounded<>(
                    jsc.sc(), transform.getSource(), context.getSerializableOptions(), stepName)
                .toJavaRDD();

        context.putDataset(transform, new BoundedDataset<>(input));
      }

      @Override
      public String toNativeString() {
        return "sparkContext.<readFrom(<source>)>()";
      }
    };
  }

  private static <T, W extends BoundedWindow> TransformEvaluator<Window.Assign<T>> window() {
    return new TransformEvaluator<Window.Assign<T>>() {
      @Override
      public void evaluate(Window.Assign<T> transform, EvaluationContext context) {
        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<T>> inRDD =
            ((BoundedDataset<T>) context.borrowDataset(transform)).getRDD();

        if (TranslationUtils.skipAssignWindows(transform, context)) {
          context.putDataset(transform, new BoundedDataset<>(inRDD));
        } else {
          context.putDataset(
              transform,
              new BoundedDataset<>(inRDD.map(new SparkAssignWindowFn<>(transform.getWindowFn()))));
        }
      }

      @Override
      public String toNativeString() {
        return "map(new <windowFn>())";
      }
    };
  }

  private static <ReadT, WriteT>
      TransformEvaluator<View.CreatePCollectionView<ReadT, WriteT>> createPCollView() {
    return new TransformEvaluator<View.CreatePCollectionView<ReadT, WriteT>>() {
      @Override
      public void evaluate(
          View.CreatePCollectionView<ReadT, WriteT> transform, EvaluationContext context) {
        Iterable<? extends WindowedValue<?>> iter =
            context.getWindowedValues(context.getInput(transform));
        PCollectionView<WriteT> output = transform.getView();
        Coder<Iterable<WindowedValue<?>>> coderInternal =
            (Coder)
                IterableCoder.of(
                    WindowedValue.getFullCoder(
                        output.getCoderInternal(),
                        output.getWindowingStrategyInternal().getWindowFn().windowCoder()));

        @SuppressWarnings("unchecked")
        Iterable<WindowedValue<?>> iterCast = (Iterable<WindowedValue<?>>) iter;

        context.putPView(output, iterCast, coderInternal);
      }

      @Override
      public String toNativeString() {
        return "<createPCollectionView>";
      }
    };
  }

  private static <K, V, W extends BoundedWindow> TransformEvaluator<Reshuffle<K, V>> reshuffle() {
    return new TransformEvaluator<Reshuffle<K, V>>() {
      @Override
      public void evaluate(Reshuffle<K, V> transform, EvaluationContext context) {
        @SuppressWarnings("unchecked")
        JavaRDD<WindowedValue<KV<K, V>>> inRDD =
            ((BoundedDataset<KV<K, V>>) context.borrowDataset(transform)).getRDD();
        @SuppressWarnings("unchecked")
        final WindowingStrategy<?, W> windowingStrategy =
            (WindowingStrategy<?, W>) context.getInput(transform).getWindowingStrategy();
        @SuppressWarnings("unchecked")
        final KvCoder<K, V> coder = (KvCoder<K, V>) context.getInput(transform).getCoder();
        @SuppressWarnings("unchecked")
        final WindowFn<Object, W> windowFn = (WindowFn<Object, W>) windowingStrategy.getWindowFn();

        final Coder<K> keyCoder = coder.getKeyCoder();
        final WindowedValue.WindowedValueCoder<V> wvCoder =
            WindowedValue.FullWindowedValueCoder.of(coder.getValueCoder(), windowFn.windowCoder());

        JavaRDD<WindowedValue<KV<K, V>>> reshuffled =
            GroupCombineFunctions.reshuffle(inRDD, keyCoder, wvCoder);

        context.putDataset(transform, new BoundedDataset<>(reshuffled));
      }

      @Override
      public String toNativeString() {
        return "repartition(...)";
      }
    };
  }

  private static final Map<String, TransformEvaluator<?>> EVALUATORS = new HashMap<>();

  static {
    EVALUATORS.put(PTransformTranslation.READ_TRANSFORM_URN, readBounded());
    EVALUATORS.put(PTransformTranslation.PAR_DO_TRANSFORM_URN, parDo());
    EVALUATORS.put(PTransformTranslation.GROUP_BY_KEY_TRANSFORM_URN, groupByKey());
    EVALUATORS.put(PTransformTranslation.COMBINE_GROUPED_VALUES_TRANSFORM_URN, combineGrouped());
    EVALUATORS.put(PTransformTranslation.COMBINE_GLOBALLY_TRANSFORM_URN, combineGlobally());
    EVALUATORS.put(PTransformTranslation.COMBINE_PER_KEY_TRANSFORM_URN, combinePerKey());
    EVALUATORS.put(PTransformTranslation.FLATTEN_TRANSFORM_URN, flattenPColl());
    EVALUATORS.put(PTransformTranslation.CREATE_VIEW_TRANSFORM_URN, createPCollView());
    EVALUATORS.put(PTransformTranslation.ASSIGN_WINDOWS_TRANSFORM_URN, window());
    EVALUATORS.put(PTransformTranslation.RESHUFFLE_URN, reshuffle());
  }

  @Nullable
  private static TransformEvaluator<?> getTranslator(PTransform<?, ?> transform) {
    @Nullable String urn = PTransformTranslation.urnForTransformOrNull(transform);
    return urn == null ? null : EVALUATORS.get(urn);
  }

  /** Translator matches Beam transformation with the appropriate evaluator. */
  public static class Translator implements SparkPipelineTranslator {

    @Override
    public boolean hasTranslation(PTransform<?, ?> transform) {
      return EVALUATORS.containsKey(PTransformTranslation.urnForTransformOrNull(transform));
    }

    @Override
    public <TransformT extends PTransform<?, ?>> TransformEvaluator<TransformT> translateBounded(
        PTransform<?, ?> transform) {
      @SuppressWarnings("unchecked")
      TransformEvaluator<TransformT> transformEvaluator =
          (TransformEvaluator<TransformT>) getTranslator(transform);
      checkState(
          transformEvaluator != null,
          "No TransformEvaluator registered for BOUNDED transform %s",
          transform);
      return transformEvaluator;
    }

    @Override
    public <TransformT extends PTransform<?, ?>> TransformEvaluator<TransformT> translateUnbounded(
        PTransform<?, ?> transform) {
      throw new IllegalStateException(
          "TransformTranslator used in a batch pipeline only " + "supports BOUNDED transforms.");
    }
  }
}


text:
namespace dropkick.Configuration.Dsl.Dsn
{
    public interface DsnOptions
    {
        void ForDatabase(string name);
    }
}


text:
#ifndef VGA_RAST_DIRECT_MIRROR_H
#define VGA_RAST_DIRECT_MIRROR_H

#include "vga/rasterizer.h"
#include "vga/rast/direct.h"

namespace vga {
namespace rast {

/*
 * A variation on Direct that just redraws another rasterizer's content, but
 * upside down.  The output can also be flipped horizontal (i.e. scanned out
 * backwards) and vertically shifted.
 *
 * If you can't imagine how you'd use this... you are not imagining hard enough.
 */
class DirectMirror : public Rasterizer {
public:
  DirectMirror(Direct const & rast,
               unsigned top_line,
               bool flip_horizontal = true);

  RasterInfo rasterize(unsigned, unsigned, Pixel *) override;

  unsigned get_width() const { return _r.get_width(); }
  unsigned get_height() const { return _r.get_height(); }
  unsigned char *get_fg_buffer() const { return _r.get_fg_buffer(); }
  unsigned char *get_bg_buffer() const { return _r.get_bg_buffer(); }

private:
  Direct const & _r;
  unsigned _top_line;
  bool _flip_horizontal;
};

}  // namespace rast
}  // namespace vga

#endif  // VGA_RAST_DIRECT_MIRROR_H


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Tillaea acutifolia Kirk

### Remarks
null


text:
title:  Korzenie Abrahama
date:  30/04/2022
---

### Studium Bieżącego Tygodnia
Rdz 12,1-20; Iz 48,20; 36,6.9; Jr 2,18; Rdz 13,1-14,24; Hbr 7,1-10.

>
Tekst Pamięciowy

> "Przez wiarę usłuchał Abraham, gdy został powołany, aby pójść na miejsce, które miał wziąć w dziedzictwo, i wyszedł, nie wiedząc, dokąd idzie" (Hbr 11,8).

Dotarliśmy do centrum Księgi Rodzaju. Ta środkowa część omawia wędrówkę Abrahama, począwszy od pierwszego Bożego wezwania: "Wyjdź [hebr. lech lecha]" (Rdz 12,1), po którym Abraham zostawia swoją przeszłość, do drugiego Bożego wezwania: "Udaj się [również hebr. lech lecha]" (Rdz 22,2), po którym Abraham miał zostawić swoją przyszłość (związaną z synem). Abraham jest więc stale w drodze, stale wędruje, a Biblia nazywa go przychodniem (zob. Rdz 17,8).

W swojej wędrówce Abraham jest zawieszony w próżni — bez przeszłości, którą utracił, i bez przyszłości, której jeszcze nie widzi. Między tymi dwoma powołaniami, które określają wędrówkę wiary Abrahama, patriarcha słyszy głos Boga, który upewnia go:

— "Nie bój się" (Rdz 15,1).

Te trzy słowa Boga wyznaczają trzy etapy wędrówki Abrahama, które przestudiujemy w szóstej, siódmej i ósmej lekcji.

Abraham jest wzorem wiary (zob. Rdz 15,6) i został upamiętniony w Piśmie Świętym jako mąż wiary (zob. Ne 9,7-8). W Nowym Testamencie Abraham jest najczęściej wymienianą postacią ze Starego Testamentu. W tym tygodniu zaczniemy się przekonywać, dlaczego tak jest.