text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnsupervisedLearning.UserProfiles.Normalization
{
  public class FeatureScaling : IRatingsNormalization
  {
    public string print
    {
      get
      {
        return "feature_scaling";
      }
    }

    public Func<double, double> setupNormalizationFunction(IList<double> ratings)
    {
      var min = ratings.Min();
      var max = ratings.Max();

      return r => (r - min) / (max - min);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0, maximum-scale=1, minimum-scale=1" >
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,500,700" rel="stylesheet" type="text/css">
    <title>PartyWebService</title>
    <link href="css/main.css" rel="stylesheet" />

  </audio>


text:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Globalization;

namespace Org.Apache.Etch.Bindings.Csharp.Util
{
    /// <summary>
    /// Constants and methods related to tcp transport.
    /// </summary>
    abstract public class TcpTransport : Connection<SessionData>, TransportData
    {
        /// <summary>
        /// Constructs the TcpTransport. Pulls common parameters off the uri.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="resources"></param>
        protected TcpTransport(URL uri, Resources resources)
        {
            options = new TcpOptions(uri, resources);
        }

        private readonly TcpOptions options;

        protected override void Stop0()
        {
            try
            {
                Close(false);
            }
            catch
            {
                // ignore
            }
            base.Stop0();
        }

        protected Socket socket;

        /// <summary>
        /// Checks the connection socket for being open.
        /// </summary>
        /// <returns>the connection socket</returns>
        protected Socket CheckSocket()
        {
            Socket s = socket;

            if (s == null)
                throw new IOException("socket closed");

            return s;
        }

        public override void Close(bool reset)
        {
            Socket s = socket;
            if (s != null)
            {
                try
                {
                    try
                    {
                        if (reset)
                            s.LingerState = new LingerOption(false, 0);
                        else
                        {
                            Flush();
                            ShutdownOutput();
                        }
                    }
                    finally
                    {
                        s.Close();
                    }
                }
                catch
                {
                    // ignore.
                }
                finally
                {
                    stream = null;
                    socket = null;
                }
            }
        }

        /// <summary>
        /// Sends some data to the remote end. The output data is buffered
        /// until the buffer is full or the buffer is flushed.
        /// </summary>
        /// <param name="buf">the bytes to be sent</param>
        /// Exception:
        ///     throws Exception if there is a problem transmitting the
        ///     data. Such a problem causes the current connection to be
        ///     reset.
        /// <seealso cref="Flush()"/>
        /// <seealso cref="TcpOptions.autoFlush"/>
        public void Send(byte[] buf)
        {
            Send(buf, 0, buf.Length);
        }

        /// <summary>
        /// Sends some data to the remote end. The output data is buffered
        /// until the buffer is full or the buffer is flushed.
        /// </summary>
        /// <param name="buf">the bytes to be sent</param>
        /// <param name="off">the offset into buf of the first byte to send</param>
        /// <param name="len">the number of bytes to send</param>
        public void Send(byte[] buf, int off, int len)
        {
            try
            {
                Stream s = checkStream();
                s.Write(buf, off, len);
                if (options.autoFlush)
                {
                    s.Flush();
                }
            }
            catch (Exception)
            {
                Close(true);
                throw;
            }
        }

        public void Flush()
        {
            try
            {
                checkStream().Flush();
            }
            catch (Exception)
            {
                Close(true);
                throw;
            }
        }

        protected Stream checkStream()
        {
            Stream ns = stream;
            if (ns == null)
                throw new IOException("net stream closed");
            return ns;
        }

        private void FireData(FlexBuffer buf)
        {
            session.SessionData(null, buf);
        }

        protected Stream stream;

        public override EndPoint LocalAddress()
        {
            return CheckSocket().LocalEndPoint;
        }

        public override EndPoint RemoteAddress()
        {
            return CheckSocket().RemoteEndPoint;
        }

        public void TransportData(Who recipient, FlexBuffer buf)
        {
            Send(buf.GetBuf(), buf.Index(), buf.Avail());
        }

        protected override void SetUpSocket()
        {
            Socket s = CheckSocket();

            s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, options.keepAlive);
            s.LingerState = new LingerOption(options.lingerTime >= 0, options.lingerTime >= 0 ? options.lingerTime : 0);
            s.NoDelay = options.noDelay;

            stream = new NetworkStream(socket);
            // TODO do something about buffering this stream.
        }

        public void ShutdownInput()
        {
            CheckSocket().Shutdown(SocketShutdown.Receive);
        }

        public void ShutdownOutput()
        {
            CheckSocket().Shutdown(SocketShutdown.Send);
        }

        abstract protected Socket NewSocket();

        abstract protected bool IsServer();

        public override object TransportQuery(object query)
        {
            if (query.Equals(TransportConsts.IS_SERVER))
                return IsServer();

            return base.TransportQuery(query);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        protected override bool OpenSocket(bool reconnect)
        {
            // if a one time connection from a server socket listener, just
            // return the existing socket.
            if (!reconnect && socket != null)
                return true;

            // if a one time connection from a server socket listener, and
            // this is a reconnect, then bail.
            if (reconnect && IsServer())
                return false;

            // if a reconnect but no retries allowed, then bail.
            if (reconnect && options.reconnectDelay == 0)
                return false;

            // ok, we don't have an existing socket, and this is either the first
            // connection attempt or a reconnect with delay > 0.

            bool first = true;

            while (IsStarted())
            {
                // if reconnect is false and first is true, this is our
                // very first attempt to connect. otherwise, we are trying
                // to reconnect a broken link or establish a link where we
                // have already failed at least once.

                if (reconnect || !first)
                {
                    if (options.reconnectDelay == 0)
                        return false;

                    System.Threading.Monitor.Wait(this, options.reconnectDelay);

                    if (!IsStarted())
                        break;
                }

                // try to open a socket.

                try
                {
                    socket = NewSocket();
                    return true;
                }
                catch (Exception e)
                {
                    if (first)
                    {
                        first = false;
                        FireException("open", e);
                    }
                }
            }

            return false;
        }

        protected override void ReadSocket()
        {

            //set the language to English in order to make sure the following
            //string comparisons work also with an installed .Net Framework Language Pack

            //save users current CI
            CultureInfo userCI = Thread.CurrentThread.CurrentCulture;

            //set CI to English
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            Stream ns = checkStream();
            FlexBuffer buf = new FlexBuffer(new byte[8192]);

            try
            {
                while (IsStarted())
                {
                    int n = ns.Read(buf.GetBuf(), 0, buf.Length());

                    if (n <= 0)
                       break;

                    buf.SetLength(n);
                    buf.SetIndex(0);
                    FireData(buf);
                }
              }
            catch (Exception e)
            {
                string errorMessage = e.Message;

                if (errorMessage == null)
                  throw;
                if (errorMessage.Contains("connection was aborted"))
                  return;
                if (errorMessage.Contains("blocking operation"))
                  return;
                if (errorMessage.Contains("socket closed"))
                  return;
                if (errorMessage.Contains("read operation failed"))
                  return;
                throw;

            }
            finally
            {
                //set CI back to the users CI
                Thread.CurrentThread.CurrentCulture = userCI;
                Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
            }
        }
    }
}


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

<title>TopicManager</title>
<meta name="date" content="2015-02-11">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.rivescript

Class TopicManager

java.lang.Object

com.rivescript.TopicManager

public class TopicManager
extends java.lang.Object

A topic manager class for RiveScript.

Constructor Summary

Constructors

Constructor and Description

TopicManager()

Create a topic manager.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
exists(java.lang.String topic)

Test whether a topic exists.

Trigger
findTriggerByInheritance(java.lang.String topic,
                        java.lang.String pattern,
                        int depth)

Walk the inherit/include trees starting with one topic and find the trigger
 object that corresponds to the search trigger.

java.lang.String[]
getTopicTree(java.lang.String topic,
            int depth)

Walk the inherit/include trees starting with one topic and list every topic we find.

java.lang.String[]
listTopics()

Retrieve a list of the existing topics.

void
sortReplies()

Sort the replies in all the topics.

Topic
topic(java.lang.String topic)

Specify which topic any following operations will operate under.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TopicManager

public TopicManager()

Create a topic manager. Only one per RiveScript interpreter needed.

Method Detail

topic

public Topic topic(java.lang.String topic)

Specify which topic any following operations will operate under.

Parameters:

topic - Name of the topic (will be constructed if it doesn't exist).

exists

public boolean exists(java.lang.String topic)

Test whether a topic exists.

Parameters:

topic - Name of the topic to test.

listTopics

public java.lang.String[] listTopics()

Retrieve a list of the existing topics.

sortReplies

public void sortReplies()

Sort the replies in all the topics. This will build trigger lists of
 the topics (taking into account topic inheritence/includes) and sending
 the final trigger list into each topic's individual sortTriggers() method.

findTriggerByInheritance

public Trigger findTriggerByInheritance(java.lang.String topic,
                                        java.lang.String pattern,
                                        int depth)

Walk the inherit/include trees starting with one topic and find the trigger
 object that corresponds to the search trigger. Or rather, if you have a trigger
 that was part of a topic's sort list, but that topic itself doesn't manage
 that trigger, this function will search the tree to find the topic that does,
 and return its Trigger object.

Parameters:

topic - The name of the topic to start at.

pattern - The trigger pattern text.

depth - The current depth limit (should start at 0), for recursion.

getTopicTree

public java.lang.String[] getTopicTree(java.lang.String topic,
                                       int depth)

Walk the inherit/include trees starting with one topic and list every topic we find.

Parameters:

topic - The name of the topic to start at.

depth - The current depth limit (should start at 0), for recursion.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace Test\CrudBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class TestCrudBundle extends Bundle
{
}


text:
namespace arrow {

using internal::AdaptiveIntBuilderBase;

AdaptiveIntBuilderBase::AdaptiveIntBuilderBase(uint8_t start_int_size, MemoryPool* pool,
                                               int64_t alignment)
    : ArrayBuilder(pool, alignment),
      start_int_size_(start_int_size),
      int_size_(start_int_size) {}

void AdaptiveIntBuilderBase::Reset() {
  ArrayBuilder::Reset();
  data_.reset();
  raw_data_ = nullptr;
  pending_pos_ = 0;
  pending_has_nulls_ = false;
  int_size_ = start_int_size_;
}

Status AdaptiveIntBuilderBase::Resize(int64_t capacity) {
  RETURN_NOT_OK(CheckCapacity(capacity));
  capacity = std::max(capacity, kMinBuilderCapacity);

  int64_t nbytes = capacity * int_size_;
  if (capacity_ == 0) {
    ARROW_ASSIGN_OR_RAISE(data_, AllocateResizableBuffer(nbytes, pool_));
  } else {
    RETURN_NOT_OK(data_->Resize(nbytes));
  }
  raw_data_ = reinterpret_cast<uint8_t*>(data_->mutable_data());

  return ArrayBuilder::Resize(capacity);
}

template <typename new_type, typename old_type>
typename std::enable_if<sizeof(old_type) >= sizeof(new_type), Status>::type
AdaptiveIntBuilderBase::ExpandIntSizeInternal() {
  return Status::OK();
}

template <typename new_type, typename old_type>
typename std::enable_if<(sizeof(old_type) < sizeof(new_type)), Status>::type
AdaptiveIntBuilderBase::ExpandIntSizeInternal() {
  int_size_ = sizeof(new_type);
  RETURN_NOT_OK(Resize(data_->size() / sizeof(old_type)));

  const old_type* src = reinterpret_cast<old_type*>(raw_data_);
  new_type* dst = reinterpret_cast<new_type*>(raw_data_);
  // By doing the backward copy, we ensure that no element is overridden during
  // the copy process while the copy stays in-place.
  std::copy_backward(src, src + length_, dst + length_);

  return Status::OK();
}

std::shared_ptr<DataType> AdaptiveUIntBuilder::type() const {
  auto int_size = int_size_;
  if (pending_pos_ != 0) {
    const uint8_t* valid_bytes = pending_has_nulls_ ? pending_valid_ : nullptr;
    int_size =
        internal::DetectUIntWidth(pending_data_, valid_bytes, pending_pos_, int_size_);
  }
  switch (int_size) {
    case 1:
      return uint8();
    case 2:
      return uint16();
    case 4:
      return uint32();
    case 8:
      return uint64();
    default:
      DCHECK(false);
  }
  return nullptr;
}

std::shared_ptr<DataType> AdaptiveIntBuilder::type() const {
  auto int_size = int_size_;
  if (pending_pos_ != 0) {
    const uint8_t* valid_bytes = pending_has_nulls_ ? pending_valid_ : nullptr;
    int_size = internal::DetectIntWidth(reinterpret_cast<const int64_t*>(pending_data_),
                                        valid_bytes, pending_pos_, int_size_);
  }
  switch (int_size) {
    case 1:
      return int8();
    case 2:
      return int16();
    case 4:
      return int32();
    case 8:
      return int64();
    default:
      DCHECK(false);
  }
  return nullptr;
}

AdaptiveIntBuilder::AdaptiveIntBuilder(uint8_t start_int_size, MemoryPool* pool,
                                       int64_t alignment)
    : AdaptiveIntBuilderBase(start_int_size, pool, alignment) {}

Status AdaptiveIntBuilder::FinishInternal(std::shared_ptr<ArrayData>* out) {
  RETURN_NOT_OK(CommitPendingData());

  std::shared_ptr<Buffer> null_bitmap;
  RETURN_NOT_OK(null_bitmap_builder_.Finish(&null_bitmap));
  RETURN_NOT_OK(TrimBuffer(length_ * int_size_, data_.get()));

  *out = ArrayData::Make(type(), length_, {null_bitmap, data_}, null_count_);

  data_ = nullptr;
  capacity_ = length_ = null_count_ = 0;
  return Status::OK();
}

Status AdaptiveIntBuilder::CommitPendingData() {
  if (pending_pos_ == 0) {
    return Status::OK();
  }
  RETURN_NOT_OK(Reserve(pending_pos_));
  const uint8_t* valid_bytes = pending_has_nulls_ ? pending_valid_ : nullptr;
  RETURN_NOT_OK(AppendValuesInternal(reinterpret_cast<const int64_t*>(pending_data_),
                                     pending_pos_, valid_bytes));
  pending_has_nulls_ = false;
  pending_pos_ = 0;
  return Status::OK();
}

static constexpr int64_t kAdaptiveIntChunkSize = 8192;

Status AdaptiveIntBuilder::AppendValuesInternal(const int64_t* values, int64_t length,
                                                const uint8_t* valid_bytes) {
  if (pending_pos_ > 0) {
    // UnsafeAppendToBitmap expects length_ to be the pre-update value, satisfy it
    DCHECK_EQ(length, pending_pos_) << "AppendValuesInternal called while data pending";
    length_ -= pending_pos_;
  }

  while (length > 0) {
    // In case `length` is very large, we don't want to trash the cache by
    // scanning it twice (first to detect int width, second to copy the data).
    // Instead, process data in L2-cacheable chunks.
    const int64_t chunk_size = std::min(length, kAdaptiveIntChunkSize);

    uint8_t new_int_size;
    new_int_size = internal::DetectIntWidth(values, valid_bytes, chunk_size, int_size_);

    DCHECK_GE(new_int_size, int_size_);
    if (new_int_size > int_size_) {
      // This updates int_size_
      RETURN_NOT_OK(ExpandIntSize(new_int_size));
    }

    switch (int_size_) {
      case 1:
        internal::DowncastInts(values, reinterpret_cast<int8_t*>(raw_data_) + length_,
                               chunk_size);
        break;
      case 2:
        internal::DowncastInts(values, reinterpret_cast<int16_t*>(raw_data_) + length_,
                               chunk_size);
        break;
      case 4:
        internal::DowncastInts(values, reinterpret_cast<int32_t*>(raw_data_) + length_,
                               chunk_size);
        break;
      case 8:
        internal::DowncastInts(values, reinterpret_cast<int64_t*>(raw_data_) + length_,
                               chunk_size);
        break;
      default:
        DCHECK(false);
    }

    // UnsafeAppendToBitmap increments length_ by chunk_size
    ArrayBuilder::UnsafeAppendToBitmap(valid_bytes, chunk_size);
    values += chunk_size;
    if (valid_bytes != nullptr) {
      valid_bytes += chunk_size;
    }
    length -= chunk_size;
  }

  return Status::OK();
}

Status AdaptiveUIntBuilder::CommitPendingData() {
  if (pending_pos_ == 0) {
    return Status::OK();
  }
  RETURN_NOT_OK(Reserve(pending_pos_));
  const uint8_t* valid_bytes = pending_has_nulls_ ? pending_valid_ : nullptr;
  RETURN_NOT_OK(AppendValuesInternal(pending_data_, pending_pos_, valid_bytes));
  pending_has_nulls_ = false;
  pending_pos_ = 0;
  return Status::OK();
}

Status AdaptiveIntBuilder::AppendValues(const int64_t* values, int64_t length,
                                        const uint8_t* valid_bytes) {
  RETURN_NOT_OK(CommitPendingData());
  RETURN_NOT_OK(Reserve(length));

  return AppendValuesInternal(values, length, valid_bytes);
}

template <typename new_type>
Status AdaptiveIntBuilder::ExpandIntSizeN() {
  switch (int_size_) {
    case 1:
      return ExpandIntSizeInternal<new_type, int8_t>();
    case 2:
      return ExpandIntSizeInternal<new_type, int16_t>();
    case 4:
      return ExpandIntSizeInternal<new_type, int32_t>();
    case 8:
      return ExpandIntSizeInternal<new_type, int64_t>();
    default:
      DCHECK(false);
  }
  return Status::OK();
}

Status AdaptiveIntBuilder::ExpandIntSize(uint8_t new_int_size) {
  switch (new_int_size) {
    case 1:
      return ExpandIntSizeN<int8_t>();
    case 2:
      return ExpandIntSizeN<int16_t>();
    case 4:
      return ExpandIntSizeN<int32_t>();
    case 8:
      return ExpandIntSizeN<int64_t>();
    default:
      DCHECK(false);
  }
  return Status::OK();
}

AdaptiveUIntBuilder::AdaptiveUIntBuilder(uint8_t start_int_size, MemoryPool* pool)
    : AdaptiveIntBuilderBase(start_int_size, pool) {}

Status AdaptiveUIntBuilder::FinishInternal(std::shared_ptr<ArrayData>* out) {
  RETURN_NOT_OK(CommitPendingData());

  std::shared_ptr<Buffer> null_bitmap;
  RETURN_NOT_OK(null_bitmap_builder_.Finish(&null_bitmap));
  RETURN_NOT_OK(TrimBuffer(length_ * int_size_, data_.get()));

  *out = ArrayData::Make(type(), length_, {null_bitmap, data_}, null_count_);

  data_ = nullptr;
  capacity_ = length_ = null_count_ = 0;
  return Status::OK();
}

Status AdaptiveUIntBuilder::AppendValuesInternal(const uint64_t* values, int64_t length,
                                                 const uint8_t* valid_bytes) {
  if (pending_pos_ > 0) {
    // UnsafeAppendToBitmap expects length_ to be the pre-update value, satisfy it
    DCHECK_EQ(length, pending_pos_) << "AppendValuesInternal called while data pending";
    length_ -= pending_pos_;
  }

  while (length > 0) {
    // See AdaptiveIntBuilder::AppendValuesInternal
    const int64_t chunk_size = std::min(length, kAdaptiveIntChunkSize);

    uint8_t new_int_size;
    new_int_size = internal::DetectUIntWidth(values, valid_bytes, chunk_size, int_size_);

    DCHECK_GE(new_int_size, int_size_);
    if (new_int_size > int_size_) {
      // This updates int_size_
      RETURN_NOT_OK(ExpandIntSize(new_int_size));
    }

    switch (int_size_) {
      case 1:
        internal::DowncastUInts(values, reinterpret_cast<uint8_t*>(raw_data_) + length_,
                                chunk_size);
        break;
      case 2:
        internal::DowncastUInts(values, reinterpret_cast<uint16_t*>(raw_data_) + length_,
                                chunk_size);
        break;
      case 4:
        internal::DowncastUInts(values, reinterpret_cast<uint32_t*>(raw_data_) + length_,
                                chunk_size);
        break;
      case 8:
        internal::DowncastUInts(values, reinterpret_cast<uint64_t*>(raw_data_) + length_,
                                chunk_size);
        break;
      default:
        DCHECK(false);
    }

    // UnsafeAppendToBitmap increments length_ by chunk_size
    ArrayBuilder::UnsafeAppendToBitmap(valid_bytes, chunk_size);
    values += chunk_size;
    if (valid_bytes != nullptr) {
      valid_bytes += chunk_size;
    }
    length -= chunk_size;
  }

  return Status::OK();
}

Status AdaptiveUIntBuilder::AppendValues(const uint64_t* values, int64_t length,
                                         const uint8_t* valid_bytes) {
  RETURN_NOT_OK(Reserve(length));

  return AppendValuesInternal(values, length, valid_bytes);
}

template <typename new_type>
Status AdaptiveUIntBuilder::ExpandIntSizeN() {
  switch (int_size_) {
    case 1:
      return ExpandIntSizeInternal<new_type, uint8_t>();
    case 2:
      return ExpandIntSizeInternal<new_type, uint16_t>();
    case 4:
      return ExpandIntSizeInternal<new_type, uint32_t>();
    case 8:
      return ExpandIntSizeInternal<new_type, uint64_t>();
    default:
      DCHECK(false);
  }
  return Status::OK();
}

Status AdaptiveUIntBuilder::ExpandIntSize(uint8_t new_int_size) {
  switch (new_int_size) {
    case 1:
      return ExpandIntSizeN<uint8_t>();
    case 2:
      return ExpandIntSizeN<uint16_t>();
    case 4:
      return ExpandIntSizeN<uint32_t>();
    case 8:
      return ExpandIntSizeN<uint64_t>();
    default:
      DCHECK(false);
  }
  return Status::OK();
}

}  // namespace arrow


text:
package com.epam.ta.reportportal.ws.model;

import com.epam.ta.reportportal.ws.model.attribute.ItemAttributesRQ;
import com.epam.ta.reportportal.ws.model.issue.Issue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

/**
 * @author Pavel Bortnik
 */
public class FinishTestItemSerializerTest {

	private ObjectMapper om = getObjectMapper();

	private static final String FINISH_TEST_ITEM_RQ = "{\"attributes\":[],\"status\":\"PASSED\",\"description\":\"description\","
			+ "\"issue\":{\"autoAnalyzed\":false,\"ignoreAnalyzer\":false},\"retry\":false}";

	@Test
	public void testSerializer() throws JsonProcessingException {
		String json = om.writeValueAsString(getFinishTestItem());
		Assert.assertEquals("Incorrect serialization result", FINISH_TEST_ITEM_RQ, json);
	}

	@Test
	public void testDeserializer() throws IOException {
		FinishTestItemRQ rq = om.readValue(FINISH_TEST_ITEM_RQ.getBytes(StandardCharsets.UTF_8), FinishTestItemRQ.class);
		Assert.assertEquals("Incorrect deserialization result", rq.getStatus(), "PASSED");
	}

	private FinishTestItemRQ getFinishTestItem() {
		FinishTestItemRQ finishTestItemRQ = new FinishTestItemRQ();
		finishTestItemRQ.setStatus("PASSED");
		finishTestItemRQ.setRetry(false);
		finishTestItemRQ.setDescription("description");
		finishTestItemRQ.setIssue(new Issue());
		finishTestItemRQ.setAttributes(Collections.<ItemAttributesRQ>emptySet());

		return finishTestItemRQ;
	}

	private ObjectMapper getObjectMapper() {
		ObjectMapper om = new ObjectMapper();
		om.configure(SerializationFeature.INDENT_OUTPUT, false);
		return om;
	}

}


text:
from __future__ import absolute_import

import factory

from django.contrib.auth.models import Group, Permission, User

from .models import Article

def _get_perm(perm_name):
    """
    Returns permission instance with given name.

    Permission name is a string like 'auth.add_user'.
    """
    app_label, codename = perm_name.split('.')
    return Permission.objects.get(
        content_type__app_label=app_label, codename=codename)

class ArticleFactory(factory.django.DjangoModelFactory):
    title = factory.Sequence(lambda n: 'Article number {0}'.format(n))
    body = factory.Sequence(lambda n: 'Body of article {0}'.format(n))

    class Meta:
        model = Article
        abstract = False

class GroupFactory(factory.django.DjangoModelFactory):
    name = factory.Sequence(lambda n: 'group{0}'.format(n))

    class Meta:
        model = Group
        abstract = False

class UserFactory(factory.django.DjangoModelFactory):
    username = factory.Sequence(lambda n: 'user{0}'.format(n))
    first_name = factory.Sequence(lambda n: 'John {0}'.format(n))
    last_name = factory.Sequence(lambda n: 'Doe {0}'.format(n))
    email = factory.Sequence(lambda n: 'user{0}@example.com'.format(n))
    password = 'asdf1234'

    class Meta:
        model = User
        abstract = False

    @classmethod
    def _prepare(cls, create, **kwargs):
        password = kwargs.pop('password', None)
        user = super(UserFactory, cls)._prepare(create, **kwargs)
        if password:
            user.set_password(password)
            if create:
                user.save()
        return user

    @factory.post_generation
    def permissions(self, create, extracted, **kwargs):
        if create and extracted:
            # We have a saved object and a list of permission names
            self.user_permissions.add(*[_get_perm(pn) for pn in extracted])


text:
<!doctype html>
<!-- Copyright 2020 The Chromium Authors
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->
<html>
  <head>
  </head>
</html>


text:
<?php

/**
 * This file is part of the Future CI package.
 * Future CI is licensed under MIT (https://github.com/f500/future-ci/blob/master/LICENSE).
 */

namespace spec\F500\CI\Command;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

/**
 * Class CommandSpec
 *
 * @copyright 2014 Future500 B.V.
 * @license   https://github.com/f500/future-ci/blob/master/LICENSE MIT
 * @package   spec\F500\CI\Command
 */
class CommandSpec extends ObjectBehavior
{

    function it_is_initializable()
    {
        $this->shouldHaveType('F500\CI\Command\Command');
    }

    function it_has_an_id()
    {
        $this->getId()->shouldBeString();
    }

    function it_can_add_an_argument_to_itself()
    {
        $this->addArg('ls');
        $this->getArgs()->shouldReturn(array('ls'));
    }

    function it_has_a_current_working_directory_after_setting_it()
    {
        $this->setCwd('/tmp');
        $this->getCwd()->shouldReturn('/tmp');
    }

    function it_can_add_an_environment_variable_to_itself()
    {
        $this->addEnv('PATH', '/usr/local/bin:/usr/bin:/bin');
        $this->getEnv()->shouldReturn(array('PATH' => '/usr/local/bin:/usr/bin:/bin'));
    }

    function it_stringifies_itself_for_representation()
    {
        $this->addArg('ls');
        $this->addArg('-l');

        $this->stringify()->shouldReturn('ls -l');
    }

    function it_stringifies_itself_for_shorter_representation()
    {
        $this->addArg('echo');
        $this->addArg(
            'Fusce quis pellentesque ipsum. Proin aliquam varius dolor pretium sollicitudin. Donec aliquet tortor eu leo iaculis sed.'
        );

        $this->stringify(true)->shouldReturn(
            'echo Fusce quis pellentesque ipsum. Proin aliquam varius dolor pretium sollic...'
        );
    }

    function it_has_no_result_code_initially()
    {
        $this->shouldThrow('\RuntimeException')->during(
            'getResultCode'
        );
    }

    function it_has_a_result_code_after_result_is_set()
    {
        $this->setResult(0, array('Successful output...'));

        $this->getResultCode()->shouldReturn(0);
    }

    function it_has_no_output_initially()
    {
        $this->shouldThrow('\RuntimeException')->during(
            'getOutput'
        );
    }

    function it_has_output_after_result_is_set()
    {
        $this->setResult(0, array('Some output...'));

        $this->getOutput()->shouldReturn(array('Some output...'));
    }
}


text:
using System.Reflection;

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("../../../../nunit.snk")]
[assembly: AssemblyKeyName("")]


text:
using System.Net;
using Core.WebApi.Middlewares.ExceptionHandling;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Warehouse.Api.Core.Commands;
using Warehouse.Api.Core.Queries;
using Warehouse.Api.Products;
using Warehouse.Api.Storage;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddEndpointsApiExplorer()
    .AddSwaggerGen()
    .AddDbContext<WarehouseDBContext>(
        options => options.UseNpgsql("name=ConnectionStrings:WarehouseDB"))
    .AddProductServices();

var app = builder.Build();

app.UseExceptionHandlingMiddleware();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger()
        .UseSwaggerUI();

    using var scope = app.Services.CreateScope();
    await using var dbContext = scope.ServiceProvider.GetRequiredService<WarehouseDBContext>();
    await dbContext.Database.MigrateAsync();
}

// Get Products
app.MapGet(
        "/api/products",
        (
                [FromServices] QueryHandler<GetProducts, IReadOnlyList<ProductListItem>> getProducts,
                string? filter,
                int? page,
                int? pageSize,
                CancellationToken ct
            ) =>
            getProducts(GetProducts.With(filter, page, pageSize), ct)
    )
    .Produces((int)HttpStatusCode.BadRequest);

// Get Product Details by Id
app.MapGet(
        "/api/products/{id:guid}",
        async (
                [FromServices] QueryHandler<GetProductDetails, ProductDetails?> getProductById,
                Guid id,
                CancellationToken ct
            ) =>
            await getProductById(GetProductDetails.With(id), ct)
                is { } product
                ? Results.Ok(product)
                : Results.NotFound()
    )
    .Produces(StatusCodes.Status400BadRequest)
    .Produces(StatusCodes.Status404NotFound);

// Register new product
app.MapPost(
        "api/products/",
        async (
            [FromServices] CommandHandler<RegisterProduct> registerProduct,
            RegisterProductRequest request,
            CancellationToken ct
        ) =>
        {
            var productId = Guid.NewGuid();
            var (sku, name, description) = request;

            await registerProduct(
                RegisterProduct.With(productId, sku, name, description),
                ct);

            return Results.Created($"/api/products/{productId}", productId);
        }
    )
    .Produces(StatusCodes.Status400BadRequest)
    .Produces(StatusCodes.Status404NotFound);

app.Run();

public record RegisterProductRequest(
    string? SKU,
    string? Name,
    string? Description
);


text:
package jena;

public class sparql
{
    // Call-through to arq command line application
    public static void main(String[] args)
    {
        InvokingUtil.invokeCmd("arq.sparql",args) ;
    }
}


text:
import AssembledDiagnosisForm from './row_form_pieces/AssembledDiagnosisForm';
import AssembledDissectionForm from './row_form_pieces/AssembledDissectionForm'
import AssembledFamilyMemberForm from './row_form_pieces/AssembledFamilyMemberForm'
import AssembledGeneticTestForm from './row_form_pieces/AssembledGeneticTestForm'
import AssembledHeartMeasurementForm from './row_form_pieces/AssembledHeartMeasurementForm';
import AssembledHospitalizationForm from './row_form_pieces/AssembledHospitalizationForm';
import AssembledMeasurementForm from './row_form_pieces/AssembledMeasurementForm'
import AssembledMedicationForm from './row_form_pieces/AssembledMedicationForm';
import AssembledProcedureForm from './row_form_pieces/AssembledProcedureForm';
import AssembledVitalForm from './row_form_pieces/AssembledVitalForm';

export default {
  renderByTopicType(topic, allTopics, unsortedTopics, visit, rowID) {
    let form = null
    switch (topic.topic_type) {
      case 'diagnosis':
        form = AssembledDiagnosisForm(topic, allTopics, visit, rowID)
        break;
      case 'dissection':
        form = AssembledDissectionForm(topic, unsortedTopics, visit, rowID)
        break;
      case 'family member':
        form = AssembledFamilyMemberForm(topic, unsortedTopics, visit, rowID)
        break;
      case 'genetic test':
        form = AssembledGeneticTestForm(topic, visit, rowID)
        break;
      case 'heart_measurement':
        form = AssembledHeartMeasurementForm(topic, visit, rowID)
        break;
      case 'hospitalization':
        form = AssembledHospitalizationForm(topic, unsortedTopics, visit, rowID)
        break;
      case 'measurement':
        form = AssembledMeasurementForm(topic, unsortedTopics, visit, rowID)
        break;
      case 'medication':
        form = AssembledMedicationForm(topic, visit, rowID)
        break;
      case 'procedure':
        form = AssembledProcedureForm(topic, unsortedTopics, visit, rowID)
        break;
      case 'vital':
        form = AssembledVitalForm(topic, visit, rowID)
        break;
      default:
    }
    return form
  }
}


text:
# frozen_string_literal: true

require "active_support/descendants_tracker"

module ActionMailer
  module Previews # :nodoc:
    extend ActiveSupport::Concern

    included do
      # Add the location of mailer previews through app configuration:
      #
      #     config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews"
      #
      mattr_accessor :preview_paths, instance_writer: false, default: []

      # Enable or disable mailer previews through app configuration:
      #
      #     config.action_mailer.show_previews = true
      #
      # Defaults to +true+ for development environment
      #
      mattr_accessor :show_previews, instance_writer: false

      # :nodoc:
      mattr_accessor :preview_interceptors, instance_writer: false, default: [ActionMailer::InlinePreviewInterceptor]
    end

    def preview_path
      ActionMailer.deprecator.warn(<<-MSG.squish)
        Using preview_path option is deprecated and will be removed in Rails 7.2.
        Please use preview_paths instead.
      MSG
      self.class.preview_paths.first
    end

    module ClassMethods
      def preview_path=(value)
        ActionMailer.deprecator.warn(<<-MSG.squish)
          Using preview_path= option is deprecated and will be removed in Rails 7.2.
          Please use preview_paths= instead.
        MSG
        self.preview_paths << value
      end

      def preview_path
        ActionMailer.deprecator.warn(<<-MSG.squish)
          Using preview_path option is deprecated and will be removed in Rails 7.2.
          Please use preview_paths instead.
        MSG
        self.preview_paths.first
      end

      # Register one or more Interceptors which will be called before mail is previewed.
      def register_preview_interceptors(*interceptors)
        interceptors.flatten.compact.each { |interceptor| register_preview_interceptor(interceptor) }
      end

      # Unregister one or more previously registered Interceptors.
      def unregister_preview_interceptors(*interceptors)
        interceptors.flatten.compact.each { |interceptor| unregister_preview_interceptor(interceptor) }
      end

      # Register an Interceptor which will be called before mail is previewed.
      # Either a class or a string can be passed in as the Interceptor. If a
      # string is passed in it will be constantized.
      def register_preview_interceptor(interceptor)
        preview_interceptor = interceptor_class_for(interceptor)

        unless preview_interceptors.include?(preview_interceptor)
          preview_interceptors << preview_interceptor
        end
      end

      # Unregister a previously registered Interceptor.
      # Either a class or a string can be passed in as the Interceptor. If a
      # string is passed in it will be constantized.
      def unregister_preview_interceptor(interceptor)
        preview_interceptors.delete(interceptor_class_for(interceptor))
      end

      private
        def interceptor_class_for(interceptor)
          case interceptor
          when String, Symbol
            interceptor.to_s.camelize.constantize
          else
            interceptor
          end
        end
    end
  end

  class Preview
    extend ActiveSupport::DescendantsTracker

    attr_reader :params

    def initialize(params = {})
      @params = params
    end

    class << self
      # Returns all mailer preview classes.
      def all
        load_previews if descendants.empty?
        descendants
      end

      # Returns the mail object for the given email name. The registered preview
      # interceptors will be informed so that they can transform the message
      # as they would if the mail was actually being delivered.
      def call(email, params = {})
        preview = new(params)
        message = preview.public_send(email)
        inform_preview_interceptors(message)
        message
      end

      # Returns all of the available email previews.
      def emails
        public_instance_methods(false).map(&:to_s).sort
      end

      # Returns +true+ if the email exists.
      def email_exists?(email)
        emails.include?(email)
      end

      # Returns +true+ if the preview exists.
      def exists?(preview)
        all.any? { |p| p.preview_name == preview }
      end

      # Find a mailer preview by its underscored class name.
      def find(preview)
        all.find { |p| p.preview_name == preview }
      end

      # Returns the underscored name of the mailer preview without the suffix.
      def preview_name
        name.delete_suffix("Preview").underscore
      end

      private
        def load_previews
          preview_paths.each do |preview_path|
            Dir["#{preview_path}/**/*_preview.rb"].sort.each { |file| require_dependency file }
          end
        end

        def preview_paths
          Base.preview_paths
        end

        def show_previews
          Base.show_previews
        end

        def inform_preview_interceptors(message)
          Base.preview_interceptors.each do |interceptor|
            interceptor.previewing_email(message)
          end
        end
    end
  end
end


text:
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;

using Common.Logging;

using Naru.Core;
using Naru.WPF.Dialog;
using Naru.WPF.Menu;
using Naru.WPF.Presentation;
using Naru.WPF.Windows.Controls;
using Naru.WPF.MVVM;
using Naru.WPF.Scheduler;
using Naru.WPF.ToolBar;
using Naru.WPF.UserInteractionHost;
using Naru.WPF.ViewModel;

namespace Nitrogen.Client.Shell
{
    public class ShellViewModel : Workspace, IWindowViewModel
    {
        private readonly Func<IUserInteractionHostViewModel> _userInteractionHostViewModelFactory;
        public BindableCollection<IMenuItem> MenuItems { get; private set; }

        public BindableCollection<IToolBarItem> ToolBarItems { get; private set; }

        public BindableCollection<Link> TitleLinks { get; private set; }

        public BindableCollection<IViewModel> Items { get; private set; }

        #region ShowUserInteractionHost

        private bool _showUserInteractionHost;

        public bool ShowUserInteractionHost
        {
            get { return _showUserInteractionHost; }
            private set
            {
                _showUserInteractionHost = value;
                RaisePropertyChanged(() => ShowUserInteractionHost);
            }
        }

        #endregion

        #region UserInteractionHost

        private IUserInteractionHostViewModel _userInteractionHost;

        public IUserInteractionHostViewModel UserInteractionHost
        {
            get { return _userInteractionHost; }
            private set
            {
                _userInteractionHost = value;
                RaisePropertyChanged(() => UserInteractionHost);
            }
        }

        #endregion

        public ShellViewModel(ILog log, IDispatcherSchedulerProvider scheduler, IStandardDialog standardDialog,
                              IToolBarService toolBarService, IMenuService menuService,
                              BindableCollection<IViewModel> itemsCollection,
                              BindableCollection<Link> lnkCollection,
                              IMessageStream messageStream,
                              IUserInteraction userInteraction,
                              Func<IUserInteractionHostViewModel> userInteractionHostViewModelFactory)
            : base(log, scheduler, standardDialog)
        {
            _userInteractionHostViewModelFactory = userInteractionHostViewModelFactory;
            ToolBarItems = toolBarService.Items;
            MenuItems = menuService.Items;

            TitleLinks = lnkCollection;
            Items = itemsCollection;

            messageStream.Of<IViewModel>()
                .ObserveOn(Scheduler.Dispatcher.RX)
                .Subscribe(x => Items.Add(x));

            userInteraction.RegisterHandler(UserInteractionModalHandler);
        }

        private Task UserInteractionModalHandler<TViewModel>(TViewModel viewModel)
            where TViewModel : IUserInteractionViewModel
        {
            var tcs = new TaskCompletionSource<object>();

            Scheduler.Dispatcher.ExecuteSync(() =>
            {
                var userInteractionHostViewModel = _userInteractionHostViewModelFactory();
                userInteractionHostViewModel.Initialise(viewModel);

                IDisposable closing = null;
                closing = userInteractionHostViewModel.ClosingStrategy.Closed
                                   .Subscribe(x =>
                                   {
                                       tcs.TrySetResult(null);

                                       ShowUserInteractionHost = false;

                                       if (closing != null)
                                       {
                                           closing.Dispose();
                                       }
                                   });

                UserInteractionHost = userInteractionHostViewModel;
                ShowUserInteractionHost = true;
            });

            return tcs.Task;
        }
    }
}


text:
static NSString * ArchiveKeyForDirection = @"direction";

@implementation LinearGradientOverlay
@synthesize direction = _direction;

#pragma mark - NSCoder implementations
- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.direction = [aDecoder decodeIntForKey:ArchiveKeyForDirection];
    }

    return self;
}

- (void) encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];

    [aCoder encodeInt:_direction forKey:ArchiveKeyForDirection];
}

#pragma mark - Initializers
- (LinearGradientOverlay *) init {
    return [self initWithGradientStops:nil];
}

- (LinearGradientOverlay *) initWithGradientStops: (NSArray *)gradientStops {
    return [self initWithGradientStops:gradientStops AndDirection:LinearGradientDirection_Vertical];
}

- (LinearGradientOverlay *) initWithGradientStops: (NSArray *)gradientStops AndDirection:(LinearGradientDirection)direction {
    if (self = [super initWithGradientStops:gradientStops]) {
        self.direction = direction;
    }

    return self;
}

#pragma mark - Getters / Setters
- (void) setDirection:(LinearGradientDirection)direction {
    if (direction >= LinearGradientDirection_Max) {
        _direction = LinearGradientDirection_Vertical;
    }
    else {
        _direction = direction;
    }
}

@end


text:
<?php

namespace Jaxon\Exception;

class Exception extends \Exception
{
    public function __construct(string $sMessage)
    {
        parent::__construct($sMessage);
    }
}


text:
import * as React from 'react';
import {createContext, Component, useContext, useState} from 'react';
import PropTypes from 'prop-types';

function someNamedFunction() {}

function formatContextForDisplay(name, value) {
  return (

      {name}:
{JSON.stringify(value, null, 2)}

  );
}

const contextData = {
  array: ['first', 'second', 'third'],
  bool: true,
  func: someNamedFunction,
  number: 123,
  object: {outer: {inner: {}}},
  string: 'abc',
  symbol: Symbol.for('symbol'),
  null: null,
  undefined: undefined,
};

class LegacyContextProvider extends Component<any> {
  static childContextTypes = {
    array: PropTypes.array,
    bool: PropTypes.bool,
    func: PropTypes.func,
    number: PropTypes.number,
    object: PropTypes.object,
    string: PropTypes.string,
    symbol: PropTypes.symbol,
    null: PropTypes.any,
    undefined: PropTypes.any,
  };

  getChildContext() {
    return contextData;
  }

  render() {
    return this.props.children;
  }
}

class LegacyContextConsumer extends Component<any> {
  static contextTypes = {
    array: PropTypes.array,
    bool: PropTypes.bool,
    func: PropTypes.func,
    number: PropTypes.number,
    object: PropTypes.object,
    string: PropTypes.string,
    symbol: PropTypes.symbol,
    null: PropTypes.any,
    undefined: PropTypes.any,
  };

  render() {
    return formatContextForDisplay('LegacyContextConsumer', this.context);
  }
}

class LegacyContextProviderWithUpdates extends Component<any> {
  constructor(props) {
    super(props);
    this.state = {type: 'desktop'};
  }

  getChildContext() {
    return {type: this.state.type};
  }

  handleChange = event => {
    this.setState({type: event.target.value});
  };

  render() {
    return (
      <>
        <LegacyFunctionalContextConsumer />

          <input value={this.state.type} onChange={this.handleChange} />

      </>
    );
  }
}

LegacyContextProviderWithUpdates.childContextTypes = {
  type: PropTypes.string,
};

function LegacyFunctionalContextConsumer(props, context) {
  return formatContextForDisplay('LegacyFunctionContextConsumer', context.type);
}
LegacyFunctionalContextConsumer.contextTypes = {
  type: PropTypes.string,
};

const ModernContext = createContext();
ModernContext.displayName = 'ModernContext';
const ArrayContext = createContext(contextData.array);
ArrayContext.displayName = 'ArrayContext';
const BoolContext = createContext(contextData.bool);
BoolContext.displayName = 'BoolContext';
const FuncContext = createContext(contextData.func);
FuncContext.displayName = 'FuncContext';
const NumberContext = createContext(contextData.number);
NumberContext.displayName = 'NumberContext';
const StringContext = createContext(contextData.string);
StringContext.displayName = 'StringContext';
const SymbolContext = createContext(contextData.symbol);
SymbolContext.displayName = 'SymbolContext';
const NullContext = createContext(null);
NullContext.displayName = 'NullContext';
const UndefinedContext = createContext(undefined);
UndefinedContext.displayName = 'UndefinedContext';

class ModernContextType extends Component<any> {
  static contextType = ModernContext;

  render() {
    return formatContextForDisplay('ModernContextType', this.context);
  }
}

function FunctionalContextConsumer() {
  const value = useContext(StringContext);
  return formatContextForDisplay('FunctionalContextConsumer', value);
}

const StringContextWithUpdates = createContext({
  string: contextData.string,
  setString: (string: string) => {},
});
const StringContextWithUpdates2 = createContext({
  string2: contextData.string,
  setString2: (string: string) => {},
});

function FunctionalContextProviderWithContextUpdates() {
  const [string, setString] = useState(contextData.string);
  const [string2, setString2] = useState(contextData.string);
  const value = {string, setString};
  const value2 = {string2, setString2};

  return (
    <StringContextWithUpdates.Provider value={value}>
      <StringContextWithUpdates2.Provider value={value2}>
        <FunctionalContextConsumerWithContextUpdates />
      </StringContextWithUpdates2.Provider>
    </StringContextWithUpdates.Provider>
  );
}

function FunctionalContextConsumerWithContextUpdates() {
  const {string, setString} = useContext(StringContextWithUpdates);
  const {string2, setString2} = useContext(StringContextWithUpdates2);
  const [state, setState] = useState('state');

  const handleChange = e => setString(e.target.value);
  const handleChange2 = e => setString2(e.target.value);

  return (
    <>
      {formatContextForDisplay(
        'FunctionalContextConsumerWithUpdates',
        `context: ${string}, context 2: ${string2}`,
      )}

        context: <input value={string} onChange={handleChange} />

        context 2: <input value={string2} onChange={handleChange2} />

        {state}

          test state:{' '}
          <input value={state} onChange={e => setState(e.target.value)} />

    </>
  );
}

class ModernClassContextProviderWithUpdates extends Component<any> {
  constructor(props) {
    super(props);
    this.setString = string => {
      this.setState({string});
    };

    this.state = {
      string: contextData.string,
      setString: this.setString,
    };
  }

  render() {
    return (
      <StringContextWithUpdates.Provider value={this.state}>
        <ModernClassContextConsumerWithUpdates />
      </StringContextWithUpdates.Provider>
    );
  }
}

class ModernClassContextConsumerWithUpdates extends Component<any> {
  render() {
    return (
      <StringContextWithUpdates.Consumer>
        {({string, setString}) => (
          <>
            {formatContextForDisplay(
              'ModernClassContextConsumerWithUpdates',
              string,
            )}
            <input value={string} onChange={e => setString(e.target.value)} />
          </>
        )}
      </StringContextWithUpdates.Consumer>
    );
  }
}

export default function Contexts() {
  return (

Contexts

        <LegacyContextProvider>
          <LegacyContextConsumer />
        </LegacyContextProvider>
        <LegacyContextProviderWithUpdates />
        <ModernContext.Provider value={contextData}>
          <ModernContext.Consumer>
            {value => formatContextForDisplay('ModernContext.Consumer', value)}
          </ModernContext.Consumer>
          <ModernContextType />
        </ModernContext.Provider>
        <FunctionalContextConsumer />
        <FunctionalContextProviderWithContextUpdates />
        <ModernClassContextProviderWithUpdates />
        <ArrayContext.Consumer>
          {value => formatContextForDisplay('ArrayContext.Consumer', value)}
        </ArrayContext.Consumer>
        <BoolContext.Consumer>
          {value => formatContextForDisplay('BoolContext.Consumer', value)}
        </BoolContext.Consumer>
        <FuncContext.Consumer>
          {value => formatContextForDisplay('FuncContext.Consumer', value)}
        </FuncContext.Consumer>
        <NumberContext.Consumer>
          {value => formatContextForDisplay('NumberContext.Consumer', value)}
        </NumberContext.Consumer>
        <StringContext.Consumer>
          {value => formatContextForDisplay('StringContext.Consumer', value)}
        </StringContext.Consumer>
        <SymbolContext.Consumer>
          {value => formatContextForDisplay('SymbolContext.Consumer', value)}
        </SymbolContext.Consumer>
        <NullContext.Consumer>
          {value => formatContextForDisplay('NullContext.Consumer', value)}
        </NullContext.Consumer>
        <UndefinedContext.Consumer>
          {value => formatContextForDisplay('UndefinedContext.Consumer', value)}
        </UndefinedContext.Consumer>

  );
}


text:
"use strict";

var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ConnectionError = ConnectionError;
exports.RequestError = RequestError;

var _util = require('util');

var _util2 = _interopRequireDefault(_util);

function ConnectionError(message, code) {
  if (!(this instanceof ConnectionError)) {
    if (message instanceof ConnectionError) {
      return message;
    }

    return new ConnectionError(message, code);
  }

  Error.call(this);

  this.message = message;
  this.code = code;

  Error.captureStackTrace(this, this.constructor);
}

_util2["default"].inherits(ConnectionError, Error);

ConnectionError.prototype.name = "ConnectionError";

function RequestError(message, code) {
  if (!(this instanceof RequestError)) {
    if (message instanceof RequestError) {
      return message;
    }

    return new RequestError(message, code);
  }

  Error.call(this);

  this.message = message;
  this.code = code;

  Error.captureStackTrace(this, this.constructor);
}

_util2["default"].inherits(RequestError, Error);

RequestError.prototype.name = "RequestError";


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

/**
 *  @file GREYVisibilityChecker+Internal.h
 *  @brief Exposes GREYVisibilityChecker' interfaces and methods that are otherwise private
 *  for testing purposes.
 */

@interface GREYVisibilityChecker (Internal)

/**
 *   @return The last known original image used by the visibility checker.
 *
 *   @remark This is available only for internal testing purposes.
 */
+ (UIImage *)grey_lastActualBeforeImage;
/**
 *   @return The last known actual color shifted image used by visibility checker.
 *
 *   @remark This is available only for internal testing purposes.
 */
+ (UIImage *)grey_lastActualAfterImage;
/**
 *   @return The last known actual color shifted image used by visibility checker.
 *
 *   @remark This is available only for internal testing purposes.
 */
+ (UIImage *)grey_lastExpectedAfterImage;

@end


text:
'use strict';

// utility to standardize our logging so we always have stack traces
// available for errors.
function err() {
  var failure = {};
  var args = [ "\n" + "-".repeat(80) + "\n" ];

  Array.prototype.push.apply(args, arguments);

  Error.captureStackTrace(failure);
  args.push("\nat stack\n")
  args.push(failure.stack);

  console.error.apply({}, args);
  process.exit();
};

function out() {
  // Uncomment for debugging
  console.log.apply({}, arguments);
};

module.exports.err = err;
module.exports.out = out;


text:
package com.googlesource.gerrit.plugins.hooks.rtc.api;

import java.util.Calendar;

import javax.xml.bind.DatatypeConverter;

import com.google.gson.JsonObject;

public class AbstractDeserializer {

  protected final String extractRdfResourceUrl(JsonObject json, String memberName) {
    JsonObject rdf = json.getAsJsonObject(memberName);
    return rdf.get("rdf:resource").getAsString();
  }

  protected final Calendar extractDateTime(JsonObject root, final String memberName) {
    String txt = extractString(root, memberName);
    return DatatypeConverter.parseDateTime(txt);
  }

  protected final String extractString(JsonObject root, final String memberName) {
    return root.get(memberName).getAsString();
  }

  protected final Long extractLong(JsonObject root, final String memberName) {
    return root.get(memberName).getAsLong();
  }

  protected final String extractIdenFromRdfResource(JsonObject root, final String memberName) {
    final String rdf = extractRdfResourceUrl(root, memberName);
    if (rdf != null) {
      return rdf.substring(rdf.lastIndexOf('/')+1);
    }
    else
      return null;
  }

  protected String extractRdf(JsonObject root) {
    return extractString(root, "rdf:resource");
  }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RunWebserverHere
{
    public partial class InstallUninstallForm : Form
    {
        public InstallUninstallForm()
        {
            InitializeComponent();
        }

        private void InstallButton_Click(object sender, EventArgs e)
        {
            try
            {
                var key = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("Directory\\shell\\runwebserverhere", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
                key.SetValue(null, "Run Webserver Here");
                var commandKey = key.CreateSubKey("command");
                commandKey.SetValue(null, string.Format("\"{0}\" \"%1\"", Assembly.GetExecutingAssembly().Location));

                var key2 = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("Directory\\shell\\runwebserverhere_cfg", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
                key2.SetValue(null, "Configure Webserver Here");
                key2.SetValue("Extended", "");
                var commandKey2 = key2.CreateSubKey("command");
                commandKey2.SetValue(null, string.Format("\"{0}\" \"%1\" --configure", Assembly.GetExecutingAssembly().Location));

                MessageBox.Show("Installed successfully!", "RunWebserverHere", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch
            {
                MessageBox.Show("Install failed! Try running as admin.", "RunWebserverHere", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                this.Close();
            }
        }
    }
}


text:
declare function run(): void;

declare function suite(name: string, fn: (err?) => void);
declare function test(name: string, fn: (done?: (err?) => void) => void);
declare function suiteSetup(fn: (done?: (err?) => void) => void);
declare function suiteTeardown(fn: (done?: (err?) => void) => void);
declare function setup(fn: (done?: (err?) => void) => void);
declare function teardown(fn: (done?: (err?) => void) => void);


text:
/*
 * Format for Selenium Remote Control Java client (TestNG)
 */

var subScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
subScriptLoader.loadSubScript('chrome://java-formatters/content/formats/java-rc.js', this);

this.name = "java-rc-testng";

// TestNG reverses the order of assert functions
Equals.prototype.assert = function() {
	return "assertEquals(" + this.e2.toString() + ", " + this.e1.toString() + ");";
};

Equals.prototype.verify = function() {
	return "verifyEquals(" + this.e2.toString() + ", " + this.e1.toString() + ");";
};

options.superClass = "SeleneseTestNgHelper";

function defaultExtension() {
  return this.options.defaultExtension;
}

options.header =
	"package ${packageName};\n" +
	"\n" +
	"import com.thoughtworks.selenium.*;\n" +
	"import org.testng.annotations.*;\n" +
	"import static org.testng.Assert.*;\n" +
	"import java.util.regex.Pattern;\n" +
	"\n" +
    "public class ${className} extends ${superClass} {\n" +
    "\t@Test public void ${methodName}() throws Exception {\n";

this.configForm =
	'<description>Variable for Selenium instance</description>' +
	'<textbox id="options_receiver" />' +
	'<description>Package</description>' +
	'<textbox id="options_packageName" />' +
	'<description>Superclass</description>' +
	'<textbox id="options_superClass" />';


text:
"""Implementation of :class:`FiniteField` class."""

import numbers
import random

from ..core import Dummy, integer_digits
from ..ntheory import factorint
from ..polys.galoistools import dup_gf_irreducible
from ..polys.polyerrors import CoercionFailed
from .field import Field
from .groundtypes import DiofantInteger
from .integerring import GMPYIntegerRing, PythonIntegerRing, ZZ_python
from .quotientring import QuotientRingElement
from .simpledomain import SimpleDomain

__all__ = 'FiniteField', 'GMPYFiniteField', 'PythonFiniteField'

_modular_integer_cache = {}

class FiniteField(Field, SimpleDomain):
    """General class for finite fields."""

    is_FiniteField = True
    is_Numerical = True

    def __new__(cls, order, dom, modulus=None):
        try:
            pp = factorint(order)
            if not order or len(pp) != 1:
                raise ValueError
            mod, deg = pp.popitem()
        except ValueError:
            raise ValueError(f'order must be a prime power, got {order}')

        if deg == 1:
            if modulus:
                deg = len(modulus) - 1
            else:
                modulus = [1, 0]

        order = mod**deg

        if modulus is None:
            random.seed(0)
            modulus = dup_gf_irreducible(deg, ZZ_python.finite_field(mod))
        elif deg != len(modulus) - 1:
            raise ValueError('degree of a defining polynomial for the field'
                             ' does not match extension degree')

        modulus = tuple(map(dom.dtype, modulus))

        mod = dom.convert(mod)

        key = order, dom, mod, modulus

        obj = super().__new__(cls)

        obj.domain = dom
        obj.mod = mod
        obj.order = order

        if order > mod:
            obj.rep = f'GF({obj.mod}, {list(map(ZZ_python, modulus))})'
        else:
            obj.rep = f'GF({obj.mod})'

        try:
            obj.dtype = _modular_integer_cache[key]
        except KeyError:
            if deg == 1:
                obj.dtype = type('ModularInteger', (ModularInteger,),
                                 {'mod': mod, 'domain': dom, '_parent': obj})
            else:
                ff = dom.finite_field(mod).inject(Dummy('x'))
                mod = ff.from_dense(modulus)
                if not mod.is_irreducible:
                    raise ValueError('defining polynomial must be irreducible')
                obj.dtype = type('GaloisFieldElement', (GaloisFieldElement,),
                                 {'mod': mod, 'domain': ff, '_parent': obj})
            _modular_integer_cache[key] = obj.dtype

        obj.zero = obj.dtype(0)
        obj.one = obj.dtype(1)

        return obj

    def __hash__(self):
        return hash((self.__class__.__name__, self.dtype, self.order, self.domain))

    def __eq__(self, other):
        return isinstance(other, FiniteField) and \
            self.order == other.order and self.domain == other.domain

    def __getnewargs_ex__(self):
        return (self.order,), {}

    @property
    def characteristic(self):
        return self.mod

    def to_expr(self, element):
        return DiofantInteger(int(element))

    def from_expr(self, expr):
        if expr.is_Integer:
            return self.dtype(self.domain.dtype(int(expr)))
        elif expr.is_Float and int(expr) == expr:
            return self.dtype(self.domain.dtype(int(expr)))
        else:
            raise CoercionFailed(f'expected an integer, got {expr}')

    def _from_PythonFiniteField(self, a, K0=None):
        return self.dtype(self.domain.convert(a.rep, K0.domain))

    def _from_PythonIntegerRing(self, a, K0=None):
        return self.dtype(self.domain.convert(a, K0) % self.characteristic)
    _from_GMPYIntegerRing = _from_PythonIntegerRing

    def _from_PythonRationalField(self, a, K0=None):
        if a.denominator == 1:
            return self.convert(a.numerator)

    def _from_GMPYFiniteField(self, a, K0=None):
        return self.dtype(self.domain.convert(a.rep, K0.domain))

    def _from_GMPYRationalField(self, a, K0=None):
        if a.denominator == 1:
            return self.convert(a.numerator)

    def _from_RealField(self, a, K0):
        p, q = K0.to_rational(a)

        if q == 1:
            return self.dtype(self.domain.dtype(p))

    def is_normal(self, a):
        return True

class PythonFiniteField(FiniteField):
    """Finite field based on Python's integers."""

    def __new__(cls, order, modulus=None):
        return super().__new__(cls, order, PythonIntegerRing(), modulus)

class GMPYFiniteField(FiniteField):
    """Finite field based on GMPY's integers."""

    def __new__(cls, order, modulus=None):
        return super().__new__(cls, order, GMPYIntegerRing(), modulus)

class ModularInteger(QuotientRingElement):
    """A class representing a modular integer."""

    @property
    def numerator(self):
        return self

    @property
    def denominator(self):
        return self.parent.one

class GaloisFieldElement(ModularInteger):
    def __init__(self, rep):
        if isinstance(rep, numbers.Integral):
            rep = integer_digits(rep % self.parent.order, self.parent.mod)

        if isinstance(rep, (list, tuple)):
            rep = self.domain.from_dense(rep)

        super().__init__(rep)

    def __int__(self):
        rep = self.rep.set_domain(self.parent.domain)
        return int(rep.eval(0, self.parent.mod))


text:
<technique vs="LitSolid" ps="LitSolid">
    <pass name="base" vsdefines="AO" psdefines="AO" />
    <pass name="light" depthtest="equal" depthwrite="false" blend="add" />
    <pass name="prepass" psdefines="PREPASS" />
    <pass name="material" vsdefines="AO" psdefines="MATERIAL AO" depthtest="equal" depthwrite="false" />
    <pass name="deferred" vsdefines="AO" psdefines="DEFERRED AO" />
    <pass name="depth" vs="Depth" ps="Depth" />
    <pass name="shadow" vs="Shadow" ps="Shadow" />
</technique>


text:
require 'spec_helper'

RSpec.describe StudentSupportSummitQuestionnaire do

end


text:
import requests
import sys
import os
import untangle
import time
from led_sign.client import SignClient
from datetime import datetime
from pytz import timezone

def get_bart_estimates(station='ROCK', direction=None):
  API_URL = 'http://api.bart.gov/api/etd.aspx'

  try:
    key = os.environ['BART_KEY']
  except KeyError:
    print('Set the BART_KEY environment variable')
    raise

  data = {
    'cmd': 'etd',
    'key': key,
    'orig': station,
    'dir': direction,
  }

  r = requests.get(API_URL, params=data)

  if r.status_code != 200:
    print("returned {}".format(r.status_code))
    return [["error: {}".format(r.status_code),'']]

  doc = untangle.parse(r.text)

  lines = []

  # for each estimated destination,
  try:
    for etd in doc.root.station.etd:
      destination = etd.destination.cdata
      mins = []
      cars = None
      for estimate in etd.estimate:
        mins.append(estimate.minutes.cdata)
        cars = estimate.length.cdata
      lines.append(format_estimate(destination, cars, mins))
  except:
    print(r.text)
    print(sys.exc_info()[0])
    lines = [['No trains','until next morning']]
  lines.append(get_time_lines())
  return lines

def get_time_lines():
  pst = timezone('US/Pacific')
  pst_time = datetime.now(pst)
  return [pst_time.strftime('%b %d, %Y'), pst_time.strftime('%H:%M')]

def format_estimate(destination, cars, mins):
  minutes = ', '.join(mins)
  first_line = '{}'.format(destination, cars)
  second_line = '{} mins'.format(minutes)
  return [first_line, second_line]

def main():
  # New client to write to led sign
  pwd = os.path.dirname(os.path.realpath(__file__))
  led_sign_path = '/'.join([pwd, 'led_sign'])
  glyphs_path = '/'.join([led_sign_path, 'glyphs'])

  sign_client = SignClient(glyphs_path, led_sign_path)

  while True:
    try:
      estimates = get_bart_estimates('ROCK', 's')
      sign_client.send_text_to_sign(estimates)
      time.sleep(30)
    except:
      sign_client.send_text_to_sign(['ERROR',''])
      print(sys.exc_info()[0])
      raise
      time.sleep(3)
#-------------------------------------------------------------------------------
if __name__ == "__main__":
  main()


text:
package org.spongepowered.common.mixin.core.world.gen.feature;

import com.google.common.base.MoreObjects;
import net.minecraft.world.gen.feature.WorldGenDeadBush;
import org.spongepowered.api.world.gen.populator.DeadBush;
import org.spongepowered.asm.mixin.Mixin;

@Mixin(WorldGenDeadBush.class)
public abstract class WorldGenDeadBushMixin extends WorldGeneratorMixin {

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("Type", "DeadBush")
                .add("PerChunk", ((DeadBush) this).getShrubsPerChunk())
                .toString();
    }

}


text:
/* global CustomEvent */
export const PAGEVIEW_EVENT_NAME = `${process.env.SITE_NAME || 'iris'}_pageview`;

export default () => {
  if (__CLIENT__) {
    // Register custom event
    const pageviewEvent = typeof CustomEvent !== 'undefined' && // Required as it's not defined during tests.
      new CustomEvent(PAGEVIEW_EVENT_NAME);
    // Dispatch custom event on the window for tracking
    window.dispatchEvent(pageviewEvent);
  }
};


text:
// Tests error reporting for missing #if

//E t_2_012.cpp(13): error: the #if for this directive is missing: #else
#else
#endif

//H 10: t_2_012.cpp(13): #else
//H 18: boost::wave::preprocess_exception


text:
//
// Vector
//

#include "liquid.internal.h"

#define VECTOR(name)    LIQUID_CONCAT(liquid_vectorcf,name)
#define T               float complex
#define TP              float

#include "vector_norm.proto.c"


text:
package org.apache.helix.manager.zk;

import org.apache.helix.TestHelper;
import org.apache.helix.ZkTestHelper;
import org.apache.helix.testutil.ZkTestBase;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestZkManagerFlappingDetection extends ZkTestBase {
  @Test
  public void testDisconnectHistory() throws Exception {
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    final String clusterName = className + "_" + methodName;

    TestHelper.setupCluster(clusterName, _zkaddr, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        10, // partitions per resource
        5, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    String instanceName = "localhost_" + (12918 + 0);
    MockParticipant manager = new MockParticipant(_zkaddr, clusterName, instanceName);

    manager.connect();
    ZkClient zkClient = manager.getZkClient();
    ZkTestHelper.expireSession(zkClient);
    for (int i = 0; i < 4; i++) {
      ZkTestHelper.expireSession(zkClient);
      Thread.sleep(1000);
      if (i < 5) {
        // System.out.println(i);
        Assert.assertTrue(manager.isConnected());
      }
    }
    ZkTestHelper.disconnectSession(zkClient);
    for (int i = 0; i < 20; i++) {
      Thread.sleep(500);
      System.out.println(i);
      if (!manager.isConnected())
        break;
    }
    Assert.assertFalse(manager.isConnected());
  }

  // TODO test was disabled. check if it is still needed
  // @Test(enabled = false)
  // public void testDisconnectFlappingWindow() throws Exception {
  // String className = TestHelper.getTestClassName();
  // String methodName = TestHelper.getTestMethodName();
  // String instanceName = "localhost_" + (12918 + 1);
  // final String clusterName = className + "_" + methodName + UUID.randomUUID();
  //
  // testDisconnectFlappingWindow2(instanceName, InstanceType.PARTICIPANT);
  // testDisconnectFlappingWindow2("admin", InstanceType.ADMINISTRATOR);
  // }
  //
  // public void testDisconnectFlappingWindow2(String instanceName, InstanceType type)
  // throws Exception {
  // String className = TestHelper.getTestClassName();
  // String methodName = TestHelper.getTestMethodName();
  // final String clusterName = className + "_" + methodName + UUID.randomUUID();
  //
  // TestHelper.setupCluster(clusterName, zkaddr, 12918, // participant port
  // "localhost", // participant name prefix
  // "TestDB", // resource name prefix
  // 1, // resources
  // 10, // partitions per resource
  // 5, // number of nodes
  // 3, // replicas
  // "MasterSlave", true); // do rebalance
  //
  // // flapping time window to 5 sec
  // System.setProperty("helixmanager.flappingTimeWindow", "15000");
  // System.setProperty("helixmanager.maxDisconnectThreshold", "7");
  // ZkHelixTestManager manager2 = new ZkHelixTestManager(clusterName, instanceName, type, zkaddr);
  // manager2.connect();
  // ZkClient zkClient = manager2.getZkClient();
  // for (int i = 0; i < 3; i++) {
  // ZkTestHelper.expireSession(zkClient);
  // Thread.sleep(500);
  // Assert.assertTrue(manager2.isConnected());
  // }
  // Thread.sleep(15000);
  // // Old entries should be cleaned up
  // for (int i = 0; i < 7; i++) {
  // ZkTestHelper.expireSession(zkClient);
  // Thread.sleep(1000);
  // Assert.assertTrue(manager2.isConnected());
  // }
  // ZkTestHelper.disconnectSession(zkClient);
  // for (int i = 0; i < 20; i++) {
  // Thread.sleep(500);
  // if (!manager2.isConnected())
  // break;
  // }
  // Assert.assertFalse(manager2.isConnected());
  // }

  // @Test
  public void testDisconnectFlappingWindowController() throws Exception {
    String className = TestHelper.getTestClassName();
    String methodName = TestHelper.getTestMethodName();
    final String clusterName = className + "_" + methodName;

    TestHelper.setupCluster(clusterName, _zkaddr, 12918, // participant port
        "localhost", // participant name prefix
        "TestDB", // resource name prefix
        1, // resources
        10, // partitions per resource
        5, // number of nodes
        3, // replicas
        "MasterSlave", true); // do rebalance

    // flapping time window to 5 sec
    System.setProperty("helixmanager.flappingTimeWindow", "5000");
    System.setProperty("helixmanager.maxDisconnectThreshold", "3");
    MockController manager2 = new MockController(_zkaddr, clusterName, null);
    manager2.connect();
    Thread.sleep(100);
    ZkClient zkClient = manager2.getZkClient();
    for (int i = 0; i < 2; i++) {
      ZkTestHelper.expireSession(zkClient);
      Thread.sleep(500);
      Assert.assertTrue(manager2.isConnected());
    }
    Thread.sleep(5000);
    // Old entries should be cleaned up
    for (int i = 0; i < 3; i++) {
      ZkTestHelper.expireSession(zkClient);
      Thread.sleep(500);
      Assert.assertTrue(manager2.isConnected());
    }
    ZkTestHelper.disconnectSession(zkClient);
    for (int i = 0; i < 20; i++) {
      Thread.sleep(500);
      if (!manager2.isConnected())
        break;
    }
    Assert.assertFalse(manager2.isConnected());
  }
}


text:
namespace gameplay
{
// Callback for reading a png image using Stream
static void readStream(png_structp png, png_bytep data, png_size_t length)
{
    Stream* stream = reinterpret_cast<Stream*>(png_get_io_ptr(png));
    if (stream == NULL || stream->read(data, 1, length) != length)
    {
        png_error(png, "Error reading PNG.");
    }
}

Image* Image::create(const char* path)
{
    GP_ASSERT(path);

    // Open the file.
    std::unique_ptr<Stream> stream(FileSystem::open(path));
    if (stream.get() == NULL || !stream->canRead())
    {
        GP_ERROR("Failed to open image file '%s'.", path);
        return NULL;
    }

    // Verify PNG signature.
    unsigned char sig[8];
    if (stream->read(sig, 1, 8) != 8 || png_sig_cmp(sig, 0, 8) != 0)
    {
        GP_ERROR("Failed to load file '%s'; not a valid PNG.", path);
        return NULL;
    }

    // Initialize png read struct (last three parameters use stderr+longjump if NULL).
    png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png == NULL)
    {
        GP_ERROR("Failed to create PNG structure for reading PNG file '%s'.", path);
        return NULL;
    }

    // Initialize info struct.
    png_infop info = png_create_info_struct(png);
    if (info == NULL)
    {
        GP_ERROR("Failed to create PNG info structure for PNG file '%s'.", path);
        png_destroy_read_struct(&png, NULL, NULL);
        return NULL;
    }

    // Set up error handling (required without using custom error handlers above).
    if (setjmp(png_jmpbuf(png)))
    {
        GP_ERROR("Failed to set up error handling for reading PNG file '%s'.", path);
        png_destroy_read_struct(&png, &info, NULL);
        return NULL;
    }

    // Initialize file io.
    png_set_read_fn(png, stream.get(), readStream);

    // Indicate that we already read the first 8 bytes (signature).
    png_set_sig_bytes(png, 8);

    // Read the entire image into memory.
    png_read_png(png, info, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_GRAY_TO_RGB, NULL);

    Image* image = new Image();
    image->_width = png_get_image_width(png, info);
    image->_height = png_get_image_height(png, info);

    png_byte colorType = png_get_color_type(png, info);
    switch (colorType)
    {
    case PNG_COLOR_TYPE_RGBA:
        image->_format = Image::RGBA;
        break;

    case PNG_COLOR_TYPE_RGB:
        image->_format = Image::RGB;
        break;

    default:
        GP_ERROR("Unsupported PNG color type (%d) for image file '%s'.", (int)colorType, path);
        png_destroy_read_struct(&png, &info, NULL);
        return NULL;
    }

    size_t stride = png_get_rowbytes(png, info);

    // Allocate image data.
    image->_data = new unsigned char[stride * image->_height];

    // Read rows into image data.
    png_bytepp rows = png_get_rows(png, info);
    for (unsigned int i = 0; i < image->_height; ++i)
    {
        memcpy(image->_data+(stride * (image->_height-1-i)), rows[i], stride);
    }

    // Clean up.
    png_destroy_read_struct(&png, &info, NULL);

    return image;
}

Image* Image::create(unsigned int width, unsigned int height, Image::Format format, unsigned char* data)
{
    GP_ASSERT(width > 0 && height > 0);
    GP_ASSERT(format >= RGB && format <= RGBA);

    unsigned int pixelSize = 0;
    switch(format)
    {
    case Image::RGB:
        pixelSize = 3;
        break;
    case Image::RGBA:
        pixelSize = 4;
        break;
    }

    Image* image = new Image();

    unsigned int dataSize = width * height * pixelSize;

    image->_width = width;
    image->_height = height;
    image->_format = format;
    image->_data = new unsigned char[dataSize];
    if (data)
        memcpy(image->_data, data, dataSize);

    return image;
}

Image::Image() : _data(NULL), _format(RGB), _width(0), _height(0)
{
}

Image::~Image()
{
    SAFE_DELETE_ARRAY(_data);
}

}


text:
using System.Windows.Input;

namespace LyricDownload.util
{
    public class DelegateCommand : ICommand
    {
        System.Action execute;
        System.Action<object> executeWithParam;
        System.Func<bool> canExecute;

        public bool CanExecute(object parameter)
        {
            if (canExecute == null) {
                return true;
            }
            return canExecute();
        }

        public event System.EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {

            //まともな実装にしたい
            if (execute != null)
            {
                execute();
            }
            else if(executeWithParam!=null)
            {
                executeWithParam(parameter);
            }
        }

        public DelegateCommand(System.Action execute, System.Func<bool> canExecute = null)
        {

            this.execute = execute;
            this.executeWithParam = null;
            this.canExecute = canExecute;
        }
        public DelegateCommand(System.Action<object> execute, System.Func<bool> canExecute = null)
        {
            this.execute = null;
            this.executeWithParam = execute;
            this.canExecute = canExecute;
        }

    }
}


text:
//
//  @author raver119@gmail.com
//

#include <op_boilerplate.h>
#if NOT_EXCLUDED(OP_clipbyvalue)

#include <ops/declarable/CustomOperations.h>
#include <ops/declarable/helpers/transforms.h>

namespace nd4j {
    namespace ops {
        CONFIGURABLE_OP_IMPL(clipbyvalue, 1, 1, true, 2, 0) {
            auto input = INPUT_VARIABLE(0);
            auto output = OUTPUT_VARIABLE(0);

            // FIXME: extra args!!!
            auto left = T_ARG(0);
            auto right = T_ARG(1);

            REQUIRE_TRUE(left < right, 0, "clip_by_value: left bound should be lesser than right. But %f >= %f given.", left, right);
            //input->applyTransform(transform::ClipByValue, output, block.getTArguments()->data());
            helpers::clipByValue(block.launchContext(), *input, left, right, *output);
            //STORE_RESULT(*output);

            return Status::OK();
        }
        DECLARE_SYN(ClipByValue, clipbyvalue);

        DECLARE_TYPES(clipbyvalue) {
            getOpDescriptor()
                    ->setAllowedInputTypes(nd4j::DataType::ANY)
                    ->setAllowedOutputTypes({ALL_FLOATS});
        }
    }
}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">
    <string name="app_name">WiFi AP Manager</string>
    <string name="wifi_tether_configure_ap_text">Настройка точки доступа Wi-Fi</string>
    <string name="wifi_tether_configure_subtext">Сеть: <xliff:g id="NETWORK_SSID">%1$s</xliff:g>; шифрование: <xliff:g id="NETWORK_SECURITY">%2$s</xliff:g></string>
    <string name="wifi_tether_starting">Включение точки доступа…</string>
    <string name="wifi_tether_stopping">Выключение точки доступа…</string>
    <string name="wifi_tether_checkbox_text">Точка доступа Wi-Fi</string>
    <string name="wifi_ssid_hint">Введите имя сети (SSID)</string>
    <string name="wifi_ssid">Имя сети</string>
    <string name="wifi_show_password">Показать пароль</string>
    <string name="wifi_security_none">Нет</string>
    <string name="wifi_security">Защита</string>
    <string name="wifi_save">Сохранить</string>
    <string name="wifi_password">Пароль</string>
    <string name="wifi_cancel">Отмена</string>
    <string name="error">Ошибка</string>
    <string name="settings">Настройки</string>
    <string name="bad_perm">Похоже, что права доступа к файлам должны быть исправлены. Исправить?</string>
    <string name="block_dev">Блокировать этот MAC-адрес?</string>
    <string name="blocked_devices">Заблокированные устройства</string>
    <string name="build_version">Номер сборки</string>
    <string name="clear">Очистить</string>
    <string name="credentials_password_too_short">В пароле должно быть не менее 8 символов.</string>
    <string name="license1">Copyright © 2015 Emil Suleymanov</string>
    <string name="license2">Распространяется под Apache License v2.0</string>
    <string name="license3">Исходный код доступен на https://github.com/sssemil/WiFiAPManager</string>
    <string name="no_blocked_devs">Нет заблокированных устройства</string>
    <string name="no_root">Похоже, что у вас нет прав суперпользователя.</string>
    <string name="open_source_license">Лицензии открытого ПО</string>
    <string name="progress_scanning">Поиск</string>
    <string name="save">Сохранить</string>
    <string name="about">О программе</string>
    <string name="show_notification">Оповещать</string>
    <string name="show_notification_summary">Показать количество подключенных устройств</string>
    <string name="small_info">Точка доступа WiFi</string>
    <string name="tethered_notification_multi_device_message">Подключено устройств: <xliff:g id="count">%1$s</xliff:g></string>
    <string name="tethered_notification_no_device_message">Нет подключенных устройств</string>
    <string name="tethered_notification_one_device_message"><xliff:g id="count">%1$s</xliff:g> подключенное устройство</string>
    <string name="tethered_notification_title">Точка доступа активна</string>
    <string name="ver">Версия</string>
    <string name="wifi_ap_client_ap_disabled">Точка доступа отключена</string>
    <string name="wifi_ap_client_none_connected">Нет устройств</string>
    <string name="wifi_ap_clients_title">Устройства</string>
    <string name="warning">Внимание</string>
    <string name="touch_to_remove">Нажмите для удаления</string>
    <string name="enable_mobile_net">Включать мобильную сеть</string>
    <string name="enable_mobile_net_sum">Включать мобильную сеть при запуске точки доступа</string>
    <string name="blocked">ЗАБЛОКИРОВАНО</string>
    <string name="disconnected">ОТСОЕДИНЕНО</string>
    <string name="unblock_dev">Разблокировать этот MAC-адрес?</string>
</resources>


text:
<?php

namespace Ss\SsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class OrdererType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ss\SsBundle\Entity\Orderer'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ss_ssbundle_orderer';
    }
}


text:
package kv

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/cockroachdb/cockroach/storage"
)

const (
	// KVKeyPrefix is the prefix for RESTful endpoints used to
	// interact directly with the key-value datastore.
	KVKeyPrefix = "/db/"
)

// A RESTServer provides a RESTful HTTP API to interact with
// an underlying key-value store.
type RESTServer struct {
	db DB // Key-value database client
}

// NewRESTServer allocates and returns a new server.
func NewRESTServer(db DB) *RESTServer {
	return &RESTServer{db: db}
}

// HandleAction arbitrates requests to the appropriate function
// based on the request's HTTP method.
func (s *RESTServer) HandleAction(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		s.handleGetAction(w, r)
	case "PUT", "POST":
		s.handlePutAction(w, r)
	case "DELETE":
		s.handleDeleteAction(w, r)
	default:
		http.Error(w, "Bad Request", http.StatusBadRequest)
	}
}

func dbKey(path string) (storage.Key, error) {
	result, err := url.QueryUnescape(strings.TrimPrefix(path, KVKeyPrefix))
	if err == nil {
		k := storage.Key(result)
		if len(k) == 0 {
			return nil, fmt.Errorf("empty key not allowed")
		}
		return k, nil
	}
	return nil, err
}

func (s *RESTServer) handlePutAction(w http.ResponseWriter, r *http.Request) {
	key, err := dbKey(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer r.Body.Close()
	pr := <-s.db.Put(&storage.PutRequest{Key: key, Value: storage.Value{Bytes: b}})
	if pr.Error != nil {
		http.Error(w, pr.Error.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
}

func (s *RESTServer) handleGetAction(w http.ResponseWriter, r *http.Request) {
	key, err := dbKey(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	gr := <-s.db.Get(&storage.GetRequest{Key: key})
	if gr.Error != nil {
		http.Error(w, gr.Error.Error(), http.StatusInternalServerError)
		return
	}
	// An empty key will not be nil, but have zero length.
	if gr.Value.Bytes == nil {
		http.Error(w, "key not found", http.StatusNotFound)
		return
	}
	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "%s", string(gr.Value.Bytes))
}

func (s *RESTServer) handleDeleteAction(w http.ResponseWriter, r *http.Request) {
	key, err := dbKey(r.URL.Path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	dr := <-s.db.Delete(&storage.DeleteRequest{Key: key})
	if dr.Error != nil {
		http.Error(w, dr.Error.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
}


text:
package spet.sbwo.layer.picocontainer;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static spet.sbwo.layer.picocontainer.Model.*;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoBuilder;

public class SimpleDirectBoundaryTest {
    private MutablePicoContainer container;

    @Before
    public void setUp() {
        container = new PicoBuilder().build();
        container.addComponent(IA.class, A.class);
        container.addComponent(IB.class, B.class);
        container.addComponent(IC.class, C.class);
        container.addComponent(D.class);
    }

    @Test
    public void testConcrete() {
        D d = container.getComponent(D.class);
        assertTrue(d.a instanceof A);
        assertTrue(d.b instanceof B);
        assertTrue(d.c instanceof C);
    }

    @Test
    public void testInterface() {
        IC c = container.getComponent(IC.class);
        assertTrue(c instanceof C);
        assertTrue(((C)c).a instanceof A);
        assertTrue(((C)c).b instanceof B);
    }

}


text:
@implementation FSImageScrollView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
        self.scrollEnabled = NO;
		self.pagingEnabled = NO;
		self.clipsToBounds = NO;
		self.maximumZoomScale = 3.0f;
		self.minimumZoomScale = 1.0f;
		self.showsVerticalScrollIndicator = NO;
		self.showsHorizontalScrollIndicator = NO;
        self.bounces = YES;
        self.alwaysBounceVertical = NO;
		self.alwaysBounceHorizontal = NO;
        self.bouncesZoom = YES;
		self.scrollsToTop = NO;
		self.backgroundColor = [UIColor whiteColor];
		self.decelerationRate = UIScrollViewDecelerationRateFast;
    }
    return self;
}

- (void)zoomRectWithCenter:(CGPoint)center{

    if (self.zoomScale > 1.0f) {
        self.scrollEnabled = NO;
        [((FSImageView *)self.superview) killScrollViewZoom];
        return;
    }
    self.scrollEnabled = YES;
	CGRect rect;
	rect.size = CGSizeMake(self.frame.size.width / kFSImageViewerZoomScale, self.frame.size.height / kFSImageViewerZoomScale);
	rect.origin.x = MAX((center.x - (rect.size.width / 2.0f)), 0.0f);
	rect.origin.y = MAX((center.y - (rect.size.height / 2.0f)), 0.0f);

	CGRect frame = [self.superview convertRect:self.frame toView:self.superview];
	CGFloat borderX = frame.origin.x;
	CGFloat borderY = frame.origin.y;

	if (borderX > 0.0f && (center.x < borderX || center.x > self.frame.size.width - borderX)) {

		if (center.x < (self.frame.size.width / 2.0f)) {
			rect.origin.x += (borderX/kFSImageViewerZoomScale);
		} else {
			rect.origin.x -= ((borderX/kFSImageViewerZoomScale) + rect.size.width);
		}
	}

	if (borderY > 0.0f && (center.y < borderY || center.y > self.frame.size.height - borderY)) {
		if (center.y < (self.frame.size.height / 2.0f)) {
			rect.origin.y += (borderY/kFSImageViewerZoomScale);
		} else {
			rect.origin.y -= ((borderY/kFSImageViewerZoomScale) + rect.size.height);
		}
	}

	[self zoomToRect:rect animated:YES];
}

- (void)toggleBars{
	[[NSNotificationCenter defaultCenter] postNotificationName:kFSImageViewerToogleBarsNotificationKey object:nil];
}

#pragma mark - Touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	[super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
	[super touchesEnded:touches withEvent:event];
	UITouch *touch = [touches anyObject];

	if (touch.tapCount == 1) {
		[self performSelector:@selector(toggleBars) withObject:nil afterDelay:.2];
	} else if (touch.tapCount == 2) {
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(toggleBars) object:nil];
		[self zoomRectWithCenter:[[touches anyObject] locationInView:self]];
	}
}

@end


text:
package com.quakearts.tools.test.generator.primitives;

import com.quakearts.tools.test.generator.annotation.Generates;

@Generates({Character.class, char.class})
public final class CharacterGenerator extends StringRandomGenerator<Character> {

	@Override
	public Character generateRandom() {
		String string = generateRandomString();
		if(string.isEmpty())
			return '\0';

		return string.toCharArray()[0];
	}

}