text:
import {Deferred} from './promise';

/**
 * Decodes readable stream from response and writes to given writeable stream.
 * Returns a promise that resolves when first bytes are received from the
 * response, or we learn that the response is empty.
 * This function should be replaced with transform stream when well supported.
 * @param {!Window} win
 * @param {!Response} response
 * @param {!./detached-dom-stream.DetachedDomStream} writer
 * @return {!Promise<boolean>} true if response has content, false if
 * the response is empty.
 */
export function streamResponseToWriter(win, response, writer) {
  const hasContentDeferred = new Deferred();
  // Try native streaming first.
  if (win.TextDecoder && win.ReadableStream) {
    let firstRead = true;
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    reader.read().then(function handleChunk({value, done}) {
      if (firstRead) {
        hasContentDeferred.resolve(!done);
        firstRead = false;
      }

      // We need to close and flush the decoder on the last chunk even if
      // we have no more bytes and `decode` will throw if not given an
      // array buffer.
      value = value || new Uint8Array(0);
      const text = decoder.decode(value, {stream: !done});

      if (text) {
        writer.write(text);
      }

      if (!done) {
        return reader.read().then(handleChunk);
      }

      writer.close();
    });
  } else {
    // Fallback case waits for the complete response before writing.
    response.text().then((text) => {
      hasContentDeferred.resolve(!!text);
      writer.write(text);
      writer.close();
    });
  }

  return hasContentDeferred.promise;
}


text:
<?php

namespace WS\Tools\ORM\Db\Gateway;

use WS\Tools\ORM\Db\Gateway;

/**
 * Common gateway engine
 *
 * In the configuration you must specify the Bitrix class.
 *
 * @author my.sokolovsky@gmail.com
 */
class Common extends Gateway {

    protected function findEngine() {
        list($arFilter, $arOrder) = func_get_args();
        $bxClass = $this->analyzer->getParam('bitrixClass');
        $bxClass = $bxClass[0];
        /* @var $dbRes \CDBResult */
        $dbRes = call_user_func(array($bxClass, 'getList'), $arOrder, $arFilter);
        return $dbRes;
    }

    protected function setupFilterClass() {
        return \WS\Tools\ORM\Db\Filter\Common::className();
    }

    /**
     * Update database row
     *
     * @param $id
     * @param $fields
     * @return mixed
     */
    protected function updateRow($id, $fields) {
        $bxClass = $this->analyzer->getParam('bitrixClass', 1);
        $bxObject = new $bxClass;
        $res = $bxObject->Update($id, $fields);
        if (!$res) {
            throw new SaveException($bxObject->LAST_ERROR);
        }
    }

    /**
     * Insert database row
     *
     * @param $fields
     * @return mixed
     */
    protected function insertRow($fields) {
        $bxClass = $this->analyzer->getParam('bitrixClass', 1);
        $bxObject = new $bxClass;
        $res = $bxObject->Add($fields);
        if (!$res) {
            throw new SaveException($bxObject->LAST_ERROR);
        }
        return $res;
    }

    /**
     * @param $entity
     */
    public function remove($entity) {
        $bxClass = $this->analyzer->getParam('bitrixClass', 1);
        $bxObject = new $bxClass;
        $bxObject->Delete($entity->id);
        $entity->id = null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { useCallback } from 'react';

import createCustomEvent from '../utils/createCustomEvent';
import useReadTelemetryDimensions from './internal/useReadTelemetryDimensions';
import useWebChatAPIContext from './internal/useWebChatAPIContext';

export default function useTrackException() {
  const { onTelemetry } = useWebChatAPIContext();
  const readTelemetryDimensions = useReadTelemetryDimensions();

  return useCallback(
    (error, fatal = true) => {
      if (!(error instanceof Error)) {
        return console.warn(
          'botframework-webchat: "error" passed to "useTrackException" must be specified and of type Error.'
        );
      }

      onTelemetry &&
        onTelemetry(
          createCustomEvent('exception', {
            dimensions: { ...readTelemetryDimensions() },
            error,
            fatal: !!fatal
          })
        );
    },
    [onTelemetry, readTelemetryDimensions]
  );
}


text:
"""Parser for STIX Domain Name Object.

see: https://docs.oasis-open.org/cti/stix/v2.1/csprd01/stix-v2.1-csprd01.html#_Toc16070687
"""
# standard library
from typing import Iterable, Union

# third-party
from stix2 import DomainName

# first-party
from tcex.stix.model import StixModel

class StixDomainNameObject(StixModel):
    """Parser for STIX Domain Name Object.

    see: https://docs.oasis-open.org/cti/stix/v2.1/csprd01/stix-v2.1-csprd01.html#_Toc16070687
    """

    # pylint: disable=arguments-differ
    def produce(self, tc_data: Union[list, dict], **kwargs) -> Iterable[DomainName]:
        """Produce STIX 2.0 JSON object from TC API response."""
        if isinstance(tc_data, list) and len(tc_data) > 0 and 'summary' in tc_data[0]:
            indicator_field = 'summary'
        else:
            indicator_field = 'hostName'

        parse_map = {
            'type': 'domain-name',
            'spec_version': '2.1',
            'id': '@.id',
            'value': f'@."{indicator_field}"',
        }

        yield from (DomainName(**stix_data) for stix_data in self._map(tc_data, parse_map))

    # pylint: disable=arguments-differ
    def consume(self, stix_data: Union[list, dict]):
        """Produce a ThreatConnect object from a STIX 2.0 JSON object."""
        parse_map = {
            'type': 'Host',
            'hostName': '@.value',
            'xid': '@.id',
            'confidence': '@.confidence',
            'attributes': [{'type': 'External ID', 'value': '@.id'}],
        }
        parse_map.update(self.default_map)

        yield from self._map(
            stix_data, parse_map,
        )


text:
package tv.floe.metronome.vectorization;

import java.util.zip.CRC32;
import java.util.zip.Checksum;

import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.Test;

import tv.floe.metronome.utils.Utils;

public class TestHashKernel {

	@Test
	public void testBasicHashKernel() {

		String line = "The brown cow ran down the street";

		HashKernel hk = new HashKernel(10);
		Vector v = hk.createCorrectlySizedVector();

		hk.hash(line, v);

		Utils.PrintVectorNonZero(v);

		v.assign(0);

		System.out.println( "Cleared: ");
		Utils.PrintVectorNonZero(v);

	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cylindrocarpon suballantoideum Wollenw.

### Remarks
null


text:
class AddUserFkToHealthRecords < ActiveRecord::Migration
  def change
    add_column :health_records, :user_id, :integer
  end
end


text:
package org.apache.reef.tang.util;

import java.util.*;
import java.util.Map.Entry;

public abstract class AbstractMonotonicMultiMap<K, V> implements Collection<Entry<K, V>> {
  protected Map<K, Set<V>> map;
  private int size = 0;

  public AbstractMonotonicMultiMap(Map<K, Set<V>> map) {
    this.map = map;
  }

  public void put(K key, V v) {
    Set<V> vals = map.get(key);
    if (vals == null) {
      vals = new MonotonicHashSet<V>();
      map.put(key, vals);
    }
    vals.add(v);
    size++;
  }

  public Set<K> keySet() {
    return map.keySet();
  }

  public Set<V> getValuesForKey(K key) {
    Set<V> ret = map.get(key);
    if (ret == null) {
      return new MonotonicHashSet<V>();
    } else {
      return ret;
    }
  }

  public boolean contains(K key, V v) {
    Set<V> vals = map.get(key);
    if (vals != null) {
      return vals.contains(v);
    }
    return false;
  }

  @Override
  public boolean add(Entry<K, V> e) {
    put(e.getKey(), e.getValue());
    return true;
  }

  @Override
  public boolean addAll(Collection<? extends Entry<K, V>> c) {
    boolean ret = false;
    for (Entry<K, V> e : c) {
      add(e);
      ret = true;
    }
    return ret;
  }

  @Override
  public void clear() {
    throw new UnsupportedOperationException("MonotonicMultiMap cannot be cleared!");
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean contains(Object o) {
    Entry<?, ?> e = (Entry<?, ?>) o;
    return contains((K) e.getKey(), (V) e.getValue());
  }

  @Override
  public boolean containsAll(Collection<?> c) {
    for (Object o : c) {
      if (!contains(o)) {
        return false;
      }
    }
    return true;
  }

  @Override
  public boolean isEmpty() {
    return size == 0;
  }

  @Override
  public Iterator<Entry<K, V>> iterator() {
    final Iterator<Entry<K, Set<V>>> it = map.entrySet().iterator();
    return new Iterator<Entry<K, V>>() {
      Iterator<V> cur;
      K curKey;

      @Override
      public boolean hasNext() {
        return it.hasNext() || (cur != null && cur.hasNext());
      }

      @Override
      public Entry<K, V> next() {
        if (cur == null) {
          if (it.hasNext()) {
            Entry<K, Set<V>> e = it.next();
            curKey = e.getKey();
            cur = e.getValue().iterator();
          }
        }
        final K k = curKey;
        final V v = cur.next();
        if (!cur.hasNext()) {
          cur = null;
        }

        return new Entry<K, V>() {

          @Override
          public K getKey() {
            return k;
          }

          @Override
          public V getValue() {
            return v;
          }

          @Override
          public V setValue(V value) {
            throw new UnsupportedOperationException();
          }

        };
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }

    };
  }

  public Set<V> values() {
    Set<V> s = new HashSet<>();
    for (Entry<K, V> e : this) {
      s.add(e.getValue());
    }
    return s;
  }

  @Override
  public boolean remove(Object o) {
    throw new UnsupportedOperationException("MonotonicMultiMap does not support non-monotonic method remove!");
  }

  @Override
  public boolean removeAll(Collection<?> c) {
    throw new UnsupportedOperationException("MonotonicMultiMap does not support non-monotonic method removeAll!");
  }

  @Override
  public boolean retainAll(Collection<?> c) {
    throw new UnsupportedOperationException("MonotonicMultiMap does not support non-monotonic method retainAll!");
  }

  @Override
  public int size() {
    return size;
  }

  @Override
  public Entry<K, V>[] toArray() {
    throw new UnsupportedOperationException("No toArray() for MonotonicMulitMap (yet)");
  }

  @Override
  public <T> T[] toArray(T[] a) {
    throw new UnsupportedOperationException("No toArray() for MonotonicMulitMap (yet)");
  }

  public boolean containsKey(K k) {
    if (map.containsKey(k)) {
      return !getValuesForKey(k).isEmpty();
    } else {
      return false;
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<template type="basic" name="DcpH1C13N15probeINIT" author="Agilent" investigator=""
        time_created="20120331T120000" tabname="BioSolidsPack" menu1="Commands" menu2="Init Probe File" apptype="solidsseq1d"
        application="BioSolids" scans="DcpH1C13N15probeINIT" seqfil="ahXX">
  <protocol title="DcpH1C13N15probeINIT" type="protocol">
    <action  type="CMD" status="Ready" lock="off" title="DcpH1C13N15probeINIT" exp="DcpH1C13N15probeINIT"
        time="1:45" macro="DcpH1C13N15probeINIT" data="" />
  </protocol>
</template>


text:
namespace ExifProcessLib.Models
{
    public enum ExifExposureProgram
    {
        NotDefined              = 0,
        Manual                  = 1,
        ProgramAE               = 2,
        AperturePriorityAE      = 3,
        ShutterSpeedPriorityAE  = 4,
        CreativeSlowSpeed       = 5,
        ActionHighSpeed         = 6,
        Portrait                = 7,
        Landscape               = 8,
        Bulb                    = 9
    }
}


text:
@extends('layouts._two_columns_left_sidebar')

@section('sidebar')
    @include('forum._sidebar')
@stop

@section('content')
{{ Form::model($thread->resource) }}

Editar tópico

            {{ Form::label('subject', 'Assunto', ['class' => 'field-title']) }}
            {{ Form::text('subject', null, ['placeholder' => 'Assunto']) }}
            {{ $errors->first('subject', ':message') }}

            {{ Form::label('body', 'Tópico', ['class' => 'field-title']) }}
            {{ Form::textarea("body", null) }}
            {{ $errors->first('body', ':message') }}
            Aprenda a usar as marcações.

            {{ Form::label('is_question', 'Que tipo de tópico é esse?', ['class' => 'field-title']) }}

                        Pergunta
                        {{ Form::radio('is_question', 1, $thread->is_question) }}

                        Conversa
                        {{ Form::radio('is_question', 0, $thread->is_question) }}

            {{ $errors->first('is_question', ':message') }}

            {{ Form::label('laravel_version', 'Versão do Laravel', ['class' => 'field-title']) }}

                @foreach($versions as $value => $version)

                            {{ $version }}
                            {{ Form::radio('laravel_version', $value) }}

                @endforeach

            {{ $errors->first('laravel_version', ':message') }}

            @include('forum._tag_chooser', ['comment' => $thread])

            {{ Form::button('Salvar', ['type' => 'submit', 'class' => 'button']) }}

    {{ Form::close() }}
@stop


text:
var usePE = !!navigator.pointerEnabled;
var eventPrefix = usePE ? 'pointer' : 'mouse';
var activeCards = {};

function onStart(e) {
  var card = e.currentTarget;
  activeCards[usePE ? e.pointerId : 1] = card;
  if (!card.classList.contains('moving'))
  {
    card.classList.add('moving');
    card.startX = e.clientX;
    card.startY = e.clientY;
  }
  e.preventDefault();
}

function onMove(e) {
  var card = activeCards[usePE ? e.pointerId : 1];
  if (card) {
    card.style.webkitTransform = 'translate(' +
      (e.clientX - card.startX) + 'px, ' +
      (e.clientY - card.startY) + 'px)';
    e.preventDefault();
  }
}

function onEnd(e) {
  var id = usePE ? e.pointerId : 1;
  var card = activeCards[id];
  if (card) {
    card.classList.remove('moving');
    card.style.webkitTransform = '';
    e.preventDefault();
    if (e.target.classList.contains('circle'))
      removeCardFromCircle(card, e.target);
    delete activeCards[id];
  }
}

function onOver(e) {
  var card = activeCards[usePE ? e.pointerId : 1];
  if (card) {
    addCardToCircle(card, e.currentTarget);
  }
}

function onOut(e) {
  var card = activeCards[usePE ? e.pointerId : 1];
  if (card) {
    removeCardFromCircle(card, e.currentTarget);
  }
}

function addCardToCircle(card, circle)
{
  if (!circle.cardsOver)
    circle.classList.add('open');
  circle.cardsOver++;
}

function removeCardFromCircle(card, circle)
{
  circle.cardsOver--;
  if (!circle.cardsOver)
    circle.classList.remove('open');
}

var cards = document.querySelectorAll('.card');
for(var i = 0; i < cards.length; i++) {
  var c = cards[i];
  c.addEventListener(eventPrefix + 'down', onStart, false);
}

var circles = document.querySelectorAll('.circle');
for(var i = 0; i < circles.length; i++) {
  var c = circles[i];
  c.addEventListener(eventPrefix + 'over', onOver, false);
  c.addEventListener(eventPrefix + 'out', onOut, false);
  c.cardsOver = 0;
}

document.body.addEventListener(eventPrefix + 'move', onMove, false);
document.body.addEventListener(eventPrefix + 'up', onEnd, false);
if (usePE)
  document.body.addEventListener(eventPrefix + 'cancel', onEnd, false);
  document.body.addEventListener(eventPrefix + 'out', function(e) {
  if (e.relatedTarget == document.documentElement)
    onEnd(e);
}, false);


text:
from django.db import models
from apps.teams.models import Team

# Create your models here.

class Competition(models.Model):
    name = models.CharField(max_length=50, default='')
    image = models.ImageField(upload_to='competition_image', blank=True)
    team = models.ManyToManyField(Team)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name


text:
namespace crashpad {

//! \brief An interface to read to files and other file-like objects with
//!     semantics matching the underlying platform (POSIX or Windows).
class FileReaderInterface : public virtual FileSeekerInterface {
 public:
  virtual ~FileReaderInterface() {}

  //! \brief Wraps ReadFile(), or provides an implementation with identical
  //!     semantics.
  //!
  //! \return The number of bytes actually read if the operation succeeded,
  //!     which may be `0` or any positive value less than or equal to \a size.
  //!     `-1` if the operation failed, with an error message logged.
  virtual FileOperationResult Read(void* data, size_t size) = 0;

  //! \brief Wraps Read(), ensuring that the read succeeded and exactly \a size
  //!     bytes were read.
  //!
  //! Semantically, this behaves as LoggingReadFileExactly().
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged. Short reads are treated as failures.
  bool ReadExactly(void* data, size_t size);
};

//! \brief A file reader backed by a FileHandle.
//!
//! FileReader requires users to provide a FilePath to open, but this class
//! accepts an already-open FileHandle instead. Like FileReader, this class may
//! read from a filesystem-based file, but unlike FileReader, this class is not
//! responsible for opening or closing the file. Users of this class must ensure
//! that the file handle is closed appropriately elsewhere. Objects of this
//! class may be used to read from file handles not associated with
//! filesystem-based files, although special attention should be paid to the
//! Seek() method, which may not function on file handles that do not refer to
//! disk-based files.
//!
//! This class is expected to be used when other code is responsible for
//! opening files and already provides file handles.
class WeakFileHandleFileReader : public FileReaderInterface {
 public:
  explicit WeakFileHandleFileReader(FileHandle file_handle);

  WeakFileHandleFileReader(const WeakFileHandleFileReader&) = delete;
  WeakFileHandleFileReader& operator=(const WeakFileHandleFileReader&) = delete;

  ~WeakFileHandleFileReader() override;

  // FileReaderInterface:
  FileOperationResult Read(void* data, size_t size) override;

  // FileSeekerInterface:

  //! \copydoc FileReaderInterface::Seek()
  //!
  //! \note This method is only guaranteed to function on file handles referring
  //!     to disk-based files.
  FileOffset Seek(FileOffset offset, int whence) override;

 private:
  void set_file_handle(FileHandle file_handle) { file_handle_ = file_handle; }

  FileHandle file_handle_;  // weak

  // FileReader uses this class as its internal implementation, and it needs to
  // be able to call set_file_handle(). FileReader cannot initialize a
  // WeakFileHandleFileReader with a correct file descriptor at the time of
  // construction because no file descriptor will be available until
  // FileReader::Open() is called.
  friend class FileReader;
};

//! \brief A file reader implementation that wraps traditional system file
//!     operations on files accessed through the filesystem.
class FileReader : public FileReaderInterface {
 public:
  FileReader();

  FileReader(const FileReader&) = delete;
  FileReader& operator=(const FileReader&) = delete;

  ~FileReader() override;

  // FileReaderInterface:

  //! \brief Wraps LoggingOpenFileForRead().
  //!
  //! \return `true` if the operation succeeded, `false` if it failed, with an
  //!     error message logged.
  //!
  //! \note After a successful call, this method cannot be called again until
  //!     after Close().
  bool Open(const base::FilePath& path);

  //! \brief Wraps CheckedCloseHandle().
  //!
  //! \note It is only valid to call this method on an object that has had a
  //!     successful Open() that has not yet been matched by a subsequent call
  //!     to this method.
  void Close();

  // FileReaderInterface:

  //! \copydoc FileReaderInterface::Read()
  //!
  //! \note It is only valid to call this method between a successful Open() and
  //!     a Close().
  FileOperationResult Read(void* data, size_t size) override;

  // FileSeekerInterface:

  //! \copydoc FileReaderInterface::Seek()
  //!
  //! \note It is only valid to call this method between a successful Open() and
  //!     a Close().
  FileOffset Seek(FileOffset offset, int whence) override;

 private:
  ScopedFileHandle file_;
  WeakFileHandleFileReader weak_file_handle_file_reader_;
};

}  // namespace crashpad

#endif  // CRASHPAD_UTIL_FILE_FILE_READER_H_


text:
namespace update_client {

CrxUpdateItem::CrxUpdateItem()
    : state(State::kNew),
      on_demand(false),
      diff_update_failed(false),
      error_category(0),
      error_code(0),
      extra_code1(0),
      diff_error_category(0),
      diff_error_code(0),
      diff_extra_code1(0) {
}

CrxUpdateItem::~CrxUpdateItem() {
}

CrxComponent::CrxComponent() : allow_background_download(true) {
}

CrxComponent::~CrxComponent() {
}

// It is important that an instance of the UpdateClient binds an unretained
// pointer to itself. Otherwise, a life time circular dependency between this
// instance and its inner members prevents the destruction of this instance.
// Using unretained references is allowed in this case since the life time of
// the UpdateClient instance exceeds the life time of its inner members,
// including any thread objects that might execute callbacks bound to it.
UpdateClientImpl::UpdateClientImpl(
    const scoped_refptr<Configurator>& config,
    scoped_ptr<PingManager> ping_manager,
    UpdateChecker::Factory update_checker_factory,
    CrxDownloader::Factory crx_downloader_factory)
    : is_stopped_(false),
      config_(config),
      ping_manager_(ping_manager.Pass()),
      update_engine_(
          new UpdateEngine(config,
                           update_checker_factory,
                           crx_downloader_factory,
                           ping_manager_.get(),
                           base::Bind(&UpdateClientImpl::NotifyObservers,
                                      base::Unretained(this)))) {}

UpdateClientImpl::~UpdateClientImpl() {
  DCHECK(thread_checker_.CalledOnValidThread());

  DCHECK(task_queue_.empty());
  DCHECK(tasks_.empty());

  config_ = nullptr;
}

void UpdateClientImpl::Install(const std::string& id,
                               const CrxDataCallback& crx_data_callback,
                               const CompletionCallback& completion_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (IsUpdating(id)) {
    completion_callback.Run(Error::ERROR_UPDATE_IN_PROGRESS);
    return;
  }

  std::vector<std::string> ids;
  ids.push_back(id);

  // Partially applies |completion_callback| to OnTaskComplete, so this
  // argument is available when the task completes, along with the task itself.
  const auto callback =
      base::Bind(&UpdateClientImpl::OnTaskComplete, this, completion_callback);
  scoped_ptr<TaskUpdate> task(new TaskUpdate(update_engine_.get(), true, ids,
                                             crx_data_callback, callback));

  // Install tasks are run concurrently and never queued up.
  RunTask(task.Pass());
}

void UpdateClientImpl::Update(const std::vector<std::string>& ids,
                              const CrxDataCallback& crx_data_callback,
                              const CompletionCallback& completion_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());

  const auto callback =
      base::Bind(&UpdateClientImpl::OnTaskComplete, this, completion_callback);
  scoped_ptr<TaskUpdate> task(new TaskUpdate(update_engine_.get(), false, ids,
                                             crx_data_callback, callback));

  // If no other tasks are running at the moment, run this update task.
  // Otherwise, queue the task up.
  if (tasks_.empty()) {
    RunTask(task.Pass());
  } else {
    task_queue_.push(task.release());
  }
}

void UpdateClientImpl::RunTask(scoped_ptr<Task> task) {
  DCHECK(thread_checker_.CalledOnValidThread());
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(&Task::Run, base::Unretained(task.get())));
  tasks_.insert(task.release());
}

void UpdateClientImpl::OnTaskComplete(
    const CompletionCallback& completion_callback,
    Task* task,
    int error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(task);

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::Bind(completion_callback, error));

  // Remove the task from the set of the running tasks. Only tasks handled by
  // the update engine can be in this data structure.
  tasks_.erase(task);

  // Delete the completed task. A task can be completed because the update
  // engine has run it or because it has been canceled but never run.
  delete task;

  if (is_stopped_)
    return;

  // Pick up a task from the queue if the queue has pending tasks and no other
  // task is running.
  if (tasks_.empty() && !task_queue_.empty()) {
    RunTask(scoped_ptr<Task>(task_queue_.front()).Pass());
    task_queue_.pop();
  }
}

void UpdateClientImpl::AddObserver(Observer* observer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  observer_list_.AddObserver(observer);
}

void UpdateClientImpl::RemoveObserver(Observer* observer) {
  DCHECK(thread_checker_.CalledOnValidThread());
  observer_list_.RemoveObserver(observer);
}

void UpdateClientImpl::NotifyObservers(Observer::Events event,
                                       const std::string& id) {
  DCHECK(thread_checker_.CalledOnValidThread());
  FOR_EACH_OBSERVER(Observer, observer_list_, OnEvent(event, id));
}

bool UpdateClientImpl::GetCrxUpdateState(const std::string& id,
                                         CrxUpdateItem* update_item) const {
  return update_engine_->GetUpdateState(id, update_item);
}

bool UpdateClientImpl::IsUpdating(const std::string& id) const {
  DCHECK(thread_checker_.CalledOnValidThread());

  for (const auto& task : tasks_) {
    const auto ids(task->GetIds());
    if (std::find(ids.begin(), ids.end(), id) != ids.end()) {
      return true;
    }
  }

  return false;
}

void UpdateClientImpl::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());

  is_stopped_ = true;

  // In the current implementation it is sufficient to cancel the pending
  // tasks only. The tasks that are run by the update engine will stop
  // making progress naturally, as the main task runner stops running task
  // actions. Upon the browser shutdown, the resources employed by the active
  // tasks will leak, as the operating system kills the thread associated with
  // the update engine task runner. Further refactoring may be needed in this
  // area, to cancel the running tasks by canceling the current action update.
  // This behavior would be expected, correct, and result in no resource leaks
  // in all cases, in shutdown or not.
  //
  // Cancel the pending tasks. These tasks are safe to cancel and delete since
  // they have not picked up by the update engine, and not shared with any
  // task runner yet.
  while (!task_queue_.empty()) {
    const auto task(task_queue_.front());
    task_queue_.pop();
    task->Cancel();
  }
}

scoped_refptr<UpdateClient> UpdateClientFactory(
    const scoped_refptr<Configurator>& config) {
  scoped_ptr<PingManager> ping_manager(new PingManager(*config));
  return new UpdateClientImpl(config, ping_manager.Pass(),
                              &UpdateChecker::Create, &CrxDownloader::Create);
}

}  // namespace update_client


text:
require_dependency "renalware"

module Renalware
  module Broadcasting
    include Wisper::Publisher
    extend ActiveSupport::Concern

    class Subscriber
      attr_reader :klass_name, :async
      alias_method :async?, :async

      def initialize(klass_name, async: false)
        @klass_name = klass_name
        @async = async
      end

      # Note that when using the wisper-activejob gem
      # we subscribe the class not an instance, and the subscriber must have class
      # methods matching the event names it wants to handle.
      # https://github.com/krisleech/wisper-activejob
      def instance
        async? ? klass : klass.new
      end

      def klass
        klass_name.to_s.constantize
      end
    end

    # Subscribes any listeners configured in Renalware.config.broadcast_subscription_map
    # to the current instance.
    #
    # Example usage
    #
    #   class SomeServiceObject
    #     include Broadcasting
    #
    #     def call
    #       ..
    #     end
    #   end
    #
    #   SomeServiceObject.new(..).broadcasting_to_configured_subscribers.call(..)
    #
    # See https://github.com/krisleech/wisper
    #
    def broadcasting_to_configured_subscribers
      subscribers = Array(Renalware.config.broadcast_subscription_map[self.class.name])
      subscribers.each do |subscriber|
        # Support String subscribers eg a simple class name as well as Subscriber instances.
        subscriber = Subscriber.new(subscriber) unless subscriber.respond_to?(:klass)
        subscribe(subscriber.instance, async: subscriber.async?)
      end
      self
    end
  end
end


text:
require 'dronr'

require 'support/sample_drones'
require 'support/fixture_path'

RSpec.configure do |config|

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.include Helpers::FixturePath

end


text:
package org.simplemart.product;

import io.dropwizard.Configuration;

public final class ProductConfiguration extends Configuration {

}


text:
<?php

namespace MusicBrainz\Relation\Type\Place;

use MusicBrainz\Value\EntityType;

/**
 * A relation between a place and a url
 *
 * @link https://musicbrainz.org/relationships/place-url
 */
abstract class Url extends \MusicBrainz\Relation\Type\Place
{
    /**
     * Returns the entity type of the related entity.
     *
     * @return EntityType
     */
    final public static function getRelatedEntityType(): EntityType
    {
        return new EntityType(EntityType::URL);
    }
}


text:
package com.fasterxml.jackson.databind.exc;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * Base class for {@link JsonMappingException}s that are specifically related
 * to problems related to binding an individual property.
 *
 * @since 2.3
 */
@SuppressWarnings("serial")
public abstract class PropertyBindingException
    extends MismatchedInputException // since 2.9
{
    /**
     * Class that does not contain mapping for the unrecognized property.
     */
    protected final Class<?> _referringClass;

    /**
     *<p>
     * Note: redundant information since it is also included in the
     * reference path.
     */
    protected final String _propertyName;

    /**
     * Set of ids of properties that are known for the type, if this
     * can be statically determined.
     */
    protected final Collection<Object> _propertyIds;

    /**
     * Lazily constructed description of known properties, used for
     * constructing actual message if and as needed.
     */
    protected transient String _propertiesAsString;

    /**
     * @since 2.7
     */
    protected PropertyBindingException(JsonParser p, String msg, JsonLocation loc,
            Class<?> referringClass, String propName,
            Collection<Object> propertyIds)
    {
        super(p, msg, loc);
        _referringClass = referringClass;
        _propertyName = propName;
        _propertyIds = propertyIds;
    }

    /**
     * @deprecated Since 2.7
     */
    @Deprecated // since 2.7
    protected PropertyBindingException(String msg, JsonLocation loc,
            Class<?> referringClass, String propName,
            Collection<Object> propertyIds)
    {
        this(null, msg, loc, referringClass, propName, propertyIds);
    }

    /*
    /**********************************************************
    /* Overrides
    /**********************************************************
     */

    /**
     * Somewhat arbitrary limit, but let's try not to create uselessly
     * huge error messages
     */
    private final static int MAX_DESC_LENGTH = 1000;

    @Override
    public String getMessageSuffix()
    {
        String suffix = _propertiesAsString;
        if (suffix == null && _propertyIds != null) {
            StringBuilder sb = new StringBuilder(100);
            int len = _propertyIds.size();
            if (len == 1) {
                sb.append(" (one known property: \"");
                sb.append(String.valueOf(_propertyIds.iterator().next()));
                sb.append('"');
            } else {
                sb.append(" (").append(len).append(" known properties: ");
                Iterator<Object> it = _propertyIds.iterator();
                while (it.hasNext()) {
                    sb.append('"');
                    sb.append(String.valueOf(it.next()));
                    sb.append('"');
                    // one other thing: limit max length
                    if (sb.length() > MAX_DESC_LENGTH) {
                        sb.append(" [truncated]");
                        break;
                    }
                    if (it.hasNext()) {
                        sb.append(", ");
                    }
                }
            }
            sb.append("])");
            _propertiesAsString = suffix = sb.toString();
        }
        return suffix;
    }

    /*
    /**********************************************************
    /* Extended API
    /**********************************************************
     */

    /**
     * Method for accessing type (class) that is missing definition to allow
     * binding of the unrecognized property.
     */
    public Class<?> getReferringClass() {
        return _referringClass;
    }

    /**
     * Convenience method for accessing logical property name that could
     * not be mapped. Note that it is the last path reference in the
     * underlying path.
     */
    public String getPropertyName() {
        return _propertyName;
    }

    public Collection<Object> getKnownPropertyIds()
    {
        if (_propertyIds == null) {
            return null;
        }
        return Collections.unmodifiableCollection(_propertyIds);
    }
}


text:
class FastwayResponse {

  /**
   * @param {FastwayInternalResponse|object} response
   */
  constructor(response) {
    this.raw = response;
  }

  /**
   * @throws
   * @returns {*}
   */
  getResult() {
    const error = this.getError();
    if(error) {
      throw error;
    }
    return this.raw && (this.raw.result || this.raw.data) || {};
  }

  /**
   * @returns {number}
   */
  getGeneratedIn() {
    return this.raw && this.raw.generated_in || 0;
  }

  getError() {
    if(this.error) {
      return this.error;
    }
    if(!(this.raw && this.raw.error)) {
      return null;
    }
    return this.error = new Error(this.raw.error);
  }

}

/**
 * @typedef {object} FastwayInternalResponse
 * @property {object} result
 * @property {object|null} data
 * @property {number} generated_in
 * @property {string|null} error
 */

module.exports = FastwayResponse;


text:
{{ site.rockstarTrainersTitle }}

				{{ site.rockstarTrainersButtonText }}


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

<!--L
   Copyright Ekagra Software Technologies Ltd.
   Copyright SAIC, SAIC-Frederick

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/common-security-module/LICENSE.txt for details.
L-->

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.7"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.7
	http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.7.xsd">
	<preConditions>
		<dbms type="mysql" />
	</preConditions>

	<changeSet author="uptdb41" id="1">
		<modifyColumn tableName="CSM_USER">
			<column name="LOGIN_NAME" type="VARCHAR(500)" />
		</modifyColumn>
		<addColumn tableName="CSM_USER">
			<column name="MIGRATED_FLAG" type="BOOL" defaultValue="0">
				<constraints nullable="false" />
			</column>
		</addColumn>
		<addColumn tableName="CSM_USER">
			<column name="PREMGRT_LOGIN_NAME" type="VARCHAR(100)"></column>
		</addColumn>
		<modifyColumn tableName="CSM_PG_PE">
			<column name="UPDATE_DATE" type="DATE" defaultValue="0000-00-00" />
		</modifyColumn>
		<dropColumn tableName="CSM_ROLE_PRIVILEGE" columnName="UPDATE_DATE" />
		<dropColumn tableName="CSM_USER_PE" columnName="UPDATE_DATE" />
		<renameColumn columnDataType="VARCHAR(4000)"
			newColumnName="GENERATED_SQL_USER"
            		oldColumnName="GENERATED_SQL"
            		tableName="CSM_FILTER_CLAUSE" />
		<addColumn tableName="CSM_FILTER_CLAUSE">
			<column name="GENERATED_SQL_GROUP" type="VARCHAR(4000)">
				<constraints nullable="false" />
			</column>
		</addColumn>
	</changeSet>
</databaseChangeLog>


text:
require 'set'
require 'active_support/all'
require 'compass'
require 'thor'

module Toppings
  SASS_DEPENDENCIES ||= Set.new

  def self.gem_root
    @gem_root ||= File.expand_path('../..', __FILE__)
  end

  def self.conf
    @conf = Toppings::Config.load
  end
end

require 'toppings/version'
require 'toppings/config'
require 'toppings/helper'
require 'toppings/generators'


text:
package jp.co.opentone.bsol.linkbinder.view.correspon.attachment;

import jp.co.opentone.bsol.framework.web.view.Page;
import jp.co.opentone.bsol.framework.web.view.util.ViewHelper;
import jp.co.opentone.bsol.linkbinder.attachment.AttachmentInfo;

/**
 * 添付ファイルをダウンロード可能なページ.
 * @author opentone
 */
public interface AttachmentDownloadablePage extends Page {

    /**
     * ダウンロード対象の添付ファイル情報を返す.
     * @return 添付ファイル情報
     */
    AttachmentInfo getDownloadingAttachmentInfo();

    /**
     * View関連処理のためのヘルパーオブジェクトを返す.
     * @return ヘルパーオブジェクト
     */
    ViewHelper getViewHelper();
}


text:
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel

Partial Class BVAdmin_Catalog_ProductModifierEdit
    Inherits BaseAdminPage

    Private _isShared As Boolean = False
    Private productModifierEditControl As Content.ProductModifierTemplate

    Protected Sub Page_PreInit1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Me.PageTitle = "Product Modifier Edit"
        Me.CurrentTab = AdminTabType.Catalog
        ValidateCurrentUserHasPermission(Membership.SystemPermissions.CatalogView)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SharedChoiceProductList.Visible = Me._isShared
        If ViewState("modifierId") IsNot Nothing Then
            SharedChoiceProductList.SharedChoiceType = Catalog.ChoiceInputTypeEnum.Modifier
            SharedChoiceProductList.SharedChoiceId = ViewState("modifierId").ToString()
        End If
    End Sub

    Protected Sub FinishedEditing(ByVal sender As Object, ByVal e As Content.BVModuleEventArgs)
        Dim editor As Content.ProductModifierTemplate = DirectCast(sender, Content.ProductModifierTemplate)
        If e.Info = "Canceled" Then
            If ViewState("pid") = "shared" Then
                Response.Redirect("~/BVAdmin/Catalog/ProductSharedChoices.aspx")
            Else
                'we need to pass our original product id back to the previous page
                Session(ViewState("pid")) = DirectCast(ViewState("originalProduct"), Catalog.Product)
                Response.Redirect("~/BVAdmin/Catalog/ProductChoices.aspx?source=ProductModifierEdit&id=" & ViewState("pid"))
            End If
        Else
            If ViewState("pid") = "shared" Then
                If (editor.Product IsNot Nothing) AndAlso (ViewState("modifierId") IsNot Nothing) Then
                    If editor.Product.ChoicesAndInputs.FindBusinessObject(ViewState("modifierId")) IsNot Nothing Then
                        editor.Product.ChoicesAndInputs.FindBusinessObject(ViewState("modifierId")).IsShared = True
                        editor.Product.ChoicesAndInputs.FindBusinessObject(ViewState("modifierId")).ParentProductId = ""
                        editor.Product.ChoicesAndInputs.FindBusinessObject(ViewState("modifierId")).Commit()
                    End If
                    Response.Redirect("~/BVAdmin/Catalog/ProductSharedChoices.aspx?source=ModifierEdit&modifierId=" & HttpUtility.UrlEncode(ViewState("modifierId")))
                Else
                    'we had some issues, take me away!
                    Response.Redirect("~/BVAdmin/Catalog/ProductSharedChoices.aspx")
                End If
            Else
                'we need to pass our original product id back to the previous page
                Session(ViewState("pid")) = editor.Product
                Response.Redirect("~/BVAdmin/Catalog/ProductChoices.aspx?source=ProductModifierEdit&id=" & ViewState("pid"))
        End If
        End If
    End Sub

    Protected Sub Page_PreLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
        If (Request.QueryString("pid") IsNot Nothing) Then
            If Request.QueryString("pid") = "shared" Then
                _isShared = True
            End If
            If (Request.QueryString("id") Is Nothing) AndAlso (Request.QueryString("modifierType") Is Nothing) Then
                Response.Redirect(DefaultCatalogPage)
            End If

            ViewState("pid") = Request.QueryString("pid")
            Dim product As Catalog.Product = Nothing
            Dim loadedFromViewstate As Boolean = False
            'If Not _isShared Then
            product = CType(Session(ViewState("pid")), Catalog.Product)
            If product IsNot Nothing Then
                ViewState("product") = product
                If Not Page.IsPostBack Then
                    ViewState("originalProduct") = product
                End If
                Session.Remove(ViewState("pid"))
            Else
                product = ViewState("product")
                If product Is Nothing Then
                    If Not _isShared Then
                        Response.Redirect(DefaultCatalogPage)
                    Else
                        product = New Catalog.Product()
                    End If
                Else
                    loadedFromViewstate = True
                End If
            End If
            If Not String.IsNullOrEmpty(product.ParentId) Then
                Response.Redirect(String.Format("{0}?id={1}&pid={2}", HttpContext.Current.Request.Url.AbsolutePath, Request.QueryString("id"), product.ParentId))
            End If

            'if we have a modifier type then we are adding a new modifier
            Dim modifier As Catalog.ProductModifier
            If Request.QueryString("modifierType") IsNot Nothing Then
                If Not loadedFromViewstate Then
                    'we are adding a new modifier so pass it in
                    modifier = New Catalog.ProductModifier()
                    ViewState("modifierId") = modifier.Bvin
                    modifier.Type = Request.QueryString("modifierType")
                    If product IsNot Nothing Then
                        product.ChoicesAndInputs.Add(modifier)
                        ViewState("product") = product
                    End If
                Else
                    modifier = product.ChoicesAndInputs.FindBusinessObject(CStr(ViewState("modifierId")))
                End If
            Else
                If _isShared Then
                    modifier = Catalog.ProductModifier.FindByBvin(Request.QueryString("id"))
                    ViewState("modifierId") = modifier.Bvin
                    product.ChoicesAndInputs.Add(modifier)
                Else
                    modifier = product.ChoicesAndInputs.FindBusinessObject(Request.QueryString("id"))
                    ViewState("modifierId") = modifier.Bvin
                End If
            End If
            productModifierEditControl = Content.ModuleController.LoadProductModifierEdit(modifier.Type, Me)
            productModifierEditControl.ID = "ModifierEditControl1"
            productModifierEditControl.BlockId = modifier.Bvin
            productModifierEditControl.Product = product
            AddHandler productModifierEditControl.EditingComplete, AddressOf FinishedEditing
            EditPanel.Controls.Add(productModifierEditControl)
        Else
            Response.Redirect(DefaultCatalogPage)
        End If
    End Sub
End Class


text:
describe port(8773) do
  it { should be_listening }
  its('processes') { should include 'python' }
end

describe port(8774) do
  it { should be_listening }
  its('processes') { should include 'python' }
end

describe port(8775) do
  it { should be_listening }
  its('processes') { should include 'python' }
end

describe file('/etc/nova/nova.conf') do
  its(:content) { should match /rabbit_userid = openstack/ }
  it { should exist }
end

describe file('/etc/nova/nova-compute.conf') do
  its(:content) { should match /virt_type=qemu/ }
  it { should exist }
end

describe service('nova-api') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-cert') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-compute') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-conductor') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-consoleauth') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-novncproxy') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe service('nova-scheduler') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end


text:
const autoprefixer = require(`autoprefixer`);
const CleanCss = require(`clean-css`);
const magicImporter = require(`node-sass-magic-importer`);
const postcss = require(`postcss`);
const postcssScssSyntax = require(`postcss-scss`);
const sass = require(`node-sass`);

const writeFile = require(`./write-file.js`);

module.exports = (
  inputFile,
  outputFile,
  options = { cwd: process.cwd() },
  clean = false,
  includePaths = []
) => {
  sass.render({
    file: inputFile,
    importer: magicImporter(options),
    includePaths,
  }, (error, result) => {
    if (error) throw error;

    let css = result.css.toString();
    // eslint-disable-next-line prefer-destructuring
    css = postcss(autoprefixer).process(css, { syntax: postcssScssSyntax }).css;

    if (clean) {
      css = new CleanCss({
        level: 2,
      }).minify(css).styles;
    }

    writeFile(outputFile, css);
  });
};


text:
function testToStringBeforeValueOf()
{
    var o = {toString: function() { return "s"; }, valueOf: function() { return "v"; } };
    var a = [];
    for (var i = 0; i < 10; i++)
        a.push(String(o));
    return a.join(",");
}
assertEq(testToStringBeforeValueOf(), "s,s,s,s,s,s,s,s,s,s");
checkStats({
    recorderStarted: 1,
    sideExitIntoInterpreter: 1
});


text:
package com.taodian.monitor.bolt;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taodian.monitor.core.DataService;
import com.taodian.monitor.storm.DataBolt;
import com.taodian.monitor.storm.TopologyContext;

public abstract class AbstractClickMonitorBolt implements DataBolt{
	//public static
	//private Log log = LogFactory.getLog("click.mointor");
	protected Log log = LogFactory.getLog("lm.mointor.bolt");

	protected DataService dsPool = null;

	public void setDataService(DataService s){
		this.dsPool = s;
	}

	@Override
	public void prepare(TopologyContext context) {

	}

	@Override
	public void shutdown(){

	}

}


text:
package result

import (
	"path/filepath"
	"time"

	"github.com/getgauge/gauge-proto/go/gauge_messages"
	"github.com/getgauge/gauge/config"
	"github.com/getgauge/gauge/env"
)

// SuitResult represents the result of suit execution
type SuiteResult struct {
	SpecResults             []*SpecResult
	PreSuite                *(gauge_messages.ProtoHookFailure)
	PostSuite               *(gauge_messages.ProtoHookFailure)
	IsFailed                bool
	SpecsFailedCount        int
	ExecutionTime           int64 //in milliseconds
	UnhandledErrors         []error
	Environment             string
	Tags                    string
	ProjectName             string
	Timestamp               string
	SpecsSkippedCount       int
	PreHookMessages         []string
	PostHookMessages        []string
	PreHookScreenshotFiles  []string
	PostHookScreenshotFiles []string
	PreHookScreenshots      [][]byte
	PostHookScreenshots     [][]byte
}

// NewSuiteResult is a constructor for SuitResult
func NewSuiteResult(tags string, startTime time.Time) *SuiteResult {
	result := new(SuiteResult)
	result.SpecResults = make([]*SpecResult, 0)
	result.Timestamp = startTime.Format(config.LayoutForTimeStamp)
	result.ProjectName = filepath.Base(config.ProjectRoot)
	result.Environment = env.CurrentEnvironments()
	result.Tags = tags
	return result
}

// SetFailure sets the result to failed
func (sr *SuiteResult) SetFailure() {
	sr.IsFailed = true
}

// SetSpecsSkippedCount sets the count of specs skipped.
func (sr *SuiteResult) SetSpecsSkippedCount() {
	sr.SpecsSkippedCount = 0
	for _, specRes := range sr.SpecResults {
		if specRes.Skipped {
			sr.SpecsSkippedCount++
		}
	}
}

// AddUnhandledError adds the unhandled error to suit result.
func (sr *SuiteResult) AddUnhandledError(err error) {
	sr.UnhandledErrors = append(sr.UnhandledErrors, err)
}

func (sr *SuiteResult) UpdateExecTime(startTime time.Time) {
	sr.ExecutionTime = int64(time.Since(startTime) / 1e6)
}

// AddSpecResult adds a specs result to suit result.
func (sr *SuiteResult) AddSpecResult(specResult *SpecResult) {
	if specResult.IsFailed {
		sr.IsFailed = true
		sr.SpecsFailedCount++
	}
	sr.ExecutionTime += specResult.ExecutionTime
	sr.SpecResults = append(sr.SpecResults, specResult)
}

// AddSpecResults adds multiple spec results to suit result.
func (sr *SuiteResult) AddSpecResults(specResults []*SpecResult) {
	for _, result := range specResults {
		sr.AddSpecResult(result)
	}
}

func (sr *SuiteResult) GetPreHook() []*gauge_messages.ProtoHookFailure {
	if sr.PreSuite == nil {
		return []*gauge_messages.ProtoHookFailure{}
	}
	return []*gauge_messages.ProtoHookFailure{sr.PreSuite}
}

func (sr *SuiteResult) GetPostHook() []*gauge_messages.ProtoHookFailure {
	if sr.PostSuite == nil {
		return []*gauge_messages.ProtoHookFailure{}
	}
	return []*gauge_messages.ProtoHookFailure{sr.PostSuite}
}

func (sr *SuiteResult) AddPreHook(f ...*gauge_messages.ProtoHookFailure) {
	sr.PreSuite = f[0]
}

func (sr *SuiteResult) AddPostHook(f ...*gauge_messages.ProtoHookFailure) {
	sr.PostSuite = f[0]
}

// ExecTime returns the time taken to execute the suit
func (sr *SuiteResult) ExecTime() int64 {
	return sr.ExecutionTime
}

// GetFailed returns the state of the result
func (sr *SuiteResult) GetFailed() bool {
	return sr.IsFailed
}

func (sr *SuiteResult) Item() interface{} {
	return nil
}


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

package org.apache.tapestry5.commons.util;

import org.apache.tapestry5.commons.internal.util.TapestryException;
import org.apache.tapestry5.commons.services.Coercion;

/**
 * Exception used when a {@link Coercion} throws an exception while
 * trying to coerce a value.
 *
 * @since 5.8.0
 */
public class CoercionFailedException extends TapestryException
{

    private static final long serialVersionUID = 1L;

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

}


text:
Meetup = {};

OAuth.registerService('meetup', 2, null, function(query) {

  var accessToken = getAccessToken(query);
  var identity = getIdentity(accessToken);

  return {
    serviceData: {
      id: identity.id,
      accessToken: accessToken
    },
    options: {profile: {name: identity.name}}
  };
});

var getAccessToken = function (query) {
  var config = ServiceConfiguration.configurations.findOne({service: 'meetup'});
  if (!config)
    throw new ServiceConfiguration.ConfigError();

  var response;
  try {
    response = HTTP.post(
      "https://secure.meetup.com/oauth2/access", {headers: {Accept: 'application/json'}, params: {
        code: query.code,
        client_id: config.clientId,
        client_secret: OAuth.openSecret(config.secret),
        grant_type: 'authorization_code',
        redirect_uri: OAuth._redirectUri('meetup', config),
        state: query.state
      }});
  } catch (err) {
    throw _.extend(new Error("Failed to complete OAuth handshake with Meetup. " + err.message),
                   {response: err.response});
  }

  if (response.data.error) { // if the http response was a json object with an error attribute
    throw new Error("Failed to complete OAuth handshake with Meetup. " + response.data.error);
  } else {
    return response.data.access_token;
  }
};

var getIdentity = function (accessToken) {
  try {
    var response = HTTP.get(
      "https://api.meetup.com/2/members",
      {params: {member_id: 'self', access_token: accessToken}});
    return response.data.results && response.data.results[0];
  } catch (err) {
    throw _.extend(new Error("Failed to fetch identity from Meetup. " + err.message),
                   {response: err.response});
  }
};

Meetup.retrieveCredential = function(credentialToken, credentialSecret) {
  return OAuth.retrieveCredential(credentialToken, credentialSecret);
};


text:
<!DOCTYPE html>

    <title>Task 2</title>

        <button onclick="addBefore()">ADD BEFORE</button>
        <button onclick="addAfter()">ADD AFTER</button>

TARGET


text:
package kina.agent;

import kina.agent.transformer.MetadataTransformer;
import org.apache.log4j.Logger;

import java.lang.instrument.Instrumentation;

/**
 * JVM Agent used to inject new bytecode to com.datastax.driver.core.Metadata
 * kina-cassandra, needs this to dynamically get the list of replicas for a given node.
 *
 * Attach to the JVM using -javaagent:/path/to/kina-agent.jar
 *
 * Created by luca on 28/11/14.
 */
public class KinaAgent {
    private static final Logger LOG = Logger.getLogger(KinaAgent.class);

    /**
     * Entry point hook
     *
     * @param args any optional agent parameter (actually not used)
     * @param inst a reference to the {@link java.lang.instrument.Instrumentation} object
     * @throws Exception
     */
    public static void premain(String args, Instrumentation inst) throws Exception {
        inst.addTransformer(new MetadataTransformer());
        LOG.info("KinaAgent loaded");
    }
}


text:
from com.hp.hpl.jena.rdf.model import *
from com.hp.hpl.jena.vocabulary import *

personURI = "http://somewhere/JohnSmith"
givenName = "John"
familyName = "Smith"
fullName = givenName + " " + familyName
# create an empty model
model = ModelFactory.createDefaultModel()

# create the resource
#   and add the properties cascading style
johnSmith = model.createResource(personURI)
johnSmith.addProperty(VCARD.FN, fullName
        ).addProperty(VCARD.N, model.createResource(
                ).addProperty(VCARD.Given, givenName
                        ).addProperty(VCARD.Family, familyName))

# list the statements in the graph
iter_ = model.listStatements()

# print out the predicate, subject and object of each statement
while iter_.hasNext():
    stmt = iter_.nextStatement()    # get next statement
    sub = stmt.getSubject()         # get the subject
    pred = stmt.getPredicate()      # get the predicate
    obj = stmt.getObject()          # get the object

    print(sub.toString())
    print(" " + pred.toString() + " ")
    if isinstance(obj, Resource):
        print(obj.toString())
    else:
        # object is a literal
        print(" \"" + obj.toString() + "\"")
    print(" .")


text:
package org.securegraph.query;

import org.securegraph.Property;
import org.securegraph.PropertyDefinition;
import org.securegraph.SecureGraphException;
import org.securegraph.TextIndexHint;
import org.securegraph.property.StreamingPropertyValue;
import org.securegraph.type.GeoPoint;

import java.util.Map;

public enum TextPredicate implements Predicate {
    CONTAINS;

    @Override
    public boolean evaluate(final Iterable<Property> properties, final Object second, Map<String, PropertyDefinition> propertyDefinitions) {
        for (Property property : properties) {
            PropertyDefinition propertyDefinition = propertyDefinitions.get(property.getName());
            if (evaluate(property, second, propertyDefinition)) {
                return true;
            }
        }
        return false;
    }

    private boolean evaluate(Property property, Object second, PropertyDefinition propertyDefinition) {
        Object first = property.getValue();
        if (!canEvaulate(first) || !canEvaulate(second)) {
            throw new SecureGraphException("Text predicates are only valid for string or GeoPoint fields");
        }

        String firstString = valueToString(first);
        String secondString = valueToString(second);

        switch (this) {
            case CONTAINS:
                if (propertyDefinition != null && !propertyDefinition.getTextIndexHints().contains(TextIndexHint.FULL_TEXT)) {
                    return false;
                }
                return firstString.contains(secondString);
            default:
                throw new IllegalArgumentException("Invalid text predicate: " + this);
        }
    }

    private String valueToString(Object val) {
        if (val instanceof GeoPoint) {
            val = ((GeoPoint) val).getDescription();
        } else if (val instanceof StreamingPropertyValue) {
            val = ((StreamingPropertyValue) val).readToString();
        }

        return ((String) val).toLowerCase();
    }

    private boolean canEvaulate(Object first) {
        if (first instanceof String) {
            return true;
        }
        if (first instanceof GeoPoint) {
            return true;
        }
        if (first instanceof StreamingPropertyValue && ((StreamingPropertyValue) first).getValueType() == String.class) {
            return true;
        }
        return false;
    }
}


text:
/** =========================================================
  *
  * University of Alberta
  * Department of Computer Science
  * CMPUT 670 - Games, graphs and algorithms
  *
  * Author:	Alejandro Ramirez Sanabria
		(ramirezs@ualberta.ca)
  * Date:	2/FEB/2014
  *
  * Abstract:	Assignment 2 - This is the controller class
  *		for the Y Board game. This file contains the
  * 		defintion only.
  * =========================================================
*/

#ifndef Y_CONTROLLER_H
#define Y_CONTROLLER_H

#include <cstdio>
#include <cstdlib>
#include <list>
#include <typeinfo>
#include "ygui.h"
#include "ygamestate.h"
#include "yexception.h"
#include "yconstants.h"
#include "ygamestate.h"
#include "yai.h"

/** CLASS MODEL
  *
  * The class YController controls the main execution flow, using
  * a model view controller (MVC) pattern.
  *
  * Model : YGameState
  * Controller : This class
  * View : YGUI
  *
  * This file defines the controller class for the Y Game. For detailed
  * comments, view the implementation file.
*/

namespace ARS {

	class YController {

		//Class members
		private:
			YGUI * ui;	//> The UI subsystem.
			GameState * gs; //> The model/gamestate manager.
			YAI * ai;  	//> The AI manager for second player moves.

			bool interactive; 	//> Type of session running.
			bool exit; 		//> If true, the game exits.
			bool gameInProgress; 		//> If false, the game has not been initialized.
			CellType lastLegalMove; 	//> Records the player who made the last legal move.
			CellType player;
			list<PlayerMove> * history; 	//> A history list with all the previous player moves.
			bool (YController::*commands[CONST_NUM_COMMANDS]) (UICommand); 	//> A function array used to map UI actions to commands.
		private:
            UICommand generateCommAI(bool, CellType);
			bool checkIfInt(const char *);
			bool checkIfDouble(const char *);
			bool showboard(UICommand);
			bool listCommands(UICommand);
			bool boardsize(UICommand);
			bool hex(UICommand);
			bool play(UICommand);
			bool result(UICommand);
			bool undo(UICommand);
			bool quit(UICommand);
			bool aimove(UICommand);
			bool mainMenuCycle();
			bool playFull(UICommand);
			bool trainAI(UICommand);
			bool manageAI(UICommand);
			bool executeCommand(UICommand);
			//Miscellaneous AI functions.
			bool initializeAI(const char *);
			bool sendParamsToAI(const char *);
            bool tournament(const char *);
		public:
			YController();
			~YController();
			void startYGame();
	};
}

#endif


text:
package com.github.ruediste.rise.integration;

import javax.inject.Inject;

import com.github.ruediste.rendersnakeXT.canvas.HtmlCanvas;
import com.github.ruediste.rise.component.render.RiseCanvasTarget;

/**
 * Base class for {@link HtmlCanvas}es.
 *
 */
public abstract class RiseCanvasBase<TSelf extends RiseCanvasBase<TSelf>> implements RiseCanvas<TSelf> {

    @Inject
    RiseCanvasHelper helper;

    private RiseCanvasTarget target;

    @Override
    public RiseCanvasHelper internal_riseHelper() {
        return helper;
    }

    public void flush() {
        internal_target().commitAttributes();
        internal_target().flush();
    }

    @Override
    public RiseCanvasTarget internal_target() {
        return target;
    }

    public RiseCanvasTarget getTarget() {
        return target;
    }

    @Override
    public void setTarget(RiseCanvasTarget target) {
        this.target = target;
    }
}


text:
package com.hollys.postergram.entity.poster;

import java.time.LocalDateTime;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Builder
@Entity
@Table(name="poster_type")
@AllArgsConstructor(access=AccessLevel.PRIVATE)
@NoArgsConstructor(access=AccessLevel.PRIVATE)
@EntityListeners(value = { AuditingEntityListener.class })
public class PosterType {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	@Column(name="type_name")
	private String typeName;

	@OneToMany(mappedBy = "posterType", cascade = CascadeType.ALL)
	private List<PosterTypeRel> posterTypeRels;

	@CreatedDate
	private LocalDateTime createdAt;

	@LastModifiedDate
	private LocalDateTime modifiedAt;

	public static PosterType create(String typeName){
		PosterType newPosterType = new PosterType();

		newPosterType.typeName = typeName;

		return newPosterType;
	}

}


text:
[#]: subject: "How to Configure Task Switcher in KDE Plasma Desktop"
[#]: via: "https://www.debugpoint.com/2022/02/configure-task-switcher-kde/"
[#]: author: "Arindam https://www.debugpoint.com/author/admin1/"
[#]: collector: "lujun9972"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

How to Configure Task Switcher in KDE Plasma Desktop
======
This guide explains how to configure the Task Switcher in the KDE Plasma
desktop.
This guide explains how to configure the Task Switcher in the KDE Plasma desktop.

![Configure KDE Plasma Task Switcher][1]

### What is Task Switcher?

A [task switcher][2] is a component that helps you to switch between open windows or applications in your current desktop session. Usually, the feature shows up as a list of icons when you press `Alt+Tab`.

![Thumbnail Grid Task Switcher][3]

And this is highly configurable as per your exact needs in KDE Plasma. You can customise its looks, the sort order of the icons, grouping of same applications and more.

### Changing Task Switcher in KDE Plasma

Open `System Settings`. Under `Workspace` group, click on `Window Management > Task Switcher`.

On the Main tab, the Visualisation section has a below drop-down. This drop-down contains several Task Switcher options which you can try.

Select your favourite option and hit the preview button. If you are satisfied, then you can click on Apply.

![Configure Task Switcher in KDE][4]

This is how you can change the task switcher in the KDE Plasma desktop.

### The Alternative Switcher

The Alternative tab also contains the same visualisation options for the task switcher. However, you can set a different key combination other than Alt+Tab for the Alternatives configuration set. This way, you can simultaneously experience two different groups of task switchers with different combinations.

### Visualisations

As of writing this guide [until [KDE Plasma 5.24][5]], the following options are available for different task switchers.

  * Breeze
  * Breeze Dark
  * Breeze Twilight
  * Compact
  * Fedora
  * Grid
  * Informative
  * large Icons
  * Small Icons
  * Text Only
  * Thumbnail Grid
  * Thumbnails

And here are the screenshots of the above task switchers.

![Various Task Switcher][6]

![][7]

![][8]

![][9]

![][10]

![][11]

![][12]

![][13]

![][14]

Now, that is the basic configuration of the Task Switcher in the KDE Plasma desktop. Now I am going to explain how it behaves in the below scenarios.

### Task Switcher in Multiple Monitor or Display

If you have a multiple monitor or display setup, you do not need to do anything. The Task witcher will show up based on where your mouse cursor is. That means it will show up in the active display.

[][15]

SEE ALSO:   MX Linux Launches First-Ever KDE Edition with Plasma Desktop

### Task Switcher with Same Application Grouping

You can also group the same application icons in the task switcher to keep it simple and crisp. For example, if you have multiple Dolphin file manager instances open, you can select the below option to appear Dolphin icon only once in the task switcher visualisation.

![Same application grouping][16]

But you might be wondering how to navigate through the same application instances if it appears only once. You can navigate the same applications via `Alt+`` (default value) in the task switcher. Here are the options you can change as per your need and work.

### Download more task switchers

If you are not satisfied with all the above options, you can download additional task switchers from KDE Store via the same settings window.

Click on the Get New Task Switchers [annotation#5 in above image] and select your favourite one. And click Install. After complete installation, come back to the main settings window and apply the newly downloaded visualisation.

Remember, these additional items are user-contributed and may break your current theme in some cases. So use with caution. At any time, you can hit the Reset button to come back to the stock Task Switcher visualisation.

### Closing Notes

I hope this guide helps you set up a beautiful but productive task switcher in the KDE Plasma desktop. As I said, the customisation options are plenty, and you can play around with them.

Cheers.

* * *

We bring the latest tech, software news and stuff that matters. Stay in touch via [Telegram][17], [Twitter][18], [YouTube][19], and [Facebook][20] and never miss an update!

##### Also Read

--------------------------------------------------------------------------------

via: https://www.debugpoint.com/2022/02/configure-task-switcher-kde/

作者:[Arindam][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://www.debugpoint.com/author/admin1/
[b]: https://github.com/lujun9972
[1]: https://www.debugpoint.com/wp-content/uploads/2022/02/kdetaskw1-1024x576.jpg
[2]: https://docs.kde.org/trunk5/en/kwin/kcontrol/kwintabbox/index.html
[3]: https://www.debugpoint.com/wp-content/uploads/2022/02/Thumbnail-Grid-1024x177.jpg
[4]: https://www.debugpoint.com/wp-content/uploads/2022/02/Configure-Task-Switcher-in-KDE-1024x652.jpg
[5]: https://www.debugpoint.com/2022/01/kde-plasma-5-24/
[6]: https://www.debugpoint.com/wp-content/uploads/2022/02/Thumbnails-150x150.jpg
[7]: https://www.debugpoint.com/wp-content/uploads/2022/02/Thumbnail-Grid-150x150.jpg
[8]: https://www.debugpoint.com/wp-content/uploads/2022/02/Text-Only-150x150.jpg
[9]: https://www.debugpoint.com/wp-content/uploads/2022/02/Small-Icons-150x108.jpg
[10]: https://www.debugpoint.com/wp-content/uploads/2022/02/Large-Icons-150x150.jpg
[11]: https://www.debugpoint.com/wp-content/uploads/2022/02/Informative-150x150.jpg
[12]: https://www.debugpoint.com/wp-content/uploads/2022/02/Grid-Task-Switcher-150x150.jpg
[13]: https://www.debugpoint.com/wp-content/uploads/2022/02/Compact-Task-Switcher-150x150.jpg
[14]: https://www.debugpoint.com/wp-content/uploads/2022/02/Breeze-Task-Switcher-150x150.jpg
[15]: https://www.debugpoint.com/2020/08/mx-linux-kde-edition-19-2/
[16]: https://www.debugpoint.com/wp-content/uploads/2022/02/Same-application-grouping.jpg
[17]: https://t.me/debugpoint
[18]: https://twitter.com/DebugPoint
[19]: https://www.youtube.com/c/debugpoint?sub_confirmation=1
[20]: https://facebook.com/DebugPoint


text:
#include <string>
#include <vector>

namespace executor
{
	class os_proxy
	{
	public:
		int call(const std::string& application, const std::vector<std::string>& arguments);
		std::string get_current_working_directory();
	};
}

#endif


text:
<?php
defined( 'ABSPATH' ) || die( 'Cheatin\' uh?' );

if ( class_exists( 'WPS_Hide_Login' ) ) :
	add_action( 'update_option_whl_page', 'rocket_after_update_single_options', 10, 2 );
	add_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page' );
endif;

/**
 * Exclude WPS Hide Login custom url from caching
 *
 * @since 2.11 Moved to 3rd party file
 * @since 2.6
 *
 * @param array $urls An array of URLs to exclude from cache.
 * @return array Updated array of URLs
 */
function rocket_exlude_wps_hide_login_page( $urls ) {
	$urls[] = rocket_clean_exclude_file( home_url( trailingslashit( get_option( 'whl_page' ) ) ) );

	return $urls;
}

/**
 * Add WPS Hide Login custom url to caching exclusion when activating the plugin
 *
 * @since 2.11
 */
function rocket_activate_wps_hide_login() {
	add_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page' );

	// Update .htaccess file rules.
	flush_rocket_htaccess();

	// Update config file.
	rocket_generate_config_file();
}
add_action( 'activate_wps-hide-login/wps-hide-login.php', 'rocket_activate_wps_hide_login', 11 );

/**
 * Remove WPS Hide Login custom url from caching exclusion when deactivating the plugin
 *
 * @since 2.11
 */
function rocket_deactivate_wps_hide_login() {
	remove_filter( 'rocket_cache_reject_uri', 'rocket_exlude_wps_hide_login_page' );

	// Update .htaccess file rules.
	flush_rocket_htaccess();

	// Update config file.
	rocket_generate_config_file();
}
add_action( 'deactivate_wps-hide-login/wps-hide-login.php', 'rocket_deactivate_wps_hide_login', 11 );


text:
<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Grid;

/**
 * GridSearch represents the model behind the search form about `common\models\Grid`.
 */
class GridSearch extends Grid
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Grid::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if ($this->load($params) && !$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}


text:
#include "stdafx.h"

// samplers/stratified.cpp*
#include "samplers/stratified.h"
#include "paramset.h"
#include "sampling.h"

// StratifiedSampler Method Definitions
void StratifiedSampler::StartPixel(const Point2i &p) {
    // Generate single stratified samples for the pixel
    for (size_t i = 0; i < samples1D.size(); ++i) {
        StratifiedSample1D(&samples1D[i][0], xPixelSamples * yPixelSamples, rng,
                           jitterSamples);
        Shuffle(&samples1D[i][0], xPixelSamples * yPixelSamples, 1, rng);
    }
    for (size_t i = 0; i < samples2D.size(); ++i) {
        StratifiedSample2D(&samples2D[i][0], xPixelSamples, yPixelSamples, rng,
                           jitterSamples);
        Shuffle(&samples2D[i][0], xPixelSamples * yPixelSamples, 1, rng);
    }

    // Generate arrays of stratified samples for the pixel
    for (size_t i = 0; i < samples1DArraySizes.size(); ++i)
        for (int64_t j = 0; j < samplesPerPixel; ++j) {
            int count = samples1DArraySizes[i];
            StratifiedSample1D(&sampleArray1D[i][j * count], count, rng,
                               jitterSamples);
            Shuffle(&sampleArray1D[i][j * count], count, 1, rng);
        }
    for (size_t i = 0; i < samples2DArraySizes.size(); ++i)
        for (int64_t j = 0; j < samplesPerPixel; ++j) {
            int count = samples2DArraySizes[i];
            LatinHypercube(&sampleArray2D[i][j * count].x, count, 2, rng);
        }
    PixelSampler::StartPixel(p);
}

std::unique_ptr<Sampler> StratifiedSampler::Clone(int seed) {
    StratifiedSampler *ss = new StratifiedSampler(*this);
    ss->rng.SetSequence(seed);
    return std::unique_ptr<Sampler>(ss);
}

StratifiedSampler *CreateStratifiedSampler(const ParamSet &params) {
    bool jitter = params.FindOneBool("jitter", true);
    int xsamp = params.FindOneInt("xsamples", 4);
    int ysamp = params.FindOneInt("ysamples", 4);
    int sd = params.FindOneInt("dimensions", 4);
    if (PbrtOptions.quickRender) xsamp = ysamp = 1;
    return new StratifiedSampler(xsamp, ysamp, jitter, sd);
}


text:
UpsilonFit3
===========

Markov chain Monte Carlo scan of the pMSSM parameter space, in order to evaluate the SUSY-Yukawa Sum Rule.  Based on work in [arXiv:1201.5839](http://arxiv.org/abs/1201.5839).

UpsilonFit3 is written by Mike Saelim, and is a complete rewrite of the UpsilonFit2 code he wrote for [arXiv:1201.5839](http://arxiv.org/abs/1201.5839).  It is written in C++, and requires the GNU Scientific Library (GSL) and SuSpect, a FORTRAN program written to calculate SUSY spectra.  It currently uses GSL version 1.16 and SuSpect version 2.43.  Developed in NetBeans 7.4.

**Interjection: The physics part of the code (package UpsilonFit3) is not done yet, but you can see plots of the MCMC code at work on toy problems, in ToyScan1_plots.pdf and ToyScan2_plots.pdf!**

The MCMC algorithm is an adaptive Metropolis-Hastings algorithm with simulated annealing, based on the work in [arXiv:hep-ph/0602187](http://arxiv.org/abs/hep-ph/0602187).  It is adaptive because the step size changes to reflect the estimated size of the posterior distribution.  Note that, while GSL has a simulated annealing package, we found it very limited.

Structure
---------

It has three main parts:

1. The Mcmc package, which implements a general Markov chain Monte Carlo scan over a parameter space, given generic constraints.  Class McmcScan is abstract, and requires a subclass to implement key functions.

2. The ToyScans package, which implements scans on small toy problems as tests/examples of the MCMC code at work.

3. The UpsilonFit3 package, which uses the Mcmc package to implement the scan over a subspace of the phenomenological Minimal Supersymmetric Standard Model (pMSSM) parameter space, constrained by a set of measurements made at the Large Hadron Collider (LHC) or a future linear electron-positron collider like the International Linear Collider (ILC).  Its main class, PmssmScan, inherits from Mcmc::McmcScan.  It also calculates the Upsilon parameter, defined in the SUSY-Yukawa Sum Rule ([arXiv:1004.5350](http://arxiv.org/abs/1004.5350)), for the resulting posterior distribution.

Acknowledgments
---------------
Mike Saelim would like to thank
* Maxim Perelstein for the original project and his guidance over the years, and
* Curran Muhlberger for his expert development and programming advice.

**SuSpect** is written by Abdelhak Djouadi, Jean-Loic Kneur, and Gilbert Moultaka: [website](http://www.coulomb.univ-montp2.fr/perso/jean-loic.kneur/Suspect/), [arXiv:hep-ph/0211331](http://arxiv.org/abs/hep-ph/0211331).


text:
struct IDXGIFactory;
struct IDXGISwapChain;
struct ID3D11Device;
struct ID3D11DeviceContext;

namespace ImWindow
{
	class ImwWindowManagerDX11 : public ImwWindowManagerEasyWindow
	{
	public:
		ImwWindowManagerDX11(bool bCustomFrame);
		virtual							~ImwWindowManagerDX11();

		IDXGIFactory*					GetDXGIFactory() const { return m_pDXGIFactory; }
		ID3D11Device*					GetDX11Device() const { return m_pDX11Device; }
		ID3D11DeviceContext*			GetDX11DeviceContext() const { return m_pDX11DeviceContext; }
	protected:
		virtual bool					InternalInit();
		virtual void					InternalDestroy();
		virtual bool					CanCreateMultipleWindow() { return true; }
		virtual ImwPlatformWindow*		CreatePlatformWindow(EPlatformWindowType eType, ImwPlatformWindow* pParent);

		virtual float					GetTitleBarHeight() const;
		virtual void					PaintTitleBar(ImwPlatformWindow* pPlatformWindow, bool bDrawTitle);
	protected:
		IDXGIFactory*					m_pDXGIFactory;
		ID3D11Device*					m_pDX11Device;
		ID3D11DeviceContext*			m_pDX11DeviceContext;
	};
}

#endif //__IM_WINDOW_MANAGER_DX11_H__


text:
package com.cloudera.lib.service;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public interface Scheduler {

  public abstract void schedule(Callable<?> callable, long delay, long interval, TimeUnit unit);

  public abstract void schedule(Runnable runnable, long delay, long interval, TimeUnit unit);

}


text:
import { RenderTest, jitSuite, test, Count } from '..';
import { Dict } from '@glimmer/interfaces';
import { SimpleElement } from '@simple-dom/interface';
import { Option } from '@glimmer/interfaces';

class BaseModifier {
  element?: SimpleElement;
  didInsertElement(_params: unknown[], _hash: Dict<unknown>) {}
  willDestroyElement() {}
  didUpdate(_params: unknown[], _hash: Dict<unknown>) {}
}

abstract class AbstractInsertable extends BaseModifier {
  abstract didInsertElement(_params: unknown[], _hash: Dict<unknown>): void;
}

abstract class AbstractDestroyable extends BaseModifier {
  abstract willDestroyElement(): void;
}

class ModifierTests extends RenderTest {
  static suiteName = 'modifiers';

  @test
  'Element modifier with hooks'(assert: Assert, count: Count) {
    this.registerModifier(
      'foo',
      class {
        element?: SimpleElement;
        didInsertElement() {
          count.expect('didInsertElement');
          assert.ok(this.element, 'didInsertElement');
          assert.equal(this.element!.getAttribute('data-ok'), 'true', 'didInsertElement');
        }

        didUpdate() {
          count.expect('didUpdate');
          assert.ok(true, 'didUpdate');
        }

        willDestroyElement() {
          count.expect('willDestroyElement');
          assert.ok(true, 'willDestroyElement');
        }
      }
    );

    this.render('{{#if this.ok}}

{{/if}}', {
      bar: 'bar',
      ok: true,
    });

    this.rerender({ bar: 'foo' });
    this.rerender({ ok: false });
  }

  @test
  'didUpdate is not called when params are constants'(assert: Assert, count: Count) {
    this.registerModifier(
      'foo',
      class {
        element?: SimpleElement;
        didInsertElement() {
          count.expect('didInsertElement');
          assert.ok(true);
        }
        didUpdate() {
          count.expect('didUpdate', 0);
          assert.ok(false);
        }
        willDestroyElement() {
          count.expect('willDestroyElement');
        }
      }
    );

    this.render('{{#if this.ok}}

{{/if}}{{this.ok}}', {
      ok: true,
      data: 'ok',
    });
    this.rerender({ data: 'yup' });
    this.rerender({ ok: false });
  }

  @test
  'modifiers on components are forwarded to a single element receiving the splattributes'(
    assert: Assert
  ) {
    let modifierParams: Option<unknown[]> = null;
    let modifierNamedArgs: Option<Dict<unknown>> = null;
    let modifiedElement: SimpleElement | undefined;
    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
    }
    this.registerComponent('Glimmer', 'TheFoo', '
Foo
');
    this.registerModifier('bar', Bar);
    this.render('<TheFoo {{bar "something" foo="else"}}/>');
    assert.deepEqual(modifierParams, ['something']);
    assert.deepEqual(modifierNamedArgs, { foo: 'else' });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
  }

  @test
  'modifiers on components are forwarded to all the elements receiving the splattributes'(
    assert: Assert
  ) {
    let elementIds: Option<string>[] = [];
    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        assert.deepEqual(params, ['something']);
        assert.deepEqual(namedArgs, { foo: 'else' });
        if (this.element) {
          elementIds.push(this.element.getAttribute('id'));
        }
      }
    }
    this.registerComponent(
      'Glimmer',
      'TheFoo',
      '
Foo

Bar
'
    );
    this.registerModifier('bar', Bar);
    this.render('<TheFoo {{bar "something" foo="else"}}/>');
    assert.deepEqual(
      elementIds,
      ['inner-one', 'inner-two'],
      'The modifier has been instantiated twice, once for each element with splattributes'
    );
  }

  @test
  'modifiers on components accept bound arguments and track changes on them'(assert: Assert) {
    let modifierParams: Option<unknown[]> = null;
    let modifierNamedArgs: Option<Dict<unknown>> = null;
    let modifiedElement: SimpleElement | undefined;
    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
      didUpdate(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
    }
    this.registerComponent('Glimmer', 'TheFoo', '
Foo
');
    this.registerModifier('bar', Bar);
    this.render('<TheFoo {{bar this.something foo=this.foo}}/>', {
      something: 'something',
      foo: 'else',
    });
    assert.deepEqual(modifierParams, ['something']);
    assert.deepEqual(modifierNamedArgs, { foo: 'else' });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
    this.rerender({ something: 'another', foo: 'thingy' });
    assert.deepEqual(modifierParams, ['another']);
    assert.deepEqual(modifierNamedArgs, { foo: 'thingy' });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
  }

  @test
  'modifiers on components accept `this` in both positional params and named arguments, and updates when it changes'(
    assert: Assert
  ) {
    let modifierParams: Option<unknown[]> = null;
    let modifierNamedArgs: Option<Dict<unknown>> = null;
    let modifiedElement: SimpleElement | undefined;
    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
      didUpdate(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
    }
    let context = { id: 1 };
    let context2 = { id: 2 };
    this.registerComponent('Glimmer', 'TheFoo', '
Foo
');
    this.registerModifier('bar', Bar);
    this.render('<TheFoo {{bar "name" this foo=this}}/>', context);
    assert.deepEqual(modifierParams, ['name', context]);
    assert.deepEqual(modifierNamedArgs, { foo: context });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
    this.rerender(context2);
    assert.deepEqual(modifierParams, ['name', context2]);
    assert.deepEqual(modifierNamedArgs, { foo: context2 });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
  }

  @test
  'modifiers on components accept local variables in both positional params and named arguments, and updates when they change'(
    assert: Assert
  ) {
    let modifierParams: Option<unknown[]> = null;
    let modifierNamedArgs: Option<Dict<unknown>> = null;
    let modifiedElement: SimpleElement | undefined;
    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
      didUpdate(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        modifiedElement = this.element;
      }
    }
    this.registerComponent('Glimmer', 'TheFoo', '
Foo
');
    this.registerModifier('bar', Bar);
    this.render(
      `
      {{#let this.foo as |v|}}
        <TheFoo {{bar v foo=v}}/>
      {{/let}}
    `,
      { foo: 'bar' }
    );
    assert.deepEqual(modifierParams, ['bar']);
    assert.deepEqual(modifierNamedArgs, { foo: 'bar' });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
    this.rerender({ foo: 'qux' });
    assert.deepEqual(modifierParams, ['qux']);
    assert.deepEqual(modifierNamedArgs, { foo: 'qux' });
    assert.equal(
      modifiedElement && modifiedElement.getAttribute('id'),
      'inner-div',
      'Modifier is called on the element receiving the splattributes'
    );
  }

  @test
  'modifiers on components can be received and forwarded to inner components'(assert: Assert) {
    let modifierParams: Option<unknown[]> = null;
    let modifierNamedArgs: Option<Dict<unknown>> = null;
    let elementIds: Option<string>[] = [];

    class Bar extends AbstractInsertable {
      didInsertElement(params: unknown[], namedArgs: Dict<unknown>) {
        modifierParams = params;
        modifierNamedArgs = namedArgs;
        if (this.element) {
          elementIds.push(this.element.getAttribute('id'));
        }
      }
    }
    this.registerComponent(
      'Glimmer',
      'TheInner',
      '
{{yield}}
'
    );
    this.registerComponent(
      'Glimmer',
      'TheFoo',
      '
Outer
<TheInner ...attributes>Hello</TheInner>'
    );
    this.registerModifier('bar', Bar);
    this.render(
      `
      {{#let this.foo as |v|}}
        <TheFoo {{bar v foo=v}}/>
      {{/let}}
    `,
      { foo: 'bar' }
    );
    assert.deepEqual(modifierParams, ['bar']);
    assert.deepEqual(modifierNamedArgs, { foo: 'bar' });
    assert.deepEqual(elementIds, ['outer-div', 'inner-div'], 'Modifiers are called on all levels');
  }

  @test
  'same element insertion order'(assert: Assert) {
    let insertionOrder: string[] = [];

    class Foo extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('foo');
      }
    }

    class Bar extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('bar');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);

    this.render('

');
    assert.deepEqual(insertionOrder, ['foo', 'bar']);
  }

  @test
  'same element destruction order'(assert: Assert) {
    let destructionOrder: string[] = [];

    class Foo extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('foo');
      }
    }

    class Bar extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('bar');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);

    this.render('{{#if this.nuke}}

{{/if}}', { nuke: true });
    assert.deepEqual(destructionOrder, []);
    this.rerender({ nuke: false });
    assert.deepEqual(destructionOrder, ['foo', 'bar']);
  }

  @test
  'parent -> child insertion order'(assert: Assert) {
    let insertionOrder: string[] = [];

    class Foo extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('foo');
      }
    }

    class Bar extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('bar');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);

    this.render('

');
    assert.deepEqual(insertionOrder, ['bar', 'foo']);
  }

  @test
  'parent -> child destruction order'(assert: Assert) {
    let destructionOrder: string[] = [];

    class Foo extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('foo');
      }
    }

    class Bar extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('bar');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);

    this.render('{{#if this.nuke}}

{{/if}}', { nuke: true });
    assert.deepEqual(destructionOrder, []);
    this.rerender({ nuke: false });
    assert.deepEqual(destructionOrder, ['bar', 'foo']);
  }

  @test
  'sibling insertion order'(assert: Assert) {
    let insertionOrder: string[] = [];

    class Foo extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('foo');
      }
    }

    class Bar extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('bar');
      }
    }

    class Baz extends AbstractInsertable {
      didInsertElement() {
        insertionOrder.push('baz');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);
    this.registerModifier('baz', Baz);

    this.render('

');
    assert.deepEqual(insertionOrder, ['bar', 'baz', 'foo']);
  }

  @test
  'sibling destruction order'(assert: Assert) {
    let destructionOrder: string[] = [];

    class Foo extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('foo');
      }
    }

    class Bar extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('bar');
      }
    }

    class Baz extends AbstractDestroyable {
      willDestroyElement() {
        destructionOrder.push('baz');
      }
    }
    this.registerModifier('bar', Bar);
    this.registerModifier('foo', Foo);
    this.registerModifier('baz', Baz);

    this.render(
      '{{#if this.nuke}}

{{/if}}',
      {
        nuke: true,
      }
    );
    assert.deepEqual(destructionOrder, []);
    this.rerender({ nuke: false });
    assert.deepEqual(destructionOrder, ['bar', 'baz', 'foo']);
  }

  @test
  'with params'(assert: Assert, count: Count) {
    class Foo extends BaseModifier {
      didInsertElement([bar]: string[]) {
        count.expect('didInsertElement');
        assert.equal(bar, 'bar');
      }
      didUpdate([foo]: string[]) {
        count.expect('didUpdate');
        assert.equal(foo, 'foo');
      }
    }
    this.registerModifier('foo', Foo);
    this.render('

', { bar: 'bar' });
    this.rerender({ bar: 'foo' });
  }

  @test
  'with hash'(assert: Assert, count: Count) {
    class Foo extends BaseModifier {
      didInsertElement(_params: unknown[], { bar }: Dict<string>) {
        count.expect('didInsertElement');
        assert.equal(bar, 'bar');
      }
      didUpdate(_params: unknown[], { bar }: Dict<string>) {
        count.expect('didUpdate');
        assert.equal(bar, 'foo');
      }
    }
    this.registerModifier('foo', Foo);
    this.render('

', { bar: 'bar' });
    this.rerender({ bar: 'foo' });
  }

  @test
  'with hash and params'(assert: Assert, count: Count) {
    class Foo extends BaseModifier {
      didInsertElement([baz]: string[], { bar }: Dict<string>) {
        count.expect('didInsertElement');
        assert.equal(bar, 'bar');
        assert.equal(baz, 'baz');
      }
      didUpdate([foo]: string[], { bar }: Dict<string>) {
        count.expect('didUpdate');
        assert.equal(bar, 'foo');
        assert.equal(foo, 'foo');
      }
    }
    this.registerModifier('foo', Foo);
    this.render('

', { bar: 'bar', baz: 'baz' });
    this.rerender({ bar: 'foo', baz: 'foo' });
  }
}
jitSuite(ModifierTests);


text:
package carbon.shadow;

/**
 * Created by Marcin on 2014-11-19.
 */
public interface ShadowView {
    /**
     * Gets the elevation.
     *
     * @return the elevation value.
     */
    float getElevation();

    /**
     * Sets the elevation value. There are useful values of elevation defined in xml as carbon_elevationFlat, carbon_elevationLow, carbon_elevationMedium, carbon_elevationHigh, carbon_elevationMax
     *
     * @param elevation can be from range [0 - 25]
     */
    void setElevation(float elevation);

    float getTranslationZ();

    void setTranslationZ(float translationZ);

    ShadowShape getShadowShape();

    Shadow getShadow();

    void invalidateShadow();
}


text:
package com.ohmdb.exception;

@SuppressWarnings("serial")
public class InvalidIdException extends OhmDBException {

	public InvalidIdException(long id) {
		super("Invalid ID: " + id);
	}

}