text:
package org.mockitousage.verification;

import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.exceptions.base.MockitoAssertionError;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockitoutil.TestBase;

import java.util.List;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

public class AtMostXVerificationTest extends TestBase {

    @Mock private List<String> mock;

    @Test
    public void shouldVerifyAtMostXTimes() throws Exception {
        mock.clear();
        mock.clear();

        verify(mock, atMost(2)).clear();
        verify(mock, atMost(3)).clear();

        try {
            verify(mock, atMost(1)).clear();
            fail();
        } catch (MockitoAssertionError e) {}
    }

    @Test
    public void shouldWorkWithArgumentMatchers() throws Exception {
        mock.add("one");
        verify(mock, atMost(5)).add(anyString());

        try {
            verify(mock, atMost(0)).add(anyString());
            fail();
        } catch (MockitoAssertionError e) {}
    }

    @Test
    public void shouldNotAllowNegativeNumber() throws Exception {
        try {
            verify(mock, atMost(-1)).clear();
            fail();
        } catch (MockitoException e) {
            assertEquals("Negative value is not allowed here", e.getMessage());
        }
    }

    @Test
    public void shouldPrintDecentMessage() throws Exception {
        mock.clear();
        mock.clear();

        try {
            verify(mock, atMost(1)).clear();
            fail();
        } catch (MockitoAssertionError e) {
            assertEquals("\nWanted at most 1 time but was 2", e.getMessage());
        }
    }

    @Test
    public void shouldNotAllowInOrderMode() throws Exception {
        mock.clear();
        InOrder inOrder = inOrder(mock);

        try {
            inOrder.verify(mock, atMost(1)).clear();
            fail();
        } catch (MockitoException e) {
            assertEquals("AtMost is not implemented to work with InOrder", e.getMessage());
        }
    }

    @Test
    public void shouldMarkInteractionsAsVerified() throws Exception {
        mock.clear();
        mock.clear();

        verify(mock, atMost(3)).clear();
        verifyNoMoreInteractions(mock);
    }

    @Test
    public void shouldDetectUnverifiedInMarkInteractionsAsVerified() throws Exception {
        mock.clear();
        mock.clear();
        undesiredInteraction();

        verify(mock, atMost(3)).clear();
        try {
            verifyNoMoreInteractions(mock);
            fail();
        } catch(NoInteractionsWanted e) {
            assertThat(e).hasMessageContaining("undesiredInteraction(");
        }
    }

    private void undesiredInteraction() {
        mock.add("");
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.owasp.appsensor.integration.jmx (appsensor-parent 2.3.3 API)</title>
<meta name="date" content="2018-06-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package org.owasp.appsensor.integration.jmx

Interface Summary

Interface
Description

JmxEmitter.JmxAppSensorMBean

JmxEmitter.JmxAttackMBean

JmxEmitter.JmxEventMBean

JmxEmitter.JmxResponseMBean

Class Summary

Class
Description

JmxEmitter

Copyright © 2018 The Open Web Application Security Project (OWASP). All rights reserved.

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2014-2017 XDN-project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "BlockchainSynchronizer.h"

#include <functional>
#include <iostream>
#include <sstream>
#include <unordered_set>

#include "CryptoNoteCore/TransactionApi.h"
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"

using namespace Crypto;

namespace {

inline std::vector<uint8_t> stringToVector(const std::string& s) {
  std::vector<uint8_t> vec(
    reinterpret_cast<const uint8_t*>(s.data()),
    reinterpret_cast<const uint8_t*>(s.data()) + s.size());
  return vec;
}

}

namespace CryptoNote {

BlockchainSynchronizer::BlockchainSynchronizer(INode& node, const Hash& genesisBlockHash) :
  m_node(node),
  m_genesisBlockHash(genesisBlockHash),
  m_currentState(State::stopped),
  m_futureState(State::stopped) {
}

BlockchainSynchronizer::~BlockchainSynchronizer() {
  stop();
}

void BlockchainSynchronizer::addConsumer(IBlockchainConsumer* consumer) {
  assert(consumer != nullptr);
  assert(m_consumers.count(consumer) == 0);

  if (!(checkIfStopped() && checkIfShouldStop())) {
    throw std::runtime_error("Can't add consumer, because BlockchainSynchronizer isn't stopped");
  }

  m_consumers.insert(std::make_pair(consumer, std::make_shared<SynchronizationState>(m_genesisBlockHash)));
}

bool BlockchainSynchronizer::removeConsumer(IBlockchainConsumer* consumer) {
  assert(consumer != nullptr);

  if (!(checkIfStopped() && checkIfShouldStop())) {
    throw std::runtime_error("Can't remove consumer, because BlockchainSynchronizer isn't stopped");
  }

  return m_consumers.erase(consumer) > 0;
}

IStreamSerializable* BlockchainSynchronizer::getConsumerState(IBlockchainConsumer* consumer) const {
  std::unique_lock<std::mutex> lk(m_consumersMutex);
  return getConsumerSynchronizationState(consumer);
}

std::vector<Crypto::Hash> BlockchainSynchronizer::getConsumerKnownBlocks(IBlockchainConsumer& consumer) const {
  std::unique_lock<std::mutex> lk(m_consumersMutex);

  auto state = getConsumerSynchronizationState(&consumer);
  if (state == nullptr) {
    throw std::invalid_argument("Consumer not found");
  }

  return state->getKnownBlockHashes();
}

std::future<std::error_code> BlockchainSynchronizer::addUnconfirmedTransaction(const ITransactionReader& transaction) {
  std::unique_lock<std::mutex> lock(m_stateMutex);

  if (m_currentState == State::stopped || m_futureState == State::stopped) {
    throw std::runtime_error("Can't add transaction, because BlockchainSynchronizer is stopped");
  }

  std::promise<std::error_code> promise;
  auto future = promise.get_future();
  m_addTransactionTasks.emplace_back(&transaction, std::move(promise));
  m_hasWork.notify_one();

  return future;
}

std::future<void> BlockchainSynchronizer::removeUnconfirmedTransaction(const Crypto::Hash& transactionHash) {
  std::unique_lock<std::mutex> lock(m_stateMutex);

  if (m_currentState == State::stopped || m_futureState == State::stopped) {
    throw std::runtime_error("Can't remove transaction, because BlockchainSynchronizer is stopped");
  }

  std::promise<void> promise;
  auto future = promise.get_future();
  m_removeTransactionTasks.emplace_back(&transactionHash, std::move(promise));
  m_hasWork.notify_one();

  return future;
}

std::error_code BlockchainSynchronizer::doAddUnconfirmedTransaction(const ITransactionReader& transaction) {
  std::unique_lock<std::mutex> lk(m_consumersMutex);

  std::error_code ec;
  auto addIt = m_consumers.begin();
  for (; addIt != m_consumers.end(); ++addIt) {
    ec = addIt->first->addUnconfirmedTransaction(transaction);
    if (ec) {
      break;
    }
  }

  if (ec) {
    auto transactionHash = transaction.getTransactionHash();
    for (auto rollbackIt = m_consumers.begin(); rollbackIt != addIt; ++rollbackIt) {
      rollbackIt->first->removeUnconfirmedTransaction(transactionHash);
    }
  }

  return ec;
}

void BlockchainSynchronizer::doRemoveUnconfirmedTransaction(const Crypto::Hash& transactionHash) {
  std::unique_lock<std::mutex> lk(m_consumersMutex);

  for (auto& consumer : m_consumers) {
    consumer.first->removeUnconfirmedTransaction(transactionHash);
  }
}

void BlockchainSynchronizer::save(std::ostream& os) {
  os.write(reinterpret_cast<const char*>(&m_genesisBlockHash), sizeof(m_genesisBlockHash));
}

void BlockchainSynchronizer::load(std::istream& in) {
  Hash genesisBlockHash;
  in.read(reinterpret_cast<char*>(&genesisBlockHash), sizeof(genesisBlockHash));
  if (genesisBlockHash != m_genesisBlockHash) {
    throw std::runtime_error("Genesis block hash does not match stored state");
  }
}

//--------------------------- FSM ------------------------------------

bool BlockchainSynchronizer::setFutureState(State s) {
  return setFutureStateIf(s, [this, s] { return s > m_futureState; });
}

bool BlockchainSynchronizer::setFutureStateIf(State s, std::function<bool(void)>&& pred) {
  std::unique_lock<std::mutex> lk(m_stateMutex);
  if (pred()) {
    m_futureState = s;
    m_hasWork.notify_one();
    return true;
  }

  return false;
}

void BlockchainSynchronizer::actualizeFutureState() {
  std::unique_lock<std::mutex> lk(m_stateMutex);
  if (m_currentState == State::stopped && m_futureState == State::blockchainSync) { // start(), immideately attach observer
    m_node.addObserver(this);
  }

  if (m_futureState == State::stopped && m_currentState != State::stopped) { // stop(), immideately detach observer
    m_node.removeObserver(this);
  }

  while (!m_removeTransactionTasks.empty()) {
    auto& task = m_removeTransactionTasks.front();
    const Crypto::Hash& transactionHash = *task.first;
    auto detachedPromise = std::move(task.second);
    m_removeTransactionTasks.pop_front();

    try {
      doRemoveUnconfirmedTransaction(transactionHash);
      detachedPromise.set_value();
    } catch (...) {
      detachedPromise.set_exception(std::current_exception());
    }
  }

  while (!m_addTransactionTasks.empty()) {
    auto& task = m_addTransactionTasks.front();
    const ITransactionReader& transaction = *task.first;
    auto detachedPromise = std::move(task.second);
    m_addTransactionTasks.pop_front();

    try {
      auto ec = doAddUnconfirmedTransaction(transaction);
      detachedPromise.set_value(ec);
    } catch (...) {
      detachedPromise.set_exception(std::current_exception());
    }
  }

  m_currentState = m_futureState;
  switch (m_futureState) {
  case State::stopped:
    break;
  case State::blockchainSync:
    m_futureState = State::poolSync;
    lk.unlock();
    startBlockchainSync();
    break;
  case State::poolSync:
    m_futureState = State::idle;
    lk.unlock();
    startPoolSync();
    break;
  case State::idle:
    m_hasWork.wait(lk, [this] {
      return m_futureState != State::idle || !m_removeTransactionTasks.empty() || !m_addTransactionTasks.empty();
    });
    lk.unlock();
    break;
  default:
    break;
  }
}

bool BlockchainSynchronizer::checkIfShouldStop() const {
  std::unique_lock<std::mutex> lk(m_stateMutex);
  return m_futureState == State::stopped;
}

bool BlockchainSynchronizer::checkIfStopped() const {
  std::unique_lock<std::mutex> lk(m_stateMutex);
  return m_currentState == State::stopped;
}

void BlockchainSynchronizer::workingProcedure() {
  while (!checkIfShouldStop()) {
    actualizeFutureState();
  }

  actualizeFutureState();
}

void BlockchainSynchronizer::start() {
  if (m_consumers.empty()) {
    throw std::runtime_error("Can't start, because BlockchainSynchronizer has no consumers");
  }

  if (!setFutureStateIf(State::blockchainSync, [this] { return m_currentState == State::stopped && m_futureState == State::stopped; })) {
    throw std::runtime_error("BlockchainSynchronizer already started");
  }

  workingThread.reset(new std::thread([this] { workingProcedure(); }));
}

void BlockchainSynchronizer::stop() {
  setFutureState(State::stopped);

  // wait for previous processing to end
  if (workingThread.get() != nullptr && workingThread->joinable()) {
    workingThread->join();
  }

  workingThread.reset();
}

void BlockchainSynchronizer::localBlockchainUpdated(uint32_t /*height*/) {
  setFutureState(State::blockchainSync);
}

void BlockchainSynchronizer::lastKnownBlockHeightUpdated(uint32_t /*height*/) {
  setFutureState(State::blockchainSync);
}

void BlockchainSynchronizer::poolChanged() {
  setFutureState(State::poolSync);
}
//--------------------------- FSM END ------------------------------------

void BlockchainSynchronizer::getPoolUnionAndIntersection(std::unordered_set<Crypto::Hash>& poolUnion, std::unordered_set<Crypto::Hash>& poolIntersection) const {
  std::unique_lock<std::mutex> lk(m_consumersMutex);

  auto itConsumers = m_consumers.begin();
  poolUnion = itConsumers->first->getKnownPoolTxIds();
  poolIntersection = itConsumers->first->getKnownPoolTxIds();
  ++itConsumers;

  for (; itConsumers != m_consumers.end(); ++itConsumers) {
    const std::unordered_set<Crypto::Hash>& consumerKnownIds = itConsumers->first->getKnownPoolTxIds();

    poolUnion.insert(consumerKnownIds.begin(), consumerKnownIds.end());

    for (auto itIntersection = poolIntersection.begin(); itIntersection != poolIntersection.end();) {
      if (consumerKnownIds.count(*itIntersection) == 0) {
        itIntersection = poolIntersection.erase(itIntersection);
      } else {
        ++itIntersection;
      }
    }
  }
}

BlockchainSynchronizer::GetBlocksRequest BlockchainSynchronizer::getCommonHistory() {
  GetBlocksRequest request;
  std::unique_lock<std::mutex> lk(m_consumersMutex);
  if (m_consumers.empty()) {
    return request;
  }

  auto shortest = m_consumers.begin();
  auto syncStart = shortest->first->getSyncStart();
  auto it = shortest;
  ++it;
  for (; it != m_consumers.end(); ++it) {
    if (it->second->getHeight() < shortest->second->getHeight()) {
      shortest = it;
    }

    auto consumerStart = it->first->getSyncStart();
    syncStart.timestamp = std::min(syncStart.timestamp, consumerStart.timestamp);
    syncStart.height = std::min(syncStart.height, consumerStart.height);
  }

  request.knownBlocks = shortest->second->getShortHistory(m_node.getLastLocalBlockHeight());
  request.syncStart = syncStart;
  return request;
}

void BlockchainSynchronizer::startBlockchainSync() {
  GetBlocksResponse response;
  GetBlocksRequest req = getCommonHistory();

  try {
    if (!req.knownBlocks.empty()) {
      auto queryBlocksCompleted = std::promise<std::error_code>();
      auto queryBlocksWaitFuture = queryBlocksCompleted.get_future();

      m_node.queryBlocks(
        std::move(req.knownBlocks),
        req.syncStart.timestamp,
        response.newBlocks,
        response.startHeight,
        [&queryBlocksCompleted](std::error_code ec) {
          auto detachedPromise = std::move(queryBlocksCompleted);
          detachedPromise.set_value(ec);
        });

      std::error_code ec = queryBlocksWaitFuture.get();

      if (ec) {
        setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; });
        m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec);
      } else {
        processBlocks(response);
      }
    }
  } catch (std::exception&) {
    setFutureStateIf(State::idle,  [this] { return m_futureState != State::stopped; });
    m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument));
  }
}

void BlockchainSynchronizer::processBlocks(GetBlocksResponse& response) {
  BlockchainInterval interval;
  interval.startHeight = response.startHeight;
  std::vector<CompleteBlock> blocks;

  for (auto& block : response.newBlocks) {
    if (checkIfShouldStop()) {
      break;
    }

    CompleteBlock completeBlock;
    completeBlock.blockHash = block.blockHash;
    interval.blocks.push_back(completeBlock.blockHash);
    if (block.hasBlock) {
      completeBlock.block = std::move(block.block);
      completeBlock.transactions.push_back(createTransactionPrefix(completeBlock.block->baseTransaction));

      try {
        for (const auto& txShortInfo : block.txsShortInfo) {
          completeBlock.transactions.push_back(createTransactionPrefix(txShortInfo.txPrefix, reinterpret_cast<const Hash&>(txShortInfo.txId)));
        }
      } catch (std::exception&) {
        setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; });
        m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument));
        return;
      }
    }

    blocks.push_back(std::move(completeBlock));
  }

  uint32_t processedBlockCount = response.startHeight + static_cast<uint32_t>(response.newBlocks.size());
  if (!checkIfShouldStop()) {
    response.newBlocks.clear();
    std::unique_lock<std::mutex> lk(m_consumersMutex);
    auto result = updateConsumers(interval, blocks);
    lk.unlock();

    switch (result) {
    case UpdateConsumersResult::errorOccurred:
      if (setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; })) {
        m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument));
      }
      break;

    case UpdateConsumersResult::nothingChanged:
      if (m_node.getLastKnownBlockHeight() != m_node.getLastLocalBlockHeight()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
      } else {
        break;
      }

    case UpdateConsumersResult::addedNewBlocks:
      setFutureState(State::blockchainSync);
      m_observerManager.notify(
        &IBlockchainSynchronizerObserver::synchronizationProgressUpdated,
        processedBlockCount,
        std::max(m_node.getKnownBlockCount(), m_node.getLocalBlockCount()));
      break;
    }

    if (!blocks.empty()) {
      lastBlockId = blocks.back().blockHash;
    }
  }

  if (checkIfShouldStop()) { //Sic!
    m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::interrupted));
  }
}

/// \pre m_consumersMutex is locked
BlockchainSynchronizer::UpdateConsumersResult BlockchainSynchronizer::updateConsumers(const BlockchainInterval& interval, const std::vector<CompleteBlock>& blocks) {
  bool smthChanged = false;

  for (auto& kv : m_consumers) {
    auto result = kv.second->checkInterval(interval);

    if (result.detachRequired) {
      kv.first->onBlockchainDetach(result.detachHeight);
      kv.second->detach(result.detachHeight);
    }

    if (result.hasNewBlocks) {
      uint32_t startOffset = result.newBlockHeight - interval.startHeight;
      // update consumer
      if (kv.first->onNewBlocks(blocks.data() + startOffset, result.newBlockHeight, static_cast<uint32_t>(blocks.size()) - startOffset)) {
        // update state if consumer succeeded
        kv.second->addBlocks(interval.blocks.data() + startOffset, result.newBlockHeight, static_cast<uint32_t>(interval.blocks.size()) - startOffset);
        smthChanged = true;
      } else {
        return UpdateConsumersResult::errorOccurred;
      }
    }
  }

  return smthChanged ? UpdateConsumersResult::addedNewBlocks : UpdateConsumersResult::nothingChanged;
}

void BlockchainSynchronizer::startPoolSync() {
  std::unordered_set<Crypto::Hash> unionPoolHistory;
  std::unordered_set<Crypto::Hash> intersectedPoolHistory;
  getPoolUnionAndIntersection(unionPoolHistory, intersectedPoolHistory);

  GetPoolRequest unionRequest;
  unionRequest.knownTxIds.assign(unionPoolHistory.begin(), unionPoolHistory.end());
  unionRequest.lastKnownBlock = lastBlockId;

  GetPoolResponse unionResponse;
  unionResponse.isLastKnownBlockActual = false;

  std::error_code ec = getPoolSymmetricDifferenceSync(std::move(unionRequest), unionResponse);

  if (ec) {
    setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; });
    m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec);
  } else { //get union ok
    if (!unionResponse.isLastKnownBlockActual) { //bc outdated
      setFutureState(State::blockchainSync);
    } else {
      if (unionPoolHistory == intersectedPoolHistory) { //usual case, start pool processing
        m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, processPoolTxs(unionResponse));
      } else {
        GetPoolRequest intersectionRequest;
        intersectionRequest.knownTxIds.assign(intersectedPoolHistory.begin(), intersectedPoolHistory.end());
        intersectionRequest.lastKnownBlock = lastBlockId;

        GetPoolResponse intersectionResponse;
        intersectionResponse.isLastKnownBlockActual = false;

        std::error_code ec2 = getPoolSymmetricDifferenceSync(std::move(intersectionRequest), intersectionResponse);

        if (ec2) {
          setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; });
          m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec2);
        } else { //get intersection ok
          if (!intersectionResponse.isLastKnownBlockActual) { //bc outdated
            setFutureState(State::blockchainSync);
          } else {
            intersectionResponse.deletedTxIds.assign(unionResponse.deletedTxIds.begin(), unionResponse.deletedTxIds.end());
            std::error_code ec3 = processPoolTxs(intersectionResponse);

            //notify about error, or success
            m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec3);
          }
        }
      }
    }
  }
}

std::error_code BlockchainSynchronizer::getPoolSymmetricDifferenceSync(GetPoolRequest&& request, GetPoolResponse& response) {
  auto promise = std::promise<std::error_code>();
  auto future = promise.get_future();

  m_node.getPoolSymmetricDifference(
    std::move(request.knownTxIds),
    std::move(request.lastKnownBlock),
    response.isLastKnownBlockActual,
    response.newTxs,
    response.deletedTxIds,
    [&promise](std::error_code ec) {
      auto detachedPromise = std::move(promise);
      detachedPromise.set_value(ec);
    });

  return future.get();
}

std::error_code BlockchainSynchronizer::processPoolTxs(GetPoolResponse& response) {
  std::error_code error;
  {
    std::unique_lock<std::mutex> lk(m_consumersMutex);
    for (auto& consumer : m_consumers) {
      if (checkIfShouldStop()) { //if stop, return immediately, without notification
        return std::make_error_code(std::errc::interrupted);
      }

      error = consumer.first->onPoolUpdated(response.newTxs, response.deletedTxIds);
      if (error) {
        break;
      }
    }
  }

  return error;
}

///pre: m_consumersMutex is locked
SynchronizationState* BlockchainSynchronizer::getConsumerSynchronizationState(IBlockchainConsumer* consumer) const {
  assert(consumer != nullptr);

  if (!(checkIfStopped() && checkIfShouldStop())) {
    throw std::runtime_error("Can't get consumer state, because BlockchainSynchronizer isn't stopped");
  }

  auto it = m_consumers.find(consumer);
  if (it == m_consumers.end()) {
    return nullptr;
  }

  return it->second.get();
}

}


text:
<!doctype html>

  <base href="/">

  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,400i,500" rel="stylesheet">

  <title>Structure Grid Demo</title>

          Structure

          Structure

              Rows and Columns

              Responsive Grid

              Grid Column Sizes

              Shrink Columns

              Horizontal Alignment

              Vertical Alignment

              Block Grid

Introduction

                Structure Flex Grid is a flex-box based grid system for quickly creating the page structure for your html pages.
                Structure follows BEM naming conventions to clearly separate modifiers from elements.
                You can read more about BEM at getbem.com.

              Structure Flex Grid only provides you with the grid to make layout of the pages,
              which means you can easily combine Structure with any other library like Angular-Material.

              It packs some very useful modifiers for rows and columns to achieve the layout of the page you are looking for.
              For example my favorite "--shrink" modifier for columns which I use heavily in my designs. OR "--align--justify" modifier for rows
              which is very useful in making toolbars or rows which should align items to left and right edges.

              Scroll down to read more about all the modifiers.

Installation Instructions

                You can install Structure Flex Grid as an NPM package or you can insert directly in your html page:

Installing with NPM

                Install using NPM with following command

                npm install structure-flex-grid

                After installing import it in your scss file:

                @import '~structure-flex-grid';

Insert directly in your HTML file

                You can get the lastest version from unpkg.com. In the <head> tag of your .html file add:

                <link href="//unpkg.com/structure-flex-grid" rel="stylesheet">

Rows and Columns

                Easy to remember and simple, just add `.row` for Rows and `.column` for Columns. It will automatically be placed evenly distributed.
                Any number of columns can be placed in a row.

                    Col 1

                    Col 2

                    Col 3

                Show markup

Collapsed row (No gutters)

                Add `row--collapse` to the row element (both classes `row` and `row--collapse`).

                *Tip: `--collpase` is a 'modifier' which modifies how the row element behaves when this modifier is
                applied.
                Read more about BEM.

                Note: When making full-width page it is important to add row-collapse to the outermost row.

                    Col 1

                    Col 2

                    Col 3

                Show markup

Responsive Grid

                There are 4 breakpoints for the media queries, which are as follows :

                'small' for phones (320px); 'medium' for tablet sizes (600px); 'large' for desktop sizes (1024px); and; 'huge' for larger screens (1280px);

                You can use classes for columns as :

                column--[small|medium|large|huge]-[1-12]

                examples: column--large-6 OR column--medium-12

                Example below shows columns which will show as 3 columns (of size 4) on large screen but will take full width on medium and small screens
                Resize your browser window to see it take effect.

Column large-4 / medium-12

Column large-4 / medium-12

Column large-4 / medium-12

                Show markup

Grid Column Sizes

2

10

3

9

4

8

5

7

6

6

4

4

4

3

3

3

3

2

2

2

2

2

2

1

1

1

1

1

1

1

1

1

1

1

1

                Show markup

Shrink Columns

Shrink One Column

                Add `column--shrink` modifier class to the column which should shrink.

                When this class is applied, the column shrinks to size of its contents.

                    This column shrinks

                    ... And This Column fills up remaining space

                Show markup

Shrink Multiple Columns

                Your can apply `column--shrink` to multiple columns and the other columns will fill up the remaining space.

                This is very useful in creating items which have multiple links or icons which are right aligned.
                You can simply add `column--shrink` class to each column in the right, something similar to following example:

                    Title of the item here

                    Link One

                    Link Two

                Show markup

Combine it with `row--collapse`

                Building on top of above example, you can combine it with row--collapse modifer for row to get rid of the padding:

                    Title of the item here

                    Link One

                    Link Two

                Show markup

Horizontal Alignment

Center Align

                Add `row--align--center` modifier class to the row to align columns to center

Col 1

Col 2

Col 3

                Show markup

Left Align

                Add `row--align--left` modifier class to the row to align columns to left

Col 1

Col 2

Col 3

                Show markup

Right Align

                Add `row--align--right` modifier class to the row to align columns to right

Col 1

Col 2

Col 3

                Show markup

Align Spaced

                Add `row--align--spaced` modifier class to the row to align columns in a distributed way.
                The remaining space of row will be evenly distributed around the columns

Col 1

Col 2

Col 3

                Show markup

Align Justified

                Add `row--align--justify` modifier class to the row to align columns in a justified manner.
                First column will stick to left edge, Last column will stick to the right edge.

                Remaining Space will be distributed evenly.

Col 1

Col 2

Col 3

                Show markup

Vertical Alignment

Top Align

                Add `row--align--top` modifier class to the row to align columns to top.

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, fuga, sit,
                    deleniti magnam voluptas provident ea excepturi quas assumenda harum quod tempore quo
                    vel accusamus ducimus sint exercitationem repellat blanditiis et dolor qui. Voluptate,
                    saepe porro modi dolore deleniti cum itaque fugit.

Col 2

Col 3

Col 4

                Show markup

Middle Align

                Add `row--align--middle` modifier class to the row to align columns to middle.

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, fuga, sit,
                    deleniti magnam voluptas provident ea excepturi quas

Col 2

Col 3

Col 4

                Show markup

Bottom Align

                Add `row--align--bottome` modifier class to the row to align columns to bottom.

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, fuga, sit,
                    deleniti magnam voluptas provident ea excepturi quas

Col 2

Col 3

Col 4

                Show markup

Self Aligning Columns

                There are three different self--align modifiers available which can be applied to the columns to self-align the columns:

`column--self-align--top`: Aligns column to the top

`column--self-align--middle`: Aligns column to middle

`column--self-align--bottom`: Aligns column to the bottom

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id,
                    alias molestiae rerum illum laborum consequatur voluptates aspernatur delectus saepe accusantium.
                    Vel, quasi totam quae nemo ratione!

Top Aligned

Middle Aligned

Bottom Aligned

                Show markup

Block Grid

                In a `Block Grid` instead of specifying the size for each column, you just let the row know how many columns you want in a row.
                This is great for making responsive pages, as you can specify something like - 5 columns on large screen, and three columns on meduim screen, and
                1 column per row on small screens. This way you don't have to add different column sizes for each column.

                Note: block-grid is not a modifier, rather it is a way to define the grid columns. This needs the .row class applied to the block as well

                Resize this page to see how the following block grid changes from 5 columns per row to 1 column per row:

                    Col 1

Col 2

Col 3

Col 4

Col 5

                Show markup


text:
/**
 * @fileoverview Rule to flag unnecessary bind calls
 * @author Bence Dányi <bence@danyi.me>
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "disallow unnecessary calls to `.bind()`",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-extra-bind"
        },

        schema: [],

        fixable: "code",

        messages: {
            unexpected: "The function binding is unnecessary."
        }
    },

    create(context) {
        let scopeInfo = null;

        /**
         * Reports a given function node.
         *
         * @param {ASTNode} node - A node to report. This is a FunctionExpression or
         *      an ArrowFunctionExpression.
         * @returns {void}
         */
        function report(node) {
            context.report({
                node: node.parent.parent,
                messageId: "unexpected",
                loc: node.parent.property.loc.start,
                fix(fixer) {
                    const firstTokenToRemove = context.getSourceCode()
                        .getFirstTokenBetween(node.parent.object, node.parent.property, astUtils.isNotClosingParenToken);

                    return fixer.removeRange([firstTokenToRemove.range[0], node.parent.parent.range[1]]);
                }
            });
        }

        /**
         * Checks whether or not a given function node is the callee of `.bind()`
         * method.
         *
         * e.g. `(function() {}.bind(foo))`
         *
         * @param {ASTNode} node - A node to report. This is a FunctionExpression or
         *      an ArrowFunctionExpression.
         * @returns {boolean} `true` if the node is the callee of `.bind()` method.
         */
        function isCalleeOfBindMethod(node) {
            const parent = node.parent;
            const grandparent = parent.parent;

            return (
                grandparent &&
                grandparent.type === "CallExpression" &&
                grandparent.callee === parent &&
                grandparent.arguments.length === 1 &&
                parent.type === "MemberExpression" &&
                parent.object === node &&
                astUtils.getStaticPropertyName(parent) === "bind"
            );
        }

        /**
         * Adds a scope information object to the stack.
         *
         * @param {ASTNode} node - A node to add. This node is a FunctionExpression
         *      or a FunctionDeclaration node.
         * @returns {void}
         */
        function enterFunction(node) {
            scopeInfo = {
                isBound: isCalleeOfBindMethod(node),
                thisFound: false,
                upper: scopeInfo
            };
        }

        /**
         * Removes the scope information object from the top of the stack.
         * At the same time, this reports the function node if the function has
         * `.bind()` and the `this` keywords found.
         *
         * @param {ASTNode} node - A node to remove. This node is a
         *      FunctionExpression or a FunctionDeclaration node.
         * @returns {void}
         */
        function exitFunction(node) {
            if (scopeInfo.isBound && !scopeInfo.thisFound) {
                report(node);
            }

            scopeInfo = scopeInfo.upper;
        }

        /**
         * Reports a given arrow function if the function is callee of `.bind()`
         * method.
         *
         * @param {ASTNode} node - A node to report. This node is an
         *      ArrowFunctionExpression.
         * @returns {void}
         */
        function exitArrowFunction(node) {
            if (isCalleeOfBindMethod(node)) {
                report(node);
            }
        }

        /**
         * Set the mark as the `this` keyword was found in this scope.
         *
         * @returns {void}
         */
        function markAsThisFound() {
            if (scopeInfo) {
                scopeInfo.thisFound = true;
            }
        }

        return {
            "ArrowFunctionExpression:exit": exitArrowFunction,
            FunctionDeclaration: enterFunction,
            "FunctionDeclaration:exit": exitFunction,
            FunctionExpression: enterFunction,
            "FunctionExpression:exit": exitFunction,
            ThisExpression: markAsThisFound
        };
    }
};


text:
from pprint import pprint as pp
import requests
import bottle
from bottle import run, route, request, response
import json

# import balancer functions
import balance
# import global config variables
import config

# class to deal with CORS errors
class EnableCors(object):
    name = 'enable_cors'

    def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            # set CORS headers
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

            if bottle.request.method != 'OPTIONS':
                # actual request; reply with the actual response
                return fn(*args, **kwargs)

        return _enable_cors

def main():
    VirtualServerQueue = balance.ServerQue()
    VirtualServerQueue.updateStats(-1)

    app = bottle.app()
    app.install(EnableCors())

    # server route
    @app.route('/',method = 'GET')
    def process():
        return VirtualServerQueue.requestService()

    # functiont to route /stats requests
    @app.route('/stats',method = 'GET')
    def process():
        toreturn = {}
        #vm_id = int(request.query['id']) + start - 1
        vm_id = int(request.query['id']) - 1
        return VirtualServerQueue.updateStats(vm_id)

    # function to return /numserver requests. Returns the number of active VM
    @app.route('/numservers', method = "GET")
    def getservers():
        return {'n': config.servercount}

    # initiate and run the server
    app.run(host="0.0.0.0", port=8070, debug=True)

    pass

if __name__ == '__main__':
    main()


text:
<Record>
<Term>Cartilage Hair Hypoplasia</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Syndrome</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Syndrome/Cartilage Hair Hypoplasia</ClassificationPath>
<BroaderTerm>Syndrome</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Cartilage Hair Hypoplasia</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<Synonym>Cartilage Hair Hypoplasia</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Ozeki.Media.DSP;
using Ozeki.Media.MediaHandlers;
using Ozeki.Media;
using Ozeki.VoIP;
using Ozeki.Media.MediaHandlers.Video;
using Ozeki.Media.Video;
using Ozeki.Media.Video.Imaging;
using System.Windows.Media.Imaging;
using Ozeki.Media.Audio;
using TestSoftphone;
using System.ComponentModel;
using Ozeki.Media.MediaHandlers.Facade;

namespace OzekiDemoSoftphoneWPF.Model
{
    public class MediaHandlers : INotifyPropertyChanged, IDisposable
    {
        #region Fields

        private MediaConnector audioConnector;
        private MediaHandlerCollection audioCollection;

        private MediaConnector videoConnector;
        private MediaHandlerCollection videoCollection;

        private bool initialized;

        #endregion

        #region Audio Handlers

        public Microphone Microphone { get; private set; }
        public Speaker Speaker { get; private set; }
        public AudioQualityEnhancer AudioEnhancer { get; private set; }
        private DtmfEventWavePlayer dtmfPlayer;

        // mixers
        private AudioMixerMediaHandler outgoingDataMixer;
        private AudioMixerMediaHandler speakerMixer;
        private AudioMixerMediaHandler recordDataMixer;

        // phone call handlers
        private PhoneCallAudioSender phoneCallAudioSender;
        private PhoneCallAudioReceiver phoneCallAudioReceiver;

        // audio files
        private WaveStreamRecorder wavRecorder;
        private WaveStreamPlayback wavPlayer;
        private MP3StreamPlayback mp3StreamPlayback;
        private WaveStreamPlayback ringtonePlayer;
        private WaveStreamPlayback ringbackPlayer;

        #endregion

        #region Video Handlers

        public WebCamera WebCamera { get; private set; }

        // image providers
        public ImageProvider<BitmapSource> LocalImageProvider { get; private set; }
        public ImageProvider<BitmapSource> RemoteImageProvider { get; private set; }

        // phone call handlers
        private PhoneCallVideoSender phoneCallVideoSender;
        private PhoneCallVideoReceiver phoneCallVideoReceiver;

        #endregion

        #region Other Properties

        /// <summary>
        /// Gets the available noise reduction levels.
        /// </summary>
        public List<NoiseReductionLevel> NoiseReductionLevels { get; private set; }

        /// <summary>
        /// Gets the level of the microphone.
        /// </summary>
        public float MicrophoneLevel { get; private set; }

        /// <summary>
        /// Gets the level of the speaker.
        /// </summary>
        public float SpeakerLevel { get; private set; }

        /// <summary>
        /// Gets the available microphone devices.
        /// </summary>
        public List<DeviceInfo> Microphones
        {
            get { return Microphone.GetDevices(); }
        }

        /// <summary>
        /// Gets the available speaker devices.
        /// </summary>
        public List<DeviceInfo> Speakers
        {
            get { return Speaker.GetDevices(); }
        }

        /// <summary>
        /// Gets the available camera devices.
        /// </summary>
        public List<VideoDeviceInfo> Cameras
        {
            get { return WebCamera.GetDevices(); }
        }

        /// <summary>
        /// Gets the frame rates that can be set to the camera.
        /// </summary>
        public List<int> FrameRates { get; private set; }

        #endregion

        #region Events

        /// <summary>
        /// Occurs when the level of the microphone has changed.
        /// </summary>
        public event EventHandler<GEventArgs<float>> MicrophoneLevelChanged;

        /// <summary>
        /// Occurs when the the microphone stopped recording.
        /// </summary>
        public event EventHandler<EventArgs> MicrophoneStopped;

        /// <summary>
        /// Occurs when the level of the speaker has changed.
        /// </summary>
        public event EventHandler<GEventArgs<float>> SpeakerLevelChanged;

        /// <summary>
        /// Occurs when the the speaker stopped playing.
        /// </summary>
        public event EventHandler<EventArgs> SpeakerStopped;

        #endregion

        #region Init

        public MediaHandlers()
        {
            NoiseReductionLevels = new List<NoiseReductionLevel>();
            NoiseReductionLevels.Add(NoiseReductionLevel.NoReduction);
            NoiseReductionLevels.Add(NoiseReductionLevel.Low);
            NoiseReductionLevels.Add(NoiseReductionLevel.Medium);
            NoiseReductionLevels.Add(NoiseReductionLevel.High);

            FrameRates = new List<int> {0, 30, 25, 20, 15, 10, 5};

            audioConnector = new MediaConnector();
            videoConnector = new MediaConnector();
        }

        public void Init()
        {
            if (initialized)
                return;

            InitAudio();
            InitVideo();

            if (Microphone != null)
            {
                SubscribeToMicrophoneEvents();
                Microphone.Start();
            }

            if (Speaker != null)
            {
                SubscribeToSpeakerEvents();
                Speaker.Start();
            }

            initialized = true;

            /*
             * Media Connections:
             *
             * +---------------------------------------------------------------+
             * |                           PhoneCall                           |***********
             * +---------------------------------------------------------------+          *
             *              ^^                              VV                            *
             *     +--------------------+          +----------------------+  +----+   +---------+  +-----+
             *     |PhoneCallAudioSender|          |PhoneCallAudioReceiver|  |DMTF|   |Ringtones|  | TTS |
             *     +--------------------+          +----------------------+  +----+   +---------+  +-----+
             *                ^^                          V             V       V        |           |
             *       +-----------------+         +---------------+   +------------+      |           |
             *       |OutgoingDataMixer|--->>----|RecordDataMixer|   |SpeakerMixer|--<<--/----<<-----/
             *       +-----------------+         +---------------+   +------------+
             *         ^^          ^^                V                  |
             *+--------------+   +---------+    +-----------+           |
             *|AudioEnhancer |   |WavPlayer|    |WavRecorder|           V
             *+--------------+   +---------+    +-----------+           V
             *        ^^                                                |
             *    +----------+                                       +-------+
             *    |Microphone|                                       |Speaker|
             *    +----------+                                       +-------+
             */
        }

        /// <summary>
        /// Initializes the audio handlers (microphone, speaker, DTMF player etc.).
        /// </summary>
        private void InitAudio()
        {
            // ----- CREATE -----
            // devices
            Microphone = Microphone.GetDefaultDevice();
            Speaker = Speaker.GetDefaultDevice();

            // audio processors
            AudioEnhancer = new AudioQualityEnhancer();
            AudioEnhancer.SetEchoSource(Speaker);
            dtmfPlayer = new DtmfEventWavePlayer();

            // ringtones
            var ringbackStream = LoadRingbackStream();
            var ringtoneStream = LoadRingtoneStream();
            ringtonePlayer = new WaveStreamPlayback(ringtoneStream, true, false);
            ringbackPlayer = new WaveStreamPlayback(ringbackStream, true, false);

            // mixers
            outgoingDataMixer = new AudioMixerMediaHandler();
            speakerMixer = new AudioMixerMediaHandler();
            recordDataMixer = new AudioMixerMediaHandler();

            // phone handlers
            phoneCallAudioSender = new PhoneCallAudioSender();
            phoneCallAudioReceiver = new PhoneCallAudioReceiver();

            // ----- CONNECT -----
            // connect outgoing
            audioConnector.Connect(AudioEnhancer, outgoingDataMixer);
            audioConnector.Connect(outgoingDataMixer, phoneCallAudioSender);
            audioConnector.Connect(outgoingDataMixer, recordDataMixer);
            if (Microphone != null)
            {
                Microphone.LevelChanged += (Microphone_LevelChanged);
                audioConnector.Connect(Microphone, AudioEnhancer);
            }

            // connect incoming
            audioConnector.Connect(phoneCallAudioReceiver, speakerMixer);
            audioConnector.Connect(phoneCallAudioReceiver, recordDataMixer);
            audioConnector.Connect(ringtonePlayer, speakerMixer);
            audioConnector.Connect(ringbackPlayer, speakerMixer);
            audioConnector.Connect(dtmfPlayer, speakerMixer);
            if (Speaker != null)
            {
                Speaker.LevelChanged += (Speaker_LevelChanged);
                audioConnector.Connect(speakerMixer, Speaker);
            }

            // add to collection
            Dictionary<string, VoIPMediaHandler> collection = new Dictionary<string, VoIPMediaHandler>();
            collection.Add("AudioEnhancer", AudioEnhancer);
            collection.Add("DTMFPlayer", dtmfPlayer);
            collection.Add("OutgoingDataMixer", outgoingDataMixer);
            collection.Add("SpeakerMixer", speakerMixer);
            collection.Add("PhoneCallAudioSender", phoneCallAudioSender);
            collection.Add("PhoneCallAudioReceiver", phoneCallAudioReceiver);
            audioCollection = new MediaHandlerCollection(audioConnector, collection);
        }

        private Stream LoadRingbackStream()
        {
            Stream ringback = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "OzekiDemoSoftphoneWPF.Resources.ringback.wav");

            if (ringback == null)
                throw new Exception("Cannot load default ringback.");

            return ringback;
        }

        private Stream LoadRingtoneStream()
        {
            Stream basicRing = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "OzekiDemoSoftphoneWPF.Resources.basic_ring.wav");

            if (basicRing == null)
                throw new Exception("Cannot load default ringtone.");

            return basicRing;
        }

        /// <summary>
        /// Initializes the video handlers (camera, image providers etc.).
        /// </summary>
        private void InitVideo()
        {
            // ----- CREATE -----
            WebCamera = WebCamera.GetDefaultDevice();

            LocalImageProvider = new BitmapSourceProvider();
            RemoteImageProvider = new BitmapSourceProvider();

            phoneCallVideoReceiver = new PhoneCallVideoReceiver();
            phoneCallVideoSender = new PhoneCallVideoSender();

            // ----- CONNECT -----
            videoConnector.Connect(phoneCallVideoReceiver, RemoteImageProvider);
            if (WebCamera != null)
            {
                videoConnector.Connect(WebCamera, LocalImageProvider);
                videoConnector.Connect(WebCamera, phoneCallVideoSender);
            }

            // add to collection
            Dictionary<string, VoIPMediaHandler> collection = new Dictionary<string, VoIPMediaHandler>();
            collection.Add("LocalImageProvider", LocalImageProvider);
            collection.Add("RemoteImageProvider", RemoteImageProvider);
            collection.Add("PhoneCallVideoReceiver", phoneCallVideoReceiver);
            collection.Add("PhoneCallVideoSender", phoneCallVideoSender);
            videoCollection = new MediaHandlerCollection(videoConnector, collection);
        }

        #endregion

        #region Invocators

        private void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private void OnSpeakerLevelChanged(float value)
        {
            var handler = SpeakerLevelChanged;
            if (handler != null)
                handler(this, new GEventArgs<float>(value));
        }

        private void OnMicrophoneLevelChanged(float value)
        {
            var handler = MicrophoneLevelChanged;
            if (handler != null)
                handler(this, new GEventArgs<float>(value));
        }

        #endregion

        #region Audio EventHandlers

        /// <summary>
        /// This will be called when the level of the microphone has changed.
        /// </summary>
        private void Microphone_LevelChanged(object sender, VoIPEventArgs<float> e)
        {
            MicrophoneLevel = e.Item;
            OnPropertyChanged("MicrophoneLevel");

            OnMicrophoneLevelChanged(e.Item);
        }

        /// <summary>
        /// This will be called when the level of the speaker has changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Speaker_LevelChanged(object sender, VoIPEventArgs<float> e)
        {
            SpeakerLevel = e.Item;
            OnPropertyChanged("SpeakerLevel");

            OnSpeakerLevelChanged(e.Item);
        }

        #endregion

        #region Microphone

        /// <summary>
        /// Changes the microphone device.
        /// </summary>
        public void ChangeMicrophone(DeviceInfo deviceInfo)
        {
            if (!initialized)
                return;

            float prevVolume = 0;
            bool prevMuted = false;

            if (Microphone != null)
            {
                // same device
                if (Microphone.DeviceInfo.Equals(deviceInfo))
                    return;

                // backup settings
                prevVolume = Microphone.Volume;
                prevMuted = Microphone.Muted;

                // dispose previous device
                audioConnector.Disconnect(Microphone, AudioEnhancer);
                UnsubscribeFromMicrophoneEvents();
                Microphone.Dispose();
            }

            // create new microphone
            Microphone = Microphone.GetDevice(deviceInfo);

            if (Microphone != null)
            {
                SubscribeToMicrophoneEvents();
                audioConnector.Connect(Microphone, AudioEnhancer);

                // set prev device settings
                Microphone.Volume = prevVolume;
                Microphone.Muted = prevMuted;
                Microphone.Start();
            }

            OnPropertyChanged("Microphone");
        }

        private void SubscribeToMicrophoneEvents()
        {
            if (Microphone == null)
                return;

            Microphone.LevelChanged += (Microphone_LevelChanged);
            Microphone.Stopped += Microphone_Stopped;
        }

        private void UnsubscribeFromMicrophoneEvents()
        {
            if (Microphone == null)
                return;

            Microphone.LevelChanged -= (Microphone_LevelChanged);
            Microphone.Stopped -= Microphone_Stopped;
        }

        void Microphone_Stopped(object sender, EventArgs e)
        {
            var handler = MicrophoneStopped;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        #endregion

        #region Speaker

        /// <summary>
        /// Changes the speaker device and sets the volume and muted property of the new device.
        /// </summary>
        public void ChangeSpeaker(DeviceInfo deviceInfo)
        {
            if (!initialized)
                return;

            float prevVolume = 0;
            bool prevMuted = false;

            if (Speaker != null)
            {
                // same device
                if (Speaker.DeviceInfo.Equals(deviceInfo))
                    return;

                // backup settings
                prevVolume = Speaker.Volume;
                prevMuted = Speaker.Muted;

                // dispose previous device
                audioConnector.Disconnect(speakerMixer, Speaker);
                UnsubscribeFromSpeakerEvents();
                Speaker.Dispose();

                AudioEnhancer.SetEchoSource(null);
            }

            // create new microphone
            Speaker = Speaker.GetDevice(deviceInfo);

            if (Speaker != null)
            {
                SubscribeToSpeakerEvents();
                audioConnector.Connect(speakerMixer, Speaker);

                // set prev device settings
                Speaker.Volume = prevVolume;
                Speaker.Muted = prevMuted;
                Speaker.Start();

                AudioEnhancer.SetEchoSource(Speaker);
            }

            OnPropertyChanged("Speaker");
        }

        private void SubscribeToSpeakerEvents()
        {
            if (Speaker == null)
                return;

            Speaker.LevelChanged += (Speaker_LevelChanged);
            Speaker.Stopped += Speaker_Stopped;
        }

        private void UnsubscribeFromSpeakerEvents()
        {
            if (Speaker == null)
                return;

            Speaker.LevelChanged -= (Speaker_LevelChanged);
            Speaker.Stopped -= Speaker_Stopped;
        }

        void Speaker_Stopped(object sender, EventArgs e)
        {
            var handler = SpeakerStopped;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

        #endregion

        #region Camera

        /// <summary>
        /// Changes the camera device.
        /// </summary>
        public void ChangeCamera(int deviceID)
        {
            if (!initialized)
                return;

            // same device
            if (WebCamera != null && WebCamera.DeviceID == deviceID)
                return;

            // find the proper info
            VideoDeviceInfo newDeviceInfo = null;
            foreach (var info in Cameras)
            {
                if (info.DeviceID != deviceID)
                    continue;

                newDeviceInfo = info;
                break;
            }

            if (newDeviceInfo == null)
                return;

            // begin change device
            bool capturing = false;

            if (WebCamera != null)
            {
                // disconnect
                if (LocalImageProvider != null)
                    audioConnector.Disconnect(WebCamera, LocalImageProvider);
                audioConnector.Disconnect(WebCamera, phoneCallVideoSender);

                // dispose previous device
                capturing = WebCamera.Capturing;
                WebCamera.Stop();
                WebCamera.Dispose();
            }

            // create new
            WebCamera = WebCamera.GetDevice(newDeviceInfo);

            if (WebCamera != null)
            {
                audioConnector.Connect(WebCamera, LocalImageProvider);
                audioConnector.Connect(WebCamera, phoneCallVideoSender);

                if (capturing)
                    WebCamera.Start();
            }

            OnPropertyChanged("WebCamera");
        }

        /// <summary>
        /// Gets the supported video resolutions of the camera.
        /// </summary>
        /// <returns></returns>
        public List<Resolution> GetVideoResolutions()
        {
            var resolutions = new List<Resolution>();

            if (WebCamera == null)
                return resolutions;

            List<VideoCapabilities> capabilities = WebCamera.Capabilities;
            if (capabilities == null)
                return resolutions;

            resolutions.AddRange(capabilities.Select(cap => new Resolution(cap.Resolution.Width, cap.Resolution.Height)));

            return resolutions;
        }

        #endregion

        #region DTMF

        /// <summary>
        /// Starts playing the DTMF signal.
        /// </summary>
        internal void StartDtmf(DtmfNamedEvents signal)
        {
            if (!initialized)
                return;

            dtmfPlayer.Start(signal);
        }

        /// <summary>
        /// Starts playing the DTMF signal.
        /// </summary>
        internal void StartDtmf(int signal)
        {
            if (!initialized)
                return;

            dtmfPlayer.Start(signal);
        }

        /// <summary>
        /// Stops playing the DTMF signal.
        /// </summary>
        internal void StopDtmf(DtmfNamedEvents signal)
        {
            if (!initialized)
                return;

            dtmfPlayer.Stop();
        }

        /// <summary>
        /// Stops playing the DTMF signal.
        /// </summary>
        internal void StopDtmf(int signal)
        {
            if (!initialized)
                return;

            dtmfPlayer.Stop();
        }

        #endregion

        #region Wav Playback

        /// <summary>
        /// Loads a wav file for playback.
        /// </summary>
        public void LoadPlaybackWavFile(string filePath)
        {
            if (!initialized)
                return;

            if (wavPlayer != null)
            {
                audioConnector.Disconnect(wavPlayer, outgoingDataMixer);
                wavPlayer.Dispose();
                wavRecorder = null;
            }

            wavPlayer = new WaveStreamPlayback(filePath, false, true);

            audioConnector.Connect(wavPlayer, outgoingDataMixer);
        }

        /// <summary>
        /// Starts streaming the wav file.
        /// </summary>
        public void StartWavPlayback()
        {
            if (wavPlayer == null)
                return;

            wavPlayer.StartStreaming();
        }

        /// <summary>
        /// Pauses the wav file streaming.
        /// </summary>
        public void PauseWavPlayback()
        {
            if (wavPlayer == null)
                return;

            wavPlayer.PauseStreaming();
        }

        /// <summary>
        /// Stops streaming the wav file.
        /// </summary>
        public void StopWavPlayback()
        {
            if (wavPlayer == null)
                return;

            wavPlayer.StopStreaming();
        }

        #endregion

        #region Wav Record

        /// <summary>
        /// Loads a wav file for playback.
        /// </summary>
        public void LoadRecordWavFile(string filePath)
        {
            if (!initialized)
                return;

            if (wavRecorder != null)
            {
                audioConnector.Disconnect(recordDataMixer, wavRecorder);
                wavRecorder.Dispose();
                wavRecorder = null;
            }

            wavRecorder = new WaveStreamRecorder(filePath);

            audioConnector.Connect(recordDataMixer, wavRecorder);
        }

        /// <summary>
        /// Starts recording the audio into a wav file.
        /// </summary>
        public void StartWavRecording()
        {
            if (wavRecorder == null)
                return;

            wavRecorder.StartStreaming();
        }

        /// <summary>
        /// Pauses the wav recording.
        /// </summary>
        public void PauseWavRecording()
        {
            if (wavRecorder == null)
                return;

            wavRecorder.PauseStreaming();
        }

        /// <summary>
        /// Stops wav recording.
        /// </summary>
        public void StopWavRecording()
        {
            if (wavRecorder == null)
                return;

            wavRecorder.StopStreaming();
            wavRecorder.Dispose();
        }

        #endregion

        #region MP3 Playback

        /// <summary>
        /// Loads an mp3 file for playback.
        /// </summary>
        public void LoadPlaybackMP3File(string filePath)
        {
            if (!initialized)
                return;

            if (mp3StreamPlayback != null)
            {
                audioConnector.Disconnect(mp3StreamPlayback, outgoingDataMixer);
                mp3StreamPlayback.Dispose();
                mp3StreamPlayback = null;
            }

            mp3StreamPlayback = new MP3StreamPlayback(filePath, false, true);

            audioConnector.Connect(mp3StreamPlayback, outgoingDataMixer);
        }

        /// <summary>
        /// Starts recording the audio into a wav file.
        /// </summary>
        public void StartMP3Playback()
        {
            if (mp3StreamPlayback == null)
                return;

            mp3StreamPlayback.StartStreaming();
        }

        /// <summary>
        /// Pauses the wav recording.
        /// </summary>
        public void PauseMP3Playback()
        {
            if (mp3StreamPlayback == null)
                return;

            mp3StreamPlayback.PauseStreaming();
        }

        /// <summary>
        /// Stops wav recording.
        /// </summary>
        public void StopMP3Playback()
        {
            if (mp3StreamPlayback == null)
                return;

            mp3StreamPlayback.StopStreaming();
        }

        #endregion

        #region Ringtones

        internal void SetRingtone(string filePath)
        {
            bool isStreaming = false;

            // dispose previous
            if (ringtonePlayer != null)
            {
                isStreaming = ringtonePlayer.IsStreaming;

                audioConnector.Disconnect(ringtonePlayer, speakerMixer);
                ringtonePlayer.Dispose();
                ringtonePlayer = null;
            }

            // create new
            ringtonePlayer = new WaveStreamPlayback(filePath, true, true);

            audioConnector.Connect(ringtonePlayer, speakerMixer);

            // start if necessary
            if (isStreaming)
                ringtonePlayer.StartStreaming();
        }

        public void StartRingtone()
        {
            if (ringtonePlayer != null)
                ringtonePlayer.StartStreaming();
        }

        public void StopRingtone()
        {
            if (ringtonePlayer != null)
                ringtonePlayer.StopStreaming();
        }

        internal void SetRingback(string filePath)
        {
            bool isStreaming = false;

            // dispose previous
            if (ringbackPlayer != null)
            {
                isStreaming = ringbackPlayer.IsStreaming;
                audioConnector.Disconnect(ringbackPlayer, speakerMixer);
                ringbackPlayer.Dispose();
                ringbackPlayer = null;
            }

            // create new
            ringbackPlayer = new WaveStreamPlayback(filePath, true, true);
            audioConnector.Connect(ringbackPlayer, speakerMixer);

            // start if necessary
            if (isStreaming)
                ringbackPlayer.StartStreaming();
        }

        public void StartRingback()
        {
            if (ringbackPlayer != null)
                ringbackPlayer.StartStreaming();
        }

        public void StopRingback()
        {
            if (ringbackPlayer != null)
                ringbackPlayer.StopStreaming();
        }

        #endregion

        #region Audio Control

        /// <summary>
        /// Attaches the media handlers to the given phone call.
        /// </summary>
        public void AttachAudio(IPhoneCall call)
        {
            phoneCallAudioSender.AttachToCall(call);
            if (audioCollection != null)
                audioCollection.AttachToCall(call);
        }

        /// <summary>
        /// Detaches the media handlers from the phone call.
        /// </summary>
        public void DetachAudio()
        {
            if (audioCollection != null)
                audioCollection.Detach();
        }

        #endregion

        #region Video Control

        /// <summary>
        /// Attaches the media handlers to the given phone call.
        /// </summary>
        public void AttachVideo(IPhoneCall call)
        {
            if (videoCollection != null)
                videoCollection.AttachToCall(call);
        }

        /// <summary>
        /// Detaches the media handlers from the phone call.
        /// </summary>
        public void DetachVideo()
        {
            if (videoCollection != null)
                videoCollection.Detach();
        }

        /// <summary>
        /// Starts the video handlers.
        /// </summary>
        public void StartVideo()
        {
            if (WebCamera != null)
                WebCamera.Start();

            if (videoCollection != null)
                videoCollection.Start();
        }

        /// <summary>
        /// Stops the video handlers.
        /// </summary>
        public void StopVideo()
        {
            if (WebCamera != null)
                WebCamera.Stop();

            if (videoCollection != null)
                videoCollection.Stop();
        }

        #endregion

        #region Dispose

        public void Dispose()
        {
            // audio
            if (audioCollection != null)
                audioCollection.Dispose();

            if (audioConnector != null)
                audioConnector.Dispose();

            if (Microphone != null)
            {
                UnsubscribeFromMicrophoneEvents();
                Microphone.Dispose();
            }

            if (Speaker != null)
            {
                UnsubscribeFromSpeakerEvents();
                Speaker.Dispose();
            }

            if (wavRecorder != null)
                wavRecorder.Dispose();

            if (wavPlayer != null)
                wavPlayer.Dispose();

            if (mp3StreamPlayback != null)
                mp3StreamPlayback.Dispose();

            if (ringtonePlayer != null)
                ringtonePlayer.Dispose();

            if (ringbackPlayer != null)
                ringbackPlayer.Dispose();

            // video
            if (videoCollection != null)
                videoCollection.Dispose();

            if (videoConnector != null)
                videoConnector.Dispose();

            if (WebCamera != null)
                WebCamera.Dispose();
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}


text:
Up
==

Positive Feeling Business App


text:
package ch05initialization;

/**
 * Demonstration of a simple constructor.
 *
 * <pre>
 * Output:
 * Rock Rock Rock Rock Rock Rock Rock Rock Rock Rock
 * </pre>
 */
class Rock {
	Rock() { // This is the constructor
		System.out.print("Rock ");
	}
}

public class D01_SimpleConstructor {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++)
			new Rock();
	}
}


text:
package de.iritgo.aktera.persist;

import de.iritgo.aktera.core.exception.NestedException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

/**
 * Used to report a problem at the persistence level
 *
 * @author Michael Nash
 */
public class PersistenceException extends NestedException
{
	private Map errorMap = null;

	/**
	 * Most PersistenceException will be created using one of the custom
	 * constructors. Basically, there are three arguments, each of which is
	 * optional, that always appear in the same order: 1: the string message
	 * for the exception being created 2: the nested exception (or nested
	 * throwable, actually) 3: the exception "key" - for internationalization
	 *
	 * Any of these can be left out or passed as null, as required in the
	 * situation.
	 */

	/**
	 * Default constructor
	 */
	public PersistenceException()
	{
		super();
	} /* PersistenceException() */

	/**
	 * Constructor with a single message, no key
	 *
	 * @param s
	 *            exception message
	 */
	public PersistenceException(String s)
	{
		super(s);
	} /* PersistenceException */

	/**
	 * Constructor with a single message, no key
	 *
	 * @param s
	 *            exception message
	 */
	public PersistenceException(String s, Map m)
	{
		super(s);
		addErrors(m);
	} /* PersistenceException */

	/**
	 * String message and error key
	 */
	public PersistenceException(String s, String newErrorKey)
	{
		super(s, newErrorKey);
	}

	/**
	 * Constructor with a message and a nested exception
	 *
	 * @param s
	 *            The exception message
	 * @param newNested
	 *            The nested item
	 */
	public PersistenceException(String message, Throwable newNested)
	{
		super(message, newNested);
	} /* PersistenceException(String, Throwable) */

	/**
	 * Constructor with a message and a nested exception
	 *
	 * @param s
	 *            The exception message
	 * @param newNested
	 *            The nested item
	 */
	public PersistenceException(String message, Throwable newNested, Map m)
	{
		super(message, newNested);
		addErrors(m);
	} /* PersistenceException(String, Throwable) */

	/**
	 * Constructor with a single message and a nested exception with error key
	 *
	 * @param s
	 *            The exception message
	 * @param newNested
	 *            The nested item
	 * @param errorKey
	 *            A string key to the messages bundle
	 */
	public PersistenceException(String message, Throwable newNested, String newErrorKey)
	{
		super(message, newNested, newErrorKey);
	} /* PersistenceException(String, Throwable, String) */

	public PersistenceException(String message, Throwable newNested, String newErrorKey, Map m)
	{
		super(message, newNested, newErrorKey);
		addErrors(m);
	}

	/**
	 * Constructor with no message and a nested exception
	 *
	 * @param newNested
	 *            The nested exception
	 */
	public PersistenceException(Throwable newNested)
	{
		super(newNested);
	} /* PersistenceException(Throwable) */

	public PersistenceException(Throwable newNested, Map m)
	{
		super(newNested);
		addErrors(m);
	}

	/**
	 * Constructor with no message and a nested exception, but with an error
	 * key
	 *
	 * @param newNested
	 *            The nested exception
	 */
	public PersistenceException(Throwable newNested, String newErrorKey)
	{
		super(newNested, newErrorKey);
	} /* PersistenceException(Throwable) */

	public PersistenceException(Throwable newNested, String newErrorKey, Map m)
	{
		super(newNested, newErrorKey);
		addErrors(m);
	} /* PersistenceException(Throwable) */

	/**
	 * Add a Map of errors as detail errors for this overall exception
	 */
	public void addErrors(Map m)
	{
		errorMap = m;
	}

	public Map getErrors()
	{
		return errorMap;
	}

	/**
	 * Extend printStackTrace to handle the nested Error Map
	 *
	 * @param p
	 *            The PrintStream to write the exception messages into
	 */
	public void printStackTrace(PrintStream p)
	{
		super.printStackTrace(p);

		if (errorMap != null)
		{
			p.println("Error Map:-------------");

			String oneKey = null;
			Object val = null;

			for (Iterator i = errorMap.keySet().iterator(); i.hasNext();)
			{
				oneKey = i.next().toString();
				p.print(oneKey + ":");
				val = errorMap.get(oneKey);

				if (val instanceof Throwable)
				{
					((Throwable) val).printStackTrace(p);
				}
				else
				{
					p.println(val.toString());
				}
			}
		}
	}

	/**
	 * Extend printStackTrace to handle the nested Error Map
	 *
	 * @param p
	 *          The PrintWriter to write the exception messages into
	 */
	public void printStackTrace(PrintWriter p)
	{
		super.printStackTrace(p);

		if (errorMap != null)
		{
			p.println("Error Map:-------------");

			String oneKey = null;
			Object val = null;

			for (Iterator i = errorMap.keySet().iterator(); i.hasNext();)
			{
				oneKey = i.next().toString();
				p.print(oneKey + ":");
				val = errorMap.get(oneKey);

				if (val instanceof Throwable)
				{
					((Throwable) val).printStackTrace(p);
				}
				else
				{
					p.println(val.toString());
				}
			}
		}
	}
} /* PersistenceException */


text:
package TechNodefirmacraft.items;

import TechNodefirmacraft.core.CreativeTab;
import TechNodefirmacraft.core.ModDetails;
import com.bioxx.tfc.Items.ItemTerra;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.util.IIcon;

public class ItemBase extends ItemTerra {
    private IIcon[] icons;

    public ItemBase() {
        super();
        setCreativeTab(CreativeTab.TNFC_TAB);
    }

    @Override
    public void registerIcons(IIconRegister registerer) {
        if (this.metaNames == null) {
            if (this.iconString != null)
                this.itemIcon = registerer.registerIcon(ModDetails.ModID + ":" + this.textureFolder + this.getIconString());
            else
                this.itemIcon = registerer.registerIcon(ModDetails.ModID + ":" + this.textureFolder + this.getUnlocalizedName().replace("item.", ""));
        } else {
            metaIcons = new IIcon[metaNames.length];
            for (int i = 0; i < metaNames.length; i++) {
                metaIcons[i] = registerer.registerIcon(ModDetails.ModID + ":" + this.textureFolder + metaNames[i]);
            }

            //This will prevent NullPointerException errors with other mods like NEI
            this.itemIcon = metaIcons[0];
        }
    }
}


text:
<?php

namespace App\Controller\Infrastructure\Action;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

trait NewActionControllerTrait
{
    protected $form;

    public function baseNew(Request $request)
    {
        if (!isset($this->view)) {
            throw new \Exception('No view defined!');
        }

        return $this->render($this->view, [
            'actionBar' => $this->actionBar,
            'form' => $this->form->createView(),
        ]);
    }

    /**
     * Set Entity Form.
     *
     * @param Form $form
     */
    public function setForm(Form $form)
    {
        $this->form = $form;
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import random
import os
from captcha.image import ImageCaptcha

import config

IMAGE_HEIGHT = config.IMAGE_HEIGHT
IMAGE_WIDTH = config.IMAGE_WIDTH
CHARS_NUM = config.CHARS_NUM

TEST_SIZE = 1000
TRAIN_SIZE = 50000
VALID_SIZE = 20000

FLAGS = None

def gen(gen_dir, total_size, chars_num):
  if not os.path.exists(gen_dir):
    os.makedirs(gen_dir)
  image = ImageCaptcha(width=IMAGE_WIDTH, height=IMAGE_HEIGHT,font_sizes=[40])
  # must be subset of config.CHAR_SETS
  char_sets = 'ABCDEFGHIJKLMNPQRSTUVWXYZ'
  for i in xrange(total_size):
    label = ''.join(random.sample(char_sets, chars_num))
    image.write(label, os.path.join(gen_dir, label+'_num'+str(i)+'.png'))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--test_dir',
      type=str,
      default='./data/test_data',
      help='Directory testing to generate captcha data files'
  )
  parser.add_argument(
      '--train_dir',
      type=str,
      default='./data/train_data',
      help='Directory training to generate captcha data files'
  )
  parser.add_argument(
      '--valid_dir',
      type=str,
      default='./data/valid_data',
      help='Directory validation to generate captcha data files'
  )
  FLAGS, unparsed = parser.parse_known_args()
  print('>> generate %d captchas in %s' % (TEST_SIZE, FLAGS.test_dir))
  gen(FLAGS.test_dir, TEST_SIZE, CHARS_NUM)
  print ('>> generate %d captchas in %s' % (TRAIN_SIZE, FLAGS.train_dir))
  gen(FLAGS.train_dir, TRAIN_SIZE, CHARS_NUM)
  print ('>> generate %d captchas in %s' % (VALID_SIZE, FLAGS.valid_dir))
  gen(FLAGS.valid_dir, VALID_SIZE, CHARS_NUM)
  print ('>> generate Done!')


text:
class GURL;

namespace blink {
class WebFrame;
class WebSecurityOrigin;
class WebURL;
}

namespace extensions {
class Dispatcher;
}

namespace atom {
class ContentSettingsManager;
}

// Handles blocking content per content settings for each RenderFrame.
class ContentSettingsObserver
    : public content::RenderFrameObserver,
      public content::RenderFrameObserverTracker<ContentSettingsObserver>,
      public blink::WebContentSettingsClient {
 public:
  ContentSettingsObserver(content::RenderFrame* render_frame,
                          extensions::Dispatcher* extension_dispatcher,
                          bool should_whitelist,
                          service_manager::BinderRegistry* registry);
  ~ContentSettingsObserver() override;

  void SetContentSettingRules(
      const RendererContentSettingRules* content_setting_rules);

  void SetContentSettingsManager(
      atom::ContentSettingsManager* content_settings_manager);

  bool IsPluginTemporarilyAllowed(const std::string& identifier);

  // Sends an IPC notification that the specified content type was blocked.
  void DidBlockContentType(ContentSettingsType settings_type);

  // Sends an IPC notification that the specified content type was blocked
  // with additional metadata.
  void DidBlockContentType(ContentSettingsType settings_type,
                           const base::string16& details);

  // Sends an IPC notification that the specified content type was blocked.
  void DidBlockContentType(const std::string& settings_type);

  // Sends an IPC notification that the specified content type was blocked
  // with additional metadata.
  void DidBlockContentType(const std::string& settings_type,
                           const std::string& details);

  // blink::WebContentSettingsClient implementation.
  bool AllowDatabase(const blink::WebString& name,
                     const blink::WebString& display_name,
                     unsigned estimated_size) override;  // NOLINT
  void RequestFileSystemAccessAsync(
          const blink::WebContentSettingCallbacks& callbacks) override;
  bool AllowImage(bool enabled_per_settings,
                  const blink::WebURL& image_url) override;
  bool AllowIndexedDB(const blink::WebString& name,
                      const blink::WebSecurityOrigin& origin) override;
  bool AllowScript(bool enabled_per_settings) override;
  bool AllowScriptFromSource(bool enabled_per_settings,
                             const blink::WebURL& script_url) override;
  bool AllowStorage(bool local) override;
  bool AllowReadFromClipboard(bool default_value) override;
  bool AllowWriteToClipboard(bool default_value) override;
  bool AllowMutationEvents(bool default_value) override;
  bool AllowRunningInsecureContent(bool allowed_per_settings,
                                   const blink::WebSecurityOrigin& context,
                                   const blink::WebURL& url) override;
  bool AllowAutoplay(bool defaultValue) override;
  void DidNotAllowPlugins() override;
  void DidNotAllowScript() override;

  bool allow_running_insecure_content() const {
    return allow_running_insecure_content_;
  }

 private:
  void DidRunInsecureContent(GURL resouce_url);
  void DidBlockRunInsecureContent(GURL resouce_url);

  // RenderFrameObserver implementation.
  bool OnMessageReceived(const IPC::Message& message) override;
  void DidCommitProvisionalLoad(bool is_new_navigation,
                                bool is_same_page_navigation) override;
  void OnDestruct() override;
  // Resets the |content_blocked_| array.
  void ClearBlockedContentSettings();

  void OnLoadBlockedPlugins(const std::string& identifier);

  // Helpers.
  // True if |render_frame()| contains content that is white-listed for content
  // settings.
  bool IsWhitelistedForContentSettings() const;
  static bool IsWhitelistedForContentSettings(
      const blink::WebSecurityOrigin& origin,
      const GURL& document_url);

  // Owned by ChromeContentRendererClient and outlive us.
  extensions::Dispatcher* extension_dispatcher_;
  atom::ContentSettingsManager* content_settings_manager_;  // not owned

  // Insecure content may be permitted for the duration of this render view.
  bool allow_running_insecure_content_;

  // A pointer to content setting rules stored by the renderer. Normally, the
  // |RendererContentSettingRules| object is owned by
  // |ChromeRenderThreadObserver|. In the tests it is owned by the caller of
  // |SetContentSettingRules|.
  const RendererContentSettingRules* content_setting_rules_;

  // Stores if images, scripts, and plugins have actually been blocked.
  std::map<ContentSettingsType, bool> content_blocked_;

  // Caches the result of AllowStorage.
  typedef std::pair<GURL, bool> StoragePermissionsKey;
  std::map<StoragePermissionsKey, bool> cached_storage_permissions_;

  // Caches the result of AllowScript.
  std::map<blink::WebFrame*, bool> cached_script_permissions_;

  std::set<std::string> temporarily_allowed_plugins_;
  bool is_interstitial_page_;

  int current_request_id_;
  typedef std::map<int, blink::WebContentSettingCallbacks> PermissionRequestMap;
  PermissionRequestMap permission_requests_;

  // If true, IsWhitelistedForContentSettings will always return true.
  const bool should_whitelist_;

  DISALLOW_COPY_AND_ASSIGN(ContentSettingsObserver);
};

#endif  // CHROME_RENDERER_CONTENT_SETTINGS_OBSERVER_H_


text:
package tmdb

import (
	. "gopkg.in/check.v1"
)

const darkKnightID int = 49026
const fightClubID int = 550
const takenThreeID int = 260346

func (s *TmdbSuite) TestGetMovieInfo(c *C) {
	result, err := s.tmdb.GetMovieInfo(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Title, Equals, "Fight Club")
	c.Assert(result.ID, Equals, fightClubID)

	var options = make(map[string]string)
	options["append_to_response"] = "alternative_titles,credits,images,keywords,releases,videos,translations,similar,reviews,lists,changes,ratings"
	allResult, err := s.tmdb.GetMovieInfo(fightClubID, options)
	s.baseTest(&allResult, err, c)
	c.Assert(allResult.Title, Equals, "Fight Club")
	c.Assert(allResult.ID, Equals, fightClubID)
	c.Assert(allResult.AlternativeTitles, NotNil)
	c.Assert(allResult.Credits, NotNil)
	c.Assert(allResult.Images, NotNil)
	c.Assert(allResult.Keywords, NotNil)
	c.Assert(allResult.Releases, NotNil)
	c.Assert(allResult.Videos, NotNil)
	c.Assert(allResult.Translations, NotNil)
	c.Assert(allResult.Similar, NotNil)
	c.Assert(allResult.Reviews, NotNil)
	c.Assert(allResult.Lists, NotNil)
	c.Assert(allResult.Changes, NotNil)
}

func (s *TmdbSuite) TestGetMovieAccountStates(c *C) {
	result, err := s.tmdb.GetMovieAccountStates(fightClubID, s.session)
	s.baseTest(&result, err, c)
}

func (s *TmdbSuite) TestGetMovieAlternativeTitles(c *C) {
	result, err := s.tmdb.GetMovieAlternativeTitles(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Titles, Not(HasLen), 0)
	c.Assert(result.Titles[0].Iso3166_1, Equals, "PL")
}

func (s *TmdbSuite) TestGetMovieChanges(c *C) {
	result, err := s.tmdb.GetMovieChanges(takenThreeID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Changes, NotNil)
	allResultLength := len(result.Changes)

	var janOptions = make(map[string]string)
	janOptions["start_date"] = "2015-01-01"
	janOptions["end_date"] = "2015-01-14"
	janResult, err := s.tmdb.GetMovieChanges(takenThreeID, janOptions)
	s.baseTest(&janResult, err, c)
	c.Assert(janResult.Changes, NotNil)
	c.Assert(len(janResult.Changes) >= allResultLength, Equals, true)
}

func (s *TmdbSuite) TestGetMovieCredits(c *C) {
	result, err := s.tmdb.GetMovieCredits(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Cast, Not(HasLen), 0)
	c.Assert(result.Cast[0].CastID, Equals, 4)
	c.Assert(result.Cast[0].Character, Equals, "The Narrator")
	c.Assert(result.Cast[0].Name, Equals, "Edward Norton")
}

func (s *TmdbSuite) TestGetMovieImages(c *C) {
	result, err := s.tmdb.GetMovieImages(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Backdrops, Not(HasLen), 0)
	c.Assert(result.Posters, Not(HasLen), 0)
	allBackdropsLength := len(result.Backdrops)
	allPostersLength := len(result.Posters)

	var engOptions = make(map[string]string)
	engOptions["language"] = "en"
	engResult, err := s.tmdb.GetMovieImages(fightClubID, engOptions)
	s.baseTest(&engResult, err, c)
	c.Assert(engResult.ID, Equals, fightClubID)
	c.Assert(engResult.Backdrops, Not(HasLen), 0)
	c.Assert(engResult.Posters, Not(HasLen), 0)
	c.Assert(engResult.Backdrops[0].Iso639_1, Equals, "en")
	c.Assert(len(engResult.Backdrops) <= allBackdropsLength, Equals, true)
	c.Assert(len(engResult.Posters) <= allPostersLength, Equals, true)
}

func (s *TmdbSuite) TestGetMovieKeywords(c *C) {
	result, err := s.tmdb.GetMovieKeywords(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Keywords, Not(HasLen), 0)
	c.Assert(result.Keywords[0].ID, Equals, 825)
	c.Assert(result.Keywords[0].Name, Equals, "support group")
}

func (s *TmdbSuite) TestGetMovieLatest(c *C) {
	result, err := s.tmdb.GetMovieLatest()
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Not(Equals), fightClubID)
}

func (s *TmdbSuite) TestGetMovieLists(c *C) {
	result, err := s.tmdb.GetMovieLists(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Results, Not(HasLen), 0)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results[0].ID, Equals, "522effe419c2955e9922fcf3")
	c.Assert(result.Results[0].Iso639_1, Equals, "en")
	c.Assert(result.Results[0].Name, Equals, "IMDb Top 250")
	allResultLength := len(result.Results)

	var spanishOptions = make(map[string]string)
	spanishOptions["language"] = "es"
	spanishResult, err := s.tmdb.GetMovieLists(fightClubID, spanishOptions)
	s.baseTest(&spanishResult, err, c)
	c.Assert(spanishResult.ID, Equals, fightClubID)
	c.Assert(spanishResult.Page, Equals, 1)
	c.Assert(len(spanishResult.Results) < allResultLength, Equals, true)
}

func (s *TmdbSuite) TestGetMovieNowPlaying(c *C) {
	result, err := s.tmdb.GetMovieNowPlaying(nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)

	var page2Options = make(map[string]string)
	page2Options["page"] = "2"
	page2Result, err := s.tmdb.GetMovieNowPlaying(page2Options)
	s.baseTest(&page2Result, err, c)
	c.Assert(page2Result.Page, Equals, 2)
	c.Assert(page2Result.Results, Not(HasLen), 0)
}

func (s *TmdbSuite) TestGetMoviePopular(c *C) {
	result, err := s.tmdb.GetMoviePopular(nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)

	var page2Options = make(map[string]string)
	page2Options["page"] = "2"
	page2Result, err := s.tmdb.GetMoviePopular(page2Options)
	s.baseTest(&page2Result, err, c)
	c.Assert(page2Result.Page, Equals, 2)
	c.Assert(page2Result.Results, Not(HasLen), 0)
}

func (s *TmdbSuite) TestGetMovieReleases(c *C) {
	result, err := s.tmdb.GetMovieReleases(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Countries, Not(HasLen), 0)
	c.Assert(result.Countries[0].Iso3166_1, Equals, "US")
	c.Assert(result.Countries[0].Certification, Equals, "R")
	c.Assert(result.Countries[0].ReleaseDate, Equals, "1999-10-14")
}

func (s *TmdbSuite) TestGetMovieReviews(c *C) {
	result, err := s.tmdb.GetMovieReviews(darkKnightID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, darkKnightID)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)

	var engOptions = make(map[string]string)
	engOptions["language"] = "en"
	engResult, err := s.tmdb.GetMovieReviews(darkKnightID, engOptions)
	s.baseTest(&engResult, err, c)
	c.Assert(engResult.ID, Equals, darkKnightID)
	c.Assert(engResult.Page, Equals, 1)
}

func (s *TmdbSuite) TestGetMovieSimilar(c *C) {
	result, err := s.tmdb.GetMovieSimilar(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)
	c.Assert(result.Results[0].ID, Equals, 807)
	c.Assert(result.Results[0].Title, Equals, "Se7en")

	var engOptions = make(map[string]string)
	engOptions["language"] = "en"
	engResult, err := s.tmdb.GetMovieSimilar(fightClubID, engOptions)
	s.baseTest(&engResult, err, c)
	c.Assert(engResult.Page, Equals, 1)
	c.Assert(engResult.Results, Not(HasLen), 0)
}

func (s *TmdbSuite) TestGetMovieTopRated(c *C) {
	result, err := s.tmdb.GetMovieTopRated(nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)

	var page2Options = make(map[string]string)
	page2Options["page"] = "2"
	page2Result, err := s.tmdb.GetMovieTopRated(page2Options)
	s.baseTest(&page2Result, err, c)
	c.Assert(page2Result.Page, Equals, 2)
	c.Assert(page2Result.Results, Not(HasLen), 0)
}

func (s *TmdbSuite) TestGetMovieTranslations(c *C) {
	result, err := s.tmdb.GetMovieTranslations(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Translations, Not(HasLen), 0)
	c.Assert(result.Translations[0].Iso639_1, Equals, "en")
	c.Assert(result.Translations[0].EnglishName, Equals, "English")
	c.Assert(result.Translations[0].Name, Equals, "English")
}

func (s *TmdbSuite) TestGetMovieUpcoming(c *C) {
	result, err := s.tmdb.GetMovieUpcoming(nil)
	s.baseTest(&result, err, c)
	c.Assert(result.Page, Equals, 1)
	c.Assert(result.Results, Not(HasLen), 0)

	var page2Options = make(map[string]string)
	page2Options["page"] = "2"
	page2Result, err := s.tmdb.GetMovieUpcoming(page2Options)
	s.baseTest(&page2Result, err, c)
	c.Assert(page2Result.Page, Equals, 2)
	c.Assert(page2Result.Results, Not(HasLen), 0)
}

func (s *TmdbSuite) TestGetMovieVideos(c *C) {
	result, err := s.tmdb.GetMovieVideos(fightClubID, nil)
	s.baseTest(&result, err, c)
	c.Assert(result.ID, Equals, fightClubID)
	c.Assert(result.Results, Not(HasLen), 0)
	allResultsLength := len(result.Results)

	var engOptions = make(map[string]string)
	engOptions["language"] = "en"
	engResult, err := s.tmdb.GetMovieVideos(fightClubID, engOptions)
	s.baseTest(&engResult, err, c)
	c.Assert(engResult.ID, Equals, fightClubID)
	c.Assert(engResult.Results, Not(HasLen), 0)
	c.Assert(engResult.Results[0].Iso639_1, Equals, "en")
	c.Assert(len(engResult.Results) <= allResultsLength, Equals, true)
}

func (s *TmdbSuite) TestSetMovieRating(c *C) {
	// result, err := s.tmdb.SetMovieRating(takenThreeID)
	// s.baseTest(&result, err, c)
	// TODO
}


text:
A work in progress Minecraft client in Go.
Don't expect it to go anywhere, just doing this for fun.

## Images

![Steven](http://i.imgur.com/VVnmbkV.png)

![Steven with Nether style background and a resource pack](https://i.imgur.com/QjBb1UT.png)

![Steven's server list after disconnecting from a server](https://i.imgur.com/JRFXt0e.png)

## Building

To build:

```
export GOPATH=your/install/directory
go get github.com/thinkofdeath/steven/cmd/steven
```

To update, run `go get` with the `-u` option.

Requires `csfml` libraries and headers to build.

## What works

* Connecting to servers
* Online mode
* Rendering most blocks
* Block model support

## What doesn't work

* 99% of Minecraft's features

## Chat

I generally am on the `irc.spi.gt` irc network in the `#think` channel.
Feel free to pop in to say hi, [Webchat can be found here](https://irc.spi.gt/iris/?channels=think)

## Builds

**Latest:**

|  #  |      Linux      | OS X |      Windows      |
|:---:|:---------------:|:----:|:-----------------:|
| x64 | [linux_amd64.zip](http://ci.thinkofdeath.uk/guestAuth/repository/download/Steven_Client/.lastSuccessful/linux_amd64.zip) |   [Issue](https://github.com/thinkofdeath/steven/issues/27)  | [windows_amd64.zip](http://ci.thinkofdeath.uk/guestAuth/repository/download/Steven_Client/.lastSuccessful/windows_amd64.zip) |
| x32 |   [Issue](https://github.com/thinkofdeath/steven/issues/28)       |   [Issue](https://github.com/thinkofdeath/steven/issues/27)  |  [windows_386.zip](http://ci.thinkofdeath.uk/guestAuth/repository/download/Steven_Client/.lastSuccessful/windows_386.zip)  |

Older builds can be found [here](http://ci.thinkofdeath.co.uk/viewType.html?buildTypeId=Steven_Client&guest=1)

## Running

### Via the Offical Minecraft launcher

![Profile example](http://i.imgur.com/NBMGhPL.png)

You need to create a new profile (or edit an existing one) on the Minecraft
launcher and modify the profile to look like the above but replace the path
to steven with the location you built it at or downloaded it too and change the
`server` parameter to the target server. Currently only works in online mode
(with no plans for offline mode currently). If the `server` parameter isn't
passed then a server list will be displayed.

### Standalone

Just running steven via a double click (Windows) or `./steven` (everything else)
will bring up a login screen followed by a server list which you can select a server
from.

Providing a username, uuid and access token via the command line as followed:
  `--username <username> --uuid <uuid> --accessToken <access token>`
will skip the login screen and jump straight to the server list. Providing a
server address via `--server <server>:<port>` will skip the server list and
connect straight to the server. As it currently stands providing all the arguments
allows for the client to parallelise connecting to the server and loading the
textures/models/other assets as a 'quick connect'.