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

/**
 * @fileoverview Unit tests for goog.functions.
 */

goog.provide('goog.functionsTest');
goog.setTestOnly('goog.functionsTest');

goog.require('goog.functions');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.recordFunction');

var fTrue = makeCallOrderLogger('fTrue', true);
var gFalse = makeCallOrderLogger('gFalse', false);
var hTrue = makeCallOrderLogger('hTrue', true);

var stubs = new goog.testing.PropertyReplacer();

function setUp() {
  callOrder = [];
}

function tearDown() {
  stubs.reset();
}

function testTrue() {
  assertTrue(goog.functions.TRUE());
}

function testFalse() {
  assertFalse(goog.functions.FALSE());
}

function testLock() {
  function add(var_args) {
    var result = 0;
    for (var i = 0; i < arguments.length; i++) {
      result += arguments[i];
    }
    return result;
  }

  assertEquals(6, add(1, 2, 3));
  assertEquals(0, goog.functions.lock(add)(1, 2, 3));
  assertEquals(3, goog.functions.lock(add, 2)(1, 2, 3));
  assertEquals(6, goog.partial(add, 1, 2)(3));
  assertEquals(3, goog.functions.lock(goog.partial(add, 1, 2))(3));
}

function testNth() {
  assertEquals(1, goog.functions.nth(0)(1));
  assertEquals(2, goog.functions.nth(1)(1, 2));
  assertEquals('a', goog.functions.nth(0)('a', 'b'));
  assertEquals(undefined, goog.functions.nth(0)());
  assertEquals(undefined, goog.functions.nth(1)(true));
  assertEquals(undefined, goog.functions.nth(-1)());
}

function testIdentity() {
  assertEquals(3, goog.functions.identity(3));
  assertEquals(3, goog.functions.identity(3, 4, 5, 6));
  assertEquals('Hi there', goog.functions.identity('Hi there'));
  assertEquals(null, goog.functions.identity(null));
  assertEquals(undefined, goog.functions.identity());

  var arr = [1, 'b', null];
  assertEquals(arr, goog.functions.identity(arr));
  var obj = {a: 'ay', b: 'bee', c: 'see'};
  assertEquals(obj, goog.functions.identity(obj));
}

function testConstant() {
  assertEquals(3, goog.functions.constant(3)());
  assertEquals(undefined, goog.functions.constant()());
}

function testError() {
  var f = goog.functions.error('x');
  var e = assertThrows(
      'A function created by goog.functions.error must throw an error', f);
  assertEquals('x', e.message);
}

function testFail() {
  var obj = {};
  var f = goog.functions.fail(obj);
  var e = assertThrows(
      'A function created by goog.functions.raise must throw its input', f);
  assertEquals(obj, e);
}

function testCompose() {
  var add2 = function(x) {
    return x + 2;
  };

  var double = function(x) {
    return x * 2;
  };

  assertEquals(6, goog.functions.compose(double, add2)(1));
  assertEquals(4, goog.functions.compose(add2, double)(1));
  assertEquals(6, goog.functions.compose(add2, add2, double)(1));
  assertEquals(12, goog.functions.compose(double, add2, add2, double)(1));
  assertUndefined(goog.functions.compose()(1));
  assertEquals(3, goog.functions.compose(add2)(1));

  var add2Numbers = function(x, y) {
    return x + y;
  };
  assertEquals(17, goog.functions.compose(add2Numbers)(10, 7));
  assertEquals(34, goog.functions.compose(double, add2Numbers)(10, 7));
}

function testAdd() {
  assertUndefined(goog.functions.sequence()());
  assertCallOrderAndReset([]);

  assert(goog.functions.sequence(fTrue)());
  assertCallOrderAndReset(['fTrue']);

  assertFalse(goog.functions.sequence(fTrue, gFalse)());
  assertCallOrderAndReset(['fTrue', 'gFalse']);

  assert(goog.functions.sequence(fTrue, gFalse, hTrue)());
  assertCallOrderAndReset(['fTrue', 'gFalse', 'hTrue']);

  assert(goog.functions.sequence(goog.functions.identity)(true));
  assertFalse(goog.functions.sequence(goog.functions.identity)(false));
}

function testAnd() {
  // the return value is unspecified for an empty and
  goog.functions.and()();
  assertCallOrderAndReset([]);

  assert(goog.functions.and(fTrue)());
  assertCallOrderAndReset(['fTrue']);

  assertFalse(goog.functions.and(fTrue, gFalse)());
  assertCallOrderAndReset(['fTrue', 'gFalse']);

  assertFalse(goog.functions.and(fTrue, gFalse, hTrue)());
  assertCallOrderAndReset(['fTrue', 'gFalse']);

  assert(goog.functions.and(goog.functions.identity)(true));
  assertFalse(goog.functions.and(goog.functions.identity)(false));
}

function testOr() {
  // the return value is unspecified for an empty or
  goog.functions.or()();
  assertCallOrderAndReset([]);

  assert(goog.functions.or(fTrue)());
  assertCallOrderAndReset(['fTrue']);

  assert(goog.functions.or(fTrue, gFalse)());
  assertCallOrderAndReset(['fTrue']);

  assert(goog.functions.or(fTrue, gFalse, hTrue)());
  assertCallOrderAndReset(['fTrue']);

  assert(goog.functions.or(goog.functions.identity)(true));
  assertFalse(goog.functions.or(goog.functions.identity)(false));
}

function testNot() {
  assertTrue(goog.functions.not(gFalse)());
  assertCallOrderAndReset(['gFalse']);

  assertTrue(goog.functions.not(goog.functions.identity)(false));
  assertFalse(goog.functions.not(goog.functions.identity)(true));

  var f = function(a, b) {
    assertEquals(1, a);
    assertEquals(2, b);
    return false;
  };

  assertTrue(goog.functions.not(f)(1, 2));
}

function testCreate(expectedArray) {
  var tempConstructor = function(a, b) {
    this.foo = a;
    this.bar = b;
  };

  var factory = goog.partial(goog.functions.create, tempConstructor, 'baz');
  var instance = factory('qux');

  assert(instance instanceof tempConstructor);
  assertEquals(instance.foo, 'baz');
  assertEquals(instance.bar, 'qux');
}

function testWithReturnValue() {
  var obj = {};
  var f = function(a, b) {
    assertEquals(obj, this);
    assertEquals(1, a);
    assertEquals(2, b);
  };
  assertTrue(goog.functions.withReturnValue(f, true).call(obj, 1, 2));
  assertFalse(goog.functions.withReturnValue(f, false).call(obj, 1, 2));
}

function makeCallOrderLogger(name, returnValue) {
  return function() {
    callOrder.push(name);
    return returnValue;
  };
}

function assertCallOrderAndReset(expectedArray) {
  assertArrayEquals(expectedArray, callOrder);
  callOrder = [];
}

function testCacheReturnValue() {
  var returnFive = function() {
    return 5;
  };

  var recordedReturnFive = goog.testing.recordFunction(returnFive);
  var cachedRecordedReturnFive = goog.functions.cacheReturnValue(
      recordedReturnFive);

  assertEquals(0, recordedReturnFive.getCallCount());
  assertEquals(5, cachedRecordedReturnFive());
  assertEquals(1, recordedReturnFive.getCallCount());
  assertEquals(5, cachedRecordedReturnFive());
  assertEquals(1, recordedReturnFive.getCallCount());
}

function testCacheReturnValueFlagEnabled() {
  var count = 0;
  var returnIncrementingInteger = function() {
    count++;
    return count;
  };

  var recordedFunction = goog.testing.recordFunction(
      returnIncrementingInteger);
  var cachedRecordedFunction = goog.functions.cacheReturnValue(
      recordedFunction);

  assertEquals(0, recordedFunction.getCallCount());
  assertEquals(1, cachedRecordedFunction());
  assertEquals(1, recordedFunction.getCallCount());
  assertEquals(1, cachedRecordedFunction());
  assertEquals(1, recordedFunction.getCallCount());
  assertEquals(1, cachedRecordedFunction());
}

function testCacheReturnValueFlagDisabled() {
  stubs.set(goog.functions, 'CACHE_RETURN_VALUE', false);

  var count = 0;
  var returnIncrementingInteger = function() {
    count++;
    return count;
  };

  var recordedFunction = goog.testing.recordFunction(
      returnIncrementingInteger);
  var cachedRecordedFunction = goog.functions.cacheReturnValue(
      recordedFunction);

  assertEquals(0, recordedFunction.getCallCount());
  assertEquals(1, cachedRecordedFunction());
  assertEquals(1, recordedFunction.getCallCount());
  assertEquals(2, cachedRecordedFunction());
  assertEquals(2, recordedFunction.getCallCount());
  assertEquals(3, cachedRecordedFunction());
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/spinner_press" />
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/spinner_select" />
    <item android:drawable="@drawable/spinner_normal" />
</selector>

redpajama_set_name: RedPajamaGithub


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

// [START storage_create_bucket_turbo_replication]

using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreateBucketWithTurboReplicationSample
{
    public Bucket CreateBucketWithTurboReplication(
        string projectId = "your-project-id",
        string location = "your-bucket-location",
        string bucketName = "bucket-name")
    {
        var storage = StorageClient.Create();
        // Enabling turbo replication requires a bucket with dual-region configuration
        var bucket = storage.CreateBucket(projectId, new Bucket { Name = bucketName , Location = location, Rpo = "ASYNC_TURBO" });

        Console.WriteLine($"Created {bucket.Name} in {bucket.Location} with RPO Setting {bucket.Rpo}.");
        return bucket;
    }

}

// [END storage_create_bucket_turbo_replication]


text:
cd "<%= @src_path %>"
./get-janus-headers.sh
./autogen.sh
./configure --prefix=/usr

make
make install


text:
  typedef int errno_t;
#endif

#define authenc_align __attribute__ ((aligned (8)))

typedef uint64_t dig_t;

#endif


text:
describe("chorus.alerts.DataSourceAccountDelete", function() {
    beforeEach(function() {
        this.dataSource = backboneFixtures.gpdbDataSource({ id: '456' });
        setLoggedInUser({ id: "1011" });
        this.alert = new chorus.alerts.DataSourceAccountDelete({ dataSource: this.dataSource });
    });

    it("does not have a redirect url", function() {
        expect(this.alert.redirectUrl).toBeUndefined();
    });

    describe("#makeModel", function() {
        it("gets the user account for the data source that is the current page model", function(){
            expect(this.alert.model.get("userId")).toBe("1011");
            expect(this.alert.model.get("dataSourceId")).toBe("456");
        });
    });

    describe("successful deletion", function() {
        beforeEach(function() {
            spyOn(chorus, "toast");
            this.alert.model.trigger("destroy", this.alert.model);
        });

        it("displays a toast message", function() {
            expect(chorus.toast).toHaveBeenCalledWith("data_sources.account.delete.toast", undefined);
            expect(chorus.toast.calls.count()).toBe(1);
        });
    });
});


text:
<?php

namespace ByHours\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HotelType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('slug')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ByHours\HotelBundle\Entity\Hotel',
        ));
    }

    public function getName()
    {
        return 'cupon_backendbundle_hoteltype';
    }
}


text:
package com.cattong.sns.impl.kaixin;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.cattong.commons.LibResultCode;
import com.cattong.commons.LibRuntimeException;
import com.cattong.commons.Logger;
import com.cattong.commons.ServiceProvider;

class KaiXinResponseHandler implements ResponseHandler<String> {

	public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
		StatusLine statusLine = response.getStatusLine();
		HttpEntity entity = response.getEntity();
		String responseString = (entity == null ? null : EntityUtils.toString(entity));

		Logger.debug("KaiXinResponseHandler : {}", responseString);

		if (responseString != null
			&& responseString.contains("error_code")
			&& responseString.startsWith("{")) {
			try {
				JSONObject json = new JSONObject(responseString);
				if (json.has("error_code")) {
					// 明确是异常响应,而不是包含了error_code的文本
					int errorCode = json.getInt("error_code");
					String errorDesc = json.getString("error");
					String requestPath = json.getString("request");
					throw new LibRuntimeException(
						errorCode, requestPath,	errorDesc, ServiceProvider.KaiXin);
				}
			} catch (JSONException e) {
				throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.RenRen);
			}
		}

		int statusCode = statusLine.getStatusCode();
		if (statusCode >= 300) {
			throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
		}

		return responseString;
	}
}


text:
package org.jkiss.dbeaver.ui.editors.sql.terminal;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.preferences.TargetPrefPage;
import org.jkiss.dbeaver.utils.PrefUtils;

public class SQLTerminalPreferencesPage extends TargetPrefPage {
    private static final Log log = Log.getLog(SQLTerminalPreferencesPage.class);

    public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.main.sqleditor.terminalview"; //$NON-NLS-1$

    private Button showTerminalViewByDefault;
    private Button showQueryText;
    private Button showServerOutput;

    @Override
    protected boolean hasDataSourceSpecificOptions(@NotNull DBPDataSourceContainer dataSourceDescriptor) {
        DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore();
        return store.contains(SQLTerminalPreferencesConstants.SHOW_TERMINAL_VIEW_BY_DEFAULT)
            || store.contains(SQLTerminalPreferencesConstants.SHOW_QUERY_TEXT)
            || store.contains(SQLTerminalPreferencesConstants.SHOW_SERVER_OUTPUT);
    }

    @Override
    protected boolean supportsDataSourceSpecificOptions() {
        return true;
    }

    @NotNull
    @Override
    protected Control createPreferenceContent(@NotNull Composite parent) {
        Composite composite = UIUtils.createPlaceholder(parent, 2, 5);

        Composite commonGroup = UIUtils.createControlGroup(
            composite,
            SQLEditorMessages.pref_page_sql_editor_group_common,
            2,
            GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_BEGINNING,
            0
        );
        showTerminalViewByDefault = UIUtils.createCheckbox(
            commonGroup,
            SQLTerminalMessages.pref_page_sql_temrinal_show_output_console_view_label,
            SQLTerminalMessages.pref_page_sql_temrinal_show_output_console_view_tip,
            false,
            2
        );
        showQueryText = UIUtils.createCheckbox(
            commonGroup,
            SQLTerminalMessages.pref_page_sql_temrinal_show_query_text_label,
            null,
            false,
            2
        );
        showServerOutput = UIUtils.createCheckbox(
            commonGroup,
            SQLTerminalMessages.pref_page_sql_temrinal_show_server_output_label,
            null,
            false,
            2
        );

        return composite;
    }

    @Override
    protected void loadPreferences(@NotNull DBPPreferenceStore store) {
        try {
            showTerminalViewByDefault.setSelection(store.getBoolean(SQLTerminalPreferencesConstants.SHOW_TERMINAL_VIEW_BY_DEFAULT));
            showQueryText.setSelection(store.getBoolean(SQLTerminalPreferencesConstants.SHOW_QUERY_TEXT));
            showServerOutput.setSelection(store.getBoolean(SQLTerminalPreferencesConstants.SHOW_SERVER_OUTPUT));
        } catch (Exception e) {
            log.warn(e);
        }
    }

    @Override
    protected void savePreferences(@NotNull DBPPreferenceStore store) {
        try {
            store.setValue(SQLTerminalPreferencesConstants.SHOW_TERMINAL_VIEW_BY_DEFAULT, showTerminalViewByDefault.getSelection());
            store.setValue(SQLTerminalPreferencesConstants.SHOW_QUERY_TEXT, showQueryText.getSelection());
            store.setValue(SQLTerminalPreferencesConstants.SHOW_SERVER_OUTPUT, showServerOutput.getSelection());

        } catch (Exception e) {
            log.warn(e);
        }
        PrefUtils.savePreferenceStore(store);
    }

    @Override
    protected void clearPreferences(@NotNull DBPPreferenceStore store) {
        store.setToDefault(SQLTerminalPreferencesConstants.SHOW_TERMINAL_VIEW_BY_DEFAULT);
        store.setToDefault(SQLTerminalPreferencesConstants.SHOW_QUERY_TEXT);
        store.setToDefault(SQLTerminalPreferencesConstants.SHOW_SERVER_OUTPUT);
    }

    @NotNull
    @Override
    protected String getPropertyPageID() {
        return PAGE_ID;
    }

}


text:
namespace IDAAPI {
    class UIHooks {
        static int ui_notification_callback(void *, int, va_list);

    public:
        UIHooks();
        virtual ~UIHooks();

        virtual void populating_tform_popup(TForm *form, TPopupMenu *menu) { };
        virtual void finish_populating_tform_popup(TForm *form, TPopupMenu *menu) { };
    };
}

#endif //IDIOMMATCHER_UIHOOKS_H


text:
#include "uv.h"
#include "task.h"

#include <string.h>
#include <fcntl.h>

#ifndef HAVE_KQUEUE
# if defined(__APPLE__) ||                                                    \
     defined(__DragonFly__) ||                                                \
     defined(__FreeBSD__) ||                                                  \
     defined(__OpenBSD__) ||                                                  \
     defined(__NetBSD__)
#  define HAVE_KQUEUE 1
# endif
#endif

static uv_fs_event_t fs_event;
static uv_timer_t timer;
static int timer_cb_called = 0;
static int close_cb_called = 0;
static int fs_event_cb_called = 0;
static int timer_cb_touch_called = 0;

static void create_dir(uv_loop_t* loop, const char* name) {
  int r;
  uv_fs_t req;
  r = uv_fs_mkdir(loop, &req, name, 0755, NULL);
  ASSERT(r == 0 || uv_last_error(loop).code == UV_EEXIST);
  uv_fs_req_cleanup(&req);
}

static void create_file(uv_loop_t* loop, const char* name) {
  int r;
  uv_file file;
  uv_fs_t req;

  r = uv_fs_open(loop, &req, name, O_WRONLY | O_CREAT,
      S_IWRITE | S_IREAD, NULL);
  ASSERT(r != -1);
  file = r;
  uv_fs_req_cleanup(&req);
  r = uv_fs_close(loop, &req, file, NULL);
  ASSERT(r == 0);
  uv_fs_req_cleanup(&req);
}

static void touch_file(uv_loop_t* loop, const char* name) {
  int r;
  uv_file file;
  uv_fs_t req;

  r = uv_fs_open(loop, &req, name, O_RDWR, 0, NULL);
  ASSERT(r != -1);
  file = r;
  uv_fs_req_cleanup(&req);

  r = uv_fs_write(loop, &req, file, "foo", 4, -1, NULL);
  ASSERT(r != -1);
  uv_fs_req_cleanup(&req);

  r = uv_fs_close(loop, &req, file, NULL);
  ASSERT(r != -1);
  uv_fs_req_cleanup(&req);
}

static void close_cb(uv_handle_t* handle) {
  ASSERT(handle != NULL);
  close_cb_called++;
}

static void fail_cb(uv_fs_event_t* handle,
                    const char* path,
                    int events,
                    int status) {
  ASSERT(0 && "fail_cb called");
}

static void fs_event_cb_dir(uv_fs_event_t* handle, const char* filename,
  int events, int status) {
  ++fs_event_cb_called;
  ASSERT(handle == &fs_event);
  ASSERT(status == 0);
  ASSERT(events == UV_RENAME);
  ASSERT(filename == NULL || strcmp(filename, "file1") == 0);
  uv_close((uv_handle_t*)handle, close_cb);
}

static void fs_event_cb_file(uv_fs_event_t* handle, const char* filename,
  int events, int status) {
  ++fs_event_cb_called;
  ASSERT(handle == &fs_event);
  ASSERT(status == 0);
  ASSERT(events == UV_CHANGE);
  ASSERT(filename == NULL || strcmp(filename, "file2") == 0);
  uv_close((uv_handle_t*)handle, close_cb);
}

static void timer_cb_close_handle(uv_timer_t* timer, int status) {
  uv_handle_t* handle;

  ASSERT(timer != NULL);
  ASSERT(status == 0);
  handle = timer->data;

  uv_close((uv_handle_t*)timer, NULL);
  uv_close((uv_handle_t*)handle, close_cb);
}

static void fs_event_cb_file_current_dir(uv_fs_event_t* handle,
  const char* filename, int events, int status) {
  ASSERT(fs_event_cb_called == 0);
  ++fs_event_cb_called;

  ASSERT(handle == &fs_event);
  ASSERT(status == 0);
  ASSERT(events == UV_CHANGE);
  ASSERT(filename == NULL || strcmp(filename, "watch_file") == 0);

  /* Regression test for SunOS: touch should generate just one event. */
  {
    static uv_timer_t timer;
    uv_timer_init(handle->loop, &timer);
    timer.data = handle;
    uv_timer_start(&timer, timer_cb_close_handle, 250, 0);
  }
}

static void timer_cb_dir(uv_timer_t* handle, int status) {
  ++timer_cb_called;
  create_file(handle->loop, "watch_dir/file1");
  uv_close((uv_handle_t*)handle, close_cb);
}

static void timer_cb_file(uv_timer_t* handle, int status) {
  ++timer_cb_called;

  if (timer_cb_called == 1) {
    touch_file(handle->loop, "watch_dir/file1");
  } else {
    touch_file(handle->loop, "watch_dir/file2");
    uv_close((uv_handle_t*)handle, close_cb);
  }
}

static void timer_cb_touch(uv_timer_t* timer, int status) {
  ASSERT(status == 0);
  uv_close((uv_handle_t*)timer, NULL);
  touch_file(timer->loop, "watch_file");
  timer_cb_touch_called++;
}

static void timer_cb_watch_twice(uv_timer_t* handle, int status) {
  uv_fs_event_t* handles = handle->data;
  uv_close((uv_handle_t*) (handles + 0), NULL);
  uv_close((uv_handle_t*) (handles + 1), NULL);
  uv_close((uv_handle_t*) handle, NULL);
}

TEST_IMPL(fs_event_watch_dir) {
  uv_loop_t* loop = uv_default_loop();
  int r;

  /* Setup */
  remove("watch_dir/file2");
  remove("watch_dir/file1");
  remove("watch_dir/");
  create_dir(loop, "watch_dir");

  r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_cb_dir, 0);
  ASSERT(r != -1);
  r = uv_timer_init(loop, &timer);
  ASSERT(r != -1);
  r = uv_timer_start(&timer, timer_cb_dir, 100, 0);
  ASSERT(r != -1);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(fs_event_cb_called == 1);
  ASSERT(timer_cb_called == 1);
  ASSERT(close_cb_called == 2);

  /* Cleanup */
  remove("watch_dir/file2");
  remove("watch_dir/file1");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_watch_file) {
  uv_loop_t* loop = uv_default_loop();
  int r;

  /* Setup */
  remove("watch_dir/file2");
  remove("watch_dir/file1");
  remove("watch_dir/");
  create_dir(loop, "watch_dir");
  create_file(loop, "watch_dir/file1");
  create_file(loop, "watch_dir/file2");

  r = uv_fs_event_init(loop, &fs_event, "watch_dir/file2", fs_event_cb_file, 0);
  ASSERT(r != -1);
  r = uv_timer_init(loop, &timer);
  ASSERT(r != -1);
  r = uv_timer_start(&timer, timer_cb_file, 100, 100);
  ASSERT(r != -1);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(fs_event_cb_called == 1);
  ASSERT(timer_cb_called == 2);
  ASSERT(close_cb_called == 2);

  /* Cleanup */
  remove("watch_dir/file2");
  remove("watch_dir/file1");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_watch_file_twice) {
  const char path[] = "test/fixtures/empty_file";
  uv_fs_event_t watchers[2];
  uv_timer_t timer;
  uv_loop_t* loop;

  loop = uv_default_loop();
  timer.data = watchers;

  ASSERT(0 == uv_fs_event_init(loop, watchers + 0, path, fail_cb, 0));
  ASSERT(0 == uv_fs_event_init(loop, watchers + 1, path, fail_cb, 0));
  ASSERT(0 == uv_timer_init(loop, &timer));
  ASSERT(0 == uv_timer_start(&timer, timer_cb_watch_twice, 10, 0));
  ASSERT(0 == uv_run(loop, UV_RUN_DEFAULT));

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_watch_file_current_dir) {
  uv_timer_t timer;
  uv_loop_t* loop;
  int r;

  loop = uv_default_loop();

  /* Setup */
  remove("watch_file");
  create_file(loop, "watch_file");

  r = uv_fs_event_init(loop, &fs_event, "watch_file",
    fs_event_cb_file_current_dir, 0);
  ASSERT(r != -1);

  r = uv_timer_init(loop, &timer);
  ASSERT(r == 0);

  r = uv_timer_start(&timer, timer_cb_touch, 1, 0);
  ASSERT(r == 0);

  ASSERT(timer_cb_touch_called == 0);
  ASSERT(fs_event_cb_called == 0);
  ASSERT(close_cb_called == 0);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(timer_cb_touch_called == 1);
  ASSERT(fs_event_cb_called == 1);
  ASSERT(close_cb_called == 1);

  /* Cleanup */
  remove("watch_file");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_no_callback_after_close) {
  uv_loop_t* loop = uv_default_loop();
  int r;

  /* Setup */
  remove("watch_dir/file1");
  remove("watch_dir/");
  create_dir(loop, "watch_dir");
  create_file(loop, "watch_dir/file1");

  r = uv_fs_event_init(loop,
                       &fs_event,
                       "watch_dir/file1",
                       fs_event_cb_file,
                       0);
  ASSERT(r != -1);

  uv_close((uv_handle_t*)&fs_event, close_cb);
  touch_file(loop, "watch_dir/file1");
  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(fs_event_cb_called == 0);
  ASSERT(close_cb_called == 1);

  /* Cleanup */
  remove("watch_dir/file1");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_no_callback_on_close) {
  uv_loop_t* loop = uv_default_loop();
  int r;

  /* Setup */
  remove("watch_dir/file1");
  remove("watch_dir/");
  create_dir(loop, "watch_dir");
  create_file(loop, "watch_dir/file1");

  r = uv_fs_event_init(loop,
                       &fs_event,
                       "watch_dir/file1",
                       fs_event_cb_file,
                       0);
  ASSERT(r != -1);

  uv_close((uv_handle_t*)&fs_event, close_cb);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(fs_event_cb_called == 0);
  ASSERT(close_cb_called == 1);

  /* Cleanup */
  remove("watch_dir/file1");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

static void fs_event_fail(uv_fs_event_t* handle, const char* filename,
    int events, int status) {
  ASSERT(0 && "should never be called");
}

static void timer_cb(uv_timer_t* handle, int status) {
  int r;

  ASSERT(status == 0);

  r = uv_fs_event_init(handle->loop, &fs_event, ".", fs_event_fail, 0);
  ASSERT(r == 0);

  uv_close((uv_handle_t*)&fs_event, close_cb);
  uv_close((uv_handle_t*)handle, close_cb);
}

TEST_IMPL(fs_event_immediate_close) {
  uv_timer_t timer;
  uv_loop_t* loop;
  int r;

  loop = uv_default_loop();

  r = uv_timer_init(loop, &timer);
  ASSERT(r == 0);

  r = uv_timer_start(&timer, timer_cb, 1, 0);
  ASSERT(r == 0);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(close_cb_called == 2);

  MAKE_VALGRIND_HAPPY();
  return 0;
}

TEST_IMPL(fs_event_close_with_pending_event) {
  uv_loop_t* loop;
  int r;

  loop = uv_default_loop();

  create_dir(loop, "watch_dir");
  create_file(loop, "watch_dir/file");

  r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_fail, 0);
  ASSERT(r == 0);

  /* Generate an fs event. */
  touch_file(loop, "watch_dir/file");

  uv_close((uv_handle_t*)&fs_event, close_cb);

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(close_cb_called == 1);

  /* Clean up */
  remove("watch_dir/file");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

#if defined(HAVE_KQUEUE)

/* kqueue doesn't register fs events if you don't have an active watcher.
 * The file descriptor needs to be part of the kqueue set of interest and
 * that's not the case until we actually enter the event loop.
 */
TEST_IMPL(fs_event_close_in_callback) {
  fprintf(stderr, "Skipping test, doesn't work with kqueue.\n");
  return 0;
}

#else /* !HAVE_KQUEUE */

static void fs_event_cb_close(uv_fs_event_t* handle, const char* filename,
    int events, int status) {
  ASSERT(status == 0);

  ASSERT(fs_event_cb_called < 3);
  ++fs_event_cb_called;

  if (fs_event_cb_called == 3) {
    uv_close((uv_handle_t*) handle, close_cb);
  }
}

TEST_IMPL(fs_event_close_in_callback) {
  uv_loop_t* loop;
  int r;

  loop = uv_default_loop();

  create_dir(loop, "watch_dir");
  create_file(loop, "watch_dir/file1");
  create_file(loop, "watch_dir/file2");
  create_file(loop, "watch_dir/file3");
  create_file(loop, "watch_dir/file4");
  create_file(loop, "watch_dir/file5");

  r = uv_fs_event_init(loop, &fs_event, "watch_dir", fs_event_cb_close, 0);
  ASSERT(r == 0);

  /* Generate a couple of fs events. */
  touch_file(loop, "watch_dir/file1");
  touch_file(loop, "watch_dir/file2");
  touch_file(loop, "watch_dir/file3");
  touch_file(loop, "watch_dir/file4");
  touch_file(loop, "watch_dir/file5");

  uv_run(loop, UV_RUN_DEFAULT);

  ASSERT(close_cb_called == 1);
  ASSERT(fs_event_cb_called == 3);

  /* Clean up */
  remove("watch_dir/file1");
  remove("watch_dir/file2");
  remove("watch_dir/file3");
  remove("watch_dir/file4");
  remove("watch_dir/file5");
  remove("watch_dir/");

  MAKE_VALGRIND_HAPPY();
  return 0;
}

#endif /* HAVE_KQUEUE */


text:
package mesos.dns.client.protocol

import mesos.dns.client.model.Status
import spray.json.DefaultJsonProtocol

trait MesosProxyJsonProtocol extends DefaultJsonProtocol {
  implicit val statusFormat = jsonFormat4(Status.apply)
}


text:
package com.lynbrookrobotics.potassium.vision.limelight

import com.lynbrookrobotics.potassium.Signal
import com.lynbrookrobotics.potassium.clock.Clock
import com.lynbrookrobotics.potassium.streams._
import com.lynbrookrobotics.potassium.vision.{VisionProperties, VisionTargetTracking}
import edu.wpi.first.networktables.NetworkTableInstance
import squants.Time
import squants.space.{Degrees, Feet}

class LimeLightHardware(upright: Boolean)(implicit clock: Clock, props: Signal[VisionProperties]) {
  val limelightInterface = LimelightNetwork(clock)
  val tracker = new VisionTargetTracking(props)

  val distanceToTarget = tracker.distanceToTarget(limelightInterface.percentArea)

  val angleToTarget = if (upright) {
    tracker.compassAngleToTarget(limelightInterface.xOffsetAngle)
  } else {
    tracker.compassAngleToTarget(limelightInterface.yOffsetAngle)
  }

  val hasTarget = limelightInterface.hasTarget

  limelightInterface.table.getEntry("ledMode").setDouble(1)
}


text:
/* #define LOG_LEVEL LOG_LEVEL_ALL */
#include "logging.h"
#include "stringbuilder.h"
#include "xfuncs.h"

#include <assert.h>

/* All the null calculations are for when we pass our buffer to
   string_create as a NULL terminated string. */

/** Resizes the stringbuilder's internal buffer to at least the
    specified character length. */
static void stringbuilder_ensure_capacity(stringbuilder_t* builder, size_t char_capacity) {
        size_t new_capacity;
        assert(builder);

        if (builder->buffer_size == 0) {
                new_capacity = 16;
        } else {
                new_capacity = (builder->buffer_size / sizeof(wchar_t)) - 1 /* ignore null */;

                /* do we need to resize? */
                if (new_capacity >= char_capacity) {
                        return;
                }
        }

        while (new_capacity < char_capacity) {
                new_capacity *= 2;
        }

        /* add on one for null */
        new_capacity++;
        builder->buffer_size = new_capacity * sizeof(wchar_t);

        log_finest("stringbuilder_ensure_capacity: requested capacity is %u, new capacity is %u, new buffer size is %u\n",
               char_capacity, new_capacity, builder->buffer_size);

        if (builder->buffer) {
                builder->buffer = xrealloc(builder->buffer, builder->buffer_size);
        } else {
                builder->buffer = xmalloc(builder->buffer_size);
        }
}

stringbuilder_t* stringbuilder_create() {
        stringbuilder_t* result;

        result = xmalloc(sizeof(stringbuilder_t));
        result->buffer = NULL;
        result->buffer_size = 0;
        result->length = 0;

        return result;
}

void stringbuilder_append_char(stringbuilder_t* builder, wchar_t c) {
        assert(builder);
        stringbuilder_ensure_capacity(builder, builder->length + 1);
        builder->buffer[builder->length++] = c;
}

void stringbuilder_append_char32(stringbuilder_t* builder, utf32char_t c) {
        struct utf16_pair pair;

        if (utf16_char_needs_encoding(c)) {
                utf16_encode_char(c, &pair);
                stringbuilder_append_char(builder, pair.c1);
                stringbuilder_append_char(builder, pair.c2);
        } else {
                stringbuilder_append_char(builder, (wchar_t) c);
        }
}

static void _do_append(stringbuilder_t* builder, const wchar_t* string, size_t length) {
        stringbuilder_ensure_capacity(builder, builder->length + length);
        memcpy(builder->buffer + builder->length, string, length * sizeof(wchar_t));
        builder->length += length;
}

void stringbuilder_append(stringbuilder_t* builder, const string_t* string) {
        assert(string);
        _do_append(builder, string_get_cstring(string), string_get_length(string));
}

void stringbuilder_append_cstring(stringbuilder_t* builder, const wchar_t* cstring) {
        assert(cstring);
        _do_append(builder, cstring, wstrlen(cstring));
}

void stringbuilder_reset(stringbuilder_t* builder) {
        assert(builder);
        builder->length = 0;
}

size_t stringbuilder_get_length(stringbuilder_t* builder) {
        assert(builder);
        return builder->length;
}

int stringbuilder_is_empty(stringbuilder_t* builder) {
        return (stringbuilder_get_length(builder) == 0);
}

string_t* stringbuilder_to_string(stringbuilder_t* builder) {
        if (builder->buffer) {
                builder->buffer[builder->length] = L'\0';
                return string_create(builder->buffer);
        } else {
                return string_create(L"");
        }
}

void stringbuilder_destroy(stringbuilder_t* builder) {
        if (builder) {
                free(builder->buffer);
                free(builder);
        }
}


text:
package net.comze.framework.orm.util;

/**
 * @author GK.ZHONG
 * @since 3.1.0
 * @version DataAccessException.java 3.1.0 Mar 22, 2012 5:27:04 PM
 */
public class DataAccessException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public DataAccessException() {}

	public DataAccessException(String message, Throwable cause) {
		super(message, cause);
	}

	public DataAccessException(String message) {
		super(message);
	}

	public DataAccessException(Throwable cause) {
		super(cause);
	}

}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_ValueType3507792607.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Networking.UIntFloat
struct  UIntFloat_t1624724448
{
public:
	union
	{
		#pragma pack(push, tp, 1)
		struct
		{
			// System.Single UnityEngine.Networking.UIntFloat::floatValue
			float ___floatValue_0;
		};
		#pragma pack(pop, tp)
		struct
		{
			float ___floatValue_0_forAlignmentOnly;
		};
		#pragma pack(push, tp, 1)
		struct
		{
			// System.UInt32 UnityEngine.Networking.UIntFloat::intValue
			uint32_t ___intValue_1;
		};
		#pragma pack(pop, tp)
		struct
		{
			uint32_t ___intValue_1_forAlignmentOnly;
		};
		#pragma pack(push, tp, 1)
		struct
		{
			// System.Double UnityEngine.Networking.UIntFloat::doubleValue
			double ___doubleValue_2;
		};
		#pragma pack(pop, tp)
		struct
		{
			double ___doubleValue_2_forAlignmentOnly;
		};
		#pragma pack(push, tp, 1)
		struct
		{
			// System.UInt64 UnityEngine.Networking.UIntFloat::longValue
			uint64_t ___longValue_3;
		};
		#pragma pack(pop, tp)
		struct
		{
			uint64_t ___longValue_3_forAlignmentOnly;
		};
	};

public:
	inline static int32_t get_offset_of_floatValue_0() { return static_cast<int32_t>(offsetof(UIntFloat_t1624724448, ___floatValue_0)); }
	inline float get_floatValue_0() const { return ___floatValue_0; }
	inline float* get_address_of_floatValue_0() { return &___floatValue_0; }
	inline void set_floatValue_0(float value)
	{
		___floatValue_0 = value;
	}

	inline static int32_t get_offset_of_intValue_1() { return static_cast<int32_t>(offsetof(UIntFloat_t1624724448, ___intValue_1)); }
	inline uint32_t get_intValue_1() const { return ___intValue_1; }
	inline uint32_t* get_address_of_intValue_1() { return &___intValue_1; }
	inline void set_intValue_1(uint32_t value)
	{
		___intValue_1 = value;
	}

	inline static int32_t get_offset_of_doubleValue_2() { return static_cast<int32_t>(offsetof(UIntFloat_t1624724448, ___doubleValue_2)); }
	inline double get_doubleValue_2() const { return ___doubleValue_2; }
	inline double* get_address_of_doubleValue_2() { return &___doubleValue_2; }
	inline void set_doubleValue_2(double value)
	{
		___doubleValue_2 = value;
	}

	inline static int32_t get_offset_of_longValue_3() { return static_cast<int32_t>(offsetof(UIntFloat_t1624724448, ___longValue_3)); }
	inline uint64_t get_longValue_3() const { return ___longValue_3; }
	inline uint64_t* get_address_of_longValue_3() { return &___longValue_3; }
	inline void set_longValue_3(uint64_t value)
	{
		___longValue_3 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
@extends('admin/layout')

@section('main')

            @if(session('success') !== null)

                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        ×
                    </button>
                    {{session('success')}}

            @endif

                    {{$school->name}}

                    <form class="form-horizontal" action="/admin/school/{{$school->id}}" enctype="multipart/form-data" method="post">
                        {!! csrf_field() !!}
                        <fieldset>

                                Autobusi

                                    <input id="bus" name="bus" type="text" class="form-control input-md" value="{{$school->bus}}">
                                    Brojeve odvojite zarezom

                                Slike

                                    {!! Form::file('images[]', array('multiple'=>true)) !!}

                                    <button type="submit" class="btn btn-success">Izmeni</button>

                        </fieldset>
                    </form>

Slike:

                    @foreach($school->photos as $photo)

                            location}}" alt="" style="width: 100%">
                            id)}}">Obrisi

                    @endforeach

@endsection

@section('js')
@endsection


text:
function is_fedora {
  if [[ -x $(command -v dnf 2>/dev/null) ]]; then
      sudo dnf install -qy redhat-lsb-core
  else
      return
  fi

  if [[ -x $(command -v lsb_release 2>/dev/null) ]]; then
    os_VENDOR=$(lsb_release -i -s)

    if [ "$os_VENDOR" = "Fedora" ] || [ "$os_VENDOR" = "Red Hat" ] || \
        [ "$os_VENDOR" = "RedHatEnterpriseServer" ] || \
        [ "$os_VENDOR" = "RedHatEnterprise" ] || \
        [ "$os_VENDOR" = "CentOS" ] || [ "$os_VENDOR" = "OracleServer" ] || \
        [ "$os_VENDOR" = "Virtuozzo" ] ; then
        return 0
    else
        return
    fi
  fi
}

# The root password for the MySQL database; pass it in via
# MYSQL_ROOT_PW.
DB_ROOT_PW=${MYSQL_ROOT_PW:-insecure_slave}

# This user and its password are used by the tests, if you change it,
# your tests might fail.
DB_USER=openstack_citest
DB_PW=openstack_citest

if is_fedora ; then
    # services are not started by default

    # Enable and start MariaDB
    sudo systemctl enable --now mariadb

    # Intialiaze, Enable and start PostgreSQL
    pg_hba=/var/lib/pgsql/data/pg_hba.conf
    pg_conf=/var/lib/pgsql/data/postgresql.conf
    if ! sudo [ -e $pg_hba ]; then
        sudo postgresql-setup initdb
    fi
    sudo systemctl enable --now postgresql

    if sudo [ -e $pg_conf ]; then
        # Listen on all addresses
        sudo sed -i "/listen_addresses/s/.*/listen_addresses = '*'/" $pg_conf
    fi

    if sudo [ -e $pg_hba ];then
        # Do password auth from all IPv4 clients
        sudo sed -i "/^host/s/all\s\+127.0.0.1\/32\s\+ident/$DB_USER\t0.0.0.0\/0\tpassword/" $pg_hba
        # Do password auth for all IPv6 clients
        sudo sed -i "/^host/s/all\s\+::1\/128\s\+ident/$DB_USER\t::0\/0\tpassword/" $pg_hba
    fi

    sudo systemctl stop postgresql
    sudo systemctl start postgresql
fi

sudo -H mysqladmin -u root password $DB_ROOT_PW

# It's best practice to remove anonymous users from the database.  If
# a anonymous user exists, then it matches first for connections and
# other connections from that host will not work.
sudo -H mysql -u root -p$DB_ROOT_PW -h localhost -e "
    DELETE FROM mysql.user WHERE User='';
    FLUSH PRIVILEGES;
    CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PW';
    GRANT ALL PRIVILEGES ON *.* TO '$DB_USER'@'%' WITH GRANT OPTION;"

# Now create our database.
mysql -u $DB_USER -p$DB_PW -h 127.0.0.1 -e "
    SET default_storage_engine=MYISAM;
    DROP DATABASE IF EXISTS openstack_citest;
    CREATE DATABASE openstack_citest CHARACTER SET utf8;"

# Same for PostgreSQL
# The root password for the PostgreSQL database; pass it in via
# POSTGRES_ROOT_PW.
DB_ROOT_PW=${POSTGRES_ROOT_PW:-insecure_slave}

# Setup user
root_roles=$(sudo -u root sudo -u postgres -i psql -t -c "
   SELECT 'HERE' from pg_roles where rolname='$DB_USER'")
if [[ ${root_roles} == *HERE ]];then
    sudo -u root sudo -u postgres -i psql -c "ALTER ROLE $DB_USER WITH SUPERUSER LOGIN PASSWORD '$DB_PW'"
else
    sudo -u root sudo -u postgres psql -c "CREATE ROLE $DB_USER WITH SUPERUSER LOGIN PASSWORD '$DB_PW'"
fi

# Store password for tests
cat << EOF > $HOME/.pgpass
*:*:*:$DB_USER:$DB_PW
EOF
chmod 0600 $HOME/.pgpass

# Now create our database
psql -h 127.0.0.1 -U $DB_USER -d template1 -c "DROP DATABASE IF EXISTS openstack_citest"
createdb -h 127.0.0.1 -U $DB_USER -l C -T template0 -E utf8 openstack_citest


text:
from astropy import table
from astropy.io.ascii import core
from itertools import izip
import random
import string

class TableSuite:
    def setup(self):
        self.lst = []
        self.lst.append([random.randint(-500, 500) for i in range(1000)])
        self.lst.append([random.random() * 500 - 500 for i in range(1000)])
        self.lst.append([''.join([random.choice(string.uppercase) for j in
                            range(6)]) for i in range(1000)])
        self.cols = [core.Column(str(i + 1)) for i in range(3)]
        for col, x in izip(self.cols, self.lst):
            col.data = x
        self.table_cols = [table.Column(x) for x in self.lst]
        self.outputter = core.TableOutputter()
        self.table = table.Table()
    def time_table_outputter(self):
        self.outputter(self.cols, {'table': {}})
    def mem_table_outputter(self):
        return self.outputter(self.cols, {'table': {}})
    def time_str_vals_int(self):
        self.table_cols[0].iter_str_vals()
    def time_str_vals_float(self):
        self.table_cols[1].iter_str_vals()
    def time_str_vals_str(self):
        self.table_cols[2].iter_str_vals()
    def time_table_init_from_list(self):
        self.table._init_from_list(self.table_cols, ['1', '2', '3'],
                                   [None, None, None], 3, True)
    def mem_table_init(self):
        return table.Table(self.lst)


text:
package ripple

import (
	"code.google.com/p/go.net/websocket"
	"fmt"
	"launchpad.net/tomb"
	"log"
	"strconv"
	"time"
)

type Connection struct {
	Ledgers               chan *Ledger
	conn                  *websocket.Conn
	t                     tomb.Tomb
	currentLedgerIndex    uint64
	currentLedgerTxnsLeft int
	currentLedger         *Ledger
}

func NewConnection(uri string) (c *Connection, err error) {
	c = &Connection{
		Ledgers: make(chan *Ledger),
	}

	// Connect to websocket server
	c.conn, err = websocket.Dial(uri, "", "http://localhost")
	if err != nil {
		return
	}

	c.conn.SetDeadline(time.Now().Add(Timeout))

	// Subscribe to all transactions, ledgers, and server messages
	msg := "{\"command\":\"subscribe\",\"id\":1,\"streams\":[\"server\", \"ledger\", \"transactions\"]}"
	err = websocket.Message.Send(c.conn, msg)
	if err != nil {
		return
	}

	// Wait for ack
	var m Message
	err = websocket.JSON.Receive(c.conn, &m)
	if err != nil {
		return
	}

	if m.Type != "response" || m.Status != "success" {
		err = fmt.Errorf("Failed to subscribe: %s", m.Error)
		return
	}

	// Get server info
	msg = "{\"command\":\"server_info\",\"id\":3}"
	err = websocket.Message.Send(c.conn, msg)
	if err != nil {
		return
	}

	go c.loop()
	return
}

func (c *Connection) GetLedger(idx uint64) (err error) {
	// Requests a single ledger from the server

	c.conn.SetDeadline(time.Now().Add(Timeout))
	msg := fmt.Sprintf("{\"command\":\"ledger\",\"id\":2,\"ledger_index\":%d,\"transactions\":1,\"expand\":1}", idx)
	err = websocket.Message.Send(c.conn, msg)
	return
}

func (c *Connection) loop() {
	defer c.t.Done()
	defer close(c.Ledgers)
	defer c.conn.Close()

	for {
		var err error
		var m Message
		c.conn.SetDeadline(time.Now().Add(Timeout))
		err = websocket.JSON.Receive(c.conn, &m)
		if err != nil {
			c.t.Kill(err)
		}
		c.handleMessage(&m)

		// If the tomb is marked dying, exit cleanly
		select {
		case <-c.t.Dying():
			return
		default:
			//pass
		}
	}
}

func (c *Connection) handleMessage(m *Message) {
	switch {
	case m.Type == "ledgerClosed":
		c.currentLedgerIndex = m.LedgerIndex
		c.currentLedgerTxnsLeft = m.TxnCount
		c.currentLedger = &Ledger{
			CloseTime: m.LedgerTime,
			Closed:    true,
			Hash:      m.LedgerHash,
			Index:     strconv.FormatUint(m.LedgerIndex, 10),
		}

	case m.Type == "transaction":
		if m.LedgerIndex == c.currentLedgerIndex && m.Validated == true {
			m.Transaction.Meta = m.Meta
			c.currentLedger.Transactions = append(c.currentLedger.Transactions, m.Transaction)

			c.currentLedgerTxnsLeft--
			if c.currentLedgerTxnsLeft == 0 {
				c.Ledgers <- c.currentLedger
			}
		}

	case m.Type == "serverStatus":
		log.Printf("Rippled Server Status: %s", m.ServerStatus)

	case m.Type == "response" && m.Id == 2 && m.Status == "success":
		c.Ledgers <- m.Result.Ledger

	case m.Type == "response" && m.Id == 3 && m.Status == "success":
		log.Printf(
			"Connected to hostid %s (%s)",
			m.Result.Info.HostID,
			m.Result.Info.BuildVersion,
		)

	default:
		c.t.Kill(fmt.Errorf(
			"Unknown response: type=%s id=%d, status=%s, error=%s",
			m.Type,
			m.Id,
			m.Status,
			m.Error,
		))

	}
}


text:
.class public Lcom/android/server/NativeDaemonConnectorException;
.super Ljava/lang/Exception;
.source "NativeDaemonConnectorException.java"

# instance fields
.field private mCmd:Ljava/lang/String;

.field private mEvent:Lcom/android/server/NativeDaemonEvent;

# direct methods
.method public constructor <init>(Ljava/lang/String;)V
    .locals 0
    .param p1, "detailMessage"    # Ljava/lang/String;

    .prologue
    .line 30
    invoke-direct {p0, p1}, Ljava/lang/Exception;-><init>(Ljava/lang/String;)V

    .line 29
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Lcom/android/server/NativeDaemonEvent;)V
    .locals 2
    .param p1, "cmd"    # Ljava/lang/String;
    .param p2, "event"    # Lcom/android/server/NativeDaemonEvent;

    .prologue
    .line 38
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v1, "command \'"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "\' failed with \'"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "\'"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-direct {p0, v0}, Ljava/lang/Exception;-><init>(Ljava/lang/String;)V

    .line 39
    iput-object p1, p0, Lcom/android/server/NativeDaemonConnectorException;->mCmd:Ljava/lang/String;

    .line 40
    iput-object p2, p0, Lcom/android/server/NativeDaemonConnectorException;->mEvent:Lcom/android/server/NativeDaemonEvent;

    .line 37
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/lang/Throwable;)V
    .locals 0
    .param p1, "detailMessage"    # Ljava/lang/String;
    .param p2, "throwable"    # Ljava/lang/Throwable;

    .prologue
    .line 34
    invoke-direct {p0, p1, p2}, Ljava/lang/Exception;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    .line 33
    return-void
.end method

# virtual methods
.method public getCmd()Ljava/lang/String;
    .locals 1

    .prologue
    .line 48
    iget-object v0, p0, Lcom/android/server/NativeDaemonConnectorException;->mCmd:Ljava/lang/String;

    return-object v0
.end method

.method public getCode()I
    .locals 1

    .prologue
    .line 44
    iget-object v0, p0, Lcom/android/server/NativeDaemonConnectorException;->mEvent:Lcom/android/server/NativeDaemonEvent;

    invoke-virtual {v0}, Lcom/android/server/NativeDaemonEvent;->getCode()I

    move-result v0

    return v0
.end method

.method public rethrowAsParcelableException()Ljava/lang/IllegalArgumentException;
    .locals 2

    .prologue
    .line 56
    new-instance v0, Ljava/lang/IllegalStateException;

    invoke-virtual {p0}, Lcom/android/server/NativeDaemonConnectorException;->getMessage()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1, p0}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v0
.end method


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.buschmais.xo</groupId>
        <artifactId>xo.parent</artifactId>
        <version>2.0.0-SNAPSHOT</version>
    </parent>
    <artifactId>xo.impl</artifactId>

    <name>eXtended Objects - Implementation</name>

    <properties>
        <paxexam.version>3.5.0</paxexam.version>
    </properties>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.buschmais.xo</groupId>
            <artifactId>xo.api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.buschmais.xo</groupId>
            <artifactId>xo.spi</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe DatetimeDescriptionHelper do
  include DatetimeDescriptionHelper

  describe 'time in words from now with context' do
    before(:each) do
      stub!(:time_ago_in_words).and_return('time')
    end
    it 'should put "in" on the start when the time is in the future' do
      time = 2.months.from_now
      time_in_words_with_context(time).should == 'in time'
    end

    it 'should put "ago" on the end when the time is in the past' do
      time = 2.months.ago
      time_in_words_with_context(time).should == 'time ago'
    end

    it 'should use distance_of_time_in_words to englishificate the datetime' do
      should_receive(:time_ago_in_words).and_return('time')
      time_in_words_with_context(Time.now)
    end
  end

  describe 'regression test' do
    it 'should not crash on 100 years from now' do
      lambda { time_in_words_with_context(100.years.from_now) }.should_not raise_error(RangeError)
    end
    it 'should not crash on 30 years from now' do
      lambda { time_in_words_with_context(30.years.from_now) }.should_not raise_error(NoMethodError)
    end
  end

end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Casuarina paludosa var. robusta Macklin

### Remarks
null


text:
<?php

namespace Flugg\Responder\Tests\Unit;

use Flugg\Responder\Contracts\TransformFactory;
use Flugg\Responder\Exceptions\InvalidSerializerException;
use Flugg\Responder\Exceptions\InvalidSuccessSerializerException;
use Flugg\Responder\Pagination\CursorPaginator;
use Flugg\Responder\Pagination\PaginatorFactory;
use Flugg\Responder\Resources\ResourceFactory;
use Flugg\Responder\Serializers\SuccessSerializer;
use Flugg\Responder\Tests\TestCase;
use Flugg\Responder\TransformBuilder;
use Flugg\Responder\Transformers\Transformer;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use League\Fractal\Pagination\Cursor;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Serializer\JsonApiSerializer;
use Mockery;
use stdClass;

/**
 * Unit tests for the [Flugg\Responder\TransformBuilderTest] class.
 *
 * @package flugger/laravel-responder
 * @author  Alexander Tømmerås <flugged@gmail.com>
 * @license The MIT License
 */
class TransformBuilderTest extends TestCase
{
    /**
     * A mock of a [ResourceFactory] class.
     *
     * @var \Mockery\MockInterface
     */
    protected $resourceFactory;

    /**
     * A mock of a [TransformFactory] class.
     *
     * @var \Mockery\MockInterface
     */
    protected $transformFactory;

    /**
     * A mock of a [PaginatorFactory] class.
     *
     * @var \Mockery\MockInterface
     */
    protected $paginatorFactory;

    /**
     * A mock of a [ResourceInterface] class.
     *
     * @var \Mockery\MockInterface
     */
    protected $resource;

    /**
     * A mock of a [SerializerAbstract] class.
     *
     * @var \Mockery\MockInterface
     */
    protected $serializer;

    /**
     * The [TransformBuilder] class being tested.
     *
     * @var \Flugg\Responder\TransformBuilder
     */
    protected $builder;

    /**
     * Setup the test environment.
     *
     * @return void
     */
    public function setUp(): void
    {
        parent::setUp();

        $this->resourceFactory = Mockery::mock(ResourceFactory::class);
        $this->transformFactory = Mockery::mock(TransformFactory::class);
        $this->paginatorFactory = Mockery::mock(PaginatorFactory::class);
        $this->resourceFactory->shouldReceive('make')->andReturn($this->resource = $this->mockResource());
        $this->builder = new TransformBuilder($this->resourceFactory, $this->transformFactory, $this->paginatorFactory);
        $this->builder->serializer($this->serializer = Mockery::mock(SuccessSerializer::class));
    }

    /**
     * Assert that the [resource] method uses the [ResourceFactory] to create resources.
     */
    public function testResourceMethodUsesResourceFactory()
    {
        $result = $this->builder->resource($data = ['foo' => 1], $transformer = $this->mockTransformer(), $resourceKey = 'foo');

        $this->assertSame($this->builder, $result);
        $this->resourceFactory->shouldHaveReceived('make')->with($data, $transformer, $resourceKey)->once();
    }

    /**
     * Assert that the [resource] method sets cursor on the resource if data is an instance
     * of [CursorPaginator].
     */
    public function testResourceMethodSetsCursorOnResource()
    {
        $cursor = Mockery::mock(Cursor::class);
        $this->paginatorFactory->shouldReceive('makeCursor')->andReturn($cursor);

        $this->builder->resource($data = Mockery::mock(CursorPaginator::class));

        $this->resource->shouldHaveReceived('setCursor')->with($cursor)->once();
    }

    /**
     * Assert that the [resource] method sets paginator on the resource if data is an instance
     * of [LengthAwarePaginator].
     */
    public function testResourceMethodSetsPagintorOnResource()
    {
        $paginator = Mockery::mock(IlluminatePaginatorAdapter::class);
        $this->paginatorFactory->shouldReceive('make')->andReturn($paginator);

        $this->builder->resource($data = Mockery::mock(LengthAwarePaginator::class));

        $this->resource->shouldHaveReceived('setPaginator')->with($paginator)->once();
    }

    /**
     * Assert that the [cursor] method allows manually setting cursor on resource.
     */
    public function testCursorMethodSetsCursorsOnResource()
    {
        $cursor = Mockery::mock(Cursor::class);
        $this->paginatorFactory->shouldReceive('makeCursor')->andReturn($cursor);

        $this->builder->resource()->cursor($cursor);

        $this->resource->shouldHaveReceived('setCursor')->with($cursor)->once();
    }

    /**
     * Assert that the [paginator] method allows manually setting paginator on resource.
     */
    public function testPaginatorMethodSetsPaginatorsOnResource()
    {
        $paginator = Mockery::mock(IlluminatePaginatorAdapter::class);
        $this->paginatorFactory->shouldReceive('make')->andReturn($paginator);

        $this->builder->resource()->paginator($paginator);

        $this->resource->shouldHaveReceived('setPaginator')->with($paginator)->once();
    }

    /**
     * Assert that the [meta] method adds meta data to the resource.
     */
    public function testMetaMethodAddsMetaDataToResource()
    {
        $result = $this->builder->resource()->meta($meta = ['foo' => 1]);

        $this->assertSame($this->builder, $result);
        $this->resource->shouldHaveReceived('setMeta')->with($meta)->once();
    }

    /**
     * Assert that the [transform] method transforms data using [TransformFactory].
     */
    public function testTransformMethodUsesTransformFactoryToTransformData()
    {
        $this->transformFactory->shouldReceive('make')->andReturn($data = ['foo' => 123]);

        $result = $this->builder->resource()->transform();

        $this->assertEquals($data, $result);
        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => [],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [serializer] method sets the serializer that is sent to the
     * [TransformFactory].
     */
    public function testSerializerMethodSetsSerializerSentToTransformFactory()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->serializer($serializer = new JsonApiSerializer)->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $serializer, [
            'includes' => [],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [serializer] method allows class name strings.
     */
    public function testSerializerMethodAllowsClassNameStrings()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->serializer($serializer = JsonApiSerializer::class)->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $serializer, [
            'includes' => [],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [serializer] method throws [InvalidSuccessSerializerException] exception when
     * given an invalid serializer.
     */
    public function testSerializerMethodThrowsExceptionWhenGivenInvalidSerializer()
    {
        $this->expectException(InvalidSuccessSerializerException::class);

        $this->builder->serializer($serializer = stdClass::class);
    }

    /**
     * Assert that the [with] method sets the included relationships that are sent to the
     * [TransformFactory].
     */
    public function testWithMethodSetsIncludedRelationsSentToFactory()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->with($relations = ['foo', 'bar'])->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => $relations,
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [with] method allows to be called multiple times and accepts strings
     * as parameters.
     */
    public function testWithMethodAllowsMultipleCallsAndStrings()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->with('foo')->with('bar', 'baz')->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => ['foo', 'bar', 'baz'],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [without] method sets the excluded relationships that are sent to the
     * [TransformFactory].
     */
    public function testWithoutMethodSetsExcludedRelationsSentToFactory()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->without($relations = ['foo', 'bar'])->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => [],
            'excludes' => $relations,
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [with] method allows to be called multiple times and accepts strings
     * as parameters.
     */
    public function testWithoutMethodAllowsMultipleCallsAndStrings()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->without('foo')->without('bar', 'baz')->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => [],
            'excludes' => ['foo', 'bar', 'baz'],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [transform] method extracts default relationships from transformer and
     * automatically eager loads all relationships.
     */
    public function testTransformMethodExtractsAndEagerLoadsRelations()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);
        $this->resource->shouldReceive('getData')->andReturn($model = Mockery::mock(Model::class));
        $model->shouldReceive('load')->andReturnSelf();
        $this->resource->shouldReceive('getTransformer')->andReturn($transformer = Mockery::mock(Transformer::class));
        $transformer->shouldReceive('relations')->andReturn(['foo' => null, 'bar' => null]);
        $transformer->shouldReceive('defaultRelations')->andReturn(['baz' => null]);

        $this->builder->resource()->with($relations = ['foo' => function () { }, 'bar'])->transform();

        $model->shouldHaveReceived('load')->with(Mockery::on(function ($argument) {
            return Arr::has($argument, ['foo', 'bar', 'baz']);
        }))->once();
        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => ['foo', 'bar', 'baz'],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [transform] method extracts default relationships from transformer and
     * automatically eager loads all relationships even when the relation name contains
     * inclusion parameters separated with a colon.
     */
    public function testTransformMethodExtractsAndEagerLoadsRelationsWithParameters()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);
        $this->resource->shouldReceive('getData')->andReturn($model = Mockery::mock(Model::class));
        $model->shouldReceive('load')->andReturnSelf();
        $this->resource->shouldReceive('getTransformer')->andReturn($transformer = Mockery::mock(Transformer::class));
        $transformer->shouldReceive('relations')->andReturn(['foo:first(aa|bb)' => null, 'bar:second(cc|dd)' => null]);
        $transformer->shouldReceive('defaultRelations')->andReturn([]);

        $this->builder->resource()->with(['foo:first(aa|bb)', 'bar:second(cc|dd)'])->transform();

        $model->shouldHaveReceived('load')->with(Mockery::on(function ($argument) {
            return Arr::has($argument, ['foo', 'bar']);
        }))->once();
        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => ['foo:first(aa|bb)', 'bar:second(cc|dd)'],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [transform] method doesn't eager load relations not present in the $relations list.
     */
    public function testTransformMethodDoesntEagerLoadNonListedRelations()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);
        $this->resource->shouldReceive('getData')->andReturn($model = Mockery::mock(Model::class));
        $model->shouldReceive('load')->andReturnSelf();
        $this->resource->shouldReceive('getTransformer')->andReturn($transformer = Mockery::mock(Transformer::class));
        $transformer->shouldReceive('relations')->andReturn(['foo' => null]);
        $transformer->shouldReceive('defaultRelations')->andReturn([]);

        $this->builder->resource()->with(['foo', 'bar'])->transform();

        $model->shouldHaveReceived('load')->with(Mockery::on(function ($argument) {
            return Arr::has($argument, 'foo') && count($argument) === 1;
        }))->once();
        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => ['foo'],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [transform] method doesn't eager load relations which has an include method.
     */
    public function testTransformMethodDoesntEagerLoadRelationsWithAnIncludeMethod()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);
        $this->resource->shouldReceive('getData')->andReturn($model = Mockery::mock(Model::class));
        $model->shouldReceive('load')->andReturnSelf();
        $transformer = Mockery::mock(TransformerWithIncludeMethods::class);
        $this->resource->shouldReceive('getTransformer')->andReturn($transformer);
        $transformer->shouldReceive([
            'relations' => ['foo' => null, 'bar' => null],
            'defaultRelations' => ['baz' => null],
        ]);

        $this->builder->resource()->with($relations = ['foo', 'bar'])->transform();

        $model->shouldHaveReceived('load')->with(Mockery::on(function ($argument) {
            return Arr::has($argument, 'foo') && count($argument) === 1;
        }))->once();
        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => ['foo', 'bar', 'baz'],
            'excludes' => [],
            'fieldsets' => [],
        ])->once();
    }

    /**
     * Assert that the [only] method sets the filtered fields that are sent to the
     * [TransformFactory].
     */
    public function testOnlyMethodSetsFilteredFieldsSentToFactory()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->only($fields = ['foo', 'bar'])->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => [],
            'excludes' => [],
            'fieldsets' => $fields,
        ])->once();
    }

    /**
     * Assert that the [only] method allows to be called multiple times and accepts strings
     * as parameters.
     */
    public function testOnlyMethodAllowsMultipleCallsAndStrings()
    {
        $this->transformFactory->shouldReceive('make')->andReturn([]);

        $this->builder->resource()->only('foo')->only('bar', 'baz')->transform();

        $this->transformFactory->shouldHaveReceived('make')->with($this->resource, $this->serializer, [
            'includes' => [],
            'excludes' => [],
            'fieldsets' => ['foo', 'bar', 'baz'],
        ])->once();
    }
}

class TransformerWithIncludeMethods extends Transformer
{
    public function includeBar() { }

    public function includeBaz() { }
}


text:
#ifndef MTBL_H
#define MTBL_H

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>
#include <stdbool.h>
#include <stdint.h>

typedef enum {
	mtbl_res_failure = 0,
	mtbl_res_success = 1
} mtbl_res;

/* compression */

typedef enum {
	MTBL_COMPRESSION_NONE = 0,
	MTBL_COMPRESSION_SNAPPY = 1,
	MTBL_COMPRESSION_ZLIB = 2,
	MTBL_COMPRESSION_LZ4 = 3,
	MTBL_COMPRESSION_LZ4HC = 4,
	MTBL_COMPRESSION_ZSTD = 5,
} mtbl_compression_type;

#define MTBL_FILESET_RELOAD_INTERVAL_NEVER	UINT32_MAX /* time interval to never reload filesets */

mtbl_res
mtbl_compress(
	mtbl_compression_type,
	const uint8_t *input,
	const size_t input_size,
	uint8_t **output,
	size_t *output_size);

mtbl_res
mtbl_compress_level(
	mtbl_compression_type,
	int compression_level,
	const uint8_t *input,
	const size_t input_size,
	uint8_t **output,
	size_t *output_size);

mtbl_res
mtbl_decompress(
	mtbl_compression_type,
	const uint8_t *input,
	const size_t input_size,
	uint8_t **output,
	size_t *output_size);

const char *
mtbl_compression_type_to_str(mtbl_compression_type);

mtbl_res
mtbl_compression_type_from_str(const char *, mtbl_compression_type *);

/* exported types */

struct mtbl_iter;
struct mtbl_source;

struct mtbl_reader;
struct mtbl_reader_options;
struct mtbl_writer;
struct mtbl_writer_options;

struct mtbl_metadata;
struct mtbl_merger;
struct mtbl_merger_options;
struct mtbl_fileset;
struct mtbl_fileset_options;
struct mtbl_sorter;
struct mtbl_sorter_options;

typedef void
(*mtbl_merge_func)(void *clos,
	const uint8_t *key, size_t len_key,
	const uint8_t *val0, size_t len_val0,
	const uint8_t *val1, size_t len_val1,
	uint8_t **merged_val, size_t *len_merged_val);

typedef int
(*mtbl_dupsort_func)(void *clos,
	const uint8_t *key, size_t len_key,
	const uint8_t *val0, size_t len_val0,
	const uint8_t *val1, size_t len_val1);

typedef void *
(*mtbl_merge_init_func)(void);

typedef void
(*mtbl_merge_free_func)(void *clos);

typedef bool
(*mtbl_filename_filter_func)(const char *fname, void *clos);

/* iter */

typedef mtbl_res
(*mtbl_iter_seek_func)(
	void *,
	const uint8_t *key, size_t len_key);

typedef mtbl_res
(*mtbl_iter_next_func)(
	void *,
	const uint8_t **key, size_t *len_key,
	const uint8_t **val, size_t *len_val);

typedef void
(*mtbl_iter_free_func)(void *);

void
mtbl_iter_destroy(struct mtbl_iter **);

mtbl_res
mtbl_iter_seek(
	struct mtbl_iter *,
	const uint8_t *key, size_t len_key)
__attribute__((warn_unused_result));

mtbl_res
mtbl_iter_next(
	struct mtbl_iter *,
	const uint8_t **key, size_t *len_key,
	const uint8_t **val, size_t *len_val)
__attribute__((warn_unused_result));

/* source */

typedef struct mtbl_iter *
(*mtbl_source_iter_func)(void *);

typedef struct mtbl_iter *
(*mtbl_source_get_func)(void *, const uint8_t *key, size_t len_key);

typedef struct mtbl_iter *
(*mtbl_source_get_prefix_func)(void *, const uint8_t *key, size_t len_key);

typedef struct mtbl_iter *
(*mtbl_source_get_range_func)(
	void *,
	const uint8_t *key0, size_t len_key0,
	const uint8_t *key1, size_t len_key1);

typedef void (*mtbl_source_free_func)(void *);

struct mtbl_source *
mtbl_source_init(
	mtbl_source_iter_func,
	mtbl_source_get_func,
	mtbl_source_get_prefix_func,
	mtbl_source_get_range_func,
	mtbl_source_free_func,
	void *clos);

void
mtbl_source_destroy(struct mtbl_source **);

struct mtbl_iter *
mtbl_source_iter(const struct mtbl_source *);

struct mtbl_iter *
mtbl_source_get(const struct mtbl_source *, const uint8_t *key, size_t len_key);

struct mtbl_iter *
mtbl_source_get_prefix(const struct mtbl_source *, const uint8_t *key, size_t len_key);

struct mtbl_iter *
mtbl_source_get_range(
	const struct mtbl_source *,
	const uint8_t *key0, size_t len_key0,
	const uint8_t *key1, size_t len_key1);

mtbl_res
mtbl_source_write(const struct mtbl_source *, struct mtbl_writer *)
__attribute__((warn_unused_result));

/* writer */

struct mtbl_writer *
mtbl_writer_init(const char *fname, const struct mtbl_writer_options *);

struct mtbl_writer *
mtbl_writer_init_fd(int fd, const struct mtbl_writer_options *);

void
mtbl_writer_destroy(struct mtbl_writer **);

mtbl_res
mtbl_writer_add(
	struct mtbl_writer *,
	const uint8_t *key, size_t len_key,
	const uint8_t *val, size_t len_val)
__attribute__((warn_unused_result));

/* writer options */

struct mtbl_writer_options *
mtbl_writer_options_init(void);

void
mtbl_writer_options_destroy(struct mtbl_writer_options **);

void
mtbl_writer_options_set_compression(
	struct mtbl_writer_options *,
	mtbl_compression_type);

void
mtbl_writer_options_set_compression_level(
	struct mtbl_writer_options *,
	int);

void
mtbl_writer_options_set_block_size(
	struct mtbl_writer_options *,
	size_t);

void
mtbl_writer_options_set_block_restart_interval(
	struct mtbl_writer_options *,
	size_t);

/* reader */

struct mtbl_reader *
mtbl_reader_init(const char *fname, const struct mtbl_reader_options *);

struct mtbl_reader *
mtbl_reader_init_fd(int fd, const struct mtbl_reader_options *);

void
mtbl_reader_destroy(struct mtbl_reader **);

const struct mtbl_source *
mtbl_reader_source(struct mtbl_reader *);

const struct mtbl_metadata *
mtbl_reader_metadata(struct mtbl_reader *);

/* reader options */

struct mtbl_reader_options *
mtbl_reader_options_init(void);

void
mtbl_reader_options_destroy(struct mtbl_reader_options **);

void
mtbl_reader_options_set_madvise_random(struct mtbl_reader_options *, bool);

void
mtbl_reader_options_set_verify_checksums(struct mtbl_reader_options *, bool);

/* metadata */

typedef enum {
	MTBL_FORMAT_V1 = 0,
	MTBL_FORMAT_V2 = 1
} mtbl_file_version;

mtbl_file_version
mtbl_metadata_file_version(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_index_block_offset(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_data_block_size(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_compression_algorithm(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_count_entries(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_count_data_blocks(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_bytes_data_blocks(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_bytes_index_block(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_bytes_keys(const struct mtbl_metadata *);

uint64_t
mtbl_metadata_bytes_values(const struct mtbl_metadata *);

/* merger */

struct mtbl_merger *
mtbl_merger_init(const struct mtbl_merger_options *);

void
mtbl_merger_destroy(struct mtbl_merger **);

void
mtbl_merger_add_source(struct mtbl_merger *, const struct mtbl_source *);

const struct mtbl_source *
mtbl_merger_source(struct mtbl_merger *);

/* merger options */

struct mtbl_merger_options *
mtbl_merger_options_init(void);

void
mtbl_merger_options_destroy(struct mtbl_merger_options **);

void
mtbl_merger_options_set_merge_func(
	struct mtbl_merger_options *,
	mtbl_merge_func,
	void *clos);

void
mtbl_merger_options_set_dupsort_func(
	struct mtbl_merger_options *,
	mtbl_dupsort_func,
	void *clos);

/* fileset */

struct mtbl_fileset *
mtbl_fileset_init(const char *fname, const struct mtbl_fileset_options *);

struct mtbl_fileset *
mtbl_fileset_dup(struct mtbl_fileset *, const struct mtbl_fileset_options *);

void
mtbl_fileset_destroy(struct mtbl_fileset **);

void
mtbl_fileset_reload(struct mtbl_fileset *);

void
mtbl_fileset_reload_now(struct mtbl_fileset *);

const struct mtbl_source *
mtbl_fileset_source(struct mtbl_fileset *);

void
mtbl_fileset_partition(struct mtbl_fileset *,
		mtbl_filename_filter_func,
		void *,
		struct mtbl_merger **,
		struct mtbl_merger **);

/* fileset options */

struct mtbl_fileset_options *
mtbl_fileset_options_init(void);

void
mtbl_fileset_options_destroy(struct mtbl_fileset_options **);

void
mtbl_fileset_options_set_merge_func(
	struct mtbl_fileset_options *,
	mtbl_merge_func,
	void *clos);

void
mtbl_fileset_options_set_dupsort_func(
	struct mtbl_fileset_options *,
	mtbl_dupsort_func,
	void *clos);

void

mtbl_fileset_options_set_filename_filter_func(
	struct mtbl_fileset_options *,
	mtbl_filename_filter_func,
	void *clos);

void
mtbl_fileset_options_set_reload_interval(
	struct mtbl_fileset_options *,
	uint32_t reload_interval);

/* sorter */

struct mtbl_sorter *
mtbl_sorter_init(const struct mtbl_sorter_options *);

void
mtbl_sorter_destroy(struct mtbl_sorter **);

mtbl_res
mtbl_sorter_add(struct mtbl_sorter *,
	const uint8_t *key, size_t len_key,
	const uint8_t *val, size_t len_val)
__attribute__((warn_unused_result));

mtbl_res
mtbl_sorter_write(struct mtbl_sorter *, struct mtbl_writer *)
__attribute__((warn_unused_result));

struct mtbl_iter *
mtbl_sorter_iter(struct mtbl_sorter *s);

/* sorter options */

struct mtbl_sorter_options *
mtbl_sorter_options_init(void);

void
mtbl_sorter_options_destroy(struct mtbl_sorter_options **);

void
mtbl_sorter_options_set_merge_func(
	struct mtbl_sorter_options *,
	mtbl_merge_func merge_fp,
	void *clos);

void
mtbl_sorter_options_set_temp_dir(
	struct mtbl_sorter_options *,
	const char *);

void
mtbl_sorter_options_set_max_memory(
	struct mtbl_sorter_options *,
	size_t);

/* crc32c */

uint32_t
mtbl_crc32c(const uint8_t *buffer, size_t length);

/* fixed */

size_t
mtbl_fixed_encode32(uint8_t *dst, uint32_t value);

size_t
mtbl_fixed_encode64(uint8_t *dst, uint64_t value);

uint32_t
mtbl_fixed_decode32(const uint8_t *ptr);

uint64_t
mtbl_fixed_decode64(const uint8_t *ptr);

/* varint */

unsigned
mtbl_varint_length(uint64_t v);

unsigned
mtbl_varint_length_packed(const uint8_t *buf, size_t len_buf);

size_t
mtbl_varint_encode32(uint8_t *ptr, uint32_t value);

size_t
mtbl_varint_encode64(uint8_t *ptr, uint64_t value);

size_t
mtbl_varint_decode32(const uint8_t *ptr, uint32_t *value);

size_t
mtbl_varint_decode64(const uint8_t *ptr, uint64_t *value);

#ifdef __cplusplus
}
#endif

#endif /* MTBL_H */


text:
#include <list>
#include <sstream>
#include <stdlib.h>
#include <time.h>

#include "game.h"
#include "settings.h"
#include "sprite.h"
#include "cursor.h"
#include "thing.h"
#include "label.h"

Game::Game()
{
	running = true;
	window.w = WINDOW_WIDTH;
	window.h = WINDOW_HEIGHT;

	update_timer_id = NULL;

	pause_time = 0;
}

bool Game::init()
{
	GLdouble aspect;
	int i;
	texture* heart_texture;

	srand(time(NULL));

	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0)
		return false;

	TTF_Init();

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);

	SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 8);

	if ((surf_display = SDL_SetVideoMode(window.w, window.h, 32, SDL_HWSURFACE |
			SDL_GL_DOUBLEBUFFER | SDL_OPENGL)) == NULL)
		return false;

	glClearColor(0, 0, 0, 0);
	glClearDepth(1.0f);

	glViewport(0, 0, window.w, window.h);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	// Set up coordinate system. Initial window is from -1 to 1 on each
	// axis, so we set the window coordinates to the window dimensions
	// in pixels with matrix transformations.
	aspect = (GLdouble)window.w/(GLdouble)window.h;

	glOrtho(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, -1.0, 1.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glScalef(2.0/window.h, 2.0/window.h, 0.0);
	glTranslatef(-(window.w/2), -(window.h/2), 0.0);

	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	// Texture loading must be done after the call to SDL_SetVideoMode.
	load_thing_textures();

	title_sprite = new Sprite("title.png");
	title_sprite->x = window.w/2;
	title_sprite->y = window.h/2 + title_sprite->height/2 + WINDOW_MARGIN;
	title_sprite->update();

	full_jar_sprite = new Sprite("jar_full.png");
	full_jar_sprite->x = WINDOW_MARGIN + (full_jar_sprite->width/2);
	full_jar_sprite->y = window.h - (WINDOW_MARGIN + (full_jar_sprite->height/2));
	full_jar_sprite->update();

	heart_texture = Sprite::load_texture("heart.png");
	heart_sprites.resize(MAX_LIVES);
	for (i = 0; i <MAX_LIVES ; i++)
	{
		heart_sprites[i] = Sprite::from_texture(heart_texture);
		heart_sprites[i]->x = (i + 1)*(heart_sprites[i]->width/2 + WINDOW_MARGIN);
		heart_sprites[i]->y = WINDOW_MARGIN + heart_sprites[i]->height/2;
		heart_sprites[i]->update();
	}

	splat_sprite = new Sprite("splat.png");

	cursor = new Cursor(&score, &lives);

	if ((label_font = TTF_OpenFont(DATADIR "/fonts/FredokaOne-Regular.ttf", 16)) == NULL ||
			(label_font_big = TTF_OpenFont(DATADIR "/fonts/FredokaOne-Regular.ttf", 32)) == NULL)
		return false;

	score_label = new Label(label_font, "0", WINDOW_MARGIN + 10 + full_jar_sprite->width,
			window.h - WINDOW_MARGIN - (full_jar_sprite->height/2),
			ANCHOR_LEFT, ANCHOR_CENTER);

	lose_label = new Label(label_font_big, "You filled N jars!", window.w/2, window.h/2, ANCHOR_CENTER, ANCHOR_CENTER);
	click_label = new Label(label_font_big, "Click to Start", window.w/2, window.h/2 - WINDOW_MARGIN, ANCHOR_CENTER, ANCHOR_TOP);

	background = new Background;
	background->update(0);

	return true;
}

void Game::reset()
{
	score = 0;
	lives = MAX_LIVES;
	pickle_prob = 1.0;
	max_drop = 1;

	cursor->x = window.h/2;
	cursor->update(0);
	things.resize(0);

	drop_interval = DROP_INTERVAL;

	paused = false;
}

void Game::change_state(int new_state)
{
	std::stringstream ss;

	state = new_state;

	paused = false;

	if (update_timer_id != NULL)
		SDL_RemoveTimer(update_timer_id);

	background->unhurt();
	background->unscore();

	switch (state)
	{
		case GAME_TITLE:
			SDL_WM_GrabInput(SDL_GRAB_OFF);
			SDL_ShowCursor(1);
			break;

		case GAME_PLAYING:
			SDL_WM_GrabInput(SDL_GRAB_ON);
			SDL_ShowCursor(0);

			reset();
			score_label->set_text(0);

			last_update = last_drop = last_speedup = SDL_GetTicks();
			update_timer_id = SDL_AddTimer(UPDATE_INTERVAL, update_timer, NULL);
			break;

		case GAME_LOSE:
			SDL_WM_GrabInput(SDL_GRAB_OFF);
			SDL_ShowCursor(1);

			ss << "You filled " << (score / JAR_CAPACITY) << " jars!";
			lose_label->set_text(ss.str().c_str());

			things.clear();

			// Drop jars the player filled. The first subtraction
			// gets rid of a partial jar.
			for (score -= JAR_CAPACITY; score >= 0; score -= JAR_CAPACITY)
				things.push_back(Thing::jar(&things));

			splat_sprite->x = window.w/2;
			splat_sprite->y = window.h/2;
			splat_sprite->opacity = 1;
			splat_sprite->update();

			last_update = SDL_GetTicks();
			update_timer_id = SDL_AddTimer(UPDATE_INTERVAL, update_timer, NULL);
			break;
	}
}

int Game::loop()
{
	if (!init())
		return 1;

	SDL_Event event;

	change_state(GAME_TITLE);

	while (running)
	{
		while (SDL_PollEvent(&event))
			handle(&event);

		render();
	}

	cleanup();

	return 0;
}

void Game::handle(SDL_Event* event)
{
	switch (event->type)
	{
		case SDL_USEREVENT:
			switch (event->user.code)
			{
				case UPDATE_TIMER:
					update();
					break;
				case UNHURT_TIMER:
					background->unhurt();
					break;
				case UNSCORE_TIMER:
					background->unscore();
					break;
			}
			break;

		case SDL_KEYDOWN:
			switch (event->key.keysym.sym)
			{
				case SDLK_ESCAPE:
					running = false;
					break;

				case SDLK_p:
					toggle_pause();
					break;

				default:
					break;
			}
			break;

		case SDL_MOUSEMOTION:
			switch (state)
			{
				case GAME_PLAYING:
					if (!paused)
						cursor->move(event->motion.xrel);
					break;
			}
			break;

		case SDL_MOUSEBUTTONDOWN:
			switch (state)
			{
				case GAME_TITLE:
					change_state(GAME_PLAYING);
					break;

				case GAME_LOSE:
					change_state(GAME_TITLE);
					break;
			}
			break;

		case SDL_QUIT:
			running = false;
			break;
	}
}

void Game::update()
{
	Uint32 t = SDL_GetTicks(), dt = t - last_update;
	GLdouble secs = (GLdouble)dt/1000.0;

	last_update = t;

	if (paused)
	{
		// Keep track of the amount of time spent paused.
		pause_time += dt;
		return;
	}

	std::list<Thing*>::iterator it;
	std::list<Thing*> remove;

	switch (state)
	{
		case GAME_PLAYING:
			// If collision detection is done before updating positions, it looks
			// more like the collision should've happened.
			for (it = things.begin(); it != things.end(); it++)
			{
				if ((*it)->collide(cursor))
				{
					(*it)->on_hit();

					if ((*it)->pickle)
					{
						score++;
						score_label->set_text(score/JAR_CAPACITY);

						// Lives reset when a jar is filled
						if (score % JAR_CAPACITY == 0)
						{
							background->score();
							lives = MAX_LIVES;
						}
					}
					else
					{
						lives--;
						background->hurt();
						if (lives <= 0)
						{
							change_state(GAME_LOSE);
							return;
						}
					}
				}
				else if ((*it)->y < -100)
				{
					// Remove things that fall off the screen.
					remove.push_back(*it);
				}
				(*it)->update(secs);
			}

			if (t - last_drop >= drop_interval)
			{
				last_drop = t;
				drop();
			}

			if (t - last_speedup >= SPEEDUP_INTERVAL)
			{
				last_speedup = t;
				speed_up();
			}

			cursor->update(secs);

			background->update(secs);

			for (it = remove.begin(); it != remove.end(); it++)
				things.remove(*it);
			break;

		case GAME_LOSE:
			for (it = things.begin(); it != things.end(); it++)
			{
				if ((*it)->y < -100)
				{
					// Remove things that fall off the screen.
					remove.push_back(*it);
				}
				(*it)->update(secs);
			}

			for (it = remove.begin(); it != remove.end(); it++)
				things.remove(*it);

			if (splat_sprite->opacity > 0)
			{
				splat_sprite->opacity -= 1 * secs;
				splat_sprite->y -= SPLAT_SPEED * secs;
				splat_sprite->update();
			}

			break;
	}
}

/* Drop a random amount of things. */
void Game::drop()
{
	if (state != GAME_PLAYING)
		return;

	int i = ((rand()/(float)RAND_MAX) * max_drop);
	if (i < 1)
		i = 1;

	for (; i > 0; i--)
		things.push_back(Thing::pick(pickle_prob, &things));
}

void Game::speed_up()
{
	if (state != GAME_PLAYING)
		return;

	// Probability of dropping a pickle decreases
	pickle_prob = pickle_prob * PICKLE_PROB_REDUCTION;
	if (pickle_prob < PICKLE_PROB_MIN)
		pickle_prob = PICKLE_PROB_MIN;

	// Delay between drops decreases
	drop_interval *= DROP_INTERVAL_REDUCTION;
	if (drop_interval < DROP_INTERVAL_MIN)
		drop_interval = DROP_INTERVAL_MIN;

	// Chance that the max simultaneous drop will increase
	if (rand()/(float)RAND_MAX > ADDITIONAL_DROP_PROB)
		max_drop++;
}

void Game::toggle_pause()
{
	if (state == GAME_PLAYING)
	{
		paused = !paused;

		if (paused)
		{
			pause_time = 0;

			SDL_WM_GrabInput(SDL_GRAB_OFF);
			SDL_ShowCursor(1);
		}
		else
		{
			// Drops and speedups ignore pause time.
			last_drop += pause_time;
			last_speedup += pause_time;

			SDL_WM_GrabInput(SDL_GRAB_ON);
			SDL_ShowCursor(0);
		}
	}
}

void Game::render()
{
	std::list<Thing*>::iterator it;
	int i;

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);

	background->draw();

	switch (state)
	{
		case GAME_TITLE:
			title_sprite->draw();
			click_label->draw();
			break;

		case GAME_PLAYING:
			for (it = things.begin(); it != things.end(); it++)
				(*it)->draw();

			cursor->draw();

			for (i = 0; i < lives; i++)
				heart_sprites[i]->draw();

			full_jar_sprite->draw();
			score_label->draw();
			break;

		case GAME_LOSE:
			for (it = things.begin(); it != things.end(); it++)
				(*it)->draw();
			lose_label->draw();
			if (splat_sprite->opacity > 0)
				splat_sprite->draw();
			break;
	}

	SDL_GL_SwapBuffers();
}

void Game::cleanup()
{
	SDL_FreeSurface(surf_display);

	SDL_Quit();
	TTF_Quit();
}

void push_timer_event(int code)
{
	SDL_Event event;
	SDL_UserEvent userevent;

	userevent.type = SDL_USEREVENT;
	userevent.code = code;
	userevent.data1 = NULL;
	userevent.data2 = NULL;

	event.type = SDL_USEREVENT;
	event.user = userevent;

	SDL_PushEvent(&event);

	return;
}

Uint32 update_timer(Uint32 interval, void* param)
{
	push_timer_event(UPDATE_TIMER);
	return interval;
}


text:
package com.some.servlet.message.resp;

/**
 * Created by mqddb on 2014/5/12.
 */
public class Article {
}


text:
package com.html5parser.constants;

import java.util.HashMap;
import java.util.Map;

public class SVGAttributesTable {

	/**
	 * Value description:
	 *
	 * first column is the attribute name
	 * second column is the fixed attribute name
	 */
	public static final Map<String, String> TABLE;
	static {
		TABLE = new HashMap<String, String>();
		TABLE.put("attributename", "attributeName");
		TABLE.put("attributetype", "attributeType");
		TABLE.put("basefrequency", "baseFrequency");
		TABLE.put("baseprofile", "baseProfile");
		TABLE.put("calcmode", "calcMode");
		TABLE.put("clippathunits", "clipPathUnits");
		TABLE.put("contentscripttype", "contentScriptType");
		TABLE.put("contentstyletype", "contentStyleType");
		TABLE.put("diffuseconstant", "diffuseConstant");
		TABLE.put("edgemode", "edgeMode");
		TABLE.put("externalresourcesrequired", "externalResourcesRequired");
		TABLE.put("filterres", "filterRes");
		TABLE.put("filterunits", "filterUnits");
		TABLE.put("glyphref", "glyphRef");
		TABLE.put("gradienttransform", "gradientTransform");
		TABLE.put("gradientunits", "gradientUnits");
		TABLE.put("kernelmatrix", "kernelMatrix");
		TABLE.put("kernelunitlength", "kernelUnitLength");
		TABLE.put("keypoints", "keyPoints");
		TABLE.put("keysplines", "keySplines");
		TABLE.put("keytimes", "keyTimes");
		TABLE.put("lengthadjust", "lengthAdjust");
		TABLE.put("limitingconeangle", "limitingConeAngle");
		TABLE.put("markerheight", "markerHeight");
		TABLE.put("markerunits", "markerUnits");
		TABLE.put("markerwidth", "markerWidth");
		TABLE.put("maskcontentunits", "maskContentUnits");
		TABLE.put("maskunits", "maskUnits");
		TABLE.put("numoctaves", "numOctaves");
		TABLE.put("pathlength", "pathLength");
		TABLE.put("patterncontentunits", "patternContentUnits");
		TABLE.put("patterntransform", "patternTransform");
		TABLE.put("patternunits", "patternUnits");
		TABLE.put("pointsatx", "pointsAtX");
		TABLE.put("pointsaty", "pointsAtY");
		TABLE.put("pointsatz", "pointsAtZ");
		TABLE.put("preservealpha", "preserveAlpha");
		TABLE.put("preserveaspectratio", "preserveAspectRatio");
		TABLE.put("primitiveunits", "primitiveUnits");
		TABLE.put("refx", "refX");
		TABLE.put("refy", "refY");
		TABLE.put("repeatcount", "repeatCount");
		TABLE.put("repeatdur", "repeatDur");
		TABLE.put("requiredextensions", "requiredExtensions");
		TABLE.put("requiredfeatures", "requiredFeatures");
		TABLE.put("specularconstant", "specularConstant");
		TABLE.put("specularexponent", "specularExponent");
		TABLE.put("spreadmethod", "spreadMethod");
		TABLE.put("startoffset", "startOffset");
		TABLE.put("stddeviation", "stdDeviation");
		TABLE.put("stitchtiles", "stitchTiles");
		TABLE.put("surfacescale", "surfaceScale");
		TABLE.put("systemlanguage", "systemLanguage");
		TABLE.put("tablevalues", "tableValues");
		TABLE.put("targetx", "targetX");
		TABLE.put("targety", "targetY");
		TABLE.put("textlength", "textLength");
		TABLE.put("viewbox", "viewBox");
		TABLE.put("viewtarget", "viewTarget");
		TABLE.put("xchannelselector", "xChannelSelector");
		TABLE.put("ychannelselector", "yChannelSelector");
		TABLE.put("zoomandpan", "zoomAndPan");
	}

}


text:
(function() {
    var words = ["cherry", "apple", "blueberry"];

    var totalChars = words.reduce(function(sum, word) {
        return sum + word.length;
    }, 0);

    console.log("There are a total of " + totalChars + " characters in these words.");
})();


text:
ape.log_setter.cleanup
======================

.. currentmodule:: ape.log_setter

.. autofunction:: cleanup


text:
namespace pwn
{
namespace render
{
    Camera::Camera(
            const math::point3& position,
            const math::quat& rotation,
            real fov,
            real znear,
            real zfar)
        : position(position)
        , rotation(rotation)
        , fov(fov)
        , znear(znear)
        , zfar(zfar)
    {
    }

    void
    Camera::lookAt(const math::point3& p)
    {
        rotation = math::qLookAt(position.vec, p.vec, math::Up());
    }
}
}


text:
flightshooter
=============

A cocos2dx practice game.


text: Web pages full of experiments.


text:
package http2

func traceHasWroteHeaderField(trace *clientTrace) bool { return false }

func traceWroteHeaderField(trace *clientTrace, k, v string) {}


text:
class CreateContacts < ActiveRecord::Migration
  def change
    create_table :contacts do |t|
      t.string :name, null:false
      t.string :email, null:false
      t.string :comments

      t.timestamps null:false
    end
  end
end


text:
package com.avnt.soldi.controller;

import com.avnt.soldi.model.cheque.Cheque;
import com.avnt.soldi.model.request.RequestPreferences;
import com.avnt.soldi.service.ChequeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * Class ChequeController is controller, that handle requests of cheques.
 * Use @Autowired for connect to necessary services
 * Use RequestMapping for handle request from the client-side
 *
 * @version 1.1
 * @author Dmitry
 * @since 21.01.2016
 */

@RestController
public class ChequeController {

    private static final Logger logger = LoggerFactory.getLogger(ChequeController.class);

    @Autowired
    ChequeService chequeService;

    @RequestMapping(value = "/api/cheques/list", method = RequestMethod.POST)
    public List<Cheque> getMinChequesList(@RequestBody RequestPreferences request) {
        return chequeService.getMinChequesList(request);
    }

    @RequestMapping(value = "/api/cheques", method = RequestMethod.POST)
    public Cheque synchronizeCheque(@RequestBody Cheque cheque, Principal principal) {
        Cheque chequeAfterSync = chequeService.synchronizeCheque(cheque);
        logger.info("User " + principal.getName().toUpperCase() + " has synchronized cheque №" + chequeAfterSync.getId());
        return chequeAfterSync;
    }

    @RequestMapping(value = "/api/cheques/{chequeID}", method = RequestMethod.GET)
    public Cheque getCheque(@PathVariable Long chequeID) {return chequeService.getCheque(chequeID);}

    @RequestMapping(value = "/api/cheques/{chequeID}", method = RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.OK)
    public void deleteCheque(@PathVariable Long chequeID, Principal principal) {
        chequeService.deleteCheque(chequeID);
        logger.info("User " + principal.getName().toUpperCase() + " has removed cheque №" + chequeID);
    }

    @RequestMapping(value = "/api/attention", method = RequestMethod.GET)
    public List<Cheque> attentionCheques() {return chequeService.attentionCheques();}

    @RequestMapping(value = "/api/delay", method = RequestMethod.GET)
    public List<Cheque> attentionChequesByDelay() {return chequeService.attentionChequesByDelay();}

//    @RequestMapping(value = "/sample", method = RequestMethod.GET)
//    @ResponseStatus(value = HttpStatus.OK)
//    public void sample() {chequeService.addSampleCheques();}

//    @RequestMapping(value = "/read", method = RequestMethod.GET)
//    @ResponseStatus(value = HttpStatus.OK)
//    public void readFromExcelToDB() throws Exception {chequeService.readFromExcelToDB();}

}