text:
import { shallowMount } from '@vue/test-utils';
import DiffLineNoteForm from '~/diffs/components/diff_line_note_form.vue';
import NoteForm from '~/notes/components/note_form.vue';
import { createStore } from '~/mr_notes/stores';
import diffFileMockData from '../mock_data/diff_file';
import { noteableDataMock } from '../../notes/mock_data';

describe('DiffLineNoteForm', () => {
  let wrapper;
  let diffFile;
  let diffLines;
  const getDiffFileMock = () => ({ ...diffFileMockData });

  beforeEach(() => {
    diffFile = getDiffFileMock();
    diffLines = diffFile.highlighted_diff_lines;
    const store = createStore();
    store.state.notes.userData.id = 1;
    store.state.notes.noteableData = noteableDataMock;

    wrapper = shallowMount(DiffLineNoteForm, {
      store,
      propsData: {
        diffFileHash: diffFile.file_hash,
        diffLines,
        line: diffLines[0],
        noteTargetLine: diffLines[0],
      },
    });
  });

  describe('methods', () => {
    describe('handleCancelCommentForm', () => {
      it('should ask for confirmation when shouldConfirm and isDirty passed as truthy', () => {
        jest.spyOn(window, 'confirm').mockReturnValue(false);

        wrapper.vm.handleCancelCommentForm(true, true);

        expect(window.confirm).toHaveBeenCalled();
      });

      it('should ask for confirmation when one of the params false', () => {
        jest.spyOn(window, 'confirm').mockReturnValue(false);

        wrapper.vm.handleCancelCommentForm(true, false);

        expect(window.confirm).not.toHaveBeenCalled();

        wrapper.vm.handleCancelCommentForm(false, true);

        expect(window.confirm).not.toHaveBeenCalled();
      });

      it('should call cancelCommentForm with lineCode', done => {
        jest.spyOn(window, 'confirm').mockImplementation(() => {});
        jest.spyOn(wrapper.vm, 'cancelCommentForm').mockImplementation(() => {});
        jest.spyOn(wrapper.vm, 'resetAutoSave').mockImplementation(() => {});
        wrapper.vm.handleCancelCommentForm();

        expect(window.confirm).not.toHaveBeenCalled();
        wrapper.vm.$nextTick(() => {
          expect(wrapper.vm.cancelCommentForm).toHaveBeenCalledWith({
            lineCode: diffLines[0].line_code,
            fileHash: wrapper.vm.diffFileHash,
          });

          expect(wrapper.vm.resetAutoSave).toHaveBeenCalled();

          done();
        });
      });
    });

    describe('saveNoteForm', () => {
      it('should call saveNote action with proper params', done => {
        const saveDiffDiscussionSpy = jest
          .spyOn(wrapper.vm, 'saveDiffDiscussion')
          .mockReturnValue(Promise.resolve());

        const lineRange = {
          start: {
            line_code: wrapper.vm.commentLineStart.line_code,
            type: wrapper.vm.commentLineStart.type,
            new_line: 1,
            old_line: null,
          },
          end: {
            line_code: wrapper.vm.line.line_code,
            type: wrapper.vm.line.type,
            new_line: 1,
            old_line: null,
          },
        };

        const formData = {
          ...wrapper.vm.formData,
          lineRange,
        };

        wrapper.vm
          .handleSaveNote('note body')
          .then(() => {
            expect(saveDiffDiscussionSpy).toHaveBeenCalledWith({
              note: 'note body',
              formData,
            });
          })
          .then(done)
          .catch(done.fail);
      });
    });
  });

  describe('mounted', () => {
    it('should init autosave', () => {
      const key = 'autosave/Note/Issue/98//DiffNote//1c497fbb3a46b78edf04cc2a2fa33f67e3ffbe2a_1_1';

      expect(wrapper.vm.autosave).toBeDefined();
      expect(wrapper.vm.autosave.key).toEqual(key);
    });
  });

  describe('template', () => {
    it('should have note form', () => {
      expect(wrapper.find(NoteForm).exists()).toBe(true);
    });
  });
});


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

// Each Watchman client has a unique identifier
var hostname = os.hostname();
console.log(hostname);

redpajama_set_name: RedPajamaGithub


text:
package org.bidtime.dbutils.jdbc.dao;

import java.sql.SQLException;

/*
 * author: jss
 * 	is to get pk after, to do this.
 * example:
 *
 * Long l = dao.insertForPK(duty,
		new SQLCallback<TTableProps, GsonRow>(){
            @Override
            public String getSql(TTableProps, GsonRow g) throws SQLException {
	        	return tp
	        }
		});
 */
public abstract class SQLCallback<R, T, Z> {

	public SQLCallback() {
	}

	public abstract String getSql(R r, T t, Z z) throws SQLException;

}


text:
package org.springframework.richclient.form.binding.swing;

import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;

import org.springframework.binding.form.FormModel;
import org.springframework.richclient.form.binding.Binding;
import org.springframework.richclient.form.binding.support.AbstractBinder;
import org.springframework.util.Assert;

/**
 * @author Oliver Hutchison
 */
public class FormattedTextFieldBinder extends AbstractBinder {

    public static final String FORMATTER_FACTORY_KEY = "formatterFactory";

    public FormattedTextFieldBinder(Class requiredSourceClass) {
        super(requiredSourceClass, new String[] {FORMATTER_FACTORY_KEY});
    }

    protected Binding doBind(JComponent control, FormModel formModel, String formPropertyPath, Map context) {
        Assert.isTrue(control instanceof JFormattedTextField, "Control must be an instance of JFormattedTextField.");
        return new FormattedTextFieldBinding((JFormattedTextField)control, formModel, formPropertyPath,
                getRequiredSourceClass());
    }

    protected JComponent createControl(Map context) {
        return getComponentFactory().createFormattedTextField(
                (AbstractFormatterFactory)context.get(FORMATTER_FACTORY_KEY));
    }
}


text:
package edu.upc.fib.wordguess.data.postgres;

import java.util.List;

import org.hibernate.classic.Session;

import edu.upc.fib.wordguess.data.dao.PlayerDAO;
import edu.upc.fib.wordguess.data.exception.PlayerNotExistsException;
import edu.upc.fib.wordguess.domain.model.Player;
import edu.upc.fib.wordguess.util.HibernateUtil;

public class PostgresPlayerDAO extends PostgresGenericDAO<Player> implements PlayerDAO {

	@Override
	public boolean exists(String username) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		boolean exists = (session.get(Player.class, username) != null) ? true : false;

		session.close();

		return exists;
	}

	@Override
	public Player get(String username) throws PlayerNotExistsException {
		Session session = HibernateUtil.getSessionFactory().openSession();

		Player player = (Player) session.get(Player.class, username);
		if (player == null) {
			session.close();
			throw new PlayerNotExistsException();
		}

		session.close();
		return player;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Player> getAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();

		List<Player> players = (List<Player>) session.createQuery("from " + Player.class.getSimpleName()).list();

		session.close();

		return players;
	}

}


text:
package de.universallp.xact2.api.plugin;

import de.universallp.xact2.core.recipe.CraftRecipe;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

/**
 * Created by universallp on 06.01.2016 15:09.
 */
public interface SpecialCaseRecipe {

    boolean isSpecialCase(CraftRecipe recipe, ItemStack ingredient, int ingredientIndex);

    boolean isMatchingIngredient(CraftRecipe recipe, ItemStack ingredient, int ingredientIndex, World world);
}


text:
var sys = require('sys');
var twitter = require("twitter");
var settings = require('../site_config.js');
var twit = new twitter({
  consumer_key: settings.twitter.consumerKey,
  consumer_secret: settings.twitter.consumerSecret,
  access_token_key: settings.twitter.accessToken,
  access_token_secret: settings.twitter.accessTokenSecret
});

exports.twitter = twit;


text:
<?php namespace Controllers;

use Core\View,
    Helpers\Url,
    Core\Controller;
use Helpers\SimpleCurl as Curl;
class Search extends Controller {
  private $_model;
  private $_rests_file = 'rests.json';

  public function __construct(){
    parent::__construct();
    $this->_model = new \Models\Rests();
  }

  public function search_post() {
    if (isset($_REQUEST['q'])) {
      $this->search($_REQUEST['q']);
    } else {
      Url::redirect();
    }
  }

  public function search($keyword)
  {
    $data['title'] = 'חיפוש';
    $data['results_dishes'] = $this->_model->search_dishes($keyword);
    $data['results_restaurants'] = $this->_model->search_restaurants($keyword);
    $data['keyword'] = $keyword;

    View::renderTemplate('header', $data);
    View::render('search_results', $data);
    View::renderTemplate('footer', $data);
  }

  public function advanced_search() {
    $data['title'] = 'חיפוש מתקדם';
    $data['sub_load'] = 1;

    if (isset($_REQUEST['submit'])) {

      //build up query
      $query = 'SELECT * FROM dishes JOIN restaurants USING(rest_id) WHERE ';
      $conds = [];
      $params = [];

      if ($_REQUEST['dish_title']) {
        $conds[] = '(dish_title LIKE :dish_title OR dish_desc LIKE :dish_title)';
        $params[':dish_title'] = '%' . $_REQUEST['dish_title'] . '%';
      }

      if ($_REQUEST['is_kosher']) {
        $conds[] = 'rest_kosher = 1';
      }

      if ($_REQUEST['dish_image']) {
        $conds[] = 'dish_image <> ""';
      }

      if ($_REQUEST['price_from']) {
        $conds[] = 'dish_price >= :price_from';
        $params[':price_from'] = $_REQUEST['price_from'];
      }

      if ($_REQUEST['price_to']) {
        $conds[] = 'dish_price <= :price_to';
        $params[':price_to'] = $_REQUEST['price_to'];
      }

      $query .= implode(" AND ", $conds);
      $query .= " LIMIT 100";

      if ($conds) $data['results_dishes'] = $this->_model->advanced_search($query, $params);
    }

    View::renderTemplate('header', $data);
    View::render('search', $data, $error);

    if ($data['results_dishes']) {  View::render('search_results', $data); }

    View::renderTemplate('footer', $data);
  }
}


text:
package com.outbrain.ob1k.client.http;

import com.outbrain.ob1k.Service;
import com.outbrain.ob1k.client.ClientBuilder;
import com.outbrain.ob1k.client.Clients;
import com.outbrain.ob1k.client.ctx.AsyncClientRequestContext;
import com.outbrain.ob1k.client.targets.SimpleTargetProvider;
import com.outbrain.ob1k.common.filters.AsyncFilter;
import com.outbrain.ob1k.concurrent.ComposableFuture;
import com.outbrain.ob1k.concurrent.ComposableFutures;
import com.outbrain.ob1k.concurrent.handlers.FutureSuccessHandler;
import com.outbrain.ob1k.http.Response;
import com.outbrain.ob1k.http.TypedResponse;
import com.outbrain.ob1k.http.common.ContentType;
import com.outbrain.ob1k.server.Server;
import com.outbrain.ob1k.server.builder.ServerBuilder;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import rx.Observable;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * User: aronen
 * Date: 8/19/13
 * Time: 5:16 PM
 */
public class BasicClientRpcTest {

  private static final String HELLO_SERVICE_PATH = "/hello-service";
  private static final String CTX_PATH = "/TestApp";

  private static int port;
  private static Server server;

  private interface HelloServiceClient extends Service {
    ComposableFuture<Response> helloWorld();

    Observable<Response> getMessages(String name, int iterations, boolean failAtEnd);
  }

  private interface HelloServiceTypedClient extends Service {
    ComposableFuture<TypedResponse<String>> helloWorld();

    Observable<TypedResponse<String>> getMessages(String name, int iterations, boolean failAtEnd);
  }

  @BeforeClass
  public static void setup() {
    server = ServerBuilder.newBuilder().contextPath(CTX_PATH).
      configure(builder -> builder.useRandomPort().configureExecutorService(5, 10))
      .service(builder -> builder
        .register(new HelloService(), HELLO_SERVICE_PATH)
        .register(new ParamsService(), "/params")).resource(builder -> builder.staticPath("/static")).build();

    final InetSocketAddress address = server.start();
    port = address.getPort();
  }

  @AfterClass
  public static void tearDown() {
    server.stop();
  }

  @Test
  public void testSimpleResponse() throws Exception {
    final HelloServiceClient helloServiceClient = new ClientBuilder<>(HelloServiceClient.class).
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();

    final Response response = helloServiceClient.helloWorld().get();
    Assert.assertTrue("response should contain hello world", response.getResponseBody().contains("hello world"));
  }

  @Test
  public void testSimpleResponseStream() throws Exception {
    final HelloServiceClient helloServiceClient = new ClientBuilder<>(HelloServiceClient.class).
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();

    final List<String> names = new ArrayList<>(5);
    final Observable<Response> haim = helloServiceClient.getMessages("haim", 5, false);

    haim.toBlocking().forEach(response -> {
      try {
        names.add(response.getResponseBody());
      } catch (final IOException e) {
        throw new RuntimeException(e);
      }
    });

    Assert.assertTrue("first name should contain haim", names.get(0).contains("haim"));
  }

  @Test
  public void testTypedResponse() throws Exception {
    final HelloServiceTypedClient helloServiceClient = new ClientBuilder<>(HelloServiceTypedClient.class).
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();

    final TypedResponse<String> response = helloServiceClient.helloWorld().get();
    Assert.assertEquals("response should be hello world", "hello world", response.getTypedBody());
  }

  @Test
  public void testTypedResponseStream() throws Exception {
    final HelloServiceTypedClient helloServiceClient = new ClientBuilder<>(HelloServiceTypedClient.class).
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();

    final List<String> names = new ArrayList<>(5);
    final Observable<TypedResponse<String>> haim = helloServiceClient.getMessages("haim", 5, false);

    haim.toBlocking().forEach(response -> {
      try {
        names.add(response.getTypedBody());
      } catch (final IOException e) {
        throw new RuntimeException(e);
      }
    });

    Assert.assertTrue("first name should contain haim", names.get(0).contains("haim"));
  }

  @Test
  public void testEmptyJsonResponseBody() throws ExecutionException, InterruptedException {
    final IHelloService service = createClient(ContentType.JSON, port);
    service.emptyString().get(); // used to throw "JsonMappingException: No content to map due to end-of-input"
  }

  @Test
  public void testHelloService() {

    final IHelloService jsonClient = createClient(ContentType.JSON, port);
    final IHelloService msgPackClient = createClient(ContentType.MESSAGE_PACK, port);

    final List<TestBean> beans = createBeans();

    try {
      final ComposableFuture<List<TestBean>> result1 = jsonClient.increaseAge(beans, "programming");
      final List<TestBean> resBeans1 = result1.get();
      Assert.assertEquals(resBeans1.size(), beans.size());
      Assert.assertEquals(resBeans1.get(0).getAge(), beans.get(0).getAge() + 1);

      final ComposableFuture<List<TestBean>> result2 = msgPackClient.increaseAge(beans, "programming");
      final List<TestBean> resBeans2 = result2.get();
      Assert.assertEquals(resBeans2.size(), beans.size());
      Assert.assertEquals(resBeans2.get(0).getAge(), beans.get(0).getAge() + 1);
    } catch (InterruptedException | ExecutionException e) {
      Assert.fail(e.getMessage());
    }
  }

  @Test
  public void testMultipleClientsSharedThreads() throws Exception {
    final List<IHelloService> clients = new ArrayList<>();
    final int numOfThreadsBefore = Thread.activeCount();

    for (int i = 0; i < 100; i++) {
      final IHelloService client = createClient(ContentType.JSON, port);
      clients.add(client);
    }

    final int numOfThreads = Thread.activeCount();

    for (final IHelloService client : clients) {
      Clients.close(client);
    }

    Assert.assertTrue((numOfThreads - numOfThreadsBefore) < 100);
  }

  private List<TestBean> createBeans() {
    final List<String> habits = new ArrayList<>();
    habits.add("eating");
    habits.add("sleeping");
    final TestBean bean = new TestBean("haim", 39, habits);

    final List<TestBean> beans = new ArrayList<>();
    beans.add(bean);
    return beans;
  }

  @Test
  public void testTimeout() {
    final int requestTimeout = 100;
    final IHelloService fastClient = createClient(port, requestTimeout, 3);

    final long t1 = System.currentTimeMillis();
    final ComposableFuture<Boolean> sleepResult = fastClient.sleep(requestTimeout * 2);
    try {
      final Boolean bogusRes = sleepResult.get();
      final long t2 = System.currentTimeMillis();
      Assert.fail("request timeout should be thrown. res is: " + bogusRes + " time took: " + (t2 - t1));
    } catch (final ExecutionException e) {
      Assert.assertTrue(e.getCause() instanceof TimeoutException);
    } catch (final InterruptedException e) {
      Assert.fail(e.getMessage());
    }

    final long t2 = System.currentTimeMillis();
    final long period = t2 - t1;

    Assert.assertTrue("request time was too short", period >= requestTimeout);
    Assert.assertTrue("request time was too long", period < requestTimeout * 3);
  }

  @Test
  public void testStreamJson() {
    testStream(ContentType.JSON);
  }

  @Test
  public void testStreamMsgPack() {
    testStream(ContentType.MESSAGE_PACK);
  }

  private void testStream(final ContentType contentType) {
    final IHelloService client = createClient(contentType, port);
    final int SIZE = 10;
    final Observable<String> messages = client.getMessages("moshe", SIZE, false);

    final List<String> results = new ArrayList<>();
    messages.toBlocking().forEach(results::add);
    Assert.assertEquals(results.size(), SIZE);
    Assert.assertEquals(results.get(0), "hello moshe #0");

    final Observable<String> badMessages = client.getMessages("moshe", SIZE, true);
    final List<String> badResults = new ArrayList<>();

    try {
      badMessages.toBlocking().forEach(badResults::add);
    } catch (final RuntimeException e) {
      Assert.assertTrue("Got an unexpected exception: " + e.getMessage(), e.getMessage().contains("last message is really bad"));
    }

    Assert.assertEquals(badResults.size(), SIZE);
    Assert.assertEquals(badResults.get(0), "hello moshe #0");
  }

  @Test
  public void testSingleParamCall() {
    final IHelloService client = createClient(ContentType.JSON, port);
    try {
      final String haimMessage = client.hello("haim").get();
      Assert.assertTrue(haimMessage.contains("haim"));
    } catch (InterruptedException | ExecutionException e) {
      Assert.fail(e.getMessage());
    }

    try {
      client.hello("moshe").get();
      Assert.fail("method should throw exception with this param");
    } catch (final InterruptedException e) {
      Assert.fail(e.getMessage());
    } catch (final ExecutionException e) {
      Assert.assertNotNull(e.getCause());
    }

    try {
      ((Closeable) client).close();
    } catch (final IOException e) {
      Assert.fail("failed to close the client.");
    }

  }

  @Test
  public void testFilters() {
    final IHelloService client = createClientWithFilters(ContentType.JSON, port);
    try {
      final String res = client.hello("haim").get();
      Assert.assertEquals(res, "hello haim !!!");
    } catch (InterruptedException | ExecutionException e) {
      Assert.fail(e.getMessage());
    }

    try {
      final String res = client.helloFilter("haim").get();
      Assert.assertEquals(res, "hello haim ? !!!");
    } catch (final Throwable e) {
      Assert.fail(e.getMessage());
    }

  }

  private IHelloService createClient(final ContentType protocol, final int port) {
    return new ClientBuilder<>(IHelloService.class).
      setProtocol(protocol).
      setRequestTimeout(120000). // heavily loaded testing environment.
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();
  }

  private IHelloService createClient(final int port, final int requestTimeout, final int retries) {
    return new ClientBuilder<>(IHelloService.class).
      setProtocol(ContentType.JSON).
      setRequestTimeout(requestTimeout).
      setRetries(retries).
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();
  }

  private IHelloService createClientWithFilters(final ContentType protocol, final int port) {
    return new ClientBuilder<>(IHelloService.class).
      setProtocol(protocol).
      addFilter(new BangFilter()).
      bindEndpoint("helloFilter", new QFilter()).
      setRequestTimeout(120000). // heavily loaded testing environment.
      setTargetProvider(new SimpleTargetProvider("http://localhost:" + port + CTX_PATH + HELLO_SERVICE_PATH)).
      build();
  }

  private final static class QFilter implements AsyncFilter<String, AsyncClientRequestContext> {
    @Override
    public ComposableFuture<String> handleAsync(final AsyncClientRequestContext ctx) {
      return ctx.<String>invokeAsync()
        .continueOnSuccess((FutureSuccessHandler<String, String>) result -> ComposableFutures.fromValue(result + " ?"));
    }
  }

  private final static class BangFilter implements AsyncFilter<String, AsyncClientRequestContext> {
    @Override
    public ComposableFuture<String> handleAsync(final AsyncClientRequestContext ctx) {
      return ctx.<String>invokeAsync()
        .continueOnSuccess((FutureSuccessHandler<String, String>) result -> ComposableFutures.fromValue(result + " !!!"));
    }
  }

  @Test(expected = ExecutionException.class)
  public void testEmptyTargetBehavior() throws ExecutionException, InterruptedException {
    final IHelloService service = new ClientBuilder<>(IHelloService.class).build();
    final ComposableFuture<com.outbrain.ob1k.Response> future = service.emptyString(); // used to throw "JsonMappingException: No content to map due to end-of-input"
    Assert.assertNotNull(future);
    try {
      future.get();
    } catch (final ExecutionException e) {
      Assert.assertEquals(NoSuchElementException.class, e.getCause().getClass());
      throw e;
    }
  }

  @Test(expected = RuntimeException.class)
  public void testEmptyTargetStreamBehavior() throws ExecutionException, InterruptedException {
    final IHelloService service = new ClientBuilder<>(IHelloService.class).build();
    final Observable<String> observable = service.getMessages("name", 1, false);
    Assert.assertNotNull(observable);
    observable.toBlocking().first();
  }

}


text:
function [r mu] = circ_axialmean(alphas, m, dim)
%
% mu = circ_axialmean(alpha, w)
%   Computes the mean direction for circular data with axial
%   correction.
%
%   Input:
%     alpha	sample of angles in radians
%     [m		axial correction (2,3,4,...)]
%     [dim      statistic computed along this dimension, 1]
%
%   Output:
%     r		mean resultant length
%     mu		mean direction
%
% PHB 7/6/2008
%
% References:
%   Statistical analysis of circular data, N. I. Fisher
%   Topics in circular statistics, S. R. Jammalamadaka et al.
%   Biostatistical Analysis, J. H. Zar
%
% Circular Statistics Toolbox for Matlab

% By Philipp Berens, 2009
% berens@tuebingen.mpg.de - www.kyb.mpg.de/~berens/circStat.html
% Distributed under Open Source BSD License

if nargin < 3
  dim = 1;
end

if nargin < 2 || isempty(m)
    m = 1;
end

zbarm = mean(exp(1i*alphas*m),dim);

r = abs(zbarm);
mu = angle(zbarm)/m;


text:
package net.ghosttrails.www.mydetic.api;

import net.ghosttrails.www.mydetic.exceptions.MyDeticException;
import org.joda.time.LocalDate;

/** Interface for classes that implement the MemoryData service to fetch and store memories. */
public interface MemoryApi {

  /**
   * @param userId which user's memories to use
   * @param listener callback to receive the memory list.
   */
  void getMemories(String userId, MemoryListListener listener);

  /**
   * Get a list of memories between fromDate and toDate (inclusive). Either date can be null, which
   * indicates no bound on the range in that direction.
   *
   * @param userId which user's memories to use
   * @param fromDate If not null, only memories from this date or later will be returned.
   * @param toDate If not null, only memories on this date and earlier will be returned.
   * @param listener callback to receive the memory list.
   */
  void getMemories(
      String userId, LocalDate fromDate, LocalDate toDate, MemoryListListener listener);

  /**
   * @param userId which user's memories to use
   * @param memoryDate the date to get the memory for.
   * @param listener callback to receive the memory.
   */
  void getMemory(String userId, LocalDate memoryDate, SingleMemoryListener listener);

  /**
   * Adds or updates a memory
   *
   * @param userId which user's memories to use
   * @param memory The memory to add/update.
   * @param listener callback to receive the memory.
   */
  void putMemory(String userId, MemoryData memory, SingleMemoryListener listener);

  /**
   * @param userId which user's memories to use
   * @param memoryDate The date of the memory to delete
   * @param listener callback to receive the memory.
   */
  void deleteMemory(String userId, LocalDate memoryDate, SingleMemoryListener listener);

  /** Callback interface for Api methods that return a MemoryDataList */
  interface MemoryListListener {
    void onApiResponse(MemoryDataList memories);

    void onApiError(MyDeticException exception);
  }

  /** Callback interface for Api methods that return a MemoryData */
  interface SingleMemoryListener {
    void onApiResponse(MemoryData memory);

    void onApiError(MyDeticException exception);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sv:node sv:name="externaldocumentpicker" xmlns:sv="http://www.jcp.org/jcr/sv/1.0">
  <sv:property sv:name="jcr:primaryType" sv:type="Name">
    <sv:value>hipposysedit:namespace</sv:value>
  </sv:property>
  <sv:property sv:name="jcr:mixinTypes" sv:type="Name">
    <sv:value>mix:referenceable</sv:value>
  </sv:property>
</sv:node>


text:
package com.cardpay.pccredit.manager.dao.comdao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cardpay.pccredit.manager.model.MaintenanceAccountManager;
import com.cardpay.pccredit.riskControl.model.ManagerCustomerType;
import com.wicresoft.jrad.base.database.dao.common.CommonDao;
/**
 *
 * @author 季东晓
 *
 * 2014-11-20 下午2:21:59
 */
@Service
public class MaintenanceAccountManagerComdao {

	@Autowired
	private CommonDao commonDao;
	/**
	 * 查询客户经理参数维护
	 * @return
	 */
	public List<MaintenanceAccountManager> getMaintenanceAccountManager(){
		String sql = "select t.*,c.customer_type_code from maintenance_account_manager t,(select m.level_id,m.customer_type as customer_type_code from manager_customer_type m) c where t.hierarchy=c.level_id order by t.hierarchy asc";
		//String sql = "select t.*,c.customer_type_code from maintenance_account_manager t,(select m.level_id,wm_concat(m.customer_type) as customer_type_code from manager_customer_type m group by m.level_id) c where t.hierarchy=c.level_id order by t.hierarchy asc";
		List<MaintenanceAccountManager> list = commonDao.queryBySql(MaintenanceAccountManager.class, sql, null);
			return list;

	}

	/**
	 * 查询客户层级对应的类型
	 * @return
	 */
	public List<ManagerCustomerType> getManagerCustomerType(){
		String sql = "select m.* from manager_customer_type m where 1=1 order by m.level_id asc";
		List<ManagerCustomerType> list = commonDao.queryBySql(ManagerCustomerType.class, sql, null);
			return list;

	}

}


text: while true; do sl; done;


text:
namespace orbit_vulkan_layer {

// This class provides a wrapper for calls directly into the Vulkan loader.
// It is used, such that we can fake the called Vulkan functions in the tests.
//
// Note: in most cases we use the function pointers returned by "GetDevice/InstanceProcAddr",
// which directly point to the implementation in the next layer or ICD. So most used Vulkan
// functions don't need to show up here.
// See `DispatchTable` and `VulkanLayerController`.
class VulkanWrapper {
 public:
  VkResult CallVkEnumerateInstanceExtensionProperties(const char* layer_name,
                                                      uint32_t* property_count,
                                                      VkExtensionProperties* properties) {
    return vkEnumerateInstanceExtensionProperties(layer_name, property_count, properties);
  }
};
}  //  namespace orbit_vulkan_layer

#endif  // ORBIT_VULKAN_LAYER_VULKAN_WRAPPER_H_


text:
// collections/CollectionDifferences.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import onjava.*;

public class CollectionDifferences {
  public static void main(String[] args) {
    CollectionMethodDifferences.main(args);
  }
}
/* Output:
Collection: [add, addAll, clear, contains, containsAll,
equals, forEach, hashCode, isEmpty, iterator,
parallelStream, remove, removeAll, removeIf, retainAll,
size, spliterator, stream, toArray]
Interfaces in Collection: [Iterable]
Set extends Collection, adds: []
Interfaces in Set: [Collection]
HashSet extends Set, adds: []
Interfaces in HashSet: [Set, Cloneable, Serializable]
LinkedHashSet extends HashSet, adds: []
Interfaces in LinkedHashSet: [Set, Cloneable,
Serializable]
TreeSet extends Set, adds: [headSet,
descendingIterator, descendingSet, pollLast, subSet,
floor, tailSet, ceiling, last, lower, comparator,
pollFirst, first, higher]
Interfaces in TreeSet: [NavigableSet, Cloneable,
Serializable]
List extends Collection, adds: [replaceAll, get,
indexOf, subList, set, sort, lastIndexOf, listIterator]
Interfaces in List: [Collection]
ArrayList extends List, adds: [trimToSize,
ensureCapacity]
Interfaces in ArrayList: [List, RandomAccess,
Cloneable, Serializable]
LinkedList extends List, adds: [offerFirst, poll,
getLast, offer, getFirst, removeFirst, element,
removeLastOccurrence, peekFirst, peekLast, push,
pollFirst, removeFirstOccurrence, descendingIterator,
pollLast, removeLast, pop, addLast, peek, offerLast,
addFirst]
Interfaces in LinkedList: [List, Deque, Cloneable,
Serializable]
Queue extends Collection, adds: [poll, peek, offer,
element]
Interfaces in Queue: [Collection]
PriorityQueue extends Queue, adds: [comparator]
Interfaces in PriorityQueue: [Serializable]
Map: [clear, compute, computeIfAbsent,
computeIfPresent, containsKey, containsValue, entrySet,
equals, forEach, get, getOrDefault, hashCode, isEmpty,
keySet, merge, put, putAll, putIfAbsent, remove,
replace, replaceAll, size, values]
HashMap extends Map, adds: []
Interfaces in HashMap: [Map, Cloneable, Serializable]
LinkedHashMap extends HashMap, adds: []
Interfaces in LinkedHashMap: [Map]
SortedMap extends Map, adds: [lastKey, subMap,
comparator, firstKey, headMap, tailMap]
Interfaces in SortedMap: [Map]
TreeMap extends Map, adds: [descendingKeySet,
navigableKeySet, higherEntry, higherKey, floorKey,
subMap, ceilingKey, pollLastEntry, firstKey, lowerKey,
headMap, tailMap, lowerEntry, ceilingEntry,
descendingMap, pollFirstEntry, lastKey, firstEntry,
floorEntry, comparator, lastEntry]
Interfaces in TreeMap: [NavigableMap, Cloneable,
Serializable]
*/


text:
package gov.sandia.cognition.framework.lite;

import gov.sandia.cognition.framework.DummyCogxelFactory;
import gov.sandia.cognition.framework.DummyModuleFactory;
import junit.framework.*;
import gov.sandia.cognition.framework.CogxelFactory;
import gov.sandia.cognition.framework.DefaultCogxelFactory;

/**
 * This class implements JUnit tests for the following classes:
 *      ArrayBasedPerceptionModuleFactory
 *
 * @author Justin Basilico
 * @since 1.0
 */
public class ArrayBasedPerceptionModuleFactoryTest
    extends TestCase
{
    public ArrayBasedPerceptionModuleFactoryTest(
        String testName)
    {
        super(testName);
    }

    public static Test suite()
    {
        TestSuite suite = new TestSuite(ArrayBasedPerceptionModuleFactoryTest.class);

        return suite;
    }

    public void testConstructors()
    {
        ArrayBasedPerceptionModuleFactory instance =
            new ArrayBasedPerceptionModuleFactory();
        assertEquals(DefaultCogxelFactory.INSTANCE, instance.getCogxelFactory());

        DummyCogxelFactory dummyFactory = new DummyCogxelFactory();
        instance = new ArrayBasedPerceptionModuleFactory(dummyFactory);
        assertSame(dummyFactory, instance.getCogxelFactory());
    }

    /**
     * Test of createModule method, of class gov.sandia.isrc.cognition.framework.lite.ArrayBasedPerceptionModuleFactory.
     */
    public void testCreateModule()
    {
        ArrayBasedPerceptionModuleFactory instance =
            new ArrayBasedPerceptionModuleFactory();

        CognitiveModelLite model = new CognitiveModelLite(
            new DummyModuleFactory());

        ArrayBasedPerceptionModule module1 = instance.createModule(model);
        ArrayBasedPerceptionModule module2 = instance.createModule(model);
        assertNotNull(module1);
        assertNotNull(module2);
        assertNotSame(module1, module2);
    }

    /**
     * Test of getCogxelFactory method, of class gov.sandia.isrc.cognition.framework.lite.ArrayBasedPerceptionModuleFactory.
     */
    public void testGetCogxelFactory()
    {
        CogxelFactory factory = DefaultCogxelFactory.INSTANCE;
        ArrayBasedPerceptionModuleFactory instance =
            new ArrayBasedPerceptionModuleFactory(factory);
        assertEquals(factory, instance.getCogxelFactory());
    }
}


text:
import m from 'mithril';

var renderRawText = function(text) {
    let texts = text.split("\n");
    return m('.text', texts.map((text) => {
        return [text, m('br')]
    }));
};

var renderText = function(ctrl, lang, phrase) {
    let collapseIn = "";
    if (lang == ctrl.lang()) {
        collapseIn = " active";
    }
    let classNames = `${lang} ${collapseIn}`;
    return m('.phrase-tab.tab-pane[role="tabpanel"]',
        { id: `id-${phrase.id}-${lang}`, class: classNames },
        renderRawText(phrase[lang])
    );
};

var renderJa = function(ctrl, phrase) {
    return renderText(ctrl, 'ja', phrase);
};

var renderEn = function(ctrl, phrase) {
    return renderText(ctrl, 'en', phrase);
};

var renderNone = function(ctrl, phrase) {
    let collapseIn = "";
    if (ctrl.lang() != 'ja' && ctrl.lang() != 'en') {
        collapseIn = " active";
    }
    let classNames = `none ${collapseIn}`;
    return m('.phrase-tab.tab-pane[role="tabpanel"]',
        { id: `id-${phrase.id}-none`, class: classNames },
        m('span.text.glyphicon.glyphicon-bullhorn')
    );
}

var renderRelatedWordLink = function(ctrl, word) {
    let link = ctrl.words().dict[word];
    if (link) {
        return m('a', {
            href: `/${ctrl.lang()}/phrase/${link.phrase_id}`,
            config: m.route
        }, word);
    }
    return word;
}

var renderRelatedWordLinks = function(ctrl, words) {
    return words.map((word) => {
        return m('span.word', renderRelatedWordLink(ctrl, word));
    });
}

var renderSynonyms = function(ctrl, phrase, synonyms) {
    return m('span.synonyms', renderRelatedWordLinks(ctrl, synonyms));
}

var renderAntonyms = function(ctrl, phrase, antonyms) {
    let translation = antonyms.translation;
    let words = antonyms.words;
    let contents = [ renderRelatedWordLinks(ctrl, words) ];
    if (translation) {
        contents.push(m('span.an_trans', translation));
    }
    return m('span.antonyms', contents);
}

var renderWordDetail = function(ctrl, phrase, word) {
    let detail = [m('span.translation', word.translation)]
    if (word.synonyms) {
        detail.push(renderSynonyms(ctrl, phrase, word.synonyms));
    }
    if (word.antonyms) {
        detail.push(renderAntonyms(ctrl, phrase, word.antonyms));
    }
    return m('dd', detail);
}

var renderWordNotes = function(ctrl, phrase, word) {
    if (word.notes) {
        return m('dd.note', m('ul', word.notes.map((note) => {
            return m('li', note);
        })));
    }
    return "";
}

var renderWord = function(ctrl, phrase, word) {
    return [
        m('dt', word.word),
        renderWordDetail(ctrl, phrase, word),
        renderWordNotes(ctrl, phrase, word)
    ];
}

var renderWords = function(ctrl, phrase) {
    let words = ctrl.words().index[phrase.id];
    if (words) {
        return m('dl.words', words.map((word) => {
            return renderWord(ctrl, phrase, word);
        }));
    }
    return "";
}

var renderNote = function(ctrl, phrase) {
    return m('.phrase-tab.tab-pane[role="tabpanel"]',
        { id: `id-${phrase.id}-note`, class: "note" },
        renderWords(ctrl, phrase)
    );
}

var renderLangButton = function(ctrl, lang, phrase) {
    let className = "";
    let text = lang;
    if (lang == ctrl.lang()) {
        className = "active";
    }
    if (lang != 'en' && lang != 'ja') {
        text = m('span.glyphicon.glyphicon-bullhorn')
    }
    return m('li[role="presentation"]',
        { class: className },
        m('a[role="tab"][data-toggle="tab"]',
            { href: `#id-${phrase.id}-${lang}`, "aria-controls": `id-${phrase.id}-${lang}` },
            text
        )
    );
};

var renderNoteButton = function(ctrl, phrase) {
    return m('li[role="presentation"]',
        { class: 'note' },
        m('a[role="tab"][data-toggle="tab"]',
            { href: `#id-${phrase.id}-note`, "aria-controls": `id-${phrase.id}-note` },
            m('span.glyphicon.glyphicon-list-alt')
        )
    );
}

var renderLangButtons = function(ctrl, phrase) {
    return m('.tabs-below', m('ul.nav.nav-tabs[role="tablist"]', [
        renderLangButton(ctrl, 'en', phrase),
        renderLangButton(ctrl, 'ja', phrase),
        renderLangButton(ctrl, 'none', phrase),
        renderNoteButton(ctrl, phrase)
    ]));
};

var createPlayAudioPhraseHandler = function(ctrl, phrase) {
    return function() {
        let audio = document.getElementById(`audio-${phrase.id}`);
        audio.currentTime = 0;
        audio.play();
        return false;
    }
}

var createStopAudioPhraseHandler = function(ctrl, phrase) {
    return function() {
        let audio = document.getElementById(`audio-${phrase.id}`);
        let duration = audio.duration;
        let currentTime = audio.currentTime;
        if (duration - currentTime < 2) {
            audio.currentTime = 0;
            audio.play();
        } else {
            audio.pause();
        }
        return false;
    }
}

var renderPlayButton = function(ctrl, phrase) {
    let icon = null;
    let handler = null;
    if (ctrl.audioStatus() == 'ended') {
        icon = m('span.glyphicon.glyphicon-play');
        handler = createPlayAudioPhraseHandler(ctrl, phrase);
    } else {
        icon = m('span.glyphicon.glyphicon-pause');
        handler = createStopAudioPhraseHandler(ctrl, phrase);
    }
    return m('a[title="key:\'p\'"]', {
        href: '#',
        onclick: handler
    }, m('.phase-navigation.play', icon));
}

var createRedirectRandomHandler = function(ctrl, phrase) {
    return function() {
        let phrases = ctrl.duo().phrases;
        let random = phrases[Math.floor(Math.random() * phrases.length)];
        m.route(`/${ctrl.lang()}/phrase/${random.id}`);
        return false;
    }
}

var renderRandomButton = function(ctrl, phrase) {
    return m('a[title="key:\'r\'"]', {
        href: '#',
        onclick: createRedirectRandomHandler(ctrl, phrase)
    }, m('.phase-navigation', m('span.glyphicon.glyphicon-random')));
}

var directionMap = {
    'next': 'j',
    'previous': 'k'
}

var renderNavigation = function(ctrl, phrase, direction, caption) {
    let navigation = m('.phase-navigation',
        { class: direction },
        caption
    );
    if (phrase[direction]) {
        navigation = m('a',
            {
                href: `/${ctrl.lang()}/phrase/${phrase[direction].id}`,
                config: m.route,
                title: `key:'${directionMap[direction]}'`
            },
            navigation
        )
    }
    return navigation;
}

var firstOrLastPhaseInSection = function(ctrl, phrase, direction) {
    if (phrase) {
        let phrases = phrase.section.phrases;
        if (direction == 'previous') {
            return phrases[0];
        } else {
            return phrases[phrases.length - 1];
        }
    }
    return null;
}

var stepForwardOrBackwordPhrase = function(ctrl, phrase, direction) {
    let targetPhrase = firstOrLastPhaseInSection(ctrl, phrase, direction);
    if (targetPhrase.id == phrase.id) {
        let nextDirection = 'previous';
        if (direction == 'previous') {
            nextDirection = 'next';
        }
        targetPhrase = firstOrLastPhaseInSection(ctrl, phrase[direction], nextDirection);
    }
    return targetPhrase;
}

var renderSectionNavigation = function(ctrl, phrase, direction, caption) {
    let navigation = m('.phase-navigation',
        { class: direction },
        caption
    );
    let targetPhrase = stepForwardOrBackwordPhrase(ctrl, phrase, direction);

    if (targetPhrase) {
        navigation = m('a',
            { href: `/${ctrl.lang()}/phrase/${targetPhrase.id}`, config: m.route },
            navigation
        )
    }

    return navigation;
}

var renderNavigations = function(ctrl, phrase) {
    let stepBackward = m('span.glyphicon.glyphicon-step-backward');
    let backward = m('span.glyphicon.glyphicon-backward');
    let stepForward = m('span.glyphicon.glyphicon-step-forward');
    let forward = m('span.glyphicon.glyphicon-forward');
    return m('.phase-navigations', [
        renderPlayButton(ctrl, phrase),
        renderRandomButton(ctrl, phrase),
        renderSectionNavigation(ctrl, phrase, 'previous', stepBackward),
        renderNavigation(ctrl, phrase, 'previous', backward),
        renderNavigation(ctrl, phrase, 'next', forward),
        renderSectionNavigation(ctrl, phrase, 'next', stepForward)
    ]);
}

var renderSectionTitle = function(ctrl, phrase) {
    let text = `${phrase.section.name} (${phrase.id})`;
    return m('.section-title', [
        m('p', text),
        renderSectionBreadcrumb(ctrl, phrase)
    ]);
}

var createPlayingAudioHandler = function(ctrl, phrase) {
    return function(event) {
        ctrl.audioStatus("playing");
        return false;
    }
}

var createEndedAudioHandler = function(ctrl, phrase) {
    return function(event) {
        ctrl.audioStatus("ended");
        return false;
    }
}

var renderAudio = function(ctrl, phrase) {
    let attr = {
        src: `resources/${phrase.path}`,
        id: `audio-${phrase.id}`,
        onplay: createPlayingAudioHandler(ctrl, phrase),
        onplaying: createPlayingAudioHandler(ctrl, phrase),
        onended: createEndedAudioHandler(ctrl, phrase),
        onpause: createEndedAudioHandler(ctrl, phrase)
    }
    if (ctrl.lang() == 'none') {
        attr['autoplay'] = 'autoplay'
    }
    return m('.audio', m('audio[controls=controls]', attr));
}

var renderSectionBreadcrumb = function(ctrl, phrase) {
    let phrases = phrase.section.phrases;
    return m('.breadcrumb', phrases.map((_phrase) => {
        let attr = {
            class: _phrase.id == phrase.id ? 'current' : '',
            href: `/${ctrl.lang()}/phrase/${_phrase.id}`,
            config: m.route,
        };
        return m('a.phrase-nav', attr, ' ')
    }));
}

var renderFooter = function(ctrl, phrase) {
    return m('.footer', [
        renderLangButtons(ctrl, phrase),
        renderNavigations(ctrl, phrase)
    ]);
}

var createEventHandler = function(ctrl, phrase) {
    return function(el, isInitialized, context) {
        let keyupHook = function(event) {
            let targetPhrase = null;
            if (event.keyCode == 39 || event.keyCode == 74) {
                // Move next `key -> / j`
                m.route(`/${ctrl.lang()}/phrase/${phrase.next.id}`);
                return false;
            } else if (event.keyCode == 37 || event.keyCode == 75) {
                // Move previous `key <- / k`
                m.route(`/${ctrl.lang()}/phrase/${phrase.previous.id}`);
                return false;
            } else if (event.keyCode == 72) {
                // Move step previous `key h`
                targetPhrase = stepForwardOrBackwordPhrase(ctrl, phrase, 'next');
                m.route(`/${ctrl.lang()}/phrase/${targetPhrase.id}`);
                return false;
            } else if (event.keyCode == 76) {
                // Move previous next `key l`
                targetPhrase = stepForwardOrBackwordPhrase(ctrl, phrase, 'previous');
                m.route(`/${ctrl.lang()}/phrase/${targetPhrase.id}`);
                return false;
            } else if (event.keyCode == 80) {
                // Play phrase `key p`
                if (ctrl.audioStatus() == 'ended') {
                    return createPlayAudioPhraseHandler(ctrl, phrase)();
                } else {
                    return createStopAudioPhraseHandler(ctrl, phrase)();
                }
            } else if (event.keyCode == 82) {
                // Move random phrase `key r`
                return createRedirectRandomHandler(ctrl, phrase)();
            }
        }
        let swipeLeftHook = function(event) {
            // console.log('swipeleft')
            // console.log(event.detail.x2 - event.detail.x1);
            let absX = Math.abs(event.detail.x2 - event.detail.x1);
            if ( absX > window.innerWidth / 4) {
                window.history.forward();
            }
            return false;
        }
        let swipeRightHook = function(event) {
            // console.log('swiperight')
            // console.log(event.detail.x2 - event.detail.x1);
            let absX = Math.abs(event.detail.x2 - event.detail.x1);
            if ( absX > window.innerWidth / 4) {
                window.history.back();
            }
            return false;
        }
        if (!isInitialized) {
            document.addEventListener('keyup', keyupHook);
            if (window.navigator.standalone) {
                document.addEventListener('swipeleft', swipeLeftHook);
                document.addEventListener('swiperight', swipeRightHook);
            }

            context.onunload = () => {
                document.removeEventListener('keyup', keyupHook);
                if (window.navigator.standalone) {
                    document.removeEventListener('swipeleft', swipeLeftHook);
                    document.removeEventListener('swiperight', swipeRightHook);
                }
            }
        }
    }
}

export default {
    controller: (args) => {
        args.lang(m.route.param("lang"));
        let id = parseInt(m.route.param("id"));
        args.phrase(id);
        localStorage.setItem('previousUrl', m.route());
        let audioStatus = m.prop("ended");

        return {
            lang: args.lang,
            id: id,
            duo: args.duo(),
            words: args.words(),
            audioStatus: audioStatus
        };
    },
    view: (ctrl, args) => {
        let phrase = ctrl.duo().index[ctrl.id];
        return [
            m('.container-fluid.phrase', {
                config: createEventHandler(ctrl, phrase)
            }, [
                renderSectionTitle(ctrl, phrase),
                m('.row.contents', [
                    renderAudio(ctrl, phrase),
                    m('.tab-content', [
                        renderEn(ctrl, phrase),
                        renderJa(ctrl, phrase),
                        renderNone(ctrl, phrase),
                        renderNote(ctrl, phrase)
                    ])
                ]),
            ]),
            renderFooter(ctrl, phrase)
        ];
    }
};


text:
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)

function onCreatureAppear(cid)			npcHandler:onCreatureAppear(cid)			end
function onCreatureDisappear(cid)		npcHandler:onCreatureDisappear(cid)			end
function onCreatureSay(cid, type, msg)		npcHandler:onCreatureSay(cid, type, msg)		end
function onThink()				npcHandler:onThink()					end

local function creatureSayCallback(cid, type, msg)
	local player = Player(cid)
	if not npcHandler:isFocused(cid) then
		return false
	elseif msgcontains(msg, "cough syrup") then
		if player:getStorageValue(Storage.TheApeCity.Questline) == 5 then
			npcHandler:say("Do you want to buy a bottle of cough syrup for 50 gold?", cid)
			npcHandler.topic[cid] = 1
		end
	elseif msgcontains(msg, "yes") then
		if npcHandler.topic[cid] == 1 and player:removeMoney(50) then
			npcHandler:say("Thank you. Here it is.", cid)
			player:addItem(4839, 1)
			player:setStorageValue(Storage.TheApeCity.Questline, 6)
			player:setStorageValue(Storage.TheApeCity.Mission02, 4) -- The Ape City Questlog - Mission 2: The Cure
		else
			npcHandler:say("You don't have enough money.", cid)
		end
		npcHandler.topic[cid] = 0
	elseif msgcontains(msg, "no") then
		if npcHandler.topic[cid] >= 1 then
			npcHandler:say("Then no.", cid)
			npcHandler.topic[cid] = 0
		end
	return true
	end
end

keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I am the grand druid of Carlin. I am responsible for the guild, the fields, and our citizens' health."})
keywordHandler:addKeyword({'magic'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Every druid is able to learn the numerous spells of our craft."})
--keywordHandler:addKeyword({'spell'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Sorry, I don't teach spells for your vocation."})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I am Padreia, grand druid of our fine city."})
keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Time is just a crystal pillar - the centre of creation and life."})
keywordHandler:addKeyword({'druids'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "We are druids, preservers of life. Our magic is about defence, healing, and nature."})
keywordHandler:addKeyword({'sorcerers'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "Sorcerers are destructive. Their power lies in destruction and pain."})

npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:setMessage(MESSAGE_GREET, "Welcome to our humble guild, wanderer. May I be of any assistance to you?")
npcHandler:setMessage(MESSAGE_FAREWELL, "Farewell.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "Farewell.")
npcHandler:addModule(FocusModule:new())


text:
@implementation AddGoodReqBody
@synthesize imgId;
@synthesize AccountId;

-(void) dealloc
{
    [imgId release];
    [AccountId release];
    [super dealloc];
}

@end


text:
  Mainxe est
       un village
       situé dans le département de Charente en Poitou-Charentes. Elle comptait 590 habitants en 2008.

Si vous envisagez de emmenager à Mainxe, vous pourrez facilement trouver une maison à acheter.

À coté de Mainxe sont localisées les villes de
Saint-Même-les-Carrières localisée à 3 km, 1 094 habitants,
Gondeville localisée à 4 km, 511 habitants,
Bouteville située à 5 km, 338 habitants,
Julienne située à 6 km, 428 habitants,
Jarnac à 4 km, 4 535 habitants,
Saint-Preuil localisée à 5 km, 299 habitants,
 entre autres. De plus, Mainxe est située à seulement 27 km de Angoulême.

La commune propose quelques  équipements, elle propose entre autres un terrain de tennis et un terrain de sport.

À Mainxe, le prix moyen à la vente d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 788 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.

Le nombre d'habitations, à Mainxe, se décomposait en 2011 en deux appartements et 325 maisons soit
 un marché relativement équilibré.


text:
class User < ActiveRecord::Base

  has_secure_password

  has_many :movies

  validates :email, presence: true, uniqueness: true
  validates :name, presence: true
  validates :password, length: { minimum: 6 }, allow_nil: true

end


text:
<?php

namespace HarvestCloud\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * HubDeliveryWindow Entity
 *
 * @author Tom Haskins-Vaughan <tom@harvestcloud.com>
 * @since  2012-10-24
 *
 * @ORM\Entity
 */
class HubDeliveryWindow extends HubWindow
{
    /**
     * getDeliveryType()
     *
     * @author Tom Haskins-Vaughan <tom@harvestcloud.com>
     * @since  2012-10-27
     *
     * @return string
     */
    public function getDeliveryType()
    {
        return HubWindow::DELIVERY_TYPE_DELIVERY;
    }
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright 2019 ThoughtWorks, 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.
  -->

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.thoughtworks.go.domain" default-access="field" default-lazy="false">
  <class name="com.thoughtworks.go.domain.MaterialInstance" table="materials" discriminator-value="">
    <id name="id" column="id">
      <generator class="identity"/>
    </id>
    <discriminator column="type" type="string"/>

    <property name="flyweightName"/>
    <property name="fingerprint"/>
    <property name="additionalData" access="property"/>

    <subclass name="com.thoughtworks.go.domain.materials.mercurial.HgMaterialInstance" discriminator-value="HgMaterial">
      <property name="url"/>
      <property name="username"/>
      <property name="branch"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.svn.SvnMaterialInstance" discriminator-value="SvnMaterial">
      <property name="url"/>
      <property name="checkExternals"/>
      <property name="username"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.git.GitMaterialInstance" discriminator-value="GitMaterial">
      <property name="url"/>
      <property name="username"/>
      <property name="branch"/>
      <property name="submoduleFolder"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.perforce.P4MaterialInstance" discriminator-value="P4Material">
      <property name="username"/>
      <property name="url"/>
      <property name="view"/>
      <property name="useTickets"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.dependency.DependencyMaterialInstance"
              discriminator-value="DependencyMaterial">
      <property name="pipelineName"/>
      <property name="stageName"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.tfs.TfsMaterialInstance" discriminator-value="TfsMaterial">
      <property name="url"/>
      <property name="username"/>
      <property name="workspace"/>
      <property name="projectPath"/>
      <property name="domain"/>
    </subclass>

    <subclass name="com.thoughtworks.go.domain.materials.TestingMaterialInstance" discriminator-value="TestingMaterial">
      <property name="url"/>
    </subclass>
    <subclass name="com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance"
              discriminator-value="PackageMaterialInstance">
      <property name="configuration"/>
    </subclass>
    <subclass name="com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance"
              discriminator-value="PluggableSCMMaterialInstance">
      <property name="configuration"/>
    </subclass>
  </class>
</hibernate-mapping>


text:
require 'spec_helper'

describe Hash do
  let(:hash) { { :foo => 'bar', :baz => 'qux' } }

  describe 'assert_valid_keys' do
    context 'all keys are valid' do
      it 'returns the hash' do
        expect(hash.assert_valid_keys(:foo, :baz)).to eql hash
      end

      it 'doesn\'t raise an error' do
        expect{ hash.assert_valid_keys(:foo, :baz) }.not_to raise_error
      end
    end

    context 'keys are a subset of valid keys' do
      it 'returns the hash' do
        expect(hash.assert_valid_keys(:foo, :bar, :baz)).to eql hash
      end

      it 'doesn\'t raise an error' do
        expect{ hash.assert_valid_keys(:foo, :bar, :baz) }.not_to raise_error
      end
    end

    context 'keys are wrong type' do
      it 'raises an ArgumentError' do
        expect{ hash.assert_valid_keys(:foo, 'baz') }.to raise_error(ArgumentError)
      end
    end

    context 'invalid keys are present' do
      it 'raises an ArgumentError' do
        expect{ hash.assert_valid_keys(:foo, 'baz') }.to raise_error(ArgumentError)
      end
    end
  end

  describe 'stringify_keys' do
    it 'turns symbol keys into strings' do
      expect(hash.stringify_keys).to eql({'foo' => 'bar', 'baz' => 'qux'})
    end

    it 'maintains the original hash' do
      expect { hash.stringify_keys }.not_to change(hash, :keys)
    end
  end

  describe 'stringify_keys!' do
    it 'turns symbol keys into strings' do
      expect(hash.stringify_keys!).to eql({'foo' => 'bar', 'baz' => 'qux'})
    end

    it 'overwrites the original hash' do
      expect { hash.stringify_keys! }.to change(hash, :keys)
    end
  end

  describe 'symbolize_keys' do
    let(:hash) { {'foo' => 'bar' } }

    it 'turns string keys into symbols' do
      expect(hash.symbolize_keys).to eql({:foo => 'bar'})
    end

    it 'maintains the original hash' do
      expect { hash.symbolize_keys }.not_to change(hash, :keys)
    end
  end

  describe 'symbolize_keys!' do
    let(:hash) { {'foo' => 'bar' } }

    it 'turns string keys into symbols' do
      expect(hash.symbolize_keys!).to eql({:foo => 'bar'})
    end

    it 'overwrites the original hash' do
      expect{ hash.symbolize_keys! }.to change(hash, :keys)
    end
  end

  describe 'transform_keys' do
    it 'changes keys according to a block' do
      transformed = hash.transform_keys {|key| key.to_s.upcase }
      expect(transformed).to eql({'FOO' => 'bar', 'BAZ' => 'qux'})
    end

    it 'is non-destructive' do
      expect{ hash.transform_keys {|key| key.to_s.upcase } }.not_to change(hash, :keys)
    end

    context 'no block given' do
      it 'returns an enumerator' do
        expect(hash.transform_keys).to be_an(Enumerator)
      end
    end
  end

  describe 'transform_keys!' do
    it 'changes keys according to a block' do
      transformed = hash.transform_keys! {|key| key.to_s.upcase }
      expect(transformed).to eql({'FOO' => 'bar', 'BAZ' => 'qux'})
    end

    it 'is destructive' do
      expect{ hash.transform_keys! {|key| key.to_s.upcase } }.to change(hash, :keys)
    end

    context 'no block given' do
      it 'returns an enum' do
        expect(hash.transform_keys!).to be_an(Enumerator)
      end
    end
  end
end


text:
<?xml version="1.0"?>
<typemap>

  <type
     format="ttf"
     name="AchilleFYL"
     fullname="Achille FY L Regular"
     family="Achille FY L"
     glyphs="/usr/share/fonts/achillefy-regular_l-webfont.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSansB"
     fullname="DejaVu Sans Bold"
     family="DejaVu Sans"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSansMonoB"
     fullname="DejaVu Sans Mono Bold"
     family="DejaVu Sans Mono"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono-Bold.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSansMono"
     fullname="DejaVu Sans Mono"
     family="DejaVu Sans Mono"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSans"
     fullname="DejaVu Sans"
     family="DejaVu Sans"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSerifB"
     fullname="DejaVu Serif Bold"
     family="DejaVu Serif"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif-Bold.ttf"
     />

  <type
     format="ttf"
     name="DejaVuSerif"
     fullname="DejaVu Serif"
     family="DejaVu Serif"
     glyphs="/usr/share/fonts/truetype/ttf-dejavu/DejaVuSerif.ttf"
     />

  <type
     format="type1"
     name="StandardSymbols"
     fullname="Standard Symbols"
     family="Standard Symbols"
     glyphs="/usr/share/fonts/type1/gsfonts/s050000l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/s050000l.afm"
     />

  <type
     format="type1"
     name="NimbusMonoOblique"
     fullname="Nimbus Mono Regular Oblique"
     family="Nimbus Mono"
     glyphs="/usr/share/fonts/type1/gsfonts/n022023l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n022023l.afm"
     />

  <type
     format="type1"
     name="NimbusSansB"
     fullname="Nimbus Sans Bold"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019004l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019004l.afm"
     />

  <type
     format="type1"
     name="URWBookmanDbI"
     fullname="URW Bookman Demi Bold Italic"
     family="URW Bookman"
     glyphs="/usr/share/fonts/type1/gsfonts/b018035l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/b018035l.afm"
     />

  <type
     format="type1"
     name="NimbusSansC"
     fullname="Nimbus Sans Regular Condensed"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019043l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019043l.afm"
     />

  <type
     format="type1"
     name="NimbusRomanNo9Medium"
     fullname="Nimbus Roman No9 Medium"
     family="Nimbus Roman No9"
     glyphs="/usr/share/fonts/type1/gsfonts/n021004l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n021004l.afm"
     />

  <type
     format="type1"
     name="NimbusMonoBOblique"
     fullname="Nimbus Mono Bold Oblique"
     family="Nimbus Mono"
     glyphs="/usr/share/fonts/type1/gsfonts/n022024l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n022024l.afm"
     />

  <type
     format="type1"
     name="URWBookmanLI"
     fullname="URW Bookman Light Italic"
     family="URW Bookman"
     glyphs="/usr/share/fonts/type1/gsfonts/b018032l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/b018032l.afm"
     />

  <type
     format="type1"
     name="NimbusSansBI"
     fullname="Nimbus Sans Bold Italic"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019024l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019024l.afm"
     />

  <type
     format="type1"
     name="CenturySchoolbookB"
     fullname="Century Schoolbook Bold"
     family="Century Schoolbook"
     glyphs="/usr/share/fonts/type1/gsfonts/c059016l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/c059016l.afm"
     />

  <type
     format="type1"
     name="NimbusMono"
     fullname="Nimbus Mono Regular"
     family="Nimbus Mono"
     glyphs="/usr/share/fonts/type1/gsfonts/n022003l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n022003l.afm"
     />

  <type
     format="type1"
     name="NimbusRomanNo9I"
     fullname="Nimbus Roman No9 Regular Italic"
     family="Nimbus Roman No9"
     glyphs="/usr/share/fonts/type1/gsfonts/n021023l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n021023l.afm"
     />

  <type
     format="type1"
     name="NimbusSansBC"
     fullname="Nimbus Sans Bold Condensed"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019044l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019044l.afm"
     />

  <type
     format="type1"
     name="URWGothicBookOblique"
     fullname="URW Gothic Book Oblique"
     family="URW Gothic"
     glyphs="/usr/share/fonts/type1/gsfonts/a010033l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/a010033l.afm"
     />

  <type
     format="type1"
     name="URWChanceryMediumI"
     fullname="URW Chancery Medium Italic"
     family="URW Chancery"
     glyphs="/usr/share/fonts/type1/gsfonts/z003034l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/z003034l.afm"
     />

  <type
     format="type1"
     name="URWPalladioB"
     fullname="URW Palladio Bold"
     family="URW Palladio"
     glyphs="/usr/share/fonts/type1/gsfonts/p052004l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/p052004l.afm"
     />

  <type
     format="type1"
     name="Dingbats"
     fullname="Dingbats"
     family="Dingbats"
     glyphs="/usr/share/fonts/type1/gsfonts/d050000l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/d050000l.afm"
     />

  <type
     format="type1"
     name="NimbusRomanNo9"
     fullname="Nimbus Roman No9 Regular"
     family="Nimbus Roman No9"
     glyphs="/usr/share/fonts/type1/gsfonts/n021003l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n021003l.afm"
     />

  <type
     format="type1"
     name="NimbusRomanNo9MediumI"
     fullname="Nimbus Roman No9 Medium Italic"
     family="Nimbus Roman No9"
     glyphs="/usr/share/fonts/type1/gsfonts/n021024l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n021024l.afm"
     />

  <type
     format="type1"
     name="URWPalladioRoman"
     fullname="URW Palladio Roman"
     family="URW Palladio"
     glyphs="/usr/share/fonts/type1/gsfonts/p052003l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/p052003l.afm"
     />

  <type
     format="type1"
     name="NimbusSansBCI"
     fullname="Nimbus Sans Bold Condensed Italic"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019064l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019064l.afm"
     />

  <type
     format="type1"
     name="CenturySchoolbookRoman"
     fullname="Century Schoolbook Roman"
     family="Century Schoolbook"
     glyphs="/usr/share/fonts/type1/gsfonts/c059013l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/c059013l.afm"
     />

  <type
     format="type1"
     name="URWGothicDemi"
     fullname="URW Gothic Demi"
     family="URW Gothic"
     glyphs="/usr/share/fonts/type1/gsfonts/a010015l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/a010015l.afm"
     />

  <type
     format="type1"
     name="URWGothicDemiOblique"
     fullname="URW Gothic Demi Oblique"
     family="URW Gothic"
     glyphs="/usr/share/fonts/type1/gsfonts/a010035l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/a010035l.afm"
     />

  <type
     format="type1"
     name="URWPalladioI"
     fullname="URW Palladio Italic"
     family="URW Palladio"
     glyphs="/usr/share/fonts/type1/gsfonts/p052023l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/p052023l.afm"
     />

  <type
     format="type1"
     name="CenturySchoolbookI"
     fullname="Century Schoolbook Italic"
     family="Century Schoolbook"
     glyphs="/usr/share/fonts/type1/gsfonts/c059033l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/c059033l.afm"
     />

  <type
     format="type1"
     name="URWBookmanDb"
     fullname="URW Bookman Demi Bold"
     family="URW Bookman"
     glyphs="/usr/share/fonts/type1/gsfonts/b018015l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/b018015l.afm"
     />

  <type
     format="type1"
     name="URWPalladioBI"
     fullname="URW Palladio Bold Italic"
     family="URW Palladio"
     glyphs="/usr/share/fonts/type1/gsfonts/p052024l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/p052024l.afm"
     />

  <type
     format="type1"
     name="NimbusMonoB"
     fullname="Nimbus Mono Bold"
     family="Nimbus Mono"
     glyphs="/usr/share/fonts/type1/gsfonts/n022004l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n022004l.afm"
     />

  <type
     format="type1"
     name="CenturySchoolbookBI"
     fullname="Century Schoolbook Bold Italic"
     family="Century Schoolbook"
     glyphs="/usr/share/fonts/type1/gsfonts/c059036l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/c059036l.afm"
     />

  <type
     format="type1"
     name="NimbusSans"
     fullname="Nimbus Sans Regular"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019003l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019003l.afm"
     />

  <type
     format="type1"
     name="NimbusSansCI"
     fullname="Nimbus Sans Regular Condensed Italic"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019063l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019063l.afm"
     />

  <type
     format="type1"
     name="NimbusSansI"
     fullname="Nimbus Sans Regular Italic"
     family="Nimbus Sans"
     glyphs="/usr/share/fonts/type1/gsfonts/n019023l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/n019023l.afm"
     />

  <type
     format="type1"
     name="URWBookmanL"
     fullname="URW Bookman Light"
     family="URW Bookman"
     glyphs="/usr/share/fonts/type1/gsfonts/b018012l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/b018012l.afm"
     />

  <type
     format="type1"
     name="URWGothicBook"
     fullname="URW Gothic Book"
     family="URW Gothic"
     glyphs="/usr/share/fonts/type1/gsfonts/a010013l.pfb"
     metrics="/usr/share/fonts/type1/gsfonts/a010013l.afm"
     />

</typemap>


text:
import React, { PropTypes } from 'react';
import Chip from 'material-ui/Chip';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import { GridList, GridTile } from 'material-ui/GridList';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import JWTdecode from 'jwt-decode';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import { getUserFromToken } from '../../utils/tokenUtils';

const styles = {
  titleStyle: {
    color: '#ffffff',
    fontFamily: 'Roboto'
  }
};

const DocumentView = props => (

    <GridList
      cellHeight="auto"
      cols={1}
    >
      {getUserFromToken().userId === props.document.user_id ?

        <IconMenu
          style={{ float: 'right' }}
          iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
          anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          targetOrigin={{ horizontal: 'right', vertical: 'top' }}
        >
          <MenuItem
            primaryText="Edit Document"
            onTouchTap={props.onUpdate}
          />
          <MenuItem
            primaryText="Delete Document"
            onTouchTap={() => {
              props.deleteDocument(props.document.id)
                .then(() => {
                  props.listDocuments();
                });
            }
            }
          />
        </IconMenu> :
      }
      <GridTile>

{props.document.title}

        <Chip backgroundColor="#681140" labelColor="#ffffff"> {props.document.access} </Chip>

        {props.document.content}

      </GridTile>
    </GridList>

);

Document.propTypes = {
  dispatch: PropTypes.func.isRequired,
  documents: PropTypes.func.isRequired,
  onUpdate: PropTypes.func.isRequired,
};

export default DocumentView;


text:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^secret/', include(admin.site.urls)),
    url(r'^', include('starter_app.urls', namespace='starter_app')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
package thosakwe.rapier.script;

import java.util.Map;

public class RapierFunctionFinder extends RapierScriptBaseListener {
    private final RapierExecutionContext executionContext;

    RapierFunctionFinder(RapierExecutionContext executionContext) {
        this.executionContext = executionContext;
    }

    @Override
    public void enterFunctionDecl(RapierScriptParser.FunctionDeclContext ctx) {
        System.out.printf("Found a function named '%s' with body '%s'%n", ctx.name.getText(), ctx.functionBody().getText());
        executionContext.getScope().put(ctx.name.getText(), new RapierFunction(ctx.functionBody()), ctx);
        super.enterFunctionDecl(ctx);
    }
}


text:
using Lucene.Net.Util;
using System;
using Attribute = Lucene.Net.Util.Attribute;

namespace Lucene.Net.Search
{

    /// <summary>
    /// Implementation class for <see cref="IBoostAttribute"/>.
    /// <para/>
    /// @lucene.internal
    /// </summary>
    public sealed class BoostAttribute : Attribute, IBoostAttribute
    {
        private float boost = 1.0f;

        /// <summary>
        /// Gets or Sets the boost in this attribute. Default is <c>1.0f</c>.
        /// </summary>
        public float Boost
        {
            get => boost;
            set => boost = value;
        }

        public override void Clear()
        {
            boost = 1.0f;
        }

        public override void CopyTo(IAttribute target) // LUCENENET specific - intentionally expanding target to use IAttribute rather than Attribute
        {
            // LUCENENET: Added guard clauses
            if (target is null)
                throw new ArgumentNullException(nameof(target));
            if (target is not IBoostAttribute t)
                throw new ArgumentException($"Argument type {target.GetType().FullName} must implement {nameof(IBoostAttribute)}", nameof(target));
            t.Boost = boost;
        }
    }
}


text:
package main

import (
  "flag"
  "fmt"
  "github.com/pilu/traffic"
  "log"
  "net/http"
  "net/url"
)

var host *string = flag.String("host", "0.0.0.0", "host and to listen (eg: localhost)")
var port *string = flag.String("port", "8080", "port to listen")
var redisconf *string = flag.String("redis", "redis://localhost:6379/", "URL for redis Server (eg: redis://[user:pass@]localhost:6379)")

var model *RedisModel

func main() {
  flag.Parse()

  router := traffic.New()
  router.Get("/", handleIndex)
  router.Post("/", handleCreate)
  router.Get("/:id", handleShow)

  model, _ = initRedis(*redisconf)

  address := fmt.Sprintf("%s:%s", *host, *port)
  err := http.ListenAndServe(address, router)

  if err != nil {
    log.Fatal(err)
  }
}

type ResponseData struct {
  Message string
}

func initRedis(config string) (*RedisModel, error) {
  var password string

  u, _ := url.Parse(config)

  host := u.Host

  if auth := u.User; auth != nil {
    password, _ = u.User.Password()
  } else {
    password = ""
  }

  return NewRedisModel(host, password, int64(-1)), nil
}

func handleIndex(w traffic.ResponseWriter, r *http.Request) {
  traffic.Render(w, "index", ResponseData{""})
}

func handleCreate(w traffic.ResponseWriter, r *http.Request) {
  msg := ResponseData{""}
  param_url := r.FormValue("url")
  short, err := model.Create(param_url)
  var scheme string

  /*
     A dirty hack to check wether the app is hosted on https or not.
     This is the only way to guess, because URI.Scheme is empty.
     Read here for details:
     http://stackoverflow.com/questions/6899069/why-are-request-url-host-and-scheme-blank-in-the-development-server
  */
  if r.TLS != nil {
    scheme = "https"
  } else {
    scheme = "http"
  }

  if err == nil {
    msg = ResponseData{fmt.Sprintf("Shortened URL from %s to %s://%s/%s", short.Url, scheme, r.Host, short.Id)}
  } else {
    msg = ResponseData{fmt.Sprintf("Error: %s", err)}
  }

  traffic.Render(w, "index", msg)
}

func handleShow(w traffic.ResponseWriter, r *http.Request) {
  params := r.URL.Query()
  id := params.Get("id")
  log.Printf("Request ID: %s", id)

  res, err := model.FindBy("id", id)

  if err == nil {
    http.Redirect(w, r, res.Url, 302)
    return
  } else {
    traffic.Render(w, "index", ResponseData{fmt.Sprintf("Not Found Id %s", id)})
  }
}


text:
package org.apereo.openlrs.controllers;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.apache.commons.codec.binary.Base64;
import org.apereo.openlrs.Application;
import org.apereo.openlrs.OpenLRSAuthenticationFilter;
import org.apereo.openlrs.controllers.xapi.XAPIHeaderFilter;
import org.apereo.openlrs.controllers.xapi.XAPIRequestValidationFilter;
import org.apereo.openlrs.controllers.xapi.XApiConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author ggilbert
 *
 */

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes=Application.class)
@ActiveProfiles("test")
public class StatementControllerIntegrationTest {
	MockMvc mockMvc;

	@Autowired WebApplicationContext wac;
	@Autowired OpenLRSAuthenticationFilter filter;
	@Autowired XAPIHeaderFilter xapiHeaderFilter;
	@Autowired XAPIRequestValidationFilter xapiRequestValidationFilter;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);

		this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
				.addFilter(filter, "/xAPI/statements")
				.addFilter(xapiHeaderFilter, "/*")
				.addFilter(xapiRequestValidationFilter, "/xAPI/*")
				.build();

	}

	@Test
	public void thatStatementGetWithNoAuthorizationHeaderReturns401() throws Exception {
		this.mockMvc.perform(
				get("/xAPI/statements")
					.accept(MediaType.APPLICATION_JSON))
					.andDo(print())
					.andExpect(status().isUnauthorized());
	}

	@Test
	public void thatStatementGetWithNoVersionHeaderReturns400() throws Exception {
		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
			get("/xAPI/statements")
				.header("Authorization", "Basic " + new String(encodedBytes))
				.accept(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isBadRequest());
	}

	@Test
	public void thatStatementGetWithOAuthButNotConsumerKeyReturns401() throws Exception {
		this.mockMvc.perform(
				get("/xAPI/statements")
					.header("Authorization", "OAuth")
					.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
					.accept(MediaType.APPLICATION_JSON))
					.andDo(print())
					.andExpect(status().isUnauthorized());
	}

	@Test
	public void thatStatementGetWithOAuthReturns200() throws Exception {
		String oauth = "OAuth realm=\"http://localhost/xAPI/statements\",oauth_consumer_key=\"openlrs\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1409015534\",oauth_nonce=\"n2QqSd\",oauth_version=\"1.0\",oauth_signature=\"baU0sY1SpgtmLGfRMyvpq%2BXv48A%3D\"";
		this.mockMvc.perform(
				get("/xAPI/statements")
					.header("Authorization", oauth)
					.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
					.accept(MediaType.APPLICATION_JSON))
					.andDo(print())
					.andExpect(status().isOk());
	}

	@Test
	public void thatStatementGetWithBasicReturns200() throws Exception {
		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
				get("/xAPI/statements")
					.header("Authorization", "Basic " + new String(encodedBytes))
					.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
					.accept(MediaType.APPLICATION_JSON))
					.andDo(print())
					.andExpect(status().isOk());
	}

	@Test
	public void thatStatementReturnsHeaderWithVersion() throws Exception {
		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
			get("/xAPI/statements")
				.header("Authorization", "Basic " + new String(encodedBytes))
				.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
				.accept(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk())
				.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldHandleSimpleStatement() throws Exception {
		String body = "{\"id\":\"fd41c918-b88b-4b20-a0a5-a4c32391aaa0\",\"actor\":{\"objectType\": \"Agent\",\"name\":\"Project Tin Can API\", "+
							"\"mbox\":\"mailto:user@example.com\"}, "+
							"\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
							"\"display\":{\"en-US\":\"created\" }},"+
							"\"object\":{\"id\":\"http://example.adlnet.gov/xapi/example/simplestatement\","+
							"\"definition\":{\"name\":{ \"en-US\":\"simple statement\"},"+
							"\"description\":{ \"en-US\":\"A simple Experience API statement. Note that the LRS does not need to have any prior information about the Actor (learner), the "+
							"verb, or the Activity/object.\" }}}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
			post("/xAPI/statements")
				.header("Authorization", "Basic " + new String(encodedBytes))
				.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
				.contentType(MediaType.APPLICATION_JSON)
				.content(body))
				.andDo(print())
				.andExpect(status().isOk())
				.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldHandleSimpleStatementWithNoId() throws Exception {
		String body = "{\"actor\":{\"objectType\": \"Agent\",\"name\":\"Project Tin Can API\", "+
				"\"mbox\":\"mailto:user@example.com\"}, "+
				"\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
				"\"display\":{\"en-US\":\"created\" }},"+
				"\"object\":{\"id\":\"http://example.adlnet.gov/xapi/example/simplestatement\","+
				"\"definition\":{\"name\":{ \"en-US\":\"simple statement\"},"+
				"\"description\":{ \"en-US\":\"A simple Experience API statement. Note that the LRS does not need to have any prior information about the Actor (learner), the "+
				"verb, or the Activity/object.\" }}}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isOk())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldHandleStatementWithResult() throws Exception {

		String body = "{\"actor\":{\"objectType\": \"Agent\",\"name\":\"Example Learner\",\"mbox\":\"mailto:example.learner@adlnet.gov\"},"+
						"\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/attempted\",\"display\":{\"en-US\":\"attempted\"}},\"object\":{"+
						"\"id\":\"http://example.adlnet.gov/xapi/example/simpleCBT\",\"definition\":{\"name\":{\"en-US\":\"simple CBT course\""+
            			"},\"description\":{\"en-US\":\"A fictitious example CBT course.\"}}},\"result\":{\"score\":{\"scaled\":0.95},\"success\":true,\"completion\":true}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isOk())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldHandleStatementWithPrettyMuchEverything() throws Exception {
		String body = "{\"id\": \"6690e6c9-3ef0-4ed3-8b37-7f3964730bee\",\"actor\": {\"name\": \"Team PB\",\"mbox\": \"mailto:teampb@example.com\",\"member\": ["+
						"{\"name\": \"Andrew Downes\",\"account\": {\"homePage\": \"http://www.example.com\",\"name\": \"13936749\"},\"objectType\": \"Agent\""+
            			"},{\"name\": \"Toby Nichols\",\"openid\": \"http://toby.openid.example.org/\",\"objectType\": \"Agent\"},{\"name\": \"Ena Hills\","+
            			"\"mbox_sha1sum\": \"ebd31e95054c018b10727ccffd2ef2ec3a016ee9\",\"objectType\": \"Agent\"}],\"objectType\": \"Group\"},\"verb\": {"+
            			"\"id\": \"http://adlnet.gov/expapi/verbs/attended\",\"display\": {\"en-GB\": \"attended\",\"en-US\": \"attended\"}},\"result\": {"+
            			"\"extensions\": {\"http://example.com/profiles/meetings/resultextensions/minuteslocation\": \"X:\\\\meetings\\\\minutes\\\\examplemeeting.one\""+
        				"},\"success\": true,\"completion\": true,\"response\": \"We agreed on some example actions.\",\"duration\": \"PT1H0M0S\"},\"context\": {"+
        				"\"registration\": \"ec531277-b57b-4c15-8d91-d292c5b2b8f7\",\"contextActivities\": {\"parent\": [{\"id\": \"http://www.example.com/meetings/series/267\","+
        				"\"objectType\": \"Activity\"}],\"category\": [{\"id\": \"http://www.example.com/meetings/categories/teammeeting\",\"objectType\": \"Activity\","+
        				"\"definition\": {\"name\": {\"en\": \"team meeting\"},\"description\": {\"en\": \"A category of meeting used for regular team meetings.\"},"+
                        "\"type\": \"http://example.com/expapi/activities/meetingcategory\"}}],\"other\": [{\"id\": \"http://www.example.com/meetings/occurances/34257\","+
                        "\"objectType\": \"Activity\"},{\"id\": \"http://www.example.com/meetings/occurances/3425567\",\"objectType\": \"Activity\"}]},\"instructor\" :"+
                        "{\"name\": \"Andrew Downes\",\"account\": {\"homePage\": \"http://www.example.com\",\"name\": \"13936749\"},\"objectType\": \"Agent\"},"+
                        "\"team\":{\"name\": \"Team PB\",\"mbox\": \"mailto:teampb@example.com\",\"objectType\": \"Group\"}, \"platform\" : \"Example virtual meeting software\","+
                        "\"language\" : \"tlh\",\"statement\" : {\"objectType\":\"StatementRef\",\"id\" :\"6690e6c9-3ef0-4ed3-8b37-7f3964730bee\"}},\"timestamp\": \"2013-05-18T05:32:34.804Z\","+
                        "\"stored\": \"2013-05-18T05:32:34.804Z\",\"authority\": {\"account\": {\"homePage\": \"http://cloud.scorm.com/\",\"name\": \"anonymous\"},\"objectType\": \"Agent\""+
    					"},\"version\": \"1.0.0\",\"object\": {\"id\": \"http://www.example.com/meetings/occurances/34534\",\"definition\": {\"extensions\": {\"http://example.com/profiles/meetings/activitydefinitionextensions/room\": {\"name\": \"Kilby\", \"id\" : \"http://example.com/rooms/342\"}"+
            			"},\"name\": {\"en-GB\": \"example meeting\",\"en-US\": \"example meeting\"},\"description\": {\"en-GB\": \"An example meeting that happened on a specific occasion with certain people present.\","+
            			"\"en-US\": \"An example meeting that happened on a specific occasion with certain people present.\"},\"type\": \"http://adlnet.gov/expapi/activities/meeting\","+
            			"\"moreInfo\": \"http://virtualmeeting.example.com/345256\"},\"objectType\": \"Activity\"}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isOk())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));

	}

	@Test
	public void shouldReturn400WithMissingActor() throws Exception {
		String body = "{\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
				"\"display\":{\"en-US\":\"created\" }},"+
				"\"object\":{\"id\":\"http://example.adlnet.gov/xapi/example/simplestatement\","+
				"\"definition\":{\"name\":{ \"en-US\":\"simple statement\"},"+
				"\"description\":{ \"en-US\":\"A simple Experience API statement. Note that the LRS does not need to have any prior information about the Actor (learner), the "+
				"verb, or the Activity/object.\" }}}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isBadRequest())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldReturn400WithMissingVerb() throws Exception {
		String body = "{\"actor\":{\"objectType\": \"Agent\",\"name\":\"Project Tin Can API\", "+
				"\"mbox\":\"mailto:user@example.com\"}, "+
				"\"object\":{\"id\":\"http://example.adlnet.gov/xapi/example/simplestatement\","+
				"\"definition\":{\"name\":{ \"en-US\":\"simple statement\"},"+
				"\"description\":{ \"en-US\":\"A simple Experience API statement. Note that the LRS does not need to have any prior information about the Actor (learner), the "+
				"verb, or the Activity/object.\" }}}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isBadRequest())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}

	@Test
	public void shouldReturn400WithMissingObject() throws Exception {
		String body = "{\"actor\":{\"objectType\": \"Agent\",\"name\":\"Project Tin Can API\", "+
				"\"mbox\":\"mailto:user@example.com\"}, "+
				"\"verb\":{\"id\":\"http://adlnet.gov/expapi/verbs/created\","+
				"\"display\":{\"en-US\":\"created\" }}}";

		String basic = "test:test";
		final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes());
		this.mockMvc.perform(
		post("/xAPI/statements")
			.header("Authorization", "Basic " + new String(encodedBytes))
			.header(XApiConstants.XAPI_VERSION_HEADER, "someversion")
			.contentType(MediaType.APPLICATION_JSON)
			.content(body))
			.andDo(print())
			.andExpect(status().isBadRequest())
			.andExpect(header().string("X-Experience-API-Version", "someversion"));
	}
}