text:
package com.forter.contracts;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

import com.forter.contracts.mocks.*;

import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.tuple.Tuple;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.mockito.ArgumentCaptor;
import org.testng.annotations.Test;
import org.unitils.reflectionassert.ReflectionAssert;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;

/**
 * Unit Tests for {@link BaseContractsBoltExecutor}
 */
public class BaseContractsBoltExecutorTest {

    ObjectMapper mapper = new ObjectMapper();
    final String id = "1";

    @Test
    public void testContractsBolt() {
        //mock copies input to output
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = -1;
        output.optionalOutput2 = Optional.of(-1);
        IContractsBolt contractsBolt = new MockContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        assertEmitEquals(collector, output);
    }

    @Test
    public void testCachedExecution() {
        MockContractsBolt bolt = new MockContractsBolt();
        MockCacheDAO cache = new MockCacheDAO();
        MockCachedContractBoltExecutor executor = new MockCachedContractBoltExecutor(bolt, cache);
        executor.prepare(mock(Map.class), mock(TopologyContext.class));
        assertThat(cache.cache.size()).isEqualTo(0);

        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        BasicOutputCollector collector = execute(data, executor);
        Object output1 = getEmittedContract(collector);
        assertThat(cache.cache.size()).isEqualTo(1);
        assertThat(cache.cache.containsValue(output1));

        collector = execute(data, executor);
        Object output2 = getEmittedContract(collector);
        ReflectionAssert.assertReflectionEquals(output2, output1);
        assertThat(cache.cache.size()).isEqualTo(1);
    }

    @Test
    public void testCollectionContractBolt() {
        //mock copies input to output twice
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        MockCollectionContractsBolt contractsBolt = new MockCollectionContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        verify(collector, times(2)).emit((String)any(), (List<Object>) any());
    }

    @Test
    public void testOptionalContractsBolt() {
        //mock copies input to output
        String input = "{\"input1\":-1,\"optionalInput2\":-1}";
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = -1;
        output.optionalOutput2 = Optional.of(-1);
        ObjectNode data = parseJson(input);
        MockOptionalContractsBolt contractsBolt = new MockOptionalContractsBolt();
        execute(data, contractsBolt);
    }

    @Test(expectedExceptions = ContractViolationReportedFailedException.class)
    public void testNullOutput() {
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        IContractsBolt contractsBolt = new MockNullContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
    }

    @Test(expectedExceptions = ContractViolationReportedFailedException.class)
    public void testNullOptionalOutput() {
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        IContractsBolt contractsBolt = new MockNullOptionalContractsBolt();
        execute(data, contractsBolt);
    }

    @Test(enabled = false) // TODO: Itai needs to fix this
    public void testInvalidOutput() {
        //optionalInput2 must be at most 10 and mock copies input to output resulting in invalid output
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":100}");
        IContractsBolt contractsBolt = new MockContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        verify(collector).reportError(any(IllegalStateException.class));
    }

    @Test
    public void testInvalidInput() {
        //input1 must be at most 10
        String input = "{\"input1\":10000,\"optionalInput2\":-1}";
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = 0;
        output.optionalOutput2 = Optional.absent();
        ObjectNode data = parseJson(input);
        MockOptionalContractsBolt contractsBolt = new MockOptionalContractsBolt();
        BasicOutputCollector collector = mock(BasicOutputCollector.class);
        try {
            execute(data, contractsBolt, collector);
        } finally {
            assertEmitEquals(collector, output);
        }
    }

    @Test
    public void testInvalidInputTypes() {
        //input1 must be an integer
        String input = "{\"input1\":false,\"optionalInput2\":-1}";
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = 0;
        output.optionalOutput2 = Optional.absent();
        ObjectNode data = parseJson(input);
        MockOptionalContractsBolt contractsBolt = new MockOptionalContractsBolt();
        BasicOutputCollector collector = mock(BasicOutputCollector.class);
        try {
            execute(data, contractsBolt, collector);
        } finally {
            assertEmitEquals(collector, output);
        }
    }

    @Test
    public void testNullInput() {
        //optional should accept json null token
        String input = "{\"input1\":-1,\"optionalInput2\":null}";
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = -1;
        output.optionalOutput2 = Optional.absent();
        ObjectNode data = parseJson(input);
        MockOptionalContractsBolt contractsBolt = new MockOptionalContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        assertEmitEquals(collector, output);
    }

    @Test
    public void testMissingInput() {
        //optional should accept missing json value
        String input = "{\"input1\":-1}";
        MockContractsBoltOutput output = new MockContractsBoltOutput();
        output.output1 = -1;
        output.optionalOutput2 = Optional.absent();
        ObjectNode data = parseJson(input);
        MockOptionalContractsBolt contractsBolt = new MockOptionalContractsBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        assertEmitEquals(collector, output);
    }

    @Test
    public void testAbsentOutput() {
        ObjectNode data = parseJson("{}");
        IContractsBolt contractsBolt = new MockOptionalAbsentBolt();
        BasicOutputCollector collector = mock(BasicOutputCollector.class);
        try {
            execute(data, contractsBolt, collector);
        } finally {
            verify(collector, times(0)).emit((String) any(), (List<Object>) any()); //no output
        }
    }

    @Test
    public void testEmptyCollectionOutput() {
        ObjectNode data = parseJson("{\"input1\":-1,\"optionalInput2\":-1}");
        IContractsBolt contractsBolt = new MockEmptyCollectionBolt();
        BasicOutputCollector collector = execute(data, contractsBolt);
        verify(collector, times(0)).emit((String)any(), (List<Object>) any());
    }

    @Test
    public void testSerializable() {
        IContractsBolt contractsBolt = new MockEmptyCollectionBolt();
        BaseContractsBoltExecutor bolt = new BaseContractsBoltExecutor(contractsBolt);
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream( baos )) {
            oos.writeObject(bolt);
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }

    }

    private BasicOutputCollector execute(ObjectNode input, IContractsBolt bolt) {
        BasicOutputCollector collector = mock(BasicOutputCollector.class);
        execute(input, bolt, collector);
        return collector;
    }

    private BasicOutputCollector execute(ObjectNode input, BaseContractsBoltExecutor executor) {
        BasicOutputCollector collector = mock(BasicOutputCollector.class);
        execute(input, executor, collector);
        return collector;
    }

    private void execute(ObjectNode input, IContractsBolt bolt, BasicOutputCollector collector) {
        BaseContractsBoltExecutor baseContractsBoltExecutor = new BaseContractsBoltExecutor(bolt);
        baseContractsBoltExecutor.prepare(mock(Map.class), mock(TopologyContext.class));
        execute(input, baseContractsBoltExecutor, collector);
    }

    private void execute(ObjectNode input, BaseContractsBoltExecutor executor, BasicOutputCollector collector) {
        Tuple tuple = mock(Tuple.class);
        when(tuple.getValue(0)).thenReturn(id);
        when(tuple.getValue(1)).thenReturn(input);

        executor.execute(tuple, collector);
    }

    private void assertEmitEquals(BasicOutputCollector collector, Object expectedOutput) {
        Object actual = getEmittedContract(collector);
        String actualString =  ReflectionToStringBuilder.toString(actual,
                ToStringStyle.SHORT_PREFIX_STYLE, false, false);
        String expectedString =  ReflectionToStringBuilder.toString(expectedOutput,
                ToStringStyle.SHORT_PREFIX_STYLE, false, false);
        assertThat(actualString).isEqualTo(expectedString);
    }

    private Object getEmittedContract(BasicOutputCollector collector) {
        ArgumentCaptor<List> actualOutput = ArgumentCaptor.forClass(List.class);
        verify(collector).emit((String)any(), actualOutput.capture());
        List<Object> emittedObjects = (List<Object>) actualOutput.getValue();
        return emittedObjects.get(1);
    }

    private ObjectNode parseJson(String input) {
        try {
            return (ObjectNode) mapper.readTree(input);
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
}


text:
using System;

namespace stellar_dotnet_sdk.federation
{
    /// <summary>
    ///     Federation server was not found in stellar.toml file.
    /// </summary>
    internal class NoFederationServerException : Exception
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>

<refentry xml:id="function.cubrid-get-db-parameter" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>cubrid_get_db_parameter</refname>
  <refpurpose>Returns the CUBRID database parameters</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type><methodname>cubrid_get_db_parameter</methodname>
   <methodparam><type>resource</type><parameter>conn_identifier</parameter></methodparam>
  </methodsynopsis>
  <para>
   This function returns the CUBRID database parameters or it returns FALSE on
   failure. It returns an associative array with the values for the following
   parameters:
  </para>
  <para>
  <simplelist>
   <member><constant>PARAM_ISOLATION_LEVEL</constant></member>
   <member><constant>PARAM_LOCK_TIMEOUT</constant></member>
   <member><constant>PARAM_MAX_STRING_LENGTH</constant></member>
   <member><constant>PARAM_AUTO_COMMIT</constant></member>
  </simplelist>
  </para>
  <para>

   <title>Database parameters</title>
    <tgroup cols="2">

      <row>
       <entry>Parameter</entry>
       <entry>Description</entry>
      </row>

      <row>
       <entry>PARAM_ISOLATION_LEVEL</entry>
       <entry>The transaction isolation level.</entry>
      </row>
      <row>
       <entry>LOCK_TIMEOUT</entry>
       <entry>CUBRID provides the lock timeout feature, which sets the waiting
        time (in seconds) for the lock until the transaction lock setting is
        allowed. The default value of the lock_timeout_in_secs parameter is
        -1, which means the application client will wait indefinitely until
        the transaction lock is allowed.
       </entry>
      </row>
      <row>
       <entry>PARAM_AUTO_COMMIT</entry>
       <entry>In CUBRID PHP, auto-commit mode is disabled by default for
        transaction management. It can be set by using
        <function>cubrid_set_autocommit</function>.
       </entry>
      </row>

    </tgroup>

  </para>

  <para>
   The following table shows the isolation levels from 1 to 6. It consists of
   table schema (row) and isolation level:

   <title>Levels of Isolation Supported by CUBRID</title>
    <tgroup cols="2">

      <row>
       <entry>Name</entry>
       <entry>Description</entry>
      </row>

      <row>
       <entry>SERIALIZABLE (6)</entry>
       <entry>In this isolation level, problems concerning concurrency (e.g.
        dirty read, non-repeatable read, phantom read, etc.) do not
        occur.</entry>
      </row>
      <row>
       <entry>REPEATABLE READ CLASS with REPEATABLE READ INSTANCES (5)</entry>
       <entry>Another transaction T2 cannot update the schema of table A while
        transaction T1 is viewing table A.
       Transaction T1 may experience phantom read for the record R that was
       inserted by another transaction T2 when it is repeatedly retrieving a
       specific record.</entry>
      </row>
      <row>
       <entry>REPEATABLE READ CLASS with READ COMMITTED INSTANCES (or CURSOR STABILITY) (4)</entry>
       <entry>Another transaction T2 cannot update the schema of table A while
        transaction T1 is viewing table A.
       Transaction T1 may experience R read (non-repeatable read) that was
       updated and committed by another transaction T2 when it is repeatedly
       retrieving the record R.</entry>
      </row>
      <row>
       <entry>REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES (3)</entry>
       <entry>Default isolation level.  Another transaction T2 cannot update
        the schema of table A  while transaction T1 is viewing table A.
        Transaction T1 may experience R' read (dirty read) for the record that
        was updated but not committed by another transaction T2.</entry>
      </row>
      <row>
       <entry>READ COMMITTED CLASS with READ COMMITTED INSTANCES (2)</entry>
       <entry>Transaction T1 may experience A' read (non-repeatable read) for
        the table that was updated and committed by another transaction  T2
        while it is viewing table A repeatedly.  Transaction T1 may experience
        R' read (non-repeatable read) for the record that was updated and
        committed by another transaction T2 while it is retrieving the record
        R repeatedly.</entry>
      </row>
      <row>
       <entry>READ COMMITTED CLASS with READ UNCOMMITTED INSTANCES (1)</entry>
       <entry>Transaction T1 may experience A' read (non-repeatable read) for
        the table that was updated and committed by another transaction T2
        while it is repeatedly viewing table A.  Transaction T1 may experience
        R' read (dirty read) for the record that was updated but not committed
        by another transaction T2.</entry>
      </row>

    </tgroup>

  </para>
 </refsect1>

 <refsect1 role="parameters">
 &reftitle.parameters;
 <para>
  <variablelist>
   <varlistentry>
    <term><parameter>conn_identifier</parameter></term>
    <listitem><para>
      The CUBRID connection. If the connection identifier is not specified,
      the last link opened by <function>cubrid_connect</function> is assumed.
    </para></listitem>
   </varlistentry>
  </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   An associative array with CUBRID database parameters; on success.
  </para>
   <para>
    &false; on failure.
  </para>
 </refsect1>

 <refsect1 role="changelog">
  &reftitle.changelog;
  <para>
   <informaltable>
    <tgroup cols="2">

      <row>
       <entry>&Version;</entry>
       <entry>&Description;</entry>
      </row>

      <row>
       <entry>8.4.0</entry>
       <entry>
        Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to
        PARAM_MAX_STRING_LENGTH in result.
       </entry>
      </row>

    </tgroup>
   </informaltable>
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <example>
   <title><function>cubrid_get_db_parameter</function> example</title>
   <programlisting role="php">
<![CDATA[
<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
    die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
    printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>
]]>
   </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1
]]>
    </screen>
  </example>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>cubrid_set_db_parameter</function></member>
    <member><function>cubrid_get_autocommit</function></member>
   </simplelist>
  </para>
 </refsect1>
</refentry>


text:
@protocol BBWeiboDelegate <NSObject>

@optional
-(void) getPublicTimelineFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getFriendsTimelineFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getUserTimelineFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getUnreadFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getMentionedMeFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getCommentsFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getCommentsByMeFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getCommentsToMeFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getCommentsToStatusFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getCountsFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getRepostTimelineForStatusFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getRepostTimelineByUserFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) resetCountFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getEmotionsFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) postFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) uploadFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) repostFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) destroyFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) createFavoriteFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) removeFavoriteFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) commentFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) destroyCommentFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) destroyCommentsFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) replyFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) showUserFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getFolloweesFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getFollowersFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getDirectMessageFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getSentDirectMessageFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) sendDirectMessageFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) destroyDirectMessageFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) destroyDirectMessagesFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) followFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) unfollowFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) showRelationshipFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) blockFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) unblockFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) checkBlockFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getBlockListFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) verifyFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getRateLimitStatusFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getFavoritesFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getTopicsFinished: (OAServiceTicket *) tickets withData: (id) data;
-(void) getStatusesForTopicFinished: (OAServiceTicket *) tickets withData: (id) data;

@required
-(void) failed:(OAServiceTicket *) tickets withError:(NSError *) error;

@end


text:
//
//  DCHomeTopToolView.h
//  CDDStoreDemo
//
//  Created by dashen on 2017/11/28.
//Copyright © 2017年 RocketsChen. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface DCHomeTopToolView : UIView

/** 左边Item点击 */
@property (nonatomic, copy) dispatch_block_t leftItemClickBlock;
/** 右边Item点击 */
@property (nonatomic, copy) dispatch_block_t rightItemClickBlock;
/** 右边第二个Item点击 */
@property (nonatomic, copy) dispatch_block_t rightRItemClickBlock;

/** 搜索按钮点击点击 */
@property (nonatomic, copy) dispatch_block_t searchButtonClickBlock;
/** 语音按钮点击点击 */
@property (nonatomic, copy) dispatch_block_t voiceButtonClickBlock;

@end


text:
require('babel-polyfill');
import ether from './helpers/ether'
import {advanceBlock} from './helpers/advanceToBlock'
import {increaseTimeTo, duration} from './helpers/increaseTime'
import latestTime from './helpers/latestTime'
import EVMThrow from './helpers/EVMThrow'
const BigNumber = web3.BigNumber

const should = require('chai')
  .use(require('chai-as-promised'))
  .use(require('chai-bignumber')(BigNumber))
  .should()

var LindaToken = artifacts.require("../contracts/LindaToken.sol");
var LindaPresale = artifacts.require('../contracts/LindaPresale.sol')

contract('LindaPresale', function([_, owner, investor, purchaser1, purchaser2, wallet]) {

  const rate = new BigNumber(2346); //rate must be integer
  const cap = ether(3581.17);
  const lessThanCap = ether(10);
  const discount = new BigNumber(10);
  const goal = ether(42.63);
  const value = ether(5);
  const totalTokenAmount = rate.mul(value);
  const discountedAmount = totalTokenAmount.div(discount);
  const expectedTokenAmount = totalTokenAmount.add(discountedAmount);

  before(async function() {
    //Advance to the next block to correctly read time in the solidity "now" function interpreted by testrpc
    await advanceBlock();
  })

  beforeEach(async function () {
    this.startTime = latestTime() + duration.weeks(1);
    this.endTime =   this.startTime + duration.weeks(1);
    this.afterEndTime = this.endTime + duration.seconds(1);

    this.crowdsale = await LindaPresale.new(this.startTime, this.endTime, rate, goal, cap,  owner, wallet, {from: owner})

    this.token = LindaToken.at(await this.crowdsale.token())
  })

  describe('creating a valid crowdsale', function () {

    it('should fail with zero cap', async function () {
      await LindaPresale.new(this.startTime, this.endTime, rate, goal, 0,  owner, wallet, {from: owner}).should.be.rejectedWith(EVMThrow);
    })

  });

  describe('accepting payments', function () {

    beforeEach(async function () {
      await increaseTimeTo(this.startTime)
    })

    it('should accept payments within cap', async function () {
      await this.crowdsale.send(cap.minus(lessThanCap)).should.be.fulfilled
      await this.crowdsale.send(lessThanCap).should.be.fulfilled
    })

    it('should reject payments outside cap', async function () {
      await this.crowdsale.send(cap)
      await this.crowdsale.send(1).should.be.rejectedWith(EVMThrow)
    })

    it('should reject payments that exceed cap', async function () {
      await this.crowdsale.send(cap.plus(1)).should.be.rejectedWith(EVMThrow)
    })

  })

  describe('ending', function () {

    beforeEach(async function () {
      await increaseTimeTo(this.startTime)
    })

    it('should not be ended if under cap', async function () {
      let hasEnded = await this.crowdsale.hasEnded()
      hasEnded.should.equal(false)
      await this.crowdsale.send(lessThanCap)
      hasEnded = await this.crowdsale.hasEnded()
      hasEnded.should.equal(false)
    })

    it('should not be ended if just under cap', async function () {
      await this.crowdsale.send(cap.minus(1))
      let hasEnded = await this.crowdsale.hasEnded()
      hasEnded.should.equal(false)
    })

    it('should be ended if cap reached', async function () {
      await this.crowdsale.send(cap)
      let hasEnded = await this.crowdsale.hasEnded()
      hasEnded.should.equal(true)
    })

  })

  it('should be token owner', async function () {
    const owner = await this.token.owner()
    owner.should.equal(this.crowdsale.address)
  })

  it('should be ended too after end', async function () {
    let ended = await this.crowdsale.hasEnded()
    ended.should.equal(false)
    await increaseTimeTo(this.afterEndTime)
    ended = await this.crowdsale.hasEnded()
    ended.should.equal(true)
  })

  describe('accepting payments', function () {

    it('should reject payments before start', async function () {
      await this.crowdsale.send(value).should.be.rejectedWith(EVMThrow)
      await this.crowdsale.buyTokens(investor, {from: purchaser1, value: value}).should.be.rejectedWith(EVMThrow)
    })

    it('should accept payments after start', async function () {
      await increaseTimeTo(this.startTime)
      await this.crowdsale.send(value).should.be.fulfilled
      await this.crowdsale.buyTokens(investor, {value: value, from: purchaser1}).should.be.fulfilled
    })

    it('should reject payments after end', async function () {
      await increaseTimeTo(this.afterEndTime)
      await this.crowdsale.send(value).should.be.rejectedWith(EVMThrow)
      await this.crowdsale.buyTokens(investor, {value: value, from: purchaser1}).should.be.rejectedWith(EVMThrow)
    })

  })

  describe('high-level purchase', function () {

    beforeEach(async function() {
      await increaseTimeTo(this.startTime)
    })

    it('should log purchase', async function () {
      const {logs} = await this.crowdsale.sendTransaction({value: value, from: investor})

      const event = logs.find(e => e.event === 'TokenPurchase')

      should.exist(event)
      event.args.purchaser.should.equal(investor)
      event.args.beneficiary.should.equal(investor)
      event.args.value.should.be.bignumber.equal(value)
      event.args.amount.should.be.bignumber.equal(expectedTokenAmount)
    })

    it('should increase totalSupply', async function () {
      await this.crowdsale.send(value)
      const totalSupply = await this.token.totalSupply()
      totalSupply.should.be.bignumber.equal(expectedTokenAmount)
    })

       it('should assign tokens to sender', async function () {
         await this.crowdsale.sendTransaction({value: value, from: investor})
         await increaseTimeTo(this.afterEndTime)
         let balance = await this.token.balanceOf(investor);
         balance.should.be.bignumber.equal(expectedTokenAmount)
       })

       it('should forward funds to wallet', async function () {
         const pre = web3.eth.getBalance(wallet)
         await this.crowdsale.sendTransaction({value: goal, from: investor})
         await increaseTimeTo(this.afterEndTime)
         await this.crowdsale.finalize({from: owner})
         const post = web3.eth.getBalance(wallet)
         post.minus(pre).should.be.bignumber.equal(goal)
       })

  })

})


text:
//Copyright (C) Microsoft Corporation.  All rights reserved.

namespace GuiHost
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.showVisualizerButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // showVisualizerButton
            //
            this.showVisualizerButton.Location = new System.Drawing.Point(12, 28);
            this.showVisualizerButton.Name = "showVisualizerButton";
            this.showVisualizerButton.Size = new System.Drawing.Size(177, 23);
            this.showVisualizerButton.TabIndex = 0;
            this.showVisualizerButton.Text = "Show Visualizer";
            this.showVisualizerButton.UseVisualStyleBackColor = true;
            this.showVisualizerButton.Click += new System.EventHandler(this.showVisualizerButton_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(200, 79);
            this.Controls.Add(this.showVisualizerButton);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button showVisualizerButton;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:icon="@drawable/menu"
            android:title="Menu"/>
        <item
            android:icon="@drawable/video_call"
            android:title="Video"/>
        <item
            android:icon="@drawable/globe"
            android:title="Globe"/>
        <item
            android:icon="@drawable/upload"
            android:title="Upload"/>
        <item
            android:icon="@drawable/plus"
            android:title="More"/>
    </group>
</menu>


text:
require 'aws-sigv4'

module Aws
  module RDS
    module Plugins

      # This plugin populates the `:pre_signed_url` request param for the
      # CopyDBSnapshot API.
      #
      # This parameter is required by RDS when copying an encrypted snapshot
      # across regions. This plugin will be skipped if the `:pre_signed_url`
      # parameter is provided by the user.
      class CrossRegionCopying < Seahorse::Client::Plugin

        # @api private
        class Handler < Seahorse::Client::Handler

          def call(context)
            params = context.params
            if params[:source_region] && !params[:pre_signed_url]
              params[:pre_signed_url] = presigned_url(context, params)
              params[:destination_region] = context.config.region
            end
            @handler.call(context)
          end

          private
          def presigned_url(context, params)
            # :source_region is not modeled in the api
            source_region = params.delete(:source_region)
            param_list = Aws::Query::ParamList.new
            param_list.set('Action', context.operation.name)
            param_list.set('DestinationRegion', context.config.region)
            param_list.set('Version', context.config.api.version)
            Aws::Query::ParamBuilder.new(param_list).apply(
              context.operation.input,
              params
            )
            signer = Aws::Sigv4::Signer.new(
              service: 'rds',
              region: source_region,
              credentials_provider: context.config.credentials
            )
            url = Aws::Partitions::EndpointProvider.resolve(signer.region, 'rds')
            url += "?#{param_list.to_s}"
            signer.presign_url(
              http_method: 'GET',
              url: url,
              body: '',
              expires_in: 3600
            ).to_s
          end
        end

        handler(
          Handler,
          step: :initialize,
          operations: [
            :copy_db_snapshot,
            :create_db_instance_read_replica,
            :copy_db_cluster_snapshot,
            :create_db_cluster
          ]
        )

      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Using the BIND APIs</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Getting Started with Berkeley DB" />
    <link rel="up" href="DBEntry.html" title="Chapter 8. Database Records" />
    <link rel="prev" href="usingDbt.html" title="Reading and Writing Database Records" />
    <link rel="next" href="dbtJavaUsage.html" title="Database Usage Example" />

Library Version 11.2.5.3

          Using the BIND APIs

          Prev
          Chapter 8. Database Records
           Next

Using the BIND APIs

              Numerical and String Objects

              Serializable Complex Objects

              Custom Tuple Bindings

Except for Java String and boolean types, efficiently moving data in
    and out of Java byte arrays for storage in a database can be a nontrivial
    operation. To help you with this problem, DB provides the Bind APIs.
    While these APIs are described in detail in the

    Berkeley DB Collections Tutorial,

    this section provides a brief introduction to using the Bind APIs with:

Single field numerical and string objects

Use this if you want to store a single numerical or string object,
        such as Long, Double, or
        String.

Complex objects that implement Java serialization.

Use this if you are storing objects that implement
            Serializable and if you do not need to sort them.

Non-serialized complex objects.

If you are storing objects that do not implement serialization,
        you can create your own custom tuple bindings. Note that you should
        use custom tuple bindings even if your objects are serializable if
        you want to sort on that data.

Numerical and String Objects

You can use the Bind APIs to store primitive data in a DatabaseEntry
      object. That is, you can store a single field containing one of the following types:

                String

                Character

                Boolean

                Byte

                Short

                Integer

                Long

                Float

                Double

          To store primitive data using the Bind APIs:

Create an EntryBinding object.

When you do this, you use TupleBinding.getPrimitiveBinding()
          to return an appropriate binding for the conversion.

Use the EntryBinding object to place
          the numerical object on the DatabaseEntry.

Once the data is stored in the DatabaseEntry, you can put it to
      the database in whatever manner you wish. For example:

package db.GettingStarted;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseEntry;

...

Database myDatabase = null;
// Database open omitted for clarity.

// Need a key for the put.
try {
    String aKey = "myLong";
    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));

    // Now build the DatabaseEntry using a TupleBinding
    Long myLong = new Long(123456789l);
    DatabaseEntry theData = new DatabaseEntry();
    EntryBinding myBinding = TupleBinding.getPrimitiveBinding(Long.class);
    myBinding.objectToEntry(myLong, theData);

    // Now store it
    myDatabase.put(null, theKey, theData);
} catch (Exception e) {
    // Exception handling goes here
}

Retrieval from the DatabaseEntry object is
      performed in much the same way:

package db.GettingStarted;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.LockMode;
import com.sleepycat.db.OperationStatus;

...

Database myDatabase = null;
// Database open omitted for clarity

try {
    // Need a key for the get
    String aKey = "myLong";
    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));

    // Need a DatabaseEntry to hold the associated data.
    DatabaseEntry theData = new DatabaseEntry();

    // Bindings need only be created once for a given scope
    EntryBinding myBinding = TupleBinding.getPrimitiveBinding(Long.class);

    // Get it
    OperationStatus retVal = myDatabase.get(null, theKey, theData,
                                            LockMode.DEFAULT);
    String retKey = null;
    if (retVal == OperationStatus.SUCCESS) {
        // Recreate the data.
        // Use the binding to convert the byte array contained in theData
        // to a Long type.
        Long theLong = (Long) myBinding.entryToObject(theData);
        retKey = new String(theKey.getData(), "UTF-8");
        System.out.println("For key: '" + retKey + "' found Long: '" +
                            theLong + "'.");
    } else {
        System.out.println("No record found for key '" + retKey + "'.");
    }
} catch (Exception e) {
    // Exception handling goes here
}

Serializable Complex Objects

Frequently your application requires you to store and manage
      objects for your record data and/or keys. You may need to do this if you
      are caching objects created by another process. You may also want to do
      this if you want to store multiple data values on a record. When used
      with just primitive data, or with objects containing a single data member,
      DB database records effectively represent a single row in a two-column table.
      By storing a complex object in the record, you can turn each record into
      a single row in an n-column table, where
      n is the number of data members contained by the
      stored object(s).

In order to store objects in a
      DB database, you must convert them to and from a byte array.
      The first instinct for many Java programmers is to do this using Java
      serialization. While this is functionally a correct solution, the result
      is poor space-performance because this causes the class information
      to be stored on every such database record. This information can be quite large
      and it is redundant — the class information does not vary for serialized objects of the same type.

        In other words, directly using serialization to place your objects into byte
        arrays means that you will be storing a great deal of unnecessary information in
        your database, which ultimately leads to larger databases and more expensive disk
        I/O.

The easiest way for you to solve this problem is to use the Bind
      APIs to perform the serialization for you. Doing so causes the extra
      object information to be saved off to a unique Database
      dedicated for that purpose. This means that you do not have to duplicate
      that information on each record in the Database
      that your application is using to store its information.

        Note that when you use the Bind APIs to perform serialization, you still
        receive all the benefits of serialization. You can still use arbitrarily
        complex object graphs, and you still receive built-in class evolution
        through the serialVersionUID (SUID) scheme. All of the Java
        serialization rules apply without modification. For example, you can
        implement Externalizable instead of Serializable.

Usage Caveats

Before using the Bind APIs to perform serialization, you may
        want to consider writing your own custom tuple bindings. Specifically,
        avoid serialization if:

                If you need to sort based on the objects your are storing.
                The sort order is meaningless for the byte arrays that you
                obtain through serialization. Consequently, you should not use serialization for keys if you
                care about their sort order. You should
                also not use serialization for record data if your
                Database supports duplicate records and you care about sort order.

                You want to minimize the size of your byte arrays. Even when using the Bind APIs to perform the
                serialization the resulting byte array may be larger than necessary. You can achieve
                more compact results by building your own custom tuple binding.

                You want to optimize for speed. In general, custom tuple bindings are faster than serialization at
                moving data in and out of byte arrays.

            For information on building your own custom tuple binding, see Custom Tuple Bindings.

Serializing Objects

To store a serializable complex object using the
        Bind APIs:

                Implement java.io.Serializable in the class whose instances that
                you want to store.

Open (create) your databases. You need two. The first is the
            database that you use to store your data. The second is used to
            store the class information.

Instantiate a class catalog. You do this with
            com.sleepycat.bind.serial.StoredClassCatalog,
            and at that time you must provide a handle to an open database
            that is used to store the class information.

Create an entry binding that uses com.sleepycat.bind.serial.SerialBinding.

Instantiate an instance of the object that you want to
            store, and place it in a DatabaseEntry
            using the entry binding that you created in the previous step.

            For example, suppose you want to store a long, double, and a
            String as a record's data. Then you might create a class that
            looks something like this:

package db.GettingStarted;

import java.io.Serializable;

public class MyData implements Serializable {
    private long longData;
    private double doubleData;
    private String description;

    MyData() {
        longData = 0;
        doubleData = 0.0;
        description = null;
    }

    public void setLong(long data) {
        longData = data;
    }

    public void setDouble(double data) {
        doubleData = data;
    }

    public void setDescription(String data) {
        description = data;
    }

    public long getLong() {
        return longData;
    }

    public double getDouble() {
        return doubleData;
    }

    public String getDescription() {
        return description;
    }
}

You can then store instances of this class as follows:

package db.GettingStarted;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseType;
...

// The key data.
String aKey = "myData";

// The data data
MyData data2Store = new MyData();
data2Store.setLong(123456789l);
data2Store.setDouble(1234.9876543);
data2Store.setDescription("A test instance of this class");

try {
    // Open the database that you will use to store your data
    DatabaseConfig myDbConfig = new DatabaseConfig();
    myDbConfig.setAllowCreate(true);
    myDbConfig.setSortedDuplicates(true);
    myDbConfig.setType(DatabaseType.BTREE);
    Database myDatabase = new Database("myDb", null, myDbConfig);

    // Open the database that you use to store your class information.
    // The db used to store class information does not require duplicates
    // support.
    myDbConfig.setSortedDuplicates(false);
    Database myClassDb = new Database("classDb", null, myDbConfig);

    // Instantiate the class catalog
    StoredClassCatalog classCatalog = new StoredClassCatalog(myClassDb);

    // Create the binding
    EntryBinding dataBinding = new SerialBinding(classCatalog,
                                                 MyData.class);

    // Create the DatabaseEntry for the key
    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));

    // Create the DatabaseEntry for the data. Use the EntryBinding object
    // that was just created to populate the DatabaseEntry
    DatabaseEntry theData = new DatabaseEntry();
    dataBinding.objectToEntry(data2Store, theData);

    // Put it as normal
    myDatabase.put(null, theKey, theData);

    // Database and environment close omitted for brevity
} catch (Exception e) {
    // Exception handling goes here
}

Deserializing Objects

Once an object is stored in the database, you can retrieve the
        MyData objects from the retrieved
        DatabaseEntry using the Bind APIs in much the
        same way as is described above. For example:

package db.GettingStarted;

import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.StoredClassCatalog;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseType;
import com.sleepycat.db.LockMode;

...

// The key data.
String aKey = "myData";

try {
    // Open the database that stores your data
    DatabaseConfig myDbConfig = new DatabaseConfig();
    myDbConfig.setAllowCreate(false);
    myDbConfig.setType(DatabaseType.BTREE);
    Database myDatabase = new Database("myDb", null, myDbConfig);

    // Open the database that stores your class information.
    Database myClassDb = new Database("classDb", null, myDbConfig);

    // Instantiate the class catalog
    StoredClassCatalog classCatalog = new StoredClassCatalog(myClassDb);

    // Create the binding
    EntryBinding dataBinding = new SerialBinding(classCatalog,
                                                 MyData.class);

    // Create DatabaseEntry objects for the key and data
    DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
    DatabaseEntry theData = new DatabaseEntry();

    // Do the get as normal
    myDatabase.get(null, theKey, theData, LockMode.DEFAULT);

    // Recreate the MyData object from the retrieved DatabaseEntry using
    // the EntryBinding created above
    MyData retrievedData = (MyData) dataBinding.entryToObject(theData);

    // Database and environment close omitted for brevity
} catch (Exception e) {
    // Exception handling goes here
}

Custom Tuple Bindings

        If you want to store complex objects in your database, then you can use
        tuple bindings to do this. While they are more work to write and
        maintain than if you were to use serialization, the
        byte array conversion is faster. In addition, custom
        tuple bindings should allow you to create byte arrays
        that are smaller than those created by serialization. Custom tuple
        bindings also allow you to optimize your BTree comparisons, whereas
        serialization does not.

        For information on using serialization to store complex objects, see
        Serializable Complex Objects.

To store complex objects using a custom tuple binding:

Implement the class whose instances that you want to store.
          Note that you do not have to implement the Serializable interface.

Write a tuple binding using the com.sleepycat.bind.tuple.TupleBinding
          class.

Open (create) your database. Unlike serialization, you only
          need one.

Create an entry binding that uses the tuple binding that you
          implemented in step 2.

Instantiate an instance of the object that you want to store,
          and place it in a DatabaseEntry using the
          entry binding that you created in the previous step.

        For example, suppose you want to your keys to be instances of the
        following class:

package db.GettingStarted;

public class MyData2 {
    private long longData;
    private Double doubleData;
    private String description;

    public MyData2() {
        longData = 0;
        doubleData = new Double(0.0);
        description = "";
    }

    public void setLong(long data) {
        longData = data;
    }

    public void setDouble(Double data) {
        doubleData = data;
    }

    public void setString(String data) {
        description = data;
    }

    public long getLong() {
        return longData;
    }

    public Double getDouble() {
        return doubleData;
    }

    public String getString() {
        return description;
    }
}

In this case, you need to write a tuple binding for the
      MyData2 class. When you do this, you must
      implement the TupleBinding.objectToEntry()
      and TupleBinding.entryToObject() abstract methods.
      Remember the following as you implement these methods:

You use TupleBinding.objectToEntry() to convert
          objects to byte arrays. You use
          com.sleepycat.bind.tuple.TupleOutput to write
          primitive data types to the byte array. Note that
          TupleOutput provides methods that allows
          you to work with numerical types (long,
          double, int, and so forth) and
          not the corresponding java.lang numerical
          classes.

The order that you write data to the byte
          array in TupleBinding.objectToEntry() is the order that
          it appears in the array. So given the MyData2
          class as an example, if you write description,
          doubleData, and then longData,
          then the resulting byte array will contain these data elements in
          that order. This means that your records will sort based on the
          value of the description data member and then
          the doubleData member, and so forth. If you
          prefer to sort based on, say, the longData data
          member, write it to the byte array first.

You use TupleBinding.entryToObject() to convert
          the byte array back into an instance of your
          original class. You use com.sleepycat.bind.tuple.TupleInput
          to get data from the byte array.

The order that you read data from the byte
          array must be exactly the same as the order in which it was written.

For example:

package db.GettingStarted;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

public class MyTupleBinding extends TupleBinding {

    // Write a MyData2 object to a TupleOutput
    public void objectToEntry(Object object, TupleOutput to) {

        MyData2 myData = (MyData2)object;

        // Write the data to the TupleOutput (a DatabaseEntry).
        // Order is important. The first data written will be
        // the first bytes used by the default comparison routines.
        to.writeDouble(myData.getDouble().doubleValue());
        to.writeLong(myData.getLong());
        to.writeString(myData.getString());
    }

    // Convert a TupleInput to a MyData2 object
    public Object entryToObject(TupleInput ti) {

        // Data must be read in the same order that it was
        // originally written.
        Double theDouble = new Double(ti.readDouble());
        long theLong = ti.readLong();
        String theString = ti.readString();

        MyData2 myData = new MyData2();
        myData.setDouble(theDouble);
        myData.setLong(theLong);
        myData.setString(theString);

        return myData;
    }
}

In order to use the tuple binding, instantiate the binding and
      then use:

MyTupleBinding.objectToEntry() to
          convert a MyData2 object to a DatabaseEntry.

MyTupleBinding.entryToObject() to convert
          a DatabaseEntry to a MyData2
          object.

For example:

package db.GettingStarted;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.DatabaseEntry;

...

TupleBinding keyBinding = new MyTupleBinding();

MyData2 theKeyData = new MyData2();
theKeyData.setLong(123456789l);
theKeyData.setDouble(new Double(12345.6789));
theKeyData.setString("My key data");

DatabaseEntry myKey = new DatabaseEntry();

try {
    // Store theKeyData in the DatabaseEntry
    keyBinding.objectToEntry(theKeyData, myKey);

    ...
    // Database put and get activity omitted for clarity
    ...

    // Retrieve the key data
    theKeyData = (MyData2) keyBinding.entryToObject(myKey);
} catch (Exception e) {
    // Exception handling goes here
}

          Prev

            Up

           Next

          Reading and Writing Database Records

            Home

           Database Usage Example


text:
    <?php $form = $this->beginWidget('CActiveForm', array(
         'action' => $this->controller->createUrl('/comment/comment/add'),
         'id' => 'comment-form',
         'enableClientValidation' => true,
    )); ?>

<?php echo Yii::t('yupe', 'Поля, отмеченные');?> * <?php echo Yii::t('yupe', 'обязательны для заполнения');?>

    <?php if (!Yii::app()->user->isAuthenticated()): ?>

Пожалуйста, <?php echo CHtml::link('авторизуйтесь',array('/user/account/login/'));?> или <?php echo CHtml::link('зарегистрируйтесь',array('/user/account/registration/'));?> - писать будет проще =)

    <?php endif;?>

    <?php echo $form->errorSummary($model)?>

    <?php echo $form->hiddenField($model, 'model')?>

    <?php echo $form->hiddenField($model, 'model_id')?>

    <?php echo CHtml::hiddenField('redirectTo', $redirectTo);?>

    <?php if (!Yii::app()->user->isAuthenticated()): ?>

        <?php echo $form->labelEx($model, 'name'); ?>
        <?php echo $form->textField($model, 'name', array('size' => 60, 'maxlength' => 128)); ?>
        <?php echo $form->error($model, 'name'); ?>

        <?php echo $form->labelEx($model, 'email'); ?>
        <?php echo $form->textField($model, 'email', array('size' => 60, 'maxlength' => 128)); ?>
        <?php echo $form->error($model, 'email'); ?>

        <?php echo $form->labelEx($model, 'url'); ?>
        <?php echo $form->textField($model, 'url', array('size' => 60, 'maxlength' => 128)); ?>
        <?php echo $form->error($model, 'url'); ?>

    <?php else: ?>

<?php echo Yii::t('comment', 'От имени');?> : <?php echo Yii::app()->user->getState('nick_name');?>

    <?php endif;?>

        <?php echo $form->labelEx($model, 'text'); ?>
        <?php echo $form->textArea($model, 'text', array('rows' => 6, 'cols' => 50)); ?>
        <?php echo $form->error($model, 'text'); ?>

    <?php if (!Yii::app()->user->isAuthenticated() && extension_loaded('gd')): ?>

            <?php echo $form->labelEx($model, 'verifyCode'); ?>

                <?php $this->widget('CCaptcha', array(
                    'captchaAction'  => '/comment/comment/captcha',
                    'showRefreshButton' => false,
                    'clickableImage'    => true,
                )); ?>
                <?php echo $form->textField($model, 'verifyCode'); ?>

                Введите цифры указанные на картинке

    <?php endif; ?>

        <?php echo CHtml::submitButton('Написать'); ?>

    <?php $this->endWidget(); ?>


text:
def voter_photo_save_doc_template_values(url_root):
    """
    Show documentation about voterPhotoSave
    """
    required_query_parameter_list = [
        {
            'name':         'api_key',
            'value':        'string (from post, cookie, or get (in that order))',  # boolean, integer, long, string
            'description':  'The unique key provided to any organization using the WeVoteServer APIs',
        },
        {
            'name':         'voter_device_id',
            'value':        'string',  # boolean, integer, long, string
            'description':  'An 88 character unique identifier linked to a voter record on the server',
        },
        {
            'name':         'facebook_profile_image_url_https',
            'value':        'string',  # boolean, integer, long, string
            'description':  'The url on the facebook servers of this person\'s profile photo.',
        },
        {
            'name':         'twitter_profile_image_url_https',
            'value':        'string',  # boolean, integer, long, string
            'description':  'The url on the twitter servers of this person\'s profile photo.',
        },
    ]
    optional_query_parameter_list = [
        # {
        #     'name':         '',
        #     'value':        '',  # boolean, integer, long, string
        #     'description':  '',
        # },
    ]

    potential_status_codes_list = [
        {
            'code':         'VALID_VOTER_DEVICE_ID_MISSING',
            'description':  'Cannot proceed. A valid voter_device_id parameter was not included.',
        },
        {
            'code':         'MISSING_VOTER_ID',
            'description':  'Cannot proceed. Missing variables voter_id while trying to save.',
        },
        {
            'code':         'VOTER_PHOTO_SAVED',
            'description':  'Successfully saved',
        },
    ]

    try_now_link_variables_dict = {
        # 'organization_we_vote_id': 'wv85org1',
    }

    api_response = '{\n' \
                   '  "status": string (description of what happened),\n' \
                   '  "success": boolean (True as long as no db errors),\n' \
                   '  "voter_device_id": string (88 characters long),\n' \
                   '  "voter_photo_saved": boolean (did the voter address save happen?),\n' \
                   '  "facebook_profile_image_url_https": string,\n' \
                   '  "twitter_profile_image_url_https": string,\n' \
                   '}'

    template_values = {
        'api_name': 'voterPhotoSave',
        'api_slug': 'voterPhotoSave',
        'api_introduction':
            "Save one or more photos for the current voter.",
        'try_now_link': 'apis_v1:voterPhotoSaveView',
        'try_now_link_variables_dict': try_now_link_variables_dict,
        'url_root': url_root,
        'get_or_post': 'GET',
        'required_query_parameter_list': required_query_parameter_list,
        'optional_query_parameter_list': optional_query_parameter_list,
        'api_response': api_response,
        'api_response_notes':
            "",
        'potential_status_codes_list': potential_status_codes_list,
    }
    return template_values


text:
namespace rocksdb {
extern const uint64_t kCuckooTableMagicNumber;

namespace {
std::unordered_map<std::string, std::vector<uint64_t>> hash_map;

uint64_t GetSliceHash(const Slice& s, uint32_t index,
    uint64_t max_num_buckets) {
  return hash_map[s.ToString()][index];
}
}  // namespace

class CuckooBuilderTest {
 public:
  CuckooBuilderTest() {
    env_ = Env::Default();
    Options options;
    options.allow_mmap_reads = true;
    env_options_ = EnvOptions(options);
  }

  void CheckFileContents(const std::vector<std::string>& keys,
      const std::vector<std::string>& values,
      const std::vector<uint64_t>& expected_locations,
      std::string expected_unused_bucket, uint64_t expected_table_size,
      uint32_t expected_num_hash_func, bool expected_is_last_level,
      uint32_t expected_cuckoo_block_size = 1) {
    // Read file
    unique_ptr<RandomAccessFile> read_file;
    ASSERT_OK(env_->NewRandomAccessFile(fname, &read_file, env_options_));
    uint64_t read_file_size;
    ASSERT_OK(env_->GetFileSize(fname, &read_file_size));

    // Assert Table Properties.
    TableProperties* props = nullptr;
    ASSERT_OK(ReadTableProperties(read_file.get(), read_file_size,
          kCuckooTableMagicNumber, env_, nullptr, &props));
    // Check unused bucket.
    std::string unused_key = props->user_collected_properties[
      CuckooTablePropertyNames::kEmptyKey];
    ASSERT_EQ(expected_unused_bucket.substr(0,
          props->fixed_key_len), unused_key);

    uint32_t value_len_found =
      *reinterpret_cast<const uint32_t*>(props->user_collected_properties[
                CuckooTablePropertyNames::kValueLength].data());
    ASSERT_EQ(values.empty() ? 0 : values[0].size(), value_len_found);
    ASSERT_EQ(props->raw_value_size, values.size()*value_len_found);
    const uint64_t table_size =
      *reinterpret_cast<const uint64_t*>(props->user_collected_properties[
                CuckooTablePropertyNames::kHashTableSize].data());
    ASSERT_EQ(expected_table_size, table_size);
    const uint32_t num_hash_func_found =
      *reinterpret_cast<const uint32_t*>(props->user_collected_properties[
                CuckooTablePropertyNames::kNumHashFunc].data());
    ASSERT_EQ(expected_num_hash_func, num_hash_func_found);
    const uint32_t cuckoo_block_size =
      *reinterpret_cast<const uint32_t*>(props->user_collected_properties[
                CuckooTablePropertyNames::kCuckooBlockSize].data());
    ASSERT_EQ(expected_cuckoo_block_size, cuckoo_block_size);
    const bool is_last_level_found =
      *reinterpret_cast<const bool*>(props->user_collected_properties[
                CuckooTablePropertyNames::kIsLastLevel].data());
    ASSERT_EQ(expected_is_last_level, is_last_level_found);

    ASSERT_EQ(props->num_entries, keys.size());
    ASSERT_EQ(props->fixed_key_len, keys.empty() ? 0 : keys[0].size());
    ASSERT_EQ(props->data_size, expected_unused_bucket.size() *
        (expected_table_size + expected_cuckoo_block_size - 1));
    ASSERT_EQ(props->raw_key_size, keys.size()*props->fixed_key_len);
    delete props;

    // Check contents of the bucket.
    std::vector<bool> keys_found(keys.size(), false);
    size_t bucket_size = expected_unused_bucket.size();
    for (uint32_t i = 0; i < table_size + cuckoo_block_size - 1; ++i) {
      Slice read_slice;
      ASSERT_OK(read_file->Read(i*bucket_size, bucket_size,
            &read_slice, nullptr));
      size_t key_idx =
          std::find(expected_locations.begin(), expected_locations.end(), i) -
          expected_locations.begin();
      if (key_idx == keys.size()) {
        // i is not one of the expected locaitons. Empty bucket.
        ASSERT_EQ(read_slice.compare(expected_unused_bucket), 0);
      } else {
        keys_found[key_idx] = true;
        ASSERT_EQ(read_slice.compare(keys[key_idx] + values[key_idx]), 0);
      }
    }
    for (auto key_found : keys_found) {
      // Check that all keys were found.
      ASSERT_TRUE(key_found);
    }
  }

  std::string GetInternalKey(Slice user_key, bool zero_seqno) {
    IterKey ikey;
    ikey.SetInternalKey(user_key, zero_seqno ? 0 : 1000, kTypeValue);
    return ikey.GetKey().ToString();
  }

  uint64_t NextPowOf2(uint64_t num) {
    uint64_t n = 2;
    while (n <= num) {
      n *= 2;
    }
    return n;
  }

  Env* env_;
  EnvOptions env_options_;
  std::string fname;
  const double kHashTableRatio = 0.9;
};

TEST(CuckooBuilderTest, SuccessWithEmptyFile) {
  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/EmptyFile";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      4, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  ASSERT_EQ(0UL, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  CheckFileContents({}, {}, {}, "", 2, 2, false);
}

TEST(CuckooBuilderTest, WriteSuccessNoCollisionFullKey) {
  uint32_t num_hash_fun = 4;
  std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
  hash_map = {
    {user_keys[0], {0, 1, 2, 3}},
    {user_keys[1], {1, 2, 3, 4}},
    {user_keys[2], {2, 3, 4, 5}},
    {user_keys[3], {3, 4, 5, 6}}
  };
  std::vector<uint64_t> expected_locations = {0, 1, 2, 3};
  std::vector<std::string> keys;
  for (auto& user_key : user_keys) {
    keys.push_back(GetInternalKey(user_key, false));
  }
  uint64_t expected_table_size = NextPowOf2(keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/NoCollisionFullKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(keys[i]), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = GetInternalKey("key00", true);
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 2, false);
}

TEST(CuckooBuilderTest, WriteSuccessWithCollisionFullKey) {
  uint32_t num_hash_fun = 4;
  std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
  hash_map = {
    {user_keys[0], {0, 1, 2, 3}},
    {user_keys[1], {0, 1, 2, 3}},
    {user_keys[2], {0, 1, 2, 3}},
    {user_keys[3], {0, 1, 2, 3}},
  };
  std::vector<uint64_t> expected_locations = {0, 1, 2, 3};
  std::vector<std::string> keys;
  for (auto& user_key : user_keys) {
    keys.push_back(GetInternalKey(user_key, false));
  }
  uint64_t expected_table_size = NextPowOf2(keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionFullKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(keys[i]), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = GetInternalKey("key00", true);
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 4, false);
}

TEST(CuckooBuilderTest, WriteSuccessWithCollisionAndCuckooBlock) {
  uint32_t num_hash_fun = 4;
  std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
  hash_map = {
    {user_keys[0], {0, 1, 2, 3}},
    {user_keys[1], {0, 1, 2, 3}},
    {user_keys[2], {0, 1, 2, 3}},
    {user_keys[3], {0, 1, 2, 3}},
  };
  std::vector<uint64_t> expected_locations = {0, 1, 2, 3};
  std::vector<std::string> keys;
  for (auto& user_key : user_keys) {
    keys.push_back(GetInternalKey(user_key, false));
  }
  uint64_t expected_table_size = NextPowOf2(keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  uint32_t cuckoo_block_size = 2;
  fname = test::TmpDir() + "/WithCollisionFullKey2";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), cuckoo_block_size,
      false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(keys[i]), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = GetInternalKey("key00", true);
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 3, false, cuckoo_block_size);
}

TEST(CuckooBuilderTest, WithCollisionPathFullKey) {
  // Have two hash functions. Insert elements with overlapping hashes.
  // Finally insert an element with hash value somewhere in the middle
  // so that it displaces all the elements after that.
  uint32_t num_hash_fun = 2;
  std::vector<std::string> user_keys = {"key01", "key02", "key03",
    "key04", "key05"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04", "v05"};
  hash_map = {
    {user_keys[0], {0, 1}},
    {user_keys[1], {1, 2}},
    {user_keys[2], {2, 3}},
    {user_keys[3], {3, 4}},
    {user_keys[4], {0, 2}},
  };
  std::vector<uint64_t> expected_locations = {0, 1, 3, 4, 2};
  std::vector<std::string> keys;
  for (auto& user_key : user_keys) {
    keys.push_back(GetInternalKey(user_key, false));
  }
  uint64_t expected_table_size = NextPowOf2(keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionPathFullKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(keys[i]), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = GetInternalKey("key00", true);
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 2, false);
}

TEST(CuckooBuilderTest, WithCollisionPathFullKeyAndCuckooBlock) {
  uint32_t num_hash_fun = 2;
  std::vector<std::string> user_keys = {"key01", "key02", "key03",
    "key04", "key05"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04", "v05"};
  hash_map = {
    {user_keys[0], {0, 1}},
    {user_keys[1], {1, 2}},
    {user_keys[2], {3, 4}},
    {user_keys[3], {4, 5}},
    {user_keys[4], {0, 3}},
  };
  std::vector<uint64_t> expected_locations = {2, 1, 3, 4, 0};
  std::vector<std::string> keys;
  for (auto& user_key : user_keys) {
    keys.push_back(GetInternalKey(user_key, false));
  }
  uint64_t expected_table_size = NextPowOf2(keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionPathFullKeyAndCuckooBlock";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 2, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(keys[i]), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = GetInternalKey("key00", true);
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 2, false, 2);
}

TEST(CuckooBuilderTest, WriteSuccessNoCollisionUserKey) {
  uint32_t num_hash_fun = 4;
  std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
  hash_map = {
    {user_keys[0], {0, 1, 2, 3}},
    {user_keys[1], {1, 2, 3, 4}},
    {user_keys[2], {2, 3, 4, 5}},
    {user_keys[3], {3, 4, 5, 6}}
  };
  std::vector<uint64_t> expected_locations = {0, 1, 2, 3};
  uint64_t expected_table_size = NextPowOf2(user_keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/NoCollisionUserKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(GetInternalKey(user_keys[i], true)), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = user_keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = "key00";
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(user_keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 2, true);
}

TEST(CuckooBuilderTest, WriteSuccessWithCollisionUserKey) {
  uint32_t num_hash_fun = 4;
  std::vector<std::string> user_keys = {"key01", "key02", "key03", "key04"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04"};
  hash_map = {
    {user_keys[0], {0, 1, 2, 3}},
    {user_keys[1], {0, 1, 2, 3}},
    {user_keys[2], {0, 1, 2, 3}},
    {user_keys[3], {0, 1, 2, 3}},
  };
  std::vector<uint64_t> expected_locations = {0, 1, 2, 3};
  uint64_t expected_table_size = NextPowOf2(user_keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionUserKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(GetInternalKey(user_keys[i], true)), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = user_keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = "key00";
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(user_keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 4, true);
}

TEST(CuckooBuilderTest, WithCollisionPathUserKey) {
  uint32_t num_hash_fun = 2;
  std::vector<std::string> user_keys = {"key01", "key02", "key03",
    "key04", "key05"};
  std::vector<std::string> values = {"v01", "v02", "v03", "v04", "v05"};
  hash_map = {
    {user_keys[0], {0, 1}},
    {user_keys[1], {1, 2}},
    {user_keys[2], {2, 3}},
    {user_keys[3], {3, 4}},
    {user_keys[4], {0, 2}},
  };
  std::vector<uint64_t> expected_locations = {0, 1, 3, 4, 2};
  uint64_t expected_table_size = NextPowOf2(user_keys.size() / kHashTableRatio);

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionPathUserKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 2, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(GetInternalKey(user_keys[i], true)), Slice(values[i]));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  size_t bucket_size = user_keys[0].size() + values[0].size();
  ASSERT_EQ(expected_table_size * bucket_size - 1, builder.FileSize());
  ASSERT_OK(builder.Finish());
  ASSERT_OK(writable_file->Close());
  ASSERT_LE(expected_table_size * bucket_size, builder.FileSize());

  std::string expected_unused_bucket = "key00";
  expected_unused_bucket += std::string(values[0].size(), 'a');
  CheckFileContents(user_keys, values, expected_locations,
      expected_unused_bucket, expected_table_size, 2, true);
}

TEST(CuckooBuilderTest, FailWhenCollisionPathTooLong) {
  // Have two hash functions. Insert elements with overlapping hashes.
  // Finally try inserting an element with hash value somewhere in the middle
  // and it should fail because the no. of elements to displace is too high.
  uint32_t num_hash_fun = 2;
  std::vector<std::string> user_keys = {"key01", "key02", "key03",
    "key04", "key05"};
  hash_map = {
    {user_keys[0], {0, 1}},
    {user_keys[1], {1, 2}},
    {user_keys[2], {2, 3}},
    {user_keys[3], {3, 4}},
    {user_keys[4], {0, 1}},
  };

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/WithCollisionPathUserKey";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 2, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());
  for (uint32_t i = 0; i < user_keys.size(); i++) {
    builder.Add(Slice(GetInternalKey(user_keys[i], false)), Slice("value"));
    ASSERT_EQ(builder.NumEntries(), i + 1);
    ASSERT_OK(builder.status());
  }
  ASSERT_TRUE(builder.Finish().IsNotSupported());
  ASSERT_OK(writable_file->Close());
}

TEST(CuckooBuilderTest, FailWhenSameKeyInserted) {
  hash_map = {{"repeatedkey", {0, 1, 2, 3}}};
  uint32_t num_hash_fun = 4;
  std::string user_key = "repeatedkey";

  unique_ptr<WritableFile> writable_file;
  fname = test::TmpDir() + "/FailWhenSameKeyInserted";
  ASSERT_OK(env_->NewWritableFile(fname, &writable_file, env_options_));
  CuckooTableBuilder builder(writable_file.get(), kHashTableRatio,
      num_hash_fun, 100, BytewiseComparator(), 1, false, false, GetSliceHash);
  ASSERT_OK(builder.status());

  builder.Add(Slice(GetInternalKey(user_key, false)), Slice("value1"));
  ASSERT_EQ(builder.NumEntries(), 1u);
  ASSERT_OK(builder.status());
  builder.Add(Slice(GetInternalKey(user_key, true)), Slice("value2"));
  ASSERT_EQ(builder.NumEntries(), 2u);
  ASSERT_OK(builder.status());

  ASSERT_TRUE(builder.Finish().IsNotSupported());
  ASSERT_OK(writable_file->Close());
}
}  // namespace rocksdb

int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); }


text:
define(["underscore", "backbone", "views/conndialog"], function(_, Backbone, ConnectionDialog) {

    var ManageConnectionsDialog = ConnectionDialog.extend({
        className: "manage-connections-dialog",
        events: {
            "click .modal" : "remove",
            "click .close" : "remove",
            "click .close-button" : "remove",
            "click .reset" : "reset",
            "click .delete" : "deleteConnection",
            "click .btn-primary" : "save",
            "submit form" : "save",
            "click .connections option" : "chooseConnection",
            "change input" : "disableSelection",
            "change textarea" : "disableSelection"
        },
        initialize : function() {

        },

        render : function() {
            // template rendering
            var t = document.querySelector('#manage-connections-dialog-template');
            t.content.querySelector('.modal').style.background = 'rgba(0,0,0,0.5)';

            var clone = document.importNode(t.content, true);

            this.el.appendChild(clone);
            document.body.appendChild(this.el);

            this.connectionNameInput = this.el.querySelector("input[name=connection-name]");
            this.hostInput = this.el.querySelector("input[name=host]");
            this.portInput = this.el.querySelector("input[name=port]");
            this.userInput = this.el.querySelector("input[name=username]");
            this.passwordInput = this.el.querySelector("input[name=password]");
            this.privkeyInput = this.el.querySelector("textarea[name=privkey]");

            this.connectionList = this.el.querySelector(".connections");

            app.connections.on("destroy", this.onDestroy, this);

            if (app.connections.length == 0) {
                this.remove();
                return;
            }

            app.connections.each(_.bind(function(connection) {
                var connectionItem = document.createElement("option");
                connectionItem.textContent = connection.get("name");
                connectionItem.value = connection.id;
                this.connectionList.appendChild(connectionItem);
            }, this));

            this.connectionList.selectedIndex = 0;
            this.selectedConnectionId = this.connectionList.value;
            this.reset();

            this.error = this.el.querySelector(".error");
            this.error.style.display = "none";

        },

        disableSelection : function() {
            this.connectionList.disabled = true;
        },

        chooseConnection : function(e) {
            this.selectedConnectionId = e.target.value;
            this.reset();
        },

        reset : function() {
            var connection = app.connections.get(this.selectedConnectionId);

            this.connectionNameInput.value = connection.get("name");
            this.hostInput.value = connection.get("host");
            this.portInput.value = connection.get("port");
            this.userInput.value = connection.get("user");
            this.passwordInput.value = connection.get("password");
            this.privkeyInput.value = connection.get("privkey");

            this.connectionList.disabled = false;
        },

        save : function() {
            if (!this.validate()) {
                return false;
            }

            app.connections.get(this.selectedConnectionId).save({
                name : this.connectionNameInput.value,
                host : this.hostInput.value,
                user : this.userInput.value,
                password : this.passwordInput.value,
                port: this.portInput.value,
                privkey: this.privkeyInput.value
            }, {
                wait : true,
                success : _.bind(function() {
                    this.connectionList.disabled = false;
                }, this),
                error : _.bind(function() {
                    this.error.style.display = "block";
                    this.error.textContent = "There was an error updating the connection.";
                }, this)
            });

            return false;
        },

        deleteConnection : function() {
            app.connections.get(this.selectedConnectionId).destroy({wait: true});
        },

        onDestroy : function(model) {
            for (var i = 0; i < this.connectionList.length; i++) {
                if (this.connectionList[i].value == model.id) {
                    this.connectionList.remove(i);
                }
            }

            this.connectionList.remove(this.connectionList.selectedIndex);

            if (this.connectionList.length == 0) {
                this.remove();
            } else {
                this.connectionList.selectedIndex = 0;
                this.selectedConnectionId = this.connectionList.value;
                this.reset();
            }
        }

    });

    return ManageConnectionsDialog;
});


text:
#ifndef _BINYO_MISSING_H_
#define _BINYO_MISSING_H_

#ifndef HAVE_RB_IO_CHECK_BYTE_READABLE
#define rb_io_check_byte_readable(fptr)		rb_io_check_readable(fptr)
#endif

#endif /* BINYO_MISSING_H */


text:
namespace pw::stream {
namespace {

std::ios::seekdir WhenceToSeekDir(Stream::Whence whence) {
  switch (whence) {
    case Stream::Whence::kBeginning:
      return std::ios::beg;
    case Stream::Whence::kCurrent:
      return std::ios::cur;
    case Stream::Whence::kEnd:
      return std::ios::end;
  }
  PW_CRASH("Unknown value for enum Stream::Whence");
}

}  // namespace

StatusWithSize StdFileReader::DoRead(ByteSpan dest) {
  stream_.peek();  // Peek to set EOF if at the end of the file.
  if (stream_.eof()) {
    return StatusWithSize::OutOfRange();
  }

  stream_.read(reinterpret_cast<char*>(dest.data()), dest.size());
  if (stream_.bad()) {
    return StatusWithSize::Unknown();
  }

  return StatusWithSize(stream_.gcount());
}

Status StdFileReader::DoSeek(ptrdiff_t offset, Whence origin) {
  // Explicitly clear EOF bit if needed.
  if (stream_.eof()) {
    stream_.clear();
  }
  if (!stream_.seekg(offset, WhenceToSeekDir(origin))) {
    return Status::Unknown();
  }
  return OkStatus();
}

size_t StdFileReader::DoTell() {
  auto pos = static_cast<int>(stream_.tellg());
  return pos < 0 ? kUnknownPosition : pos;
}

size_t StdFileReader::ConservativeLimit(LimitType limit) const {
  if (limit == LimitType::kWrite) {
    return 0;
  }

  // Attempt to determine the number of bytes left in the file by seeking
  // to the end and checking where we end up.
  if (stream_.eof()) {
    return 0;
  }
  auto stream = const_cast<std::ifstream*>(&this->stream_);
  auto start = stream->tellg();
  if (start == -1) {
    return 0;
  }
  stream->seekg(0, std::ios::end);
  auto end = stream->tellg();
  if (end == -1) {
    return 0;
  }
  stream->seekg(start, std::ios::beg);
  return end - start;
}

Status StdFileWriter::DoWrite(ConstByteSpan data) {
  if (stream_.eof()) {
    return Status::OutOfRange();
  }

  if (stream_.write(reinterpret_cast<const char*>(data.data()), data.size())) {
    return OkStatus();
  }

  return Status::Unknown();
}

Status StdFileWriter::DoSeek(ptrdiff_t offset, Whence origin) {
  if (!stream_.seekp(offset, WhenceToSeekDir(origin))) {
    return Status::Unknown();
  }
  return OkStatus();
}

size_t StdFileWriter::DoTell() {
  auto pos = static_cast<int>(stream_.tellp());
  return pos < 0 ? kUnknownPosition : pos;
}

}  // namespace pw::stream


text:
<?php

namespace Scalia\SphinxSearch;

use Illuminate\Support\Facades\Facade;

class SphinxSearchFacade extends Facade {
	protected static function getFacadeAccessor()
	{
		return 'sphinxsearch';
	}
}


text:
package com.facebook.buck.event.listener;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

import com.facebook.buck.artifact_cache.CacheResult;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent.Finished;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.network.RemoteLogger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;

import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

public class HttpArtifactCacheEventListenerTest {

  private static final BuildId BUILD_ID = new BuildId("My Super ID");
  private static final ObjectMapper CONVERTER = ObjectMappers.newDefaultInstance();

  private RemoteLogger logger;
  private HttpArtifactCacheListener listener;

  @Before
  public void setUp() {
    logger = EasyMock.createMock(RemoteLogger.class);
    listener = new HttpArtifactCacheListener(logger, CONVERTER);
  }

  @Test
  public void creatingRowWithoutColumns() throws InterruptedException {
    Capture<String> logLineCapture = Capture.newInstance();
    EasyMock.expect(
        logger.log(
            EasyMock.capture(logLineCapture)))
        .andReturn(Optional.<ListenableFuture<Void>>absent())
        .once();
    EasyMock.expect(logger.close())
        .andReturn(null)
        .once();
    EasyMock.replay(logger);

    String errorMsg = "My super cool error message!!!";

    HttpArtifactCacheEvent.Started startedEvent = HttpArtifactCacheEvent.newFetchStartedEvent(
        ImmutableSet.<RuleKey>of());
    startedEvent.configure(-1, -1, -1, -1, null);
    Finished event = HttpArtifactCacheEvent.newFinishedEventBuilder(startedEvent)
        .setFetchResult(CacheResult.hit("http"))
        .setErrorMessage(errorMsg)
        .build();
    event.configure(-1, -1, -1, -1, BUILD_ID);
    listener.onHttpArtifactCacheEvent(event);
    listener.outputTrace(BUILD_ID);
    EasyMock.verify(logger);
    String actualLogLine = logLineCapture.getValue();
    assertFalse(Strings.isNullOrEmpty(actualLogLine));
    assertTrue(actualLogLine.contains(errorMsg));
    assertTrue(actualLogLine.contains(BUILD_ID.toString()));
  }
}


text:
var mongoose = require('../mongoose.wrapper');

var userSchema = mongoose.Schema({
    id: String,
    role: Number,
    code: String,
    name: String,
    lastName: String
});

var User = mongoose.model('User', userSchema);

module.exports = User;


text:
package de.inetsoftware.classparser;

import java.io.DataInputStream;
import java.io.IOException;

/**
 * https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.23
 *
 * @author Volker Berlin
 */
public class BootstrapMethod {

    /**
     * Signature and return type of method to be implemented by the function object.
     */
    private String      samMethodType;

    /**
     * A direct method handle describing the implementation method which should be called
     */
    private ConstantRef implMethod;

    /**
     * The signature and return type that should be enforced dynamically at invocation time. This may be the same as
     * {@code samMethodType}, or may be a specialization of it.
     */
    private String      instantiatedMethodType;

    /**
     * Create an instance.
     */
    BootstrapMethod( DataInputStream input, ConstantPool constantPool ) throws IOException {
        int ref = input.readUnsignedShort();
        ConstantMethodRef method = (ConstantMethodRef)constantPool.get( ref );

        int argCount = input.readUnsignedShort(); // ever: 3 parameters
        String factory = method.getClassName() + "." + method.getName() + method.getType();
        switch( factory ) {
            case "java/lang/invoke/LambdaMetafactory.metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;":
            case "java/lang/invoke/LambdaMetafactory.altMetafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":
                // the 3 values
                samMethodType = (String)constantPool.get( input.readUnsignedShort() );
                implMethod = (ConstantRef)constantPool.get( input.readUnsignedShort() );
                instantiatedMethodType = (String)constantPool.get( input.readUnsignedShort() );

                // skip extra parameters
                // argCount is 5 if the method is LambdaMetafactory.altMetafactory
                // occur if the Lambda type has 2 types compound with "&" like in java.time.chrono.AbstractChronology
                for( int i = 3; i < argCount; i++ ) {
                    constantPool.get( input.readUnsignedShort() );
                }
                break;

            case "java/lang/invoke/StringConcatFactory.makeConcatWithConstants(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;":
                // occur in Java 11 in java/util/logging/Logger.findResourceBundle
                String recipe = (String)constantPool.get( input.readUnsignedShort() );
                //TODO
                break;

            default:
                throw new IOException( "Unknown invoke dynamic bootstrap factory: " + factory );
        }
    }

    /**
     * Signature and return type of method to be implemented by the function object.
     *
     * @see java.lang.invoke.LambdaMetafactory#metafactory parameter samMethodType
     * @return the signature
     */
    public String getSamMethodType() {
        return samMethodType;
    }

    /**
     * The real method in the parent class that implements the lambda expression
     *
     * @return the method (ConstantMethodRef or ConstantInterfaceRef)
     */
    public ConstantRef getImplMethod() {
        return implMethod;
    }
}


text:
class Company < ActiveRecord::Base
  has_many :railway_lines
  belongs_to :service_provider_type
end


text:
import pitcher = require("../../../lib/runtime");

export class Module implements pitcher.Module {
  static constructedCount = 0;
  contributedConstructorCount = [Module.constructedCount += 1];

  includes = [SiblingA, SiblingB]
}

export class AlsoNotAModule {
}

export class SiblingA implements pitcher.Module {
  static constructedCount = 0;
  contributedConstructorCount = [SiblingA.constructedCount += 1];
}

export class SiblingB implements pitcher.Module {
  static constructedCount = 0;
  contributedConstructorCount = [SiblingB.constructedCount += 1];

  includes = [SiblingA]
}