text:
Plus1 WapStart Android SDK
==========================
Это open source библиотека для интеграции рекламы сети [Plus1 WapStart](https://plus1.wapstart.ru) в ваши Android-приложения.

Plus1 WapStart Android SDK распространяется под свободной лицензией BSD (as is).

**Оглавление:**
* [Установка и настройка](#Установка-и-настройка)
  * [Конфигурирование манифеста](#Конфигурирование-манифеста)
  * [Настройка тестового приложения](#Настройка-тестового-приложения)
* [Использование SDK](#Использование-SDK)
  * [Добавление баннера в приложение](#Добавление-баннера-в-приложение)
  * [Обработка событий от SDK в приложении](#Обработка-событий-от-SDK-в-приложении)
  * [Разрешение коллизий работы WebView в приложении](#Разрешение-коллизий-работы-webview-в-приложении)
* [Контактная информация](#Контактная-информация)

# Установка и настройка

1. Скачайте последнюю версию SDK: https://github.com/WapStart/plus1-android-sdk/tags
2. Для начала работы необходимо добавить SDK к проекту в качестве библиотеки;
3. Сконфигурируйте манифест согласно нижеприведённым инструкциям.

## Конфигурирование манифеста
В первую очередь необходимо добавить собственную url-схему и хост. Это необходимо для возврата из браузера обратно в приложение после синхронизации cookie пользователя. Если вы используете *setDisabledOpenLinkAction(true)* в [Plus1Request](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1Request.md), вы можете пропустить этот раздел (не рекомендуется).

Пример:

```xml
<intent-filter>
	<data android:scheme="wsp1bart" android:host="ru.wapstart.plus1.bart" />
	<action android:name="android.intent.action.VIEW"/>
	<category android:name="android.intent.category.DEFAULT" />
	<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
```

Для тестового приложения в качестве схемы выступает *wsp1bart://*

**Внимание:** сочетание схема-хост должно быть уникально для гарантии возврата в ваше приложение.

Для корректной работы SDK приложение должно обладать правами на доступ к сети Интернет и на получение текущего местоположения:

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```

При этом **ACCESS_FINE_LOCATION** не является обязательным, но рекомендуется для подбора релевантных рекламных объявлений.

Если ваше приложение использует геолокацию, вы можете самостоятельно устанавливать текущее местоположение (см. описание интерфейсов - [Plus1Request](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1Request.md)). При этом рекомендуется отключать автоматическое определение местоположения в SDK (метод *disableAutoDetectLocation()* в [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md)).

В блок *<application>* требуется добавить информацию об используемых Activity:

```xml
<application android:label="Bart" android:icon="@drawable/icon">
	<activity android:name="<app Activity name>" ... >
		...
	</activity>

	<activity android:name="ru.wapstart.plus1.sdk.ApplicationBrowser" />
</application>
```

*[ApplicationBrowser](https://github.com/WapStart/plus1-android-sdk/blob/master/sdk/src/ru/wapstart/plus1/sdk/ApplicationBrowser.java)* используется для перехода по ссылкам баннеров внутри приложения.

## Настройка тестового приложения
Для работы тестового приложения вам нужно передать идентификатор площадки [Plus1 WapStart](https://plus1.wapstart.ru) в методе **setApplicationId()** в файле *[BartActivity.java](https://github.com/WapStart/plus1-android-sdk/blob/master/examples/Bart/src/ru/wapstart/plus1/bart/BartActivity.java#L51)*.

Идентификатор площадки можно узнать на странице **Код для площадки** после регистрации в сети [Plus1 WapStart](https://plus1.wapstart.ru) и добавления площадки типа Android.

# Использование SDK

Примеры настройки и конфигурации баннеров можно посмотреть в тестовом приложении **Bart**. В этом разделе даются краткие пояснения для быстрой настройки собственного проекта.

## Добавление баннера в приложение
Добавьте [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md) в layout:

```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<ru.wapstart.plus1.sdk.Plus1BannerView
			android:id="@+id/plus1BannerView"
			android:layout_width="320dp"
			android:layout_height="50dp"
			android:layout_gravity="top|center"
		/>
</FrameLayout>

```
View адаптировано под размер 320x50. Рекомендуется использовать именно данные параметры.

Подключите необходимые классы в файле вашего Activity, где планируете показывать рекламу:

```java
import ru.wapstart.plus1.sdk.Plus1BannerView;
import ru.wapstart.plus1.sdk.Plus1Request;
import ru.wapstart.plus1.sdk.Plus1BannerAsker;
```

На этапе инициализации создайте и настройте объекты [Plus1Request](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1Request.md) и [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md) следующим образом:

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

	...

	mBannerView =
		(Plus1BannerView) findViewById(R.id.plus1BannerView);

	mAsker =
		new Plus1BannerAsker(
			new Plus1Request()
				.setApplicationId(...),
			mBannerView
				.enableAnimationFromTop()
				.enableCloseButton()
		)
		.setCallbackUrl(...)

}
```

В методе **setApplicationId()** задайте идентификатор вашей рекламной площадки. Его можно узнать на странице **Код для площадки** после регистрации в сети [Plus1 WapStart](https://plus1.wapstart.ru) и добавления площадки типа Android.

Установите *callback url* методом **setCallbackUrl()** согласно вашим настройкам манифеста. Если вы используете *setDisabledOpenLinkAction(true)* в [Plus1Request](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1Request.md), это делать необязательно (не рекомендуется).

Пример:

```java
        mAsker =
                new Plus1BannerAsker(
			...
                )
                .setCallbackUrl("wsp1bart://ru.wapstart.plus1.bart")

}
```

Затем необходимо предусмотреть вызов обработчиков *onResume()* и *onPause()* класса [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md):

```java
@Override
protected void onResume() {
	super.onResume();

	...

	mAsker.onResume();
}

@Override
protected void onPause() {
	super.onPause();

	...

	mAsker.onPause();
}
```

Для баннеров формата Rich Media в [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md) необходимо передавать событие нажатия клавиши "Назад":

```java
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	if ((keyCode == KeyEvent.KEYCODE_BACK) && mBannerView.canGoBack()) {
		mBannerView.goBack();
		return true;
	}

	return super.onKeyDown(keyCode, event);
}
```

Для подробного ознакомления смотрите описания интерфейсов и классов, а также исходные коды sdk:
* [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md) - отвечает за получение объявлений с сервера
* [Plus1Request](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1Request.md) - отвечает за хранение информации о пользователе и формирование запроса к серверу
* [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md) - отвечает за отображение объявления
* [Plus1BannerDownloadListener](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerDownloadListener.md) - интерфейс наблюдателя загрузки баннера

## Обработка событий от SDK в приложении
Часто возникают ситуации, когда в приложении необходима реакция на какое-то событие, связанное с баннером. Для этого в [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md) предусмотрены *наблюдатели*:

```java
public Plus1BannerView addListener(OnShowListener listener);
public Plus1BannerView addListener(OnHideListener listener);
public Plus1BannerView addListener(OnCloseButtonListener listener);
public Plus1BannerView addListener(OnExpandListener listener);
public Plus1BannerView addListener(OnCollapseListener listener);
public Plus1BannerView addListener(OnImpressionListener listener);
public Plus1BannerView addListener(OnTrackClickListener listener);
```

Для обработки событий в приложении необходимо добавить нужный *наблюдатель* для [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md). Например:

```java
mBannerView
	.addListener(new Plus1BannerView.OnShowListener() {
		public void onShow(Plus1BannerView pbv) {
			Log.d(LOGTAG, "Рекламный блок появился на экране");
		}
	})
	.addListener(new Plus1BannerView.OnHideListener() {
		public void onHide(Plus1BannerView pbv) {
			Log.d(LOGTAG, "SDK скрыл рекламный блок");
		}
	})
	.addListener(new Plus1BannerView.OnTrackClickListener() {
		public void onTrackClick(Plus1BannerView pbv) {
			Log.d(LOGTAG, "Произошло событие нажатия на баннер");
		}
	});
```

Описание всех *наблюдателей* смотрите в [Plus1BannerView](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerView.md#Наблюдатели).

## Разрешение коллизий работы WebView в приложении
Если вы используете *WebView* в разных Activity вашего приложения, то логика работы этого компонента будет нарушаться. Причины коллизии в том, что по умолчанию sdk вызывает обработчики [pauseTimers()](http://developer.android.com/reference/android/webkit/WebView.html#pauseTimers%28%29) и [resumeTimers()](http://developer.android.com/reference/android/webkit/WebView.html#resumeTimers%28%29) класса *WebView* в соответствующих контекстах событий *onPause* и *onResume* в Activity вашего приложения. Вызовы этих методов влияют на все экземпляры *WebView* и позволяют исключить обработку *WebView* в то время, когда ваше приложение (Activity) не показывается пользователю.

Для разрешения этой коллизии предлагается воспользоваться методом **setDisabledWebViewCorePausing()** класса [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md). При этом важно понимать, что *WebView* продолжает работать в то время, когда Activity с баннером приостановлена. Для экономии ресурсов процессора рекомендуем также ограничить использование *WebView* в Activity используя метод **setRemoveBannersOnPause()** класса [Plus1BannerAsker](https://github.com/WapStart/plus1-android-sdk/blob/master/doc/Plus1BannerAsker.md).

# Контактная информация

По всем возникающим у вас вопросам интеграции вы можете обратиться в службу поддержки пользователей:
E-Mail: clientsupport@co.wapstart.ru
ICQ: 553425962

---------------------------------------
Мы постоянно улучшаем наши SDK, делаем их удобнее и стабильнее. Будем рады вашему [участию в разработке](https://github.com/Wapstart/plus1-android-sdk/pulls), с радостью рассмотрим и обсудим [ваши предложениия](https://github.com/WapStart/plus1-android-sdk/issues)!


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp">
   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <ImageView
           android:id="@+id/iv_tlzimg"
           android:layout_width="48dp"
           android:layout_height="48dp"
           android:layout_centerVertical="true"
           android:layout_marginLeft="20dp"
           android:src="@drawable/tzl1"
           />
       <TextView
           android:layout_toRightOf="@id/iv_tlzimg"
           android:layout_centerVertical="true"
           android:layout_marginLeft="20dp"
           android:id="@+id/tv_tlzname"
           android:layout_width="wrap_content"
           android:layout_height="40dp"
           android:textSize="30dp"
           android:gravity="center"
           android:textColor="#000"
           android:text=""
           />

   </RelativeLayout>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package seabotserver

type BotService interface {
	Battle() interface{}
	SetBattle(b interface{})

	SetDBBot(*DBBot)
	DBBot() *DBBot

	Send(d interface{})
	SendError(err string)

	Sender()
	Handler()

	Disconnect()
}


text:
/* (C) 1999-2001 Michal Ludvig <michal@logix.cz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <linux/in.h>
#include <linux/ip.h>

#include <linux/netfilter/xt_pkttype.h>
#include <linux/netfilter/x_tables.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michal Ludvig <michal@logix.cz>");
MODULE_DESCRIPTION("IP tables match to match on linklayer packet type");
MODULE_ALIAS("ipt_pkttype");
MODULE_ALIAS("ip6t_pkttype");

static int match(const struct sk_buff *skb,
      const struct net_device *in,
      const struct net_device *out,
      const struct xt_match *match,
      const void *matchinfo,
      int offset,
      unsigned int protoff,
      int *hotdrop)
{
	u_int8_t type;
	const struct xt_pkttype_info *info = matchinfo;

	if (skb->pkt_type == PACKET_LOOPBACK)
		type = (MULTICAST(ip_hdr(skb)->daddr)
			? PACKET_MULTICAST
			: PACKET_BROADCAST);
	else
		type = skb->pkt_type;

	return (type == info->pkttype) ^ info->invert;
}

static struct xt_match xt_pkttype_match[] = {
	{
		.name		= "pkttype",
		.family		= AF_INET,
		.match		= match,
		.matchsize	= sizeof(struct xt_pkttype_info),
		.me		= THIS_MODULE,
	},
	{
		.name		= "pkttype",
		.family		= AF_INET6,
		.match		= match,
		.matchsize	= sizeof(struct xt_pkttype_info),
		.me		= THIS_MODULE,
	},
};

static int __init xt_pkttype_init(void)
{
	return xt_register_matches(xt_pkttype_match,
				   ARRAY_SIZE(xt_pkttype_match));
}

static void __exit xt_pkttype_fini(void)
{
	xt_unregister_matches(xt_pkttype_match, ARRAY_SIZE(xt_pkttype_match));
}

module_init(xt_pkttype_init);
module_exit(xt_pkttype_fini);


text:
require 'spec_helper'

describe GitHub::Client::Feeds do

  describe '.feeds', :vcr do
    it 'returns feed information' do
      feed = test_client.feeds
      feed.should be_instance_of Hash
    end
  end

end


text:
HAPPY_OPTS=-sacg
ifndef HC
	HC=ghc
endif

ifndef OPT
	OPT=-O -rtsopts
endif

ifdef PROFILE
	OPT += -prof -auto-all
	SUFFIX=_p
endif

BUILD_DIR=build$(SUFFIX)

OPT += -hidir $(BUILD_DIR) -odir $(BUILD_DIR)

INCLUDE=-ibuild/autogen -i../src -i../test-framework -isrc

all: c_test test_drivers check_args render_tests

profile : OPT += -prof -auto-all
profile : SUFFIX=_p
profile : test_drivers c_test

test_drivers: parse round_trip equiv report_fatal

# GHC bug: Main sometimes isn't recompiled (6.8.2, 6.8.3, should get fixed in 6.10)
# Therefore we add rm build/Main.o to the end of make targets
c_test: autogen
	$(HC) $(OPT) -o bin/CTest$(SUFFIX) $(INCLUDE) --make src/CTest.hs
	rm $(BUILD_DIR)/Main.o
parse: autogen
	$(HC) $(OPT) -o bin/CParse$(SUFFIX) $(INCLUDE) --make src/CParse.hs
	rm $(BUILD_DIR)/Main.o
round_trip: autogen
	$(HC) $(OPT) -o bin/CRoundTrip$(SUFFIX) $(INCLUDE) --make src/CRoundTrip.hs
	rm $(BUILD_DIR)/Main.o
equiv: autogen
	$(HC) $(OPT) -o bin/CEquiv$(SUFFIX) $(INCLUDE) --make src/CEquiv.hs
	rm $(BUILD_DIR)/Main.o
render_tests: autogen
	$(HC) $(OPT) -o bin/RenderTests$(SUFFIX) $(INCLUDE) --make src/RenderTests.hs
	rm $(BUILD_DIR)/Main.o
report_fatal: autogen
	$(HC) $(OPT) -o bin/ReportFatal$(SUFFIX) $(INCLUDE) --make src/ReportFatal.hs
	rm $(BUILD_DIR)/Main.o
check_args: autogen
	$(HC) $(OPT) -o bin/CheckGccArgs$(SUFFIX) $(INCLUDE) --make src/CheckGccArgs.hs
	rm build/Main.o
clean:
	rm -rf build/*

autogen: build/autogen/Language/C/Parser/Lexer.hs build/autogen/Language/C/Parser/Parser.hs
build/autogen/Language/C/Parser/Lexer.hs: ../src/Language/C/Parser/Lexer.x
	mkdir -p build/autogen/Language/C/Parser
	alex -g -o $@ $<
build/autogen/Language/C/Parser/Parser.hs: ../src/Language/C/Parser/Parser.y
	mkdir -p build/autogen/Language/C/Parser
	happy $(HAPPY_OPTS) -o $@ $<


text:
package com.codepine.api.testrail.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.Getter;

/**
 * TestRail test case priority.
 */
@Data
public class Priority {

    private int id;
    private String name;
    private String shortName;
    private int priority;
    @JsonProperty
    @Getter(onMethod = @_({@JsonIgnore}))
    private boolean isDefault;

}


text:
package syncbase

import (
	"v.io/v23"
	"v.io/v23/context"
	"v.io/v23/security"
	"v.io/v23/security/access"
	wire "v.io/v23/services/syncbase"
	"v.io/v23/syncbase/util"
	"v.io/v23/verror"
)

func NewService(fullName string) Service {
	return &service{
		c:        wire.ServiceClient(fullName),
		fullName: fullName,
	}
}

type service struct {
	c        wire.ServiceClientMethods
	fullName string
}

var _ Service = (*service)(nil)

// FullName implements Service.FullName.
func (s *service) FullName() string {
	return s.fullName
}

// Database implements Service.Database.
func (s *service) Database(ctx *context.T, name string, schema *Schema) Database {
	app, _, err := util.AppAndUserPatternFromBlessings(security.DefaultBlessingNames(v23.GetPrincipal(ctx))...)
	if err != nil {
		ctx.Error(verror.New(wire.ErrInferAppBlessingFailed, ctx, "Database", name, err))
		// A handle with a no-match Id blessing is returned, so all RPCs will fail.
		// TODO(ivanpi): Return the more specific error from RPCs instead of logging
		// it here.
	}
	return newDatabase(s.fullName, wire.Id{Blessing: string(app), Name: name}, schema)
}

// DatabaseForId implements Service.DatabaseForId.
func (s *service) DatabaseForId(id wire.Id, schema *Schema) Database {
	return newDatabase(s.fullName, id, schema)
}

// ListDatabases implements Service.ListDatabases.
func (s *service) ListDatabases(ctx *context.T) ([]wire.Id, error) {
	return util.ListChildIds(ctx, s.fullName)
}

// SetPermissions implements Service.SetPermissions.
func (s *service) SetPermissions(ctx *context.T, perms access.Permissions, version string) error {
	return s.c.SetPermissions(ctx, perms, version)
}

// GetPermissions implements Service.GetPermissions.
func (s *service) GetPermissions(ctx *context.T) (perms access.Permissions, version string, err error) {
	return s.c.GetPermissions(ctx)
}


text:
#ifndef LIBPRAEFECTUS_STDSYS_H_
#define LIBPRAEFECTUS_STDSYS_H_

#include "system.h"
#include "std-state.h"

__BEGIN_DECLS

/**
 * Creates a partial application interface which implements all the *_bridge()
 * methods via calls to the given standard state stack.
 *
 * All non-bridge (both optional and mandatory) methods in the returned
 * application interface are NULL. The application MUST still provide its own
 * implementations for the mandatory not-bridge methods. The application MAY
 * overwrite any number of *_bridge() methods if it wishes to do so.
 *
 * Note that the implementation of praef_app::neutralise_event_bridge() works
 * by overwriting the praef_event::apply() method of events with a no-op
 * function and a forced rewind of the underlying context to the instant of the
 * event. This is unsuitable for applications which use data in the events to
 * perform roll-back; such applications MUST provide their own implementation
 * of this method which neutralises both the apply and roll-back behaviours.
 *
 * After the praef_system is constructed with this praef_app,
 * praef_stdsys_set_system() MUST be called to inform the bridge of the system
 * in which it is participating.
 *
 * Virtually all applications will want to change at least one of
 * praef_stdsys_optimistic_events() or praef_stdsys_event_vote().
 *
 * @param stack The initialised standard-state stack. The application MUST
 * ensure this remains valid for the lifetime of the bridge.
 * @return An application interface bridging to stack, or NULL if memory
 * allocation fails.
 */
praef_app* praef_stdsys_new(praef_std_state* stack);
/**
 * Sets the praef_system associated with the given standard system bridge.
 *
 * The given praef_app MUST be an object that was returned from
 * praef_stdsys_new().
 */
void praef_stdsys_set_system(praef_app*, praef_system*);
/**
 * Configures the userdata passed into praef_context_advance() (and, by proxy,
 * to the advance and apply methods of application objects and events,
 * respectively).
 *
 * If this is not called, NULL userdata will be passed in and returned from
 * praef_stdsys_userdata().
 *
 * The given praef_app MUST be an object that was returned from
 * praef_stdsys_new().
 *
 * The given praef_app MUST be an object that was returned from
 * praef_stdsys_new().
 */
void praef_stdsys_set_userdata(praef_app*, praef_userdata);
/**
 * Returns the userdata associated with the given standard system bridge.
 *
 * This corresponds to the value passed into praef_stdsys_set_userdata(), or
 * NULL if that function was never called on this bridge.
 */
praef_userdata praef_stdsys_userdata(const praef_app*);
/**
 * Configures how optimistic events are classified. The given callback will be
 * invoked for each event to be added to the underlying context. If it returns
 * non-zero, the event will be considered optimistic with a deadline that many
 * instants after the event's instant. Returning 0 indicates a pessimistic
 * event.
 *
 * If this is never called, all events will be considered pessimistic.
 *
 * The given praef_app MUST be an object that was returned from
 * praef_stdsys_new().
 */
void praef_stdsys_optimistic_events(praef_app*,
                                    unsigned (*)(praef_app* bridge,
                                                 const praef_event*));
/**
 * Function type to determine whether the local node should vote in agreement
 * with a given event.
 *
 * @param bridge A praef_app that was produced by praef_stdsys_new().
 * @param evt The event to examine.
 * @param userdata The userdata associated with bridge.
 * @return Whether a vote should be added.
 */
typedef int (*praef_stdsys_event_vote_t)(
  praef_app* bridge, const praef_event* evt,
  praef_userdata userdata);
/**
 * Configures how the bridge decides which events it should add votes for.
 *
 * If this is never called, all pessimistic events will be voted for, as well
 * as any optimistic events that arrive before their deadline (in terms of
 * systime). While this will work for many applications, it isn't a terribly
 * good system, especially for pessimistic events or optimistic events with
 * very short deadlines.
 *
 * It is the application's responsibility to ensure it does not vote for an
 * event where casting the vote would violate the application-defined
 * constraint on how far votes can be offset from their events, if any.
 *
 * The given praef_app MUST be an object that was returned from
 * praef_stdsys_new().
 *
 * @see praef_stdsys_event_vote_t
 */
void praef_stdsys_event_vote(praef_app*, praef_stdsys_event_vote_t);
/**
 * Frees the given standard system interface, which MUST be an object returned
 * from praef_stdsys_new().
 */
void praef_stdsys_delete(praef_app*);

__END_DECLS

#endif /* LIBPRAEFECTUS_STDSYS_H_ */


text:
#include "fontcreator_plugin.h"
#include "fontcreator_widget.h"

/**
 *  @brief		コンストラクタ.
 *  @param  in  app_functions アプリケーション関数.
 */
FontCreatorPlugin::FontCreatorPlugin(const meta_tools::IPlugin::AppFunctions &app_functions) :
    IPlugin(app_functions)
  , m_window(new FontCreatorWidget())
{
    m_widget_icon->addFile(":/font_creator_resource/img/font_icon.png");
}

/**
 *  @brief		デストラクタ.
 */
FontCreatorPlugin::~FontCreatorPlugin()
{
    if (m_window)
    {
        delete m_window;
        m_window = nullptr;
    }
}

/**
 *  @breif      スタート時処理.
 */
bool FontCreatorPlugin::OnStart()
{
    AddToolWidget(m_window, "FontCreator");
    m_window->OnStart();
    return true;
}

/**
 *  @breif      スタート時処理.
 */
bool FontCreatorPlugin::OnClose()
{
    RemoveWidget(m_window);
    m_window->OnClose();
    return true;
}


text:
require "mixi_platform/version"

require "mixi_platform/oauth"
require "mixi_platform/token"
require "mixi_platform/graph_api/client/people"
require "mixi_platform/graph_api/client/groups"
require "mixi_platform/graph_api/client/persistence"


text:
@interface COConversationListController : COBaseViewController<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *msgCountView;
@property (weak, nonatomic) IBOutlet UIView *notifCountView;

- (void)showPushNotification:(NSString *)linkStr;

@end


text:
@extends('titan::layouts.admin')

@section('content')
    {{-- devices + browsers --}}

            @include('titan::admin.analytics.partials.devices_category')

            @include('titan::admin.analytics.partials.browsers')

            @include('titan::admin.analytics.partials.devices')

@endsection


text:
using namespace std;

namespace {

    class Storage {
    public:
        static Storage* getStorage() {
            static thread_local Storage instance;
            if (instance.destroyed) {
                return nullptr;
            }
            return &instance;
        }

        ItemBase* get_item(const ThreadStorageBase* key) {
            auto it = storage.find(key);
            if (it != storage.end()) {
                return it->second.get();
            }
            return nullptr;
        }

        void insert_item(const ThreadStorageBase* key, ItemBase* item) {
            storage[key].reset(item);
        }

    private:
        bool destroyed;
        Storage() : destroyed(false) {}
        ~Storage() { destroyed = true; }
        unordered_map<const ThreadStorageBase*, unique_ptr<ItemBase>> storage;
    };

}

ItemBase::~ItemBase() {}

ThreadStorageBase::ThreadStorageBase() {}
ThreadStorageBase::~ThreadStorageBase() {}

bool ThreadStorageBase::hasLocalData() const
{
    Storage* s = Storage::getStorage();
    if (!s) {
        return false;
    }
    return s->get_item(this) != nullptr;
}

ItemBase* ThreadStorageBase::get_item()
{
    Storage* s = Storage::getStorage();
    if (!s) {
        return nullptr;
    }
    return s->get_item(this);
}

void ThreadStorageBase::set_item(ItemBase* item)
{
    Storage* s = Storage::getStorage();
    if (s) {
        s->insert_item(this, item);
    } else {
        // fail silently, because we are shutting down
        delete item;
    }
}

void initialize_thread_storage()
{
    Storage::getStorage();
}


text:
/*
 *
 * CorporatePartnershipsContainer actions
 *
 */

import {
  GET_API_URL,
  GET_LOCATION_LIST,
  SELECTED_LOCATION,
  RESIZE_CHART,
} from './constants';

export function getApiUrl(url){
   return {
      type: GET_API_URL,
      payload: {
          url
      }
  }
};

export function getLocationList(locationUrl){
	return{
		type: GET_LOCATION_LIST,
		payload: {
			locationUrl
		}
	}
};

export function selectLocation(selectedLocation){
  return{
    type: SELECTED_LOCATION,
    payload: {
      selectedLocation
    }
  }
};

export function ResizeWindow(width, height){
  return{
    type: RESIZE_CHART,
    payload: {
      width: width,
      height: height
    }
  }
};


text:
package com.jpventura.popularmovies.domain.service.backend;

import retrofit.Callback;
import retrofit.client.Response;

public interface GetMovieListCallback extends Callback<ResultPage> {
    void success(ResultPage resultPage, Response response);
}


text:
Subscriber::Subscriber(){
	std::cout << "shouldn't be called" << std::endl;
}

Subscriber::Subscriber(const Subscriber& copy){
	this->owner = copy.owner;
	this->eventID = copy.eventID;

}

Subscriber::Subscriber(GameObject* owner, Uint32 watchedEvent){
	this->owner = owner;
	this->eventID = watchedEvent;
}

Subscriber::Subscriber(Subscriber &other){
	this->owner = other.owner;
	this->eventID = other.eventID;
}

void Subscriber::HandleRegisteredEvent(Uint32 e){
	owner->handleEvent(e);
}


text:
<?php

class Shopping extends MX_Controller{
	function index(){
		echo 'Shopping Controller
';
		echo modules::run('Finance/partial');

		$this->load->model('ShoppingModel','shopping');
		echo $this->shopping->orders().'
';

		$this->load->model('Finance/FinanceModel', 'finance');
		echo $this->finance->top5();

		$this->load->model('DataObjects/EmployeeModel', 'employee');
		var_dump($this->employee->getAll());
	}
}


text:
package org.sagebionetworks.repo.model.dbo.persistence;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.sagebionetworks.repo.model.Node;
import org.sagebionetworks.repo.model.NodeConstants;
import org.sagebionetworks.repo.model.dbo.dao.NodeUtils;
import org.springframework.jdbc.core.RowMapper;

/**
 * Mapper for reading a Node from a single query result.
 *
 */
public class NodeMapper implements RowMapper<Node> {

	private static final RowMapper<DBONode> NODE_MAPPER = new DBONodeMapper();
	private static final RowMapper<DBORevision> REVISION_MAPPER = new DBORevisionMapper(false);

	@Override
	public Node mapRow(ResultSet rs, int rowNum) throws SQLException {
		DBONode node = NODE_MAPPER.mapRow(rs, rowNum);
		DBORevision rev = REVISION_MAPPER.mapRow(rs, rowNum);
		Node result = NodeUtils.copyFromJDO(node, rev);
		/*
		 * Use the Zero etag for any version that is not the current version.
		 * See PLFM-1420 and PLFM-4269.
		 */
		if(!node.getCurrentRevNumber().equals(rev.getRevisionNumber())){
			result.setETag(NodeConstants.ZERO_E_TAG);
		}
		return result;
	}

}


text:
void *OS_Alloc_Mem(size_t size)
{
#ifdef NDEBUG
    return malloc(size);
#else
    // We skew the return pointer so we don't return exactly at the malloc
    // point, to prevent free() from being used directly on an address
    // acquired from OS_Alloc_Mem.  And because Rebol Core uses the same
    // trick (but stores a positive integral size), we write a negative
    // magic number.
    //
    // A 64-bit size is used in order to maintain a 64-bit alignment
    // (potentially a lesser alignment guarantee than malloc())

    void *ptr = malloc(size + sizeof(REBI64));
    *cast(REBI64*, ptr) = -1020;
    return cast(char*, ptr) + sizeof(REBI64);
#endif
}

//
//  OS_Free_Mem: C
//
// Free memory allocated in this OS environment. (See OS_Alloc_Mem)
//
void OS_Free_Mem(void *mem)
{
  #ifdef NDEBUG
    free(mem);
  #else
    char *ptr = cast(char *, mem) - sizeof(REBI64);
    if (*cast(REBI64*, ptr) != -1020) {
        rebPanic(
            "{OS_Free_Mem() mismatched with allocator!" \
            " Did you mean to use FREE() instead of OS_FREE()?}",
            rebEnd()
        );
    }
    free(ptr);
  #endif
}


text:
package org.restlet.example.book.restlet.ch04.sec4.sub2;

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

import org.restlet.data.LocalReference;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.ext.velocity.TemplateRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

/**
 * Resource corresponding to a mail received or sent with the parent mail
 * account. Leverages Velocity template engine.
 */
public class MailServerResource extends ServerResource {

    @Override
    protected Representation get() throws ResourceException {
        // Create the mail bean
        Mail mail = new Mail();
        mail.setStatus("received");
        mail.setSubject("Message to self");
        mail.setContent("Doh!");
        mail.setAccountRef(new Reference(getReference(), "..").getTargetRef()
                .toString());

        // Prepare the data model
        Map<String, Object> dataModel = new HashMap<String, Object>();
        dataModel.put("mail", mail);

        // Load the Velocity template
        Representation mailVtl = new ClientResource(
                LocalReference.createClapReference(getClass().getPackage())
                        + "/Mail.vtl").get();

        // Wraps the bean with a Velocity representation
        try {
            return new TemplateRepresentation(mailVtl, dataModel,
                    MediaType.TEXT_HTML);
        } catch (Exception e) {
            throw new ResourceException(e);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- CircularProgressBar -->
    <declare-styleable name="CircularProgressBar">
        <attr name="cpbStyle" format="reference"/>
        <attr name="cpb_color" format="color"/>
        <attr name="cpb_colors" format="reference"/>
        <attr name="cpb_stroke_width" format="dimension"/>
        <attr name="cpb_min_sweep_angle" format="integer"/>
        <attr name="cpb_max_sweep_angle" format="integer"/>
        <attr name="cpb_sweep_speed" format="float"/>
        <attr name="cpb_rotation_speed" format="float"/>
    </declare-styleable>

    <!-- SwipeBackLayout -->
    <declare-styleable name="SwipeBackLayout">
        <attr name="edge_size" format="dimension"/>
        <attr name="edge_flag">
            <enum name="left" value="0"/>
            <enum name="right" value="1"/>
            <enum name="bottom" value="2"/>
            <enum name="all" value="3"/>
        </attr>
        <attr name="shadow_left" format="reference"/>
        <attr name="shadow_right" format="reference"/>
        <attr name="shadow_bottom" format="reference"/>
    </declare-styleable>

    <attr name="SwipeBackLayoutStyle" format="reference"/>
    <declare-styleable name="EditTextHint">
        <attr name="edit_hint" format="string" />
        <attr name="edit_textColor" format="color" />
        <attr name="edit_textSize" format="dimension" />
        <attr name="edit_background" format="reference" />
        <attr name="edit_rightImage" format="reference" />
    </declare-styleable>
</resources>


text:
<?php

namespace FSB\ASTT\CoreBundle\Repository;

use Doctrine\ORM\EntityRepository;

class LetterRepository extends EntityRepository
{
    public function findAllDisplayedSorteredByDate($orderByDate = 'DESC')
    {
        $qb = $this->_em->createQueryBuilder();

        $qb->select('l')
            ->from('FSB\ASTT\CoreBundle\Entity\Letter', 'l')
            ->where('l.deleted = :deleted')
            ->setParameter('deleted', false)
            ->orderBy('l.date', $orderByDate);

        return $qb->getQuery()->getResult();
    }

    public function find($id)
    {
        $qb = $this->_em->createQueryBuilder();

        $qb->select('l')
            ->from('FSB\ASTT\CoreBundle\Entity\Letter', 'l')
            ->where('l.deleted = :deleted')
            ->andWhere('l.id = :id')
            ->setParameter('deleted', false)
            ->setParameter('id', $id)
        ;

        try {
            $result = $qb->getQuery()->getSingleResult();
        }
        catch (\Doctrine\Orm\NoResultException $NRE) {
            $result = NULL;
        }

        return $result;
    }

    public function findOneById($id)
    {
        return $this->find($id);
    }

    public function findAll()
    {
        $qb = $this->_em->createQueryBuilder();

        $qb->select('l')
            ->from('FSB\ASTT\CoreBundle\Entity\Letter', 'l')
            ->where('l.deleted = :deleted')
            ->setParameter('deleted', false)
        ;

        return $qb->getQuery()->getResult();
    }
}


text:
package conversion

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"testing"

	"github.com/google/gofuzz"
	flag "github.com/spf13/pflag"

	"k8s.io/kubernetes/pkg/util/diff"
)

var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.")

// Test a weird version/kind embedding format.
type MyWeirdCustomEmbeddedVersionKindField struct {
	ID         string `json:"ID,omitempty"`
	APIVersion string `json:"myVersionKey,omitempty"`
	ObjectKind string `json:"myKindKey,omitempty"`
	Z          string `json:"Z,omitempty"`
	Y          uint64 `json:"Y,omitempty"`
}

type TestType1 struct {
	MyWeirdCustomEmbeddedVersionKindField `json:",inline"`
	A                                     string               `json:"A,omitempty"`
	B                                     int                  `json:"B,omitempty"`
	C                                     int8                 `json:"C,omitempty"`
	D                                     int16                `json:"D,omitempty"`
	E                                     int32                `json:"E,omitempty"`
	F                                     int64                `json:"F,omitempty"`
	G                                     uint                 `json:"G,omitempty"`
	H                                     uint8                `json:"H,omitempty"`
	I                                     uint16               `json:"I,omitempty"`
	J                                     uint32               `json:"J,omitempty"`
	K                                     uint64               `json:"K,omitempty"`
	L                                     bool                 `json:"L,omitempty"`
	M                                     map[string]int       `json:"M,omitempty"`
	N                                     map[string]TestType2 `json:"N,omitempty"`
	O                                     *TestType2           `json:"O,omitempty"`
	P                                     []TestType2          `json:"Q,omitempty"`
}

type TestType2 struct {
	A string `json:"A,omitempty"`
	B int    `json:"B,omitempty"`
}

type ExternalTestType2 struct {
	A string `json:"A,omitempty"`
	B int    `json:"B,omitempty"`
}
type ExternalTestType1 struct {
	MyWeirdCustomEmbeddedVersionKindField `json:",inline"`
	A                                     string                       `json:"A,omitempty"`
	B                                     int                          `json:"B,omitempty"`
	C                                     int8                         `json:"C,omitempty"`
	D                                     int16                        `json:"D,omitempty"`
	E                                     int32                        `json:"E,omitempty"`
	F                                     int64                        `json:"F,omitempty"`
	G                                     uint                         `json:"G,omitempty"`
	H                                     uint8                        `json:"H,omitempty"`
	I                                     uint16                       `json:"I,omitempty"`
	J                                     uint32                       `json:"J,omitempty"`
	K                                     uint64                       `json:"K,omitempty"`
	L                                     bool                         `json:"L,omitempty"`
	M                                     map[string]int               `json:"M,omitempty"`
	N                                     map[string]ExternalTestType2 `json:"N,omitempty"`
	O                                     *ExternalTestType2           `json:"O,omitempty"`
	P                                     []ExternalTestType2          `json:"Q,omitempty"`
}

func testLogger(t *testing.T) DebugLogger {
	// We don't set logger to eliminate rubbish logs in tests.
	// If you want to switch it, simply switch it to: "return t"
	return nil
}

func TestConverter_byteSlice(t *testing.T) {
	c := NewConverter(DefaultNameFunc)
	src := []byte{1, 2, 3}
	dest := []byte{}
	err := c.Convert(&src, &dest, 0, nil)
	if err != nil {
		t.Fatalf("expected no error")
	}
	if e, a := src, dest; !reflect.DeepEqual(e, a) {
		t.Errorf("expected %#v, got %#v", e, a)
	}
}

func TestConverter_MismatchedTypes(t *testing.T) {
	c := NewConverter(DefaultNameFunc)

	err := c.RegisterConversionFunc(
		func(in *[]string, out *int, s Scope) error {
			if str, err := strconv.Atoi((*in)[0]); err != nil {
				return err
			} else {
				*out = str
				return nil
			}
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	src := []string{"5"}
	var dest *int
	err = c.Convert(&src, &dest, 0, nil)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if e, a := 5, *dest; e != a {
		t.Errorf("expected %#v, got %#v", e, a)
	}
}

func TestConverter_DefaultConvert(t *testing.T) {
	type A struct {
		Foo string
		Baz int
	}
	type B struct {
		Bar string
		Baz int
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	c.nameFunc = func(t reflect.Type) string { return "MyType" }

	// Ensure conversion funcs can call DefaultConvert to get default behavior,
	// then fixup remaining fields manually
	err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
		if err := s.DefaultConvert(in, out, IgnoreMissingFields); err != nil {
			return err
		}
		out.Bar = in.Foo
		return nil
	})
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	x := A{"hello, intrepid test reader!", 3}
	y := B{}

	err = c.Convert(&x, &y, 0, nil)
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if e, a := x.Foo, y.Bar; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
	if e, a := x.Baz, y.Baz; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestConverter_DeepCopy(t *testing.T) {
	type A struct {
		Foo *string
		Bar []string
		Baz interface{}
		Qux map[string]string
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)

	foo, baz := "foo", "baz"
	x := A{
		Foo: &foo,
		Bar: []string{"bar"},
		Baz: &baz,
		Qux: map[string]string{"qux": "qux"},
	}
	y := A{}

	if err := c.Convert(&x, &y, 0, nil); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	*x.Foo = "foo2"
	x.Bar[0] = "bar2"
	*x.Baz.(*string) = "baz2"
	x.Qux["qux"] = "qux2"
	if e, a := *x.Foo, *y.Foo; e == a {
		t.Errorf("expected difference between %v and %v", e, a)
	}
	if e, a := x.Bar, y.Bar; reflect.DeepEqual(e, a) {
		t.Errorf("expected difference between %v and %v", e, a)
	}
	if e, a := *x.Baz.(*string), *y.Baz.(*string); e == a {
		t.Errorf("expected difference between %v and %v", e, a)
	}
	if e, a := x.Qux, y.Qux; reflect.DeepEqual(e, a) {
		t.Errorf("expected difference between %v and %v", e, a)
	}
}

func TestConverter_CallsRegisteredFunctions(t *testing.T) {
	type A struct {
		Foo string
		Baz int
	}
	type B struct {
		Bar string
		Baz int
	}
	type C struct{}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
		out.Bar = in.Foo
		return s.Convert(&in.Baz, &out.Baz, 0)
	})
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	err = c.RegisterConversionFunc(func(in *B, out *A, s Scope) error {
		out.Foo = in.Bar
		return s.Convert(&in.Baz, &out.Baz, 0)
	})
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	x := A{"hello, intrepid test reader!", 3}
	y := B{}

	err = c.Convert(&x, &y, 0, nil)
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if e, a := x.Foo, y.Bar; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
	if e, a := x.Baz, y.Baz; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}

	z := B{"all your test are belong to us", 42}
	w := A{}

	err = c.Convert(&z, &w, 0, nil)
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if e, a := z.Bar, w.Foo; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}
	if e, a := z.Baz, w.Baz; e != a {
		t.Errorf("expected %v, got %v", e, a)
	}

	err = c.RegisterConversionFunc(func(in *A, out *C, s Scope) error {
		return fmt.Errorf("C can't store an A, silly")
	})
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	err = c.Convert(&A{}, &C{}, 0, nil)
	if err == nil {
		t.Errorf("unexpected non-error")
	}
}

func TestConverter_IgnoredConversion(t *testing.T) {
	type A struct{}
	type B struct{}

	count := 0
	c := NewConverter(DefaultNameFunc)
	if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
		count++
		return nil
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if err := c.RegisterIgnoredConversion(&A{}, &B{}); err != nil {
		t.Fatal(err)
	}
	a := A{}
	b := B{}
	if err := c.Convert(&a, &b, 0, nil); err != nil {
		t.Errorf("%v", err)
	}
	if count != 0 {
		t.Errorf("unexpected number of conversion invocations")
	}
}

func TestConverter_IgnoredConversionNested(t *testing.T) {
	type C string
	type A struct {
		C C
	}
	type B struct {
		C C
	}

	c := NewConverter(DefaultNameFunc)
	typed := C("")
	if err := c.RegisterIgnoredConversion(&typed, &typed); err != nil {
		t.Fatal(err)
	}
	a := A{C: C("test")}
	b := B{C: C("other")}
	if err := c.Convert(&a, &b, AllowDifferentFieldTypeNames, nil); err != nil {
		t.Errorf("%v", err)
	}
	if b.C != C("other") {
		t.Errorf("expected no conversion of field C: %#v", b)
	}
}

func TestConverter_GeneratedConversionOverriden(t *testing.T) {
	type A struct{}
	type B struct{}
	c := NewConverter(DefaultNameFunc)
	if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
		return nil
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error {
		return fmt.Errorf("generated function should be overriden")
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	a := A{}
	b := B{}
	if err := c.Convert(&a, &b, 0, nil); err != nil {
		t.Errorf("%v", err)
	}
}

func TestConverter_WithConversionOverriden(t *testing.T) {
	type A struct{}
	type B struct{}
	c := NewConverter(DefaultNameFunc)
	if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error {
		return fmt.Errorf("conversion function should be overriden")
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error {
		return fmt.Errorf("generated function should be overriden")
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	ext := NewConversionFuncs()
	ext.Add(func(in *A, out *B, s Scope) error {
		return nil
	})
	newc := c.WithConversions(ext)

	a := A{}
	b := B{}
	if err := c.Convert(&a, &b, 0, nil); err == nil || err.Error() != "conversion function should be overriden" {
		t.Errorf("unexpected error: %v", err)
	}
	if err := newc.Convert(&a, &b, 0, nil); err != nil {
		t.Errorf("%v", err)
	}
}

func TestConverter_MapsStringArrays(t *testing.T) {
	type A struct {
		Foo   string
		Baz   int
		Other string
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error {
		if len(*input) == 0 {
			*out = ""
		}
		*out = (*input)[0]
		return nil
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	x := map[string][]string{
		"Foo":   {"bar"},
		"Baz":   {"1"},
		"Other": {"", "test"},
		"other": {"wrong"},
	}
	y := A{"test", 2, "something"}

	if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err == nil {
		t.Error("unexpected non-error")
	}

	if err := c.RegisterConversionFunc(func(input *[]string, out *int, s Scope) error {
		if len(*input) == 0 {
			*out = 0
		}
		str := (*input)[0]
		i, err := strconv.Atoi(str)
		if err != nil {
			return err
		}
		*out = i
		return nil
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if !reflect.DeepEqual(y, A{"bar", 1, ""}) {
		t.Errorf("unexpected result: %#v", y)
	}
}

func TestConverter_MapsStringArraysWithMappingKey(t *testing.T) {
	type A struct {
		Foo   string `json:"test"`
		Baz   int
		Other string
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error {
		if len(*input) == 0 {
			*out = ""
		}
		*out = (*input)[0]
		return nil
	}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}

	x := map[string][]string{
		"Foo":  {"bar"},
		"test": {"baz"},
	}
	y := A{"", 0, ""}

	if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if !reflect.DeepEqual(y, A{"bar", 0, ""}) {
		t.Errorf("unexpected result: %#v", y)
	}

	mapping := func(key string, sourceTag, destTag reflect.StructTag) (source string, dest string) {
		if s := destTag.Get("json"); len(s) > 0 {
			return strings.SplitN(s, ",", 2)[0], key
		}
		return key, key
	}

	if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{KeyNameMapping: mapping}); err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	if !reflect.DeepEqual(y, A{"baz", 0, ""}) {
		t.Errorf("unexpected result: %#v", y)
	}
}

func TestConverter_fuzz(t *testing.T) {
	// Use the same types from the scheme test.
	table := []struct {
		from, to, check interface{}
	}{
		{&TestType1{}, &ExternalTestType1{}, &TestType1{}},
		{&ExternalTestType1{}, &TestType1{}, &ExternalTestType1{}},
	}

	f := fuzz.New().NilChance(.5).NumElements(0, 100)
	c := NewConverter(DefaultNameFunc)
	c.nameFunc = func(t reflect.Type) string {
		// Hide the fact that we don't have separate packages for these things.
		return map[reflect.Type]string{
			reflect.TypeOf(TestType1{}):         "TestType1",
			reflect.TypeOf(ExternalTestType1{}): "TestType1",
			reflect.TypeOf(TestType2{}):         "TestType2",
			reflect.TypeOf(ExternalTestType2{}): "TestType2",
		}[t]
	}
	c.Debug = testLogger(t)

	for i, item := range table {
		for j := 0; j < *fuzzIters; j++ {
			f.Fuzz(item.from)
			err := c.Convert(item.from, item.to, 0, nil)
			if err != nil {
				t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
				continue
			}
			err = c.Convert(item.to, item.check, 0, nil)
			if err != nil {
				t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
				continue
			}
			if e, a := item.from, item.check; !reflect.DeepEqual(e, a) {
				t.Errorf("(%v, %v): unexpected diff: %v", i, j, objDiff(e, a))
			}
		}
	}
}

func TestConverter_MapElemAddr(t *testing.T) {
	type Foo struct {
		A map[int]int
	}
	type Bar struct {
		A map[string]string
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	err := c.RegisterConversionFunc(
		func(in *int, out *string, s Scope) error {
			*out = fmt.Sprintf("%v", *in)
			return nil
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	err = c.RegisterConversionFunc(
		func(in *string, out *int, s Scope) error {
			if str, err := strconv.Atoi(*in); err != nil {
				return err
			} else {
				*out = str
				return nil
			}
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	f := fuzz.New().NilChance(0).NumElements(3, 3)
	first := Foo{}
	second := Bar{}
	f.Fuzz(&first)
	err = c.Convert(&first, &second, AllowDifferentFieldTypeNames, nil)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	third := Foo{}
	err = c.Convert(&second, &third, AllowDifferentFieldTypeNames, nil)
	if e, a := first, third; !reflect.DeepEqual(e, a) {
		t.Errorf("Unexpected diff: %v", objDiff(e, a))
	}
}

func TestConverter_tags(t *testing.T) {
	type Foo struct {
		A string `test:"foo"`
	}
	type Bar struct {
		A string `test:"bar"`
	}
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	err := c.RegisterConversionFunc(
		func(in *string, out *string, s Scope) error {
			if e, a := "foo", s.SrcTag().Get("test"); e != a {
				t.Errorf("expected %v, got %v", e, a)
			}
			if e, a := "bar", s.DestTag().Get("test"); e != a {
				t.Errorf("expected %v, got %v", e, a)
			}
			return nil
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	err = c.Convert(&Foo{}, &Bar{}, AllowDifferentFieldTypeNames, nil)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
}

func TestConverter_meta(t *testing.T) {
	type Foo struct{ A string }
	type Bar struct{ A string }
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)
	checks := 0
	err := c.RegisterConversionFunc(
		func(in *Foo, out *Bar, s Scope) error {
			if s.Meta() == nil {
				t.Errorf("Meta did not get passed!")
			}
			checks++
			s.Convert(&in.A, &out.A, 0)
			return nil
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	err = c.RegisterConversionFunc(
		func(in *string, out *string, s Scope) error {
			if s.Meta() == nil {
				t.Errorf("Meta did not get passed a second time!")
			}
			checks++
			return nil
		},
	)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	err = c.Convert(&Foo{}, &Bar{}, 0, &Meta{})
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if checks != 2 {
		t.Errorf("Registered functions did not get called.")
	}
}

func TestConverter_flags(t *testing.T) {
	type Foo struct{ A string }
	type Bar struct{ A string }
	table := []struct {
		from, to      interface{}
		flags         FieldMatchingFlags
		shouldSucceed bool
	}{
		// Check that DestFromSource allows extra fields only in source.
		{
			from:          &struct{ A string }{},
			to:            &struct{ A, B string }{},
			flags:         DestFromSource,
			shouldSucceed: false,
		}, {
			from:          &struct{ A, B string }{},
			to:            &struct{ A string }{},
			flags:         DestFromSource,
			shouldSucceed: true,
		},

		// Check that SourceToDest allows for extra fields only in dest.
		{
			from:          &struct{ A string }{},
			to:            &struct{ A, B string }{},
			flags:         SourceToDest,
			shouldSucceed: true,
		}, {
			from:          &struct{ A, B string }{},
			to:            &struct{ A string }{},
			flags:         SourceToDest,
			shouldSucceed: false,
		},

		// Check that IgnoreMissingFields makes the above failure cases pass.
		{
			from:          &struct{ A string }{},
			to:            &struct{ A, B string }{},
			flags:         DestFromSource | IgnoreMissingFields,
			shouldSucceed: true,
		}, {
			from:          &struct{ A, B string }{},
			to:            &struct{ A string }{},
			flags:         SourceToDest | IgnoreMissingFields,
			shouldSucceed: true,
		},

		// Check that the field type name must match unless
		// AllowDifferentFieldTypeNames is specified.
		{
			from:          &struct{ A, B Foo }{},
			to:            &struct{ A Bar }{},
			flags:         DestFromSource,
			shouldSucceed: false,
		}, {
			from:          &struct{ A Foo }{},
			to:            &struct{ A, B Bar }{},
			flags:         SourceToDest,
			shouldSucceed: false,
		}, {
			from:          &struct{ A, B Foo }{},
			to:            &struct{ A Bar }{},
			flags:         DestFromSource | AllowDifferentFieldTypeNames,
			shouldSucceed: true,
		}, {
			from:          &struct{ A Foo }{},
			to:            &struct{ A, B Bar }{},
			flags:         SourceToDest | AllowDifferentFieldTypeNames,
			shouldSucceed: true,
		},
	}
	f := fuzz.New().NilChance(.5).NumElements(0, 100)
	c := NewConverter(DefaultNameFunc)
	c.Debug = testLogger(t)

	for i, item := range table {
		for j := 0; j < *fuzzIters; j++ {
			f.Fuzz(item.from)
			err := c.Convert(item.from, item.to, item.flags, nil)
			if item.shouldSucceed && err != nil {
				t.Errorf("(%v, %v): unexpected error: %v", i, j, err)
				continue
			}
			if !item.shouldSucceed && err == nil {
				t.Errorf("(%v, %v): unexpected non-error", i, j)
				continue
			}
		}
	}
}

func TestConverter_FieldRename(t *testing.T) {
	type WeirdMeta struct {
		Name string
		Type string
	}
	type NameMeta struct {
		Name string
	}
	type TypeMeta struct {
		Type string
	}
	type A struct {
		WeirdMeta
	}
	type B struct {
		TypeMeta
		NameMeta
	}

	c := NewConverter(DefaultNameFunc)
	err := c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", TypeMeta{}, "TypeMeta")
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	err = c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", NameMeta{}, "NameMeta")
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	err = c.SetStructFieldCopy(TypeMeta{}, "TypeMeta", WeirdMeta{}, "WeirdMeta")
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	err = c.SetStructFieldCopy(NameMeta{}, "NameMeta", WeirdMeta{}, "WeirdMeta")
	if err != nil {
		t.Fatalf("unexpected error %v", err)
	}
	c.Debug = testLogger(t)

	aVal := &A{
		WeirdMeta: WeirdMeta{
			Name: "Foo",
			Type: "Bar",
		},
	}

	bVal := &B{
		TypeMeta: TypeMeta{"Bar"},
		NameMeta: NameMeta{"Foo"},
	}

	table := map[string]struct {
		from, to, expect interface{}
		flags            FieldMatchingFlags
	}{
		"to": {
			aVal,
			&B{},
			bVal,
			AllowDifferentFieldTypeNames | SourceToDest | IgnoreMissingFields,
		},
		"from": {
			bVal,
			&A{},
			aVal,
			AllowDifferentFieldTypeNames | SourceToDest,
		},
		"toDestFirst": {
			aVal,
			&B{},
			bVal,
			AllowDifferentFieldTypeNames,
		},
		"fromDestFirst": {
			bVal,
			&A{},
			aVal,
			AllowDifferentFieldTypeNames | IgnoreMissingFields,
		},
	}

	for name, item := range table {
		err := c.Convert(item.from, item.to, item.flags, nil)
		if err != nil {
			t.Errorf("%v: unexpected error: %v", name, err)
			continue
		}
		if e, a := item.expect, item.to; !reflect.DeepEqual(e, a) {
			t.Errorf("%v: unexpected diff: %v", name, objDiff(e, a))
		}
	}
}

func objDiff(a, b interface{}) string {
	ab, err := json.Marshal(a)
	if err != nil {
		panic("a")
	}
	bb, err := json.Marshal(b)
	if err != nil {
		panic("b")
	}
	return diff.StringDiff(string(ab), string(bb))

	// An alternate diff attempt, in case json isn't showing you
	// the difference. (reflect.DeepEqual makes a distinction between
	// nil and empty slices, for example.)
	//return diff.StringDiff(
	//	fmt.Sprintf("%#v", a),
	//	fmt.Sprintf("%#v", b),
	//)
}


text:
FROM php:7.2-rc-cli

RUN apt-get update \
  && apt-get install -y --no-install-recommends \
    curl \
    libmemcached-dev \
    libz-dev \
    libpq-dev \
    libjpeg-dev \
    libpng-dev \
    libfreetype6-dev \
    libssl-dev \
    libmcrypt-dev \
    gettext-base \
  && rm -rf /var/lib/apt/lists/*

# Set the PHP redis version
ENV PHPREDIS_VERSION 3.1.4

# Install PHP extentions
RUN docker-php-ext-install mysqli \
  && docker-php-ext-install pdo_mysql \
  && docker-php-ext-install pdo_pgsql \
  && docker-php-ext-configure gd \
    --enable-gd-native-ttf \
    --with-jpeg-dir=/usr/lib \
    --with-freetype-dir=/usr/include/freetype2 \
  && docker-php-ext-install gd \
  && docker-php-ext-install bcmath \
  && docker-php-ext-install zip \
  && pecl install mongodb \
  && docker-php-ext-enable mongodb \
  && curl -L -o redis.tar.gz https://github.com/phpredis/phpredis/archive/$PHPREDIS_VERSION.tar.gz \
  && tar xfz redis.tar.gz \
  && rm -r redis.tar.gz \
  && (     cd phpredis-$PHPREDIS_VERSION \
        && phpize \
        && ./configure \
        && make \
        && make install ) \
  && rm -r phpredis-$PHPREDIS_VERSION \
  && docker-php-ext-enable redis

RUN usermod -u 1000 www-data

VOLUME /var/www/html
WORKDIR /var/www/html
USER www-data


text:
namespace Moses
{

template <class MH, class MO>
class SyntacticLanguageModelFiles
{

public:

  SyntacticLanguageModelFiles(const std::vector<std::string>& filePaths);
  ~SyntacticLanguageModelFiles();

  MH* getHiddenModel();
  MO* getObservedModel();

private:
  MH* hiddenModel;
  MO* observedModel;

};

template <class MH, class MO>
SyntacticLanguageModelFiles<MH,MO>::SyntacticLanguageModelFiles(const std::vector<std::string>& filePaths)
{

  this->hiddenModel = new MH();
  this->observedModel = new MO();

  //// I. LOAD MODELS...
  std::cerr << "Reading syntactic language model files...\n";
  // For each model file...
  for ( int a=0, n=filePaths.size(); a<n; a++ ) {                                           // read models
    FILE* pf = fopen(filePaths[a].c_str(),"r"); // Read model file
    if(!pf) {
      std::cerr << "Error loading model file " << filePaths[a] << std::endl;
      return;
    }
    std::cerr << "Loading model \'" << filePaths[a] << "\'...\n";
    int c=' ';
    int i=0;
    int line=1;
    String sBuff(1000);                          // Lookahead/ctrs/buffers
    CONSUME_ALL ( pf, c, WHITESPACE(c), line);                                   // Get to first record
    while ( c!=-1 && c!='\0' && c!='\5' ) {                                      // For each record
      CONSUME_STR ( pf, c, (c!='\n' && c!='\0' && c!='\5'), sBuff, i, line );    //   Consume line
      StringInput si(sBuff.c_array());
      if ( !( sBuff[0]=='#'                                                   //   Accept comments/fields
              ||  si>>*(this->hiddenModel)>>"\0"!=NULL
              ||  si>>*(this->observedModel)>>"\0"!=NULL
            ))
        std::cerr<<"\nERROR: can't parse \'"<<sBuff<<"\' in line "<<line<<"\n\n";
      CONSUME_ALL ( pf, c, WHITESPACE(c), line);                                 //   Consume whitespace
      if ( line%100000==0 ) std::cerr<<"  "<<line<<" lines read...\n";                //   Progress for big models
    }
    std::cerr << "Model \'" << filePaths[a] << "\' loaded.\n";
  }

  std::cerr << "...reading syntactic language model files completed\n";

}

template <class MH, class MO>
SyntacticLanguageModelFiles<MH,MO>::~SyntacticLanguageModelFiles()
{

  VERBOSE(3,"Destructing syntactic language model files" << std::endl);
  delete hiddenModel;
  delete observedModel;

}

template <class MH, class MO>
MH* SyntacticLanguageModelFiles<MH,MO>::getHiddenModel()
{

  return this->hiddenModel;

}

template <class MH, class MO>
MO* SyntacticLanguageModelFiles<MH,MO>::getObservedModel()
{

  return this->observedModel;

}

}

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <title>Benchmark</title>

b8r

  <b8r-component path="../test/test-nav.component.js"></b8r-component>

    Search
    <input data-bind="value=benchmark.filterSettings.text">

    <button data-event="click:benchmark.create">Create 1,000 rows</button>
    <button data-event="click:benchmark.create10k">Create 10,000 rows</button>
    <button data-event="click:benchmark.append">Append 1,000 rows</button>
    <button data-event="click:benchmark.update">Update every 10th row</button>
    <button data-event="click:benchmark.clear">Clear</button>
    <button data-event="click:benchmark.swap">Swap Rows 4 and 7</button>

        1

          clean blue chair


text:
package ai;

public class State {
	public int x;
	public int y;
	public float reward;

	public State(int x, int y, float reward){
		this.x = x;
		this.y = y;
		this.reward = reward;
	}

	public int hashCode() {
		return (int)(Math.pow((x*7), 2) + y);
	}

	public boolean equals(Object obj){
		if(this == obj){
			return true;
		} else {
			State other = (State) obj;
			return other.x == x && other.y == y; // && other.reward == reward;
		}
	}
}


text:
echo "Cleaning up..."

CONTAINER_NAME=backup
VOLUME_NAME=backup-volume

docker stop $CONTAINER_NAME
docker rm -v $CONTAINER_NAME
docker volume rm $VOLUME_NAME


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

	<context:component-scan base-package="org.pjaygroup.restfulapp3.controller" />
	<!-- If you have all controller under org.pjaygroup.restfulapp3, with different folders -->
	<!-- <context:component-scan base-package="org.pjaygroup.restfulapp3.*"/> -->
</beans>


text:
* 2014-05-11: C++ codecs now include optional bounds checking (#130)

## 1.0-RC2 (2014-05-03)

Initial public release (based on FIX/SBE RC2)
Release to maven central