text:
program demo_block
!! Shows Fortran 2008 block namespace
!! At BLOCK exit, local allocatables are deallocated, but outer scope allocatable are NOT deallocated
!!
!! program output:
!! ./block
!! block scope j=          42
!!  block scope size(B)=           4
!!  outer scope i=          10
!!  A allocated T size(a)           4

implicit none (type, external)

integer :: i, j
real, allocatable :: A(:)

i = 10
j = 42

flowers: block
  integer :: i
  real, allocatable :: B(:)
  i = 3
  print *, 'block scope j=',j  !< 42

  i = i + 1
  allocate(A(i), B(i))

  print *, 'block scope size(B)=',size(B) !< 4, deallocates on block exit (not visible in outer scope)

end block flowers

!> next line prints 10, as the outer scope `i` was not in scope of the block
print *, 'outer scope i=',i
print *, 'A allocated',allocated(A),'size(a)',size(A)

end program

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class IncidentStockTypesHelperTest < ActionView::TestCase
end


text:
setActiveLinks = _.debounce(function() {
    $("ul.nav.navbar-nav li.active").removeClass('active');
    $("ul.nav.navbar-nav li a[href='" + location.pathname + "']").parent().addClass('active');
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.googlecode.wel4j</groupId>
		<artifactId>wel4j-parent</artifactId>
		<version>0.5.0-SNAPSHOT</version>
	</parent>
	<artifactId>wel4j-log4j</artifactId>
	<name>wel4j-log4j</name>
	<url>http://wel4j.googlecode.com/</url>

	<licenses>
    	<license>
	      	<name>The Apache Software License, Version 2.0</name>
	      	<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
	      	<distribution>repo</distribution>
    	</license>
  	</licenses>

	<dependencies>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<scope>compile</scope>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.activation</groupId>
					<artifactId>activation</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.googlecode.wel4j</groupId>
			<artifactId>wel4j-core</artifactId>
			<version>0.5.0-SNAPSHOT</version>
		</dependency>
	</dependencies>
</project>


text:
<?php

	include("include/init.php");
	loadlib("wof_elasticsearch");

	$args = array();

	if ($page = get_int32("page")){
		$args['page'] = $page;
	}

	$rsp = elasticsearch_facet('wof:tags', $args);

	$pagination = $rsp['pagination'];
	$rows = $rsp['rows'];

	$GLOBALS['smarty']->assign_by_ref("pagination", $pagination);
	$GLOBALS['smarty']->assign_by_ref("tags", $rows);

	$pagination_url = $GLOBALS['cfg']['abs_root_url'] . "tags/";
	$GLOBALS['smarty']->assign("pagination_url", $pagination_url);

	$GLOBALS['smarty']->display('page_tags.txt');
	exit();


text:
@interface JWClass : NSObject

@end


text:
package leases

import (
	"google.golang.org/grpc"

	api "github.com/containerd/containerd/api/services/leases/v1"
	"github.com/containerd/containerd/plugin"
	"github.com/containerd/containerd/services"
	ptypes "github.com/gogo/protobuf/types"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
)

func init() {
	plugin.Register(&plugin.Registration{
		Type: plugin.GRPCPlugin,
		ID:   "leases",
		Requires: []plugin.Type{
			plugin.ServicePlugin,
		},
		InitFn: func(ic *plugin.InitContext) (interface{}, error) {
			plugins, err := ic.GetByType(plugin.ServicePlugin)
			if err != nil {
				return nil, err
			}
			p, ok := plugins[services.LeasesService]
			if !ok {
				return nil, errors.New("leases service not found")
			}
			i, err := p.Instance()
			if err != nil {
				return nil, err
			}
			return &service{local: i.(api.LeasesClient)}, nil
		},
	})
}

type service struct {
	local api.LeasesClient
}

func (s *service) Register(server *grpc.Server) error {
	api.RegisterLeasesServer(server, s)
	return nil
}

func (s *service) Create(ctx context.Context, r *api.CreateRequest) (*api.CreateResponse, error) {
	return s.local.Create(ctx, r)
}

func (s *service) Delete(ctx context.Context, r *api.DeleteRequest) (*ptypes.Empty, error) {
	return s.local.Delete(ctx, r)
}

func (s *service) List(ctx context.Context, r *api.ListRequest) (*api.ListResponse, error) {
	return s.local.List(ctx, r)
}


text:
// Fetch handler

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"github.com/gofrs/uuid"
	"github.com/julienschmidt/httprouter"
	"github.com/printmaps/printmaps/pd"
)

/*
fetchMetadata fetches the meta data for a given map ID
*/
func fetchMetadata(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
	var pmErrorList pd.PrintmapsErrorList
	var pmData pd.PrintmapsData

	id := params.ByName("id")

	// verify ID
	_, err := uuid.FromString(id)
	if err != nil {
		appendError(&pmErrorList, "4001", "error = "+err.Error(), "")
	}

	// map directory must exist
	if len(pmErrorList.Errors) == 0 {
		if pd.IsExistMapDirectory(id) == false {
			appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
		}
	}

	if len(pmErrorList.Errors) == 0 {
		if err := pd.ReadMetadata(&pmData, id); err != nil {
			if os.IsNotExist(err) {
				appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
			} else {
				message := fmt.Sprintf("error <%v> at readMetadata(), id = <%s>", err, id)
				http.Error(writer, message, http.StatusInternalServerError)
				log.Printf("Response %d - %s", http.StatusInternalServerError, message)
				return
			}
		}
	}

	if len(pmErrorList.Errors) == 0 {
		content, err := json.MarshalIndent(pmData, pd.IndentPrefix, pd.IndexString)
		if err != nil {
			message := fmt.Sprintf("error <%v> at json.MarshalIndent()", err)
			http.Error(writer, message, http.StatusInternalServerError)
			log.Printf("Response %d - %s", http.StatusInternalServerError, message)
			return
		}

		writer.Header().Set("Content-Type", pd.JSONAPIMediaType)
		writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
		writer.WriteHeader(http.StatusOK)
		writer.Write(content)
	} else {
		// request not ok, response with error list
		content, err := json.MarshalIndent(pmErrorList, pd.IndentPrefix, pd.IndexString)
		if err != nil {
			message := fmt.Sprintf("error <%v> at json.MarshalIndent()", err)
			http.Error(writer, message, http.StatusInternalServerError)
			log.Printf("Response %d - %s", http.StatusInternalServerError, message)
			return
		}

		writer.Header().Set("Content-Type", pd.JSONAPIMediaType)
		writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write(content)
	}
}

/*
fetchMapstate fetches the current state of the map creation process
*/
func fetchMapstate(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
	var pmErrorList pd.PrintmapsErrorList
	var pmState pd.PrintmapsState

	id := params.ByName("id")

	// verify ID
	_, err := uuid.FromString(id)
	if err != nil {
		appendError(&pmErrorList, "4001", "error = "+err.Error(), "")
	}

	// map directory must exist
	if len(pmErrorList.Errors) == 0 {
		if pd.IsExistMapDirectory(id) == false {
			appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
		}
	}

	if len(pmErrorList.Errors) == 0 {
		if err := pd.ReadMapstate(&pmState, id); err != nil {
			if os.IsNotExist(err) {
				appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
			} else {
				message := fmt.Sprintf("error <%v> at readMapstate(), id = <%s>", err, id)
				http.Error(writer, message, http.StatusInternalServerError)
				log.Printf("Response %d - %s", http.StatusInternalServerError, message)
				return
			}
		}
	}

	if len(pmErrorList.Errors) == 0 {
		content, err := json.MarshalIndent(pmState, pd.IndentPrefix, pd.IndexString)
		if err != nil {
			message := fmt.Sprintf("error <%v> at json.MarshalIndent()", err)
			http.Error(writer, message, http.StatusInternalServerError)
			log.Printf("Response %d - %s", http.StatusInternalServerError, message)
			return
		}

		writer.Header().Set("Content-Type", pd.JSONAPIMediaType)
		writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
		writer.WriteHeader(http.StatusOK)
		writer.Write(content)
	} else {
		// request not ok, response with error list
		content, err := json.MarshalIndent(pmErrorList, pd.IndentPrefix, pd.IndexString)
		if err != nil {
			message := fmt.Sprintf("error <%v> at json.MarshalIndent()", err)
			http.Error(writer, message, http.StatusInternalServerError)
			log.Printf("Response %d - %s", http.StatusInternalServerError, message)
			return
		}

		writer.Header().Set("Content-Type", pd.JSONAPIMediaType)
		writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write(content)
	}
}

/*
fetchMapfile send the map file with the give map ID to the client
*/
func fetchMapfile(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
	var pmErrorList pd.PrintmapsErrorList
	var pmData pd.PrintmapsData
	var pmState pd.PrintmapsState

	id := params.ByName("id")

	// verify ID
	_, err := uuid.FromString(id)
	if err != nil {
		appendError(&pmErrorList, "4001", "error = "+err.Error(), "")
	}

	// map directory must exist
	if len(pmErrorList.Errors) == 0 {
		if pd.IsExistMapDirectory(id) == false {
			appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
		}
	}

	if len(pmErrorList.Errors) == 0 {
		if err := pd.ReadMetadata(&pmData, id); err != nil {
			if os.IsNotExist(err) {
				appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
			} else {
				message := fmt.Sprintf("error <%v> at readMetadata(), id = <%s>", err, id)
				http.Error(writer, message, http.StatusInternalServerError)
				log.Printf("Response %d - %s", http.StatusInternalServerError, message)
				return
			}
		}
	}

	if len(pmErrorList.Errors) == 0 {
		if err := pd.ReadMapstate(&pmState, id); err != nil {
			if os.IsNotExist(err) {
				appendError(&pmErrorList, "4002", "requested ID not found: "+id, id)
			} else {
				message := fmt.Sprintf("error <%v> at readMapstate(), id = <%s>", err, id)
				http.Error(writer, message, http.StatusInternalServerError)
				log.Printf("Response %d - %s", http.StatusInternalServerError, message)
				return
			}
		}
	}

	if len(pmErrorList.Errors) == 0 {
		// verify state
		if pmState.Data.Attributes.MapOrderSubmitted == "" {
			appendError(&pmErrorList, "6001", "please submit map build order first", id)
		} else if pmState.Data.Attributes.MapBuildStarted == "" {
			appendError(&pmErrorList, "6002", "please repeat download request later", id)
		} else if pmState.Data.Attributes.MapBuildCompleted == "" {
			appendError(&pmErrorList, "6003", "please repeat download request later", id)
		}
	}

	if len(pmErrorList.Errors) == 0 {
		// verify build completion (successful == yes/no)
		if pmState.Data.Attributes.MapBuildSuccessful == "no" {
			appendError(&pmErrorList, "6004", pmState.Data.Attributes.MapBuildMessage, id)
		}
	}

	if len(pmErrorList.Errors) == 0 {
		// request ok, response with mapfile
		filename := filepath.Join(pd.PathWorkdir, pd.PathMaps, id, pd.FileMapfile)
		http.ServeFile(writer, request, filename)
		log.Printf("Map <%s> send to client", filename)
	} else {
		// request not ok, response with error list
		content, err := json.MarshalIndent(pmErrorList, pd.IndentPrefix, pd.IndexString)
		if err != nil {
			message := fmt.Sprintf("error <%v> at json.MarshalIndent()", err)
			http.Error(writer, message, http.StatusInternalServerError)
			log.Printf("Response %d - %s", http.StatusInternalServerError, message)
			return
		}

		writer.Header().Set("Content-Type", pd.JSONAPIMediaType)
		writer.Header().Set("Content-Length", strconv.Itoa(len(content)))
		writer.WriteHeader(http.StatusBadRequest)
		writer.Write(content)
	}
}


text:
// Copyright 2022 Google LLC.
//
// 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.

#include <array>
#include <cstdint>
#include <cstring>
#include <vector>

#include "spdm_lite/common/crypto.h"
#include "spdm_lite/common/crypto_types.h"
#include "spdm_lite/common/messages.h"
#include "spdm_lite/common/session_types.h"
#include "spdm_lite/common/utils.h"
#include "spdm_lite/everparse/SPDMWrapper.h"
#include "spdm_lite/responder/responder.h"
#include "spdm_lite/testing/add_2_app.h"
#include "spdm_lite/testing/host_context.h"
#include "spdm_lite/testing/utils.h"

#include "gtest/gtest.h"

namespace {

std::vector<uint8_t> MakeAdd2AppRequest(uint16_t standard_id,
                                        const std::vector<uint8_t>& vendor_id,
                                        uint32_t num) {
  const uint32_t msg_len = sizeof(SPDM_VENDOR_DEFINED_REQ_RSP) +
                           vendor_id.size() + sizeof(uint16_t) +
                           sizeof(uint32_t);

  std::vector<uint8_t> msg(msg_len);

  auto* vendor_defined_req =
      reinterpret_cast<SPDM_VENDOR_DEFINED_REQ_RSP*>(msg.data());
  auto* out_vendor_id = reinterpret_cast<uint8_t*>(&vendor_defined_req[1]);
  auto* req_len = reinterpret_cast<uint16_t*>(out_vendor_id + vendor_id.size());
  auto* number = reinterpret_cast<uint32_t*>(&req_len[1]);

  *vendor_defined_req = {
      .preamble =
          {
              .version = 0x12,
              .request_response_code = SPDM_CODE_VENDOR_DEFINED_REQUEST,
          },
      .standard_id = standard_id,
      .vendor_id_len = static_cast<uint8_t>(vendor_id.size()),
  };

  memcpy(out_vendor_id, vendor_id.data(), vendor_id.size());
  *req_len = sizeof(*number);
  *number = num;

  return msg;
}

TEST(SessionEstablished, AppTraffic) {
  SpdmAsymPrivKey rsp_priv_key;
  SpdmAsymPubKey rsp_pub_key;
  SpdmResponderContext ctx;
  initialize_host_responder_context(&rsp_priv_key, &rsp_pub_key, &ctx,
                                    add_2_app_fn);

  SpdmAsymPrivKey req_priv_key;
  SpdmAsymPubKey req_pub_key;
  ASSERT_EQ(0, spdm_generate_asym_keypair(SPDM_ASYM_ECDSA_ECC_NIST_P256,
                                          &req_priv_key, &req_pub_key));

  SpdmDhePrivKey req_key_ex_priv_key;
  SpdmDhePubKey req_key_ex_pub_key;
  ASSERT_EQ(0,
            spdm_gen_dhe_keypair(get_mbedtls_crypto_spec(), SPDM_DHE_SECP521R1,
                                 &req_key_ex_priv_key, &req_key_ex_pub_key));

  uint8_t req_session_id[2];
  spdm_get_random(&ctx.crypto_spec, req_session_id, sizeof(req_session_id));

  std::vector<uint8_t> get_version_msg = MakeGetVersion();
  std::vector<uint8_t> get_caps_msg = MakeGetCapabilities();
  std::vector<uint8_t> negotiate_algs_msg = MakeNegotiateAlgorithms();
  std::vector<uint8_t> key_exchange_msg =
      MakeKeyExchange(req_session_id, req_key_ex_pub_key);
  std::vector<uint8_t> give_pub_key_msg = MakeGivePubKey(req_pub_key);

  ASSERT_EQ(0, DispatchRequest(&ctx, get_version_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, get_caps_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, negotiate_algs_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, key_exchange_msg));
  ASSERT_EQ(
      0, DispatchSecureRequest(&ctx, SPDM_HANDSHAKE_PHASE, give_pub_key_msg));

  SpdmHash transcript = ctx.session.transcript_hash;
  std::vector<uint8_t> digest = GetDigest(req_pub_key.data, req_pub_key.size);
  spdm_extend_hash(&transcript, digest.data(), digest.size());

  std::vector<uint8_t> finish_msg =
      MakeFinish(&transcript, ctx.session.params, req_priv_key);

  ASSERT_EQ(0, DispatchSecureRequest(&ctx, SPDM_HANDSHAKE_PHASE, finish_msg));
  ASSERT_EQ(ctx.state, STATE_SESSION_ESTABLISHED);

  uint16_t req_standard_id = 4;
  std::vector<uint8_t> req_vendor_id = {0x01, 0x02, 0x03, 0x04};
  uint32_t req_num = 1701;

  std::vector<uint8_t> app_req =
      MakeAdd2AppRequest(req_standard_id, req_vendor_id, req_num);
  std::vector<uint8_t> rsp;
  ASSERT_EQ(0, DispatchSecureRequest(&ctx, SPDM_DATA_PHASE, app_req, &rsp));

  buffer output_msg = MakeBuffer(rsp);

  uint16_t rsp_standard_id;
  buffer rsp_vendor_id;
  buffer payload;

  ASSERT_EQ(0, SpdmCheckVendorDefinedResponse(
                   &output_msg, /*rest=*/nullptr, &rsp_standard_id,
                   &rsp_vendor_id.data, &rsp_vendor_id.size, &payload.data,
                   &payload.size));

  ASSERT_EQ(rsp_standard_id, req_standard_id);
  ASSERT_EQ(rsp_vendor_id.size, req_vendor_id.size());
  ASSERT_EQ(
      0, memcmp(rsp_vendor_id.data, req_vendor_id.data(), rsp_vendor_id.size));

  ASSERT_EQ(payload.size, sizeof(Add2AppResponse) + req_pub_key.size);

  const auto* response = reinterpret_cast<const Add2AppResponse*>(payload.data);

  EXPECT_EQ(response->num, req_num + 2);
  EXPECT_EQ(
      0, memcmp(response->session_id.id, ctx.session.params.info.session_id.id,
                sizeof(response->session_id.id)));
  EXPECT_EQ(0, memcmp(payload.data + sizeof(*response), req_pub_key.data,
                      req_pub_key.size));

  const SpdmNegotiatedAlgs* session_algs =
      &ctx.session.params.info.negotiated_algs;
  EXPECT_EQ(response->asym_sign_alg, session_algs->asym_sign_alg);
  EXPECT_EQ(response->asym_verify_alg, session_algs->asym_verify_alg);
  EXPECT_EQ(response->hash_alg, session_algs->hash_alg);
  EXPECT_EQ(response->dhe_alg, session_algs->dhe_alg);
  EXPECT_EQ(response->aead_alg, session_algs->aead_alg);

  // Tear down session
  std::vector<uint8_t> end_session_msg = MakeEndSession();
  ASSERT_EQ(0, DispatchSecureRequest(&ctx, SPDM_DATA_PHASE, end_session_msg));

  // Test that we can start a new flow.
  ASSERT_EQ(0, DispatchRequest(&ctx, get_version_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, get_caps_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, negotiate_algs_msg));
  ASSERT_EQ(0, DispatchRequest(&ctx, key_exchange_msg));
  ASSERT_EQ(ctx.state, STATE_MUTUAL_AUTH_NEED_REQUESTER_KEY);

  // Restart in the middle.
  ASSERT_EQ(0, DispatchRequest(&ctx, get_version_msg));
  ASSERT_EQ(ctx.state, STATE_WAITING_FOR_GET_CAPABILITIES);
}

}  // namespace


text:
package org.guvnor.asset.management.client.editors.project.structure.widgets;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.view.client.HasData;

public interface ProjectModulesView extends IsWidget {

    enum ViewMode {
        MODULES_VIEW,
        PROJECTS_VIEW
    }

    interface Presenter {

        void onAddModule();

        void addDataDisplay( final HasData<ProjectModuleRow> display );

        void onDeleteModule( ProjectModuleRow moduleRow );

        void onEditModule( ProjectModuleRow moduleRow );
    }

    void setPresenter( Presenter presenter );

    void setMode( ViewMode mode );

    void enableActions( boolean value );

}


text:
package com.sksamuel.elastic4s

import org.elasticsearch.client.Requests

/** @author Stephen Samuel */
trait MoreLikeThisDsl {

  def mlt = new MltExpectingId
  def morelike = new MltExpectingId
  class MltExpectingId {
    def id(id: Any) = new MltExpectsIndex(id.toString)
  }

  class MltExpectsIndex(id: String) {
    def in(in: String) = in.split("/").toList match {
      case idx :: Nil => new MoreLikeThisDefinition(idx, null, id)
      case idx :: t :: Nil => new MoreLikeThisDefinition(idx, t, id)
      case _ => throw new RuntimeException
    }
  }
}

class MoreLikeThisDefinition(index: String, `type`: String, id: String) {

  private val _builder = Requests.moreLikeThisRequest(index).`type`(`type`).id(id)
  def build = _builder

  def fields(fields: String*) = {
    _builder.fields(fields: _*)
    this
  }
  def minTermFreq(freq: Int) = {
    _builder.minTermFreq(freq)
    this
  }
  def stopWords(stopWords: String*) = {
    _builder.stopWords(stopWords: _*)
    this
  }
  def percentTermsToMatch(percentTermsToMatch: Double) = {
    _builder.percentTermsToMatch(percentTermsToMatch.toFloat)
    this
  }

  def maxWordLength(maxWordLen: Int) = {
    _builder.maxWordLength(maxWordLen)
    this
  }
  def minWordLength(minWordLen: Int) = {
    _builder.minWordLength(minWordLen)
    this
  }
  def boostTerms(boostTerms: Double) = {
    _builder.boostTerms(boostTerms.toFloat)
    this
  }
  def maxQueryTerms(maxQueryTerms: Int) = {
    _builder.maxQueryTerms(maxQueryTerms)
    this
  }
  def minDocFreq(minDocFreq: Int) = {
    _builder.minDocFreq(minDocFreq)
    this
  }
  def maxDocFreq(maxDocFreq: Int) = {
    _builder.maxDocFreq(maxDocFreq)
    this
  }

  def limit(sizeHint: Int) = size(sizeHint)

  def size(sizeHint: Int) = {
    _builder.searchSize(sizeHint)
    this
  }

  def start(i: Int) = from(i)
  def from(i: Int) = {
    _builder.searchFrom(i)
    this
  }
}


text:
from bsonstream import KeyValueBSONInput
import sys

def read_field(record, f):
    r = record
    for p in f.split("/"):
        r = r[p]

    return str(r)

def read_file(source, output, fields):
    for _, record in KeyValueBSONInput(fh=source):
        try:
            print >> output, ",".join([read_field(record, f) for f in fields])
        except KeyError:
            pass
        except Exception as e:
            print >> sys.stderr, e

if __name__ == "__main__":
    if sys.argv[1] == "--stdin":
        infile = sys.stdin
    else:
        infile = open(sys.argv[1], "rb")

    if sys.argv[2] == "--stdout":
        outfile= sys.stdout
    else:
        outfile = open(sys.argv[2], "w")

    read_file(infile, outfile, sys.argv[3:])


text:
M.core_user = {};

M.core_user.init_participation = function(Y) {
	Y.on('change', function() {
		var action = Y.one('#formactionid');
		if (action.get('value') == '') {
			return;
		}
        var ok = false;
        Y.all('input.usercheckbox').each(function() {
            if (this.get('checked')) {
                ok = true;
            }
        });
        if (!ok) {
            // no checkbox selected
            return;
        }
        Y.one('#participantsform').submit();
	}, '#formactionid');

    Y.on('click', function(e) {
        // Presence of a show all link indicates we should redirect to
        // a page with all users listed and checked, otherwise just check
        // those already shown.
        var showallink = this.getAttribute('data-showallink');
        if (showallink) {
            window.location = showallink;
        }
        Y.all('input.usercheckbox').each(function() {
            this.set('checked', 'checked');
        });
    }, '#checkall, #checkallonpage');

    Y.on('click', function(e) {
        Y.all('input.usercheckbox').each(function() {
            this.set('checked', '');
        });
    }, '#checknone');
};

M.core_user.init_tree = function(Y, expand_all, htmlid) {
    Y.use('yui2-treeview', function(Y) {
        var tree = new Y.YUI2.widget.TreeView(htmlid);

        tree.subscribe("clickEvent", function(node, event) {
            // we want normal clicking which redirects to url
            return false;
        });

        if (expand_all) {
            tree.expandAll();
        }

        tree.render();
    });
};


text:
'use strict';

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _koa = require('koa');

var _koa2 = _interopRequireDefault(_koa);

var _koaCors = require('koa-cors');

var _koaCors2 = _interopRequireDefault(_koaCors);

var _koaBodyparser = require('koa-bodyparser');

var _koaBodyparser2 = _interopRequireDefault(_koaBodyparser);

var _koaRouter = require('koa-router');

var _koaRouter2 = _interopRequireDefault(_koaRouter);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

require('es6-promise').polyfill();

var router = new _koaRouter2.default();

function wrapRequest(request) {
  return {
    query: request.query,
    body: request.body,
    method: request.method,
    url: request.url,
    header: request.header
  };
}

var Fake = function () {
  function Fake() {
    (0, _classCallCheck3.default)(this, Fake);

    this.router = new _koaRouter2.default();
  }

  (0, _createClass3.default)(Fake, [{
    key: 'get',
    value: function get(route, response) {
      if (!route || !response) {
        throw new Error('function get(route, response), missing parameter');
      }

      this.router.get(route, _regenerator2.default.mark(function _callee(next) {
        return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                this.body = response(wrapRequest(this.request));
                _context.next = 3;
                return next;

              case 3:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));
    }
  }, {
    key: 'post',
    value: function post(route, response) {
      if (!route || !response) {
        throw new Error('function post(route, response), missing parameter');
      }

      this.router.post(route, _regenerator2.default.mark(function _callee2(next) {
        return _regenerator2.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                this.body = response(wrapRequest(this.request));
                _context2.next = 3;
                return next;

              case 3:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));
    }
  }, {
    key: 'use',
    value: function use(path, subRouter) {
      if (!path || !subRouter) {
        throw new Error('function use(path, subRouter), missing parameter');
      }

      router.use(path, subRouter.routes(), subRouter.allowedMethods());
    }
  }, {
    key: 'listen',
    value: function listen(port) {
      var app = (0, _koa2.default)();
      router.use('', this.router.routes(), this.router.allowedMethods());

      console.log('server is ready on port ' + (port || 4000));

      return app.use((0, _koaCors2.default)()).use((0, _koaBodyparser2.default)()).use(router.routes()).use(router.allowedMethods()).listen(port || 4000);
    }
  }]);
  return Fake;
}();

module.exports = Fake;


text:
apt-get install -y curl git mercurial make binutils bison gcc build-essential
curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer > /tmp/gvm_install
chmod +x /tmp/gvm_install
/tmp/gvm_install > /dev/null
source /root/.gvm/scripts/gvm
export PATH=$PATH:~/bin:~/.gvm/bin
gvm install $GO_VERSION


text:
package tsm1

import (
	"fmt"
	"testing"

	"github.com/influxdata/influxdb/v2/storage/reads/datatypes"
)

func TestPredicatePopTagEscape(t *testing.T) {
	cases := []struct {
		Key   string
		Tag   string
		Value string
		Rest  string
	}{
		{Key: "", Tag: "", Value: "", Rest: ""},
		{Key: "invalid", Tag: "", Value: "", Rest: ""},
		{Key: "region=west,server=b,foo=bar", Tag: "region", Value: "west", Rest: "server=b,foo=bar"},
		{Key: "region=west", Tag: "region", Value: "west", Rest: ""},
		{Key: `re\=gion=west,server=a`, Tag: `re=gion`, Value: "west", Rest: "server=a"},
		{Key: `region=w\,est,server=a`, Tag: `region`, Value: "w,est", Rest: "server=a"},
		{Key: `hi\ yo\ =w\,est,server=a`, Tag: `hi yo `, Value: "w,est", Rest: "server=a"},
		{Key: `\ e\ \=o=world,server=a`, Tag: ` e =o`, Value: "world", Rest: "server=a"},
	}

	for _, c := range cases {
		tag, value, rest := predicatePopTagEscape([]byte(c.Key))
		if string(tag) != c.Tag {
			t.Fatalf("got returned tag %q expected %q", tag, c.Tag)
		} else if string(value) != c.Value {
			t.Fatalf("got returned value %q expected %q", value, c.Value)
		} else if string(rest) != c.Rest {
			t.Fatalf("got returned remainder %q expected %q", rest, c.Rest)
		}
	}
}

func TestPredicate_Matches(t *testing.T) {
	cases := []struct {
		Name      string
		Predicate *datatypes.Predicate
		Key       string
		Matches   bool
	}{
		{
			Name: "Basic Matching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Basic Unmatching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3"))),
			Key:     "bucketorg,tag3=val2",
			Matches: false,
		},

		{
			Name: "Compound Logical Matching",
			Predicate: predicate(
				orNode(
					andNode(
						comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
						comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("no"))),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")))),
			Key:     "bucketorg,foo=bar,baz=bif,tag3=val3",
			Matches: true,
		},

		{
			Name: "Compound Logical Unmatching",
			Predicate: predicate(
				orNode(
					andNode(
						comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
						comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("no"))),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")))),
			Key:     "bucketorg,foo=bar,baz=bif,tag3=val2",
			Matches: false,
		},

		{
			Name: "Logical Or Short Circuit",
			Predicate: predicate(
				orNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("no")))),
			Key:     "bucketorg,baz=bif,foo=bar,tag3=val3",
			Matches: true,
		},

		{
			Name: "Logical And Short Circuit",
			Predicate: predicate(
				andNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("no")),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("bif")))),
			Key:     "bucketorg,baz=bif,foo=bar,tag3=val3",
			Matches: false,
		},

		{
			Name: "Logical And Matching",
			Predicate: predicate(
				andNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("bif")))),
			Key:     "bucketorg,baz=bif,foo=bar,tag3=val3",
			Matches: true,
		},

		{
			Name: "Logical And Matching Reduce (Simplify)",
			Predicate: predicate(
				andNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
					comparisonNode(datatypes.Node_ComparisonNotEqual, tagNode("foo"), stringNode("bif")))),
			Key:     "bucketorg,baz=bif,foo=bar,tag3=val3",
			Matches: true,
		},

		{
			Name: "Regex Matching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonRegex, tagNode("tag3"), regexNode("...3"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "NotRegex Matching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonNotRegex, tagNode("tag3"), regexNode("...4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Regex Unmatching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonRegex, tagNode("tag3"), regexNode("...4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: false,
		},

		{
			Name: "NotRegex Unmatching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonNotRegex, tagNode("tag3"), regexNode("...3"))),
			Key:     "bucketorg,tag3=val3",
			Matches: false,
		},

		{
			Name: "Basic Matching Reversed",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, stringNode("val3"), tagNode("tag3"))),
			Key:     "bucketorg,tag2=val2,tag3=val3",
			Matches: true,
		},

		{
			Name: "Tag Matching Tag",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag4"), tagNode("tag3"))),
			Key:     "bucketorg,tag3=val3,tag4=val3",
			Matches: true,
		},

		{
			Name: "No Tag",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag4"), stringNode("val4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: false,
		},

		{
			Name: "Not Equal",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonNotEqual, tagNode("tag3"), stringNode("val4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Starts With",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonStartsWith, tagNode("tag3"), stringNode("va"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Less",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonLess, tagNode("tag3"), stringNode("val4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Less Equal",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonLessEqual, tagNode("tag3"), stringNode("val4"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Greater",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonGreater, tagNode("tag3"), stringNode("u"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Greater Equal;",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonGreaterEqual, tagNode("tag3"), stringNode("u"))),
			Key:     "bucketorg,tag3=val3",
			Matches: true,
		},

		{
			Name: "Escaping Matching",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3"))),
			Key:     `bucketorg,tag1=\,foo,tag2=\ bar,tag2\=more=val2\,\ \=hello,tag3=val3`,
			Matches: true,
		},
	}

	for _, test := range cases {
		t.Run(test.Name, func(t *testing.T) {
			pred, err := NewProtobufPredicate(test.Predicate)
			if err != nil {
				t.Fatal("compile failure:", err)
			}

			if got, exp := pred.Matches([]byte(test.Key)), test.Matches; got != exp {
				t.Fatal("match failure:", "got", got, "!=", "exp", exp)
			}

			// Clone and try again.
			pred = pred.Clone()
			if got, exp := pred.Matches([]byte(test.Key)), test.Matches; got != exp {
				t.Fatal("cloned match failure:", "got", got, "!=", "exp", exp)
			}
		})
	}
}

func TestPredicate_Unmarshal(t *testing.T) {
	protoPred := predicate(
		orNode(
			andNode(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("foo"), stringNode("bar")),
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("baz"), stringNode("no"))),
			comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3"))))

	pred1, err := NewProtobufPredicate(protoPred)
	if err != nil {
		t.Fatal(err)
	}

	predData, err := pred1.Marshal()
	if err != nil {
		t.Fatal(err)
	}

	_, err = UnmarshalPredicate(predData)
	if err != nil {
		t.Fatal(err)
	}

	t.Skip("TODO(dstrand1): Fix cmp for predicateMatcher. See in IDPE: https://github.com/influxdata/idpe/blob/7c52ef7c9bc387905f2864c8730c7366f07f8a1e/storage/tsdb/tsm1/predicate_test.go#L285")

	//if !cmp.Equal(pred1, pred2, cmputil.IgnoreProtobufUnexported()) {
	//	t.Fatal("mismatch on unmarshal")
	//}
}

func TestPredicate_Unmarshal_InvalidTag(t *testing.T) {
	_, err := UnmarshalPredicate([]byte("\xff"))
	if err == nil {
		t.Fatal("expected error")
	}
}

func TestPredicate_Unmarshal_InvalidProtobuf(t *testing.T) {
	_, err := UnmarshalPredicate([]byte("\x00\xff"))
	if err == nil {
		t.Fatal("expected error")
	}
}

func TestPredicate_Unmarshal_Empty(t *testing.T) {
	pred, err := UnmarshalPredicate(nil)
	if err != nil {
		t.Fatal(err)
	} else if pred != nil {
		t.Fatal("expected no predicate")
	}
}

func TestPredicate_Invalid_Protobuf(t *testing.T) {
	cases := []struct {
		Name      string
		Predicate *datatypes.Predicate
	}{
		{
			Name: "Invalid Comparison Num Children",
			Predicate: predicate(&datatypes.Node{
				NodeType: datatypes.Node_TypeComparisonExpression,
				Value:    &datatypes.Node_Comparison_{Comparison: datatypes.Node_ComparisonEqual},
				Children: []*datatypes.Node{{}, {}, {}},
			}),
		},

		{
			Name: "Mismatching Left Tag Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, &datatypes.Node{
					NodeType: datatypes.Node_TypeTagRef,
					Value:    &datatypes.Node_IntegerValue{IntegerValue: 2},
				}, tagNode("tag"))),
		},

		{
			Name: "Mismatching Left Literal Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, &datatypes.Node{
					NodeType: datatypes.Node_TypeLiteral,
					Value:    &datatypes.Node_IntegerValue{IntegerValue: 2},
				}, tagNode("tag"))),
		},

		{
			Name: "Invalid Left Node Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, &datatypes.Node{
					NodeType: datatypes.Node_TypeComparisonExpression,
					Value:    &datatypes.Node_Comparison_{Comparison: datatypes.Node_ComparisonEqual},
				}, tagNode("tag"))),
		},

		{
			Name: "Mismatching Right Tag Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag"), &datatypes.Node{
					NodeType: datatypes.Node_TypeTagRef,
					Value:    &datatypes.Node_IntegerValue{IntegerValue: 2},
				})),
		},

		{
			Name: "Invalid Regex",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonRegex, tagNode("tag3"), regexNode("("))),
		},

		{
			Name: "Mismatching Right Literal Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag"), &datatypes.Node{
					NodeType: datatypes.Node_TypeLiteral,
					Value:    &datatypes.Node_IntegerValue{IntegerValue: 2},
				})),
		},

		{
			Name: "Invalid Right Node Type",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag"), &datatypes.Node{
					NodeType: datatypes.Node_TypeComparisonExpression,
					Value:    &datatypes.Node_Comparison_{Comparison: datatypes.Node_ComparisonEqual},
				})),
		},

		{
			Name: "Invalid Comparison Without Regex",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonRegex, tagNode("tag3"), stringNode("val3"))),
		},

		{
			Name: "Invalid Comparison With Regex",
			Predicate: predicate(
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), regexNode("."))),
		},

		{
			Name: "Invalid Logical Operation Children",
			Predicate: predicate(&datatypes.Node{
				NodeType: datatypes.Node_TypeLogicalExpression,
				Value:    &datatypes.Node_Logical_{Logical: datatypes.Node_LogicalAnd},
				Children: []*datatypes.Node{{}, {}, {}},
			}),
		},

		{
			Name: "Invalid Left Logical Expression",
			Predicate: predicate(
				andNode(
					tagNode("tag"),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")),
				)),
		},

		{
			Name: "Invalid Right Logical Expression",
			Predicate: predicate(
				andNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")),
					tagNode("tag"),
				)),
		},

		{
			Name: "Invalid Logical Value",
			Predicate: predicate(&datatypes.Node{
				NodeType: datatypes.Node_TypeLogicalExpression,
				Value:    &datatypes.Node_Logical_{Logical: 9999},
				Children: []*datatypes.Node{
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag3"), stringNode("val3")),
				},
			}),
		},

		{
			Name:      "Invalid Root Node",
			Predicate: predicate(tagNode("tag3")),
		},
	}

	for _, test := range cases {
		t.Run(test.Name, func(t *testing.T) {
			_, err := NewProtobufPredicate(test.Predicate)
			if err == nil {
				t.Fatal("expected compile failure")
			}
		})
	}
}

func BenchmarkPredicate(b *testing.B) {
	run := func(b *testing.B, predicate *datatypes.Predicate) {
		pred, err := NewProtobufPredicate(predicate)
		if err != nil {
			b.Fatal(err)
		}

		series := []byte("bucketorg,")
		for i := 0; i < 10; i++ {
			series = append(series, fmt.Sprintf("tag%d=val%d,", i, i)...)
		}
		series = series[:len(series)-1]

		b.SetBytes(int64(len(series)))
		b.ReportAllocs()
		b.ResetTimer()

		for i := 0; i < b.N; i++ {
			pred.Matches(series)
		}
	}

	b.Run("Basic", func(b *testing.B) {
		run(b, predicate(
			comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag5"), stringNode("val5")),
		))
	})

	b.Run("Compound", func(b *testing.B) {
		run(b, predicate(
			orNode(
				andNode(
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag0"), stringNode("val0")),
					comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag6"), stringNode("val5")),
				),
				comparisonNode(datatypes.Node_ComparisonEqual, tagNode("tag5"), stringNode("val5")),
			),
		))
	})
}

//
// Helpers to create predicate protobufs
//

func tagNode(s string) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeTagRef,
		Value:    &datatypes.Node_TagRefValue{TagRefValue: s},
	}
}

func stringNode(s string) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeLiteral,
		Value:    &datatypes.Node_StringValue{StringValue: s},
	}
}

func regexNode(s string) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeLiteral,
		Value:    &datatypes.Node_RegexValue{RegexValue: s},
	}
}

func comparisonNode(comp datatypes.Node_Comparison, left, right *datatypes.Node) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeComparisonExpression,
		Value:    &datatypes.Node_Comparison_{Comparison: comp},
		Children: []*datatypes.Node{left, right},
	}
}

func andNode(left, right *datatypes.Node) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeLogicalExpression,
		Value:    &datatypes.Node_Logical_{Logical: datatypes.Node_LogicalAnd},
		Children: []*datatypes.Node{left, right},
	}
}

func orNode(left, right *datatypes.Node) *datatypes.Node {
	return &datatypes.Node{
		NodeType: datatypes.Node_TypeLogicalExpression,
		Value:    &datatypes.Node_Logical_{Logical: datatypes.Node_LogicalOr},
		Children: []*datatypes.Node{left, right},
	}
}

func predicate(root *datatypes.Node) *datatypes.Predicate {
	return &datatypes.Predicate{Root: root}
}


text:
```php
public Result->getWinner ( ): CondorcetPHP\Condorcet\Candidate|array|null
```

Equivalent to [Condorcet/Election::getWinner($method)](../Election Class/public Election--getWinner.md).

### Return value:

*(```CondorcetPHP\Condorcet\Candidate|array|null```)* Candidate object given. Null if there are no available winner.
You can get an array with multiples winners.

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

### Related method(s)

* [Result::getLoser](../Result%20Class/public%20Result--getLoser.md)
* [Election::getWinner](../Election%20Class/public%20Election--getWinner.md)


text:
require 'rubygems'
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts "Run `bundle install` to install missing gems"
  exit e.status_code
end
require 'test/unit'

require "active_support/core_ext/class/attribute" # for class_attribute
require "action_dispatch/http/mime_type"
require "active_support/json"
require "active_support/core_ext/object/conversions" # rails ticket https://gist.github.com/971766

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rjson'

class Test::Unit::TestCase
end


text:
void CBlockVersion::SetBaseVersion(int32_t nBaseVersion)
{
    assert(nBaseVersion >= 1 && nBaseVersion < VERSION_AUXPOW);
    assert(!IsAuxpow());
    const int32_t nChainId = Params ().GetConsensus ().nAuxpowChainId;
    nVersion = nBaseVersion | (nChainId * VERSION_CHAIN_START);
}

uint256 CPureBlockHeader::GetHash() const
{
    return SerializeHash(*this);
}


text:
<?php

namespace Intacct\Functions\Common;

use Intacct\Xml\XMLWriter;

/**
 * @coversDefaultClass \Intacct\Functions\Common\ReadReport
 */
class ReadReportTest extends \PHPUnit\Framework\TestCase
{

    public function testDefaultParams(): void
    {
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
    <readReport>
        <report>TestBill Date Runtime</report>
        <waitTime>0</waitTime>
        <pagesize>1000</pagesize>
        <returnFormat>xml</returnFormat>
    </readReport>
</function>
EOF;

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');

        $readReport->writeXml($xml);

        $this->assertXmlStringEqualsXmlString($expected, $xml->flush());
    }

    public function testParamOverrides(): void
    {
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
    <readReport>
        <report>TestBill Date Runtime</report>
        <waitTime>15</waitTime>
        <pagesize>200</pagesize>
        <returnFormat>xml</returnFormat>
        <listSeparator>,</listSeparator>
    </readReport>
</function>
EOF;

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setPageSize(200);
        $readReport->setWaitTime(15);
        $readReport->setListSeparator(',');

        $readReport->writeXml($xml);

        $this->assertXmlStringEqualsXmlString($expected, $xml->flush());
    }

    public function testNoReport(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Report Name is required for read report");

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        //$readReport->setReportName('TestBill Date Runtime');

        $readReport->writeXml($xml);
    }

    public function testMinPageSize(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Page Size cannot be less than 1");

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setPageSize(0);
    }

    public function testMaxPageSize(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Page Size cannot be greater than 1000");

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setPageSize(1001);
    }

    public function testMinWaitTime(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Wait Time cannot be less than 0");

        $readReport = new ReadReport('unittest');
        $readReport->setWaitTime(-1);
    }

    public function testMaxWaitTime(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Wait Time cannot be greater than 30");

        $readReport = new ReadReport('unittest');
        $readReport->setWaitTime(31);
    }

    public function testReturnDef(): void
    {
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
    <readReport returnDef="true">
        <report>TestBill Date Runtime</report>
    </readReport>
</function>
EOF;

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setReturnDef(true);

        $readReport->writeXml($xml);

        $this->assertXmlStringEqualsXmlString($expected, $xml->flush());
    }

    public function testComplexArguments(): void
    {
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
    <readReport>
        <report>TestBill Date Runtime</report>
        <arguments>
            <APBILL.TEST_DATE>
                <FROM_DATE>1/1/2014</FROM_DATE>
                <TO_DATE>12/31/2016</TO_DATE>
            </APBILL.TEST_DATE>
        </arguments>
        <waitTime>0</waitTime>
        <pagesize>1000</pagesize>
        <returnFormat>xml</returnFormat>
    </readReport>
</function>
EOF;

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setArguments([
            'APBILL.TEST_DATE' => [
                'FROM_DATE' => '1/1/2014',
                'TO_DATE' => '12/31/2016'
            ]
        ]);

        $readReport->writeXml($xml);

        $this->assertXmlStringEqualsXmlString($expected, $xml->flush());
    }

    public function testSimpleArguments(): void
    {
        $expected = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<function controlid="unittest">
    <readReport>
        <report>TestBill Date Runtime</report>
        <arguments>
            <REPORTINGPERIOD>Current Year</REPORTINGPERIOD>
        </arguments>
        <waitTime>0</waitTime>
        <pagesize>1000</pagesize>
        <returnFormat>xml</returnFormat>
    </readReport>
</function>
EOF;

        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->setIndentString('    ');
        $xml->startDocument();

        $readReport = new ReadReport('unittest');
        $readReport->setReportName('TestBill Date Runtime');
        $readReport->setArguments([
            'REPORTINGPERIOD' => 'Current Year'
        ]);

        $readReport->writeXml($xml);

        $this->assertXmlStringEqualsXmlString($expected, $xml->flush());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<removed version="28">
    <class name="android.app.KeyguardManager">
        <method signature="dismissKeyguard(Landroid.app.Activity;Landroid.app.KeyguardManager.KeyguardDismissCallback;Landroid.os.Handler;)V"/>
    </class>
    <class name="android.app.ActivityManager">
        <method signature="getMaxNumPictureInPictureActions()I"/>
    </class>
    <class name="android.hardware.SensorManager">
        <method signature="configureDirectChannel(Landroid.hardware.SensorDirectChannel;Landroid.hardware.Sensor;I)I"/>
    </class>
    <class name="android.os.storage.StorageManager">
        <method signature="getVolumeList()[Landroid.os.storage.StorageVolume;"/>
        <method signature="getPrimaryVolume()Landroid.os.storage.StorageVolume;"/>
    </class>
    <class name="android.app.PictureInPictureArgs"/>
    <class name="android.test.mock.MockPackageManager">
        <method signature="getDefaultBrowserPackageName(I)Ljava.lang.String;"/>
        <method signature="setDefaultBrowserPackageName(Ljava.lang.String;I)Z"/>
    </class>
    <class name="android.app.Notification.Builder">
        <method signature="setChannel(Ljava.lang.String;)Landroid.app.Notification.Builder;"/>
        <method signature="setTimeout(J)Landroid.app.Notification.Builder;"/>
    </class>
    <class name="android.speech.tts.UtteranceProgressListener">
        <method signature="onUtteranceRangeStart(Ljava.lang.String;II)V"/>
    </class>
    <class name="android.media.AudioFormat">
        <method signature="<init>()V"/>
    </class>
    <class name="android.hardware.HardwareBuffer">
        <method signature="destroy()V"/>
        <method signature="isDestroyed()Z"/>
    </class>
    <class name="android.os.TestLooperManager">
        <method signature="getQueue()Landroid.os.MessageQueue;"/>
    </class>
    <class name="android.test.mock.MockContext">
        <method signature="getSharedPreferences(Ljava.io.File;I)Landroid.content.SharedPreferences;"/>
        <method signature="getSharedPreferencesPath(Ljava.lang.String;)Ljava.io.File;"/>
    </class>
    <class name="android.media.tv.TvInputManager.Hardware">
        <method signature="dispatchKeyEventToHdmi(Landroid.view.KeyEvent;)Z"/>
    </class>
    <class name="android.content.ClipData">
        <method signature="addItem(Landroid.content.ClipData.Item;Landroid.content.ContentResolver;)V"/>
    </class>
    <class name="android.os.StrictMode.VmPolicy.Builder">
        <method signature="penaltyListener(Landroid.os.StrictMode.OnVmViolationListener;Ljava.util.concurrent.Executor;)Landroid.os.StrictMode.VmPolicy.Builder;"/>
    </class>
    <class name="android.app.Notification.TvExtender">
        <method signature="getChannel()Ljava.lang.String;"/>
    </class>
    <class name="android.app.usage.StorageStatsManager">
        <method signature="isQuotaSupported(Ljava.lang.String;)Z"/>
        <method signature="getTotalBytes(Ljava.lang.String;)J"/>
        <method signature="getFreeBytes(Ljava.lang.String;)J"/>
        <method signature="queryStatsForPackage(Ljava.lang.String;Ljava.lang.String;Landroid.os.UserHandle;)Landroid.app.usage.StorageStats;"/>
        <method signature="queryStatsForUid(Ljava.lang.String;I)Landroid.app.usage.StorageStats;"/>
        <method signature="queryStatsForUser(Ljava.lang.String;Landroid.os.UserHandle;)Landroid.app.usage.StorageStats;"/>
        <method signature="queryExternalStatsForUser(Ljava.lang.String;Landroid.os.UserHandle;)Landroid.app.usage.ExternalStorageStats;"/>
    </class>
    <class name="android.os.StrictMode.ThreadPolicy.Builder">
        <method signature="penaltyListener(Landroid.os.StrictMode.OnThreadViolationListener;Ljava.util.concurrent.Executor;)Landroid.os.StrictMode.ThreadPolicy.Builder;"/>
    </class>
    <class name="android.hardware.SensorDirectChannel">
        <method signature="isValid()Z"/>
    </class>
    <class name="android.app.Notification">
        <method signature="getChannel()Ljava.lang.String;"/>
        <method signature="getTimeout()J"/>
    </class>
    <class name="android.app.usage.StorageStats">
        <method signature="getCodeBytes()J"/>
    </class>
    <class name="android.app.RecoverableSecurityException">
        <method signature="showAsNotification(Landroid.content.Context;)V"/>
    </class>
    <class name="android.content.ContextWrapper">
        <method signature="getSharedPreferences(Ljava.io.File;I)Landroid.content.SharedPreferences;"/>
        <method signature="getSharedPreferencesPath(Ljava.lang.String;)Ljava.io.File;"/>
    </class>
    <class name="android.app.Activity">
        <method signature="enterPictureInPictureMode(Landroid.app.PictureInPictureArgs;)Z"/>
        <method signature="setPictureInPictureArgs(Landroid.app.PictureInPictureArgs;)V"/>
    </class>
</removed>


text:
#ifndef __CTSTRINGATTRIBUTES__
#define __CTSTRINGATTRIBUTES__

#include <CoreText/CTDefines.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFString.h>
#include <CoreGraphics/CGColor.h>

#if defined(__cplusplus)
extern "C" {
#endif

/* The purpose of this file is to define all the attributes to which
    CoreText will respond when placed in a CFAttributedString. These
    are left out of other header file on purpose in order to avoid
    layering problems. This file is allowed to include any other header
    file it wants to. */

/* --------------------------------------------------------------------------- */
/* CFAttributedStringRef Attribute Prototypes */
/* --------------------------------------------------------------------------- */

/*!
    @const      kCTFontAttributeName
    @abstract   The font.

    @discussion Value must be a CTFontRef. Default is Helvetica 12.
*/

extern const CFStringRef kCTFontAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTForegroundColorFromContextAttributeName
    @abstract   Never set a foreground color in the CGContext; use what is set as
                the context's fill color.

    @discussion Value must be a CFBooleanRef. Default is false. The reason
                why this exists is because an NSAttributedString defaults to a
                black color if no color attribute is set. This forces CoreText to
                set the color in the context. This will allow developers to
                sidestep this, making CoreText set nothing but font information
                in the CGContext. If set, this attribute also determines the
                color used by kCTUnderlineStyleAttributeName, in which case it
                overrides the foreground color.
*/

extern const CFStringRef kCTForegroundColorFromContextAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTKernAttributeName
    @abstract   A kerning adjustment.

    @discussion Value must be a CFNumberRef float. Default is standard kerning.
                The kerning attribute indicate how many points the following
                character should be shifted from its default offset as defined
                by the current character's font in points; a positive kern
                indicates a shift farther along and a negative kern indicates a
                shift closer to the current character. If this attribute is not
                present, standard kerning will be used. If this attribute is
                set to 0.0, no kerning will be done at all.
*/

extern const CFStringRef kCTKernAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTLigatureAttributeName
    @abstract   Controls ligature formation.

    @discussion Value must be a CFNumberRef. Default is int value 1. The ligature
                attribute determines what kinds of ligatures should be used when
                displaying the string. A value of 0 indicates that only ligatures
                essential for proper rendering of text should be used, 1
                indicates that standard ligatures should be used, and 2 indicates
                that all available ligatures should be used. Which ligatures are
                standard depends on the script and possibly the font. Arabic
                text, for example, requires ligatures for many character
                sequences, but has a rich set of additional ligatures that
                combine characters. English text has no essential ligatures, and
                typically has only two standard ligatures, those for "fi" and
                "fl" -- all others being considered more advanced or fancy.

                On iOS releases prior to 6.0 essential ligatures are applied
                if the font contains glyphs for any of U+FB00 through U+FB04 and
                the font lacks AAT or OpenType shaping tables, but as of 6.0
                shaping tables (or the lack thereof) are treated as definitive.
*/

extern const CFStringRef kCTLigatureAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTForegroundColorAttributeName
    @abstract   The foreground color.

    @discussion Value must be a CGColorRef. Default value is black.
*/

extern const CFStringRef kCTForegroundColorAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTParagraphStyleAttributeName
    @abstract   A CTParagraphStyle object which is used to specify things like
                line alignment, tab rulers, writing direction, etc.

    @discussion Value must be a CTParagraphStyleRef. Default is an empty
                CTParagraphStyle object. See CTParagraphStyle.h for more
                information.
*/

extern const CFStringRef kCTParagraphStyleAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTStrokeWidthAttributeName
    @abstract   The stroke width.

    @discussion Value must be a CFNumberRef. Default value is 0.0, or no stroke.
                This attribute, interpreted as a percentage of font point size,
                controls the text drawing mode: positive values effect drawing
                with stroke only; negative values are for stroke and fill. A
                typical value for outlined text is 3.0.
*/

extern const CFStringRef kCTStrokeWidthAttributeName CT_AVAILABLE(10_6, 3_2);

/*!
    @const      kCTStrokeColorAttributeName
    @abstract   The stroke color.

    @discussion Value must be a CGColorRef. Default is the foreground color.
*/

extern const CFStringRef kCTStrokeColorAttributeName CT_AVAILABLE(10_6, 3_2);

/*!
    @const      kCTUnderlineStyleAttributeName
    @abstract   Allows the setting of an underline to be applied at render
                time.

    @discussion Value must be a CFNumberRef. Default is kCTUnderlineStyleNone.
                Set a value of something other than kCTUnderlineStyleNone to draw
                an underline. In addition, the CTUnderlineStyleModifiers can be
                used to modify the look of the underline. The underline color
                will be determined by the text's foreground color.
*/

extern const CFStringRef kCTUnderlineStyleAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTSuperscriptAttributeName
    @abstract   Controls vertical text positioning.

    @discussion Value must be a CFNumberRef. Default is int value 0. If supported
                by the specified font, a value of 1 enables superscripting and a
                value of -1 enables subscripting.
*/

extern const CFStringRef kCTSuperscriptAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTUnderlineColorAttributeName
    @abstract   The underline color.

    @discussion Value must be a CGColorRef. Default is the foreground color.
*/

extern const CFStringRef kCTUnderlineColorAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTVerticalFormsAttributeName
    @abstract   Controls glyph orientation.

    @discussion Value must be a CFBooleanRef. Default is false. A value of false
                indicates that horizontal glyph forms are to be used, true
                indicates that vertical glyph forms are to be used.
*/

extern const CFStringRef kCTVerticalFormsAttributeName CT_AVAILABLE(10_5, 4_3);

/*!
    @const      kCTGlyphInfoAttributeName
    @abstract   Allows the use of unencoded glyphs.

    @discussion Value must be a CTGlyphInfoRef. The glyph specified by this
                CTGlyphInfo object is assigned to the entire attribute range,
                provided that its contents match the specified base string and
                that the specified glyph is available in the font specified by
                kCTFontAttributeName. See CTGlyphInfo.h for more information.
*/

extern const CFStringRef kCTGlyphInfoAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTCharacterShapeAttributeName
    @abstract   Controls glyph selection.

    @discussion Value must be a CFNumberRef. Default is value is 0 (disabled).
                A non-zero value is interpreted as an SFNT kCharacterShapeType
                selector + 1; see SFNTLayoutTypes.h for selectors. For example,
                an attribute value of 1 corresponds to kTraditionalCharactersSelector.
*/

extern const CFStringRef kCTCharacterShapeAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @const      kCTLanguageAttributeName
    @abstract   Specifies text language.

    @discussion Value must be a CFStringRef containing a locale identifier. Default
                is unset. When this attribute is set to a valid identifier, it will
                be used to select localized glyphs (if supported by the font) and
                locale-specific line breaking rules.
*/

extern const CFStringRef kCTLanguageAttributeName CT_AVAILABLE(10_9, 7_0);

/*!
    @const      kCTRunDelegateAttributeName
    @abstract   Allows customization of certain aspects of a range of text's
                appearance.

    @discussion Value must be a CTRunDelegateRef. The values returned by the
                embedded object for an attribute range apply to each glyph
                resulting from the text in that range. Because an embedded object
                is only a display-time modification, care should be taken to
                avoid applying this attribute to a range of text with complex
                behavior, such as a change of writing direction, combining marks,
                etc. Consequently, it is recommended that this attribute be
                applied to a range containing the single character U+FFFC. See
                CTRunDelegate.h for more information.
*/

extern const CFStringRef kCTRunDelegateAttributeName CT_AVAILABLE(10_5, 3_2);

/*!
    @enum       CTUnderlineStyle
    @abstract   Underline style specifiers.

    @discussion These underline type specifiers can be applied to the value set
                with the kCTUnderlineStyleAttributeName attribute to tell
                CoreText that you want a different underline style.
*/

typedef CF_OPTIONS(int32_t, CTUnderlineStyle) {
    kCTUnderlineStyleNone           = 0x00,
    kCTUnderlineStyleSingle         = 0x01,
    kCTUnderlineStyleThick          = 0x02,
    kCTUnderlineStyleDouble         = 0x09
};

/*!
    @enum       CTUnderlineStyleModifiers
    @abstract   Underline style modifiers.

    @discussion Set these bits with the CTUnderlineStyle that you set with the
                kCTUnderlineStyleAttributeName attribute to modify how the
                underline will be drawn.
*/

typedef CF_OPTIONS(int32_t, CTUnderlineStyleModifiers) {
    kCTUnderlinePatternSolid        = 0x0000,
    kCTUnderlinePatternDot          = 0x0100,
    kCTUnderlinePatternDash         = 0x0200,
    kCTUnderlinePatternDashDot      = 0x0300,
    kCTUnderlinePatternDashDotDot   = 0x0400
};

/*!
    @const      kCTBaselineClassAttributeName
    @abstract   Key to reference a baseline class override.

    @discussion Value must be one of the kCTBaselineClass constants. Normally,
                glyphs on the line will be assigned baseline classes according to
                the 'bsln' or 'BASE' table in the font. This attribute may be
                used to change this assignment.

    @seealso    kCTBaselineClassRoman
    @seealso    kCTBaselineClassIdeographicCentered
    @seealso    kCTBaselineClassIdeographicLow
    @seealso    kCTBaselineClassIdeographicHigh
    @seealso    kCTBaselineClassHanging
    @seealso    kCTBaselineClassMath
*/

extern const CFStringRef kCTBaselineClassAttributeName CT_AVAILABLE(10_8, 6_0);

/*!
    @const      kCTBaselineInfoAttributeName
    @abstract   Key to reference a baseline info dictionary.

    @discussion Value must be a CFDictionaryRef. Normally, baseline offsets will
                be assigned based on the 'bsln' or 'BASE' table in the font. This
                attribute may be used to assign different offsets. Each key in
                the dictionary is one of the kCTBaselineClass constants and the
                value is a CFNumberRef of the baseline offset in points. You only
                need to specify the offsets you wish to change.

    @seealso    kCTBaselineClassRoman
    @seealso    kCTBaselineClassIdeographicCentered
    @seealso    kCTBaselineClassIdeographicLow
    @seealso    kCTBaselineClassIdeographicHigh
    @seealso    kCTBaselineClassHanging
    @seealso    kCTBaselineClassMath
*/

extern const CFStringRef kCTBaselineInfoAttributeName CT_AVAILABLE(10_8, 6_0);

/*!
    @const      kCTBaselineReferenceInfoAttributeName
    @abstract   Key to reference a baseline info dictionary for the reference baseline.

    @discussion Value must be a CFDictionaryRef. All glyphs in a run are assigned
                a baseline class and then aligned to the offset for that class in
                the reference baseline baseline info. See the discussion of
                kCTBaselineInfoAttributeName for information about the contents
                of the dictionary. You can also use the kCTBaselineReferenceFont
                key to specify that the baseline offsets of a particular
                CTFontRef should be used as the reference offsets.

    @seealso    kCTBaselineClassRoman
    @seealso    kCTBaselineClassIdeographicCentered
    @seealso    kCTBaselineClassIdeographicLow
    @seealso    kCTBaselineClassIdeographicHigh
    @seealso    kCTBaselineClassHanging
    @seealso    kCTBaselineClassMath
    @seealso    kCTBaselineReferenceFont
*/

extern const CFStringRef kCTBaselineReferenceInfoAttributeName CT_AVAILABLE(10_8, 6_0);

/*!
    @const      kCTWritingDirectionAttributeName
    @abstract   Specifies a bidirectional override or embedding.

    @discussion Value must be a CFArray of CFNumberRefs, each of which should
                have a value of either kCTWritingDirectionLeftToRight or
                kCTWritingDirectionRightToLeft, plus one of
                kCTWritingDirectionEmbedding or kCTWritingDirectionOverride.
                This array represents a sequence of nested bidirectional
                embeddings or overrides, in order from outermost to innermost,
                with (kCTWritingDirectionLeftToRight | kCTWritingDirectionEmbedding)
                corresponding to a LRE/PDF pair in plain text or
                 in HTML, (kCTWritingDirectionRightToLeft
                | kCTWritingDirectionEmbedding) corresponding to a RLE/PDF
                pair in plain text or a  in HTML,
                (kCTWritingDirectionLeftToRight | kCTWritingDirectionOverride)
                corresponding to a LRO/PDF pair in plain text or
                <bdo dir="ltr"> in HTML, and (kCTWritingDirectionRightToLeft
                | kCTWritingDirectionOverride) corresponding to a RLO/PDF
                pair in plain text or <bdo dir="rtl"> in HTML.

    @seealso    kCTWritingDirectionLeftToRight
    @seealso    kCTWritingDirectionRightToLeft
    @seealso    kCTWritingDirectionEmbedding
    @seealso    kCTWritingDirectionOverride
*/

extern const CFStringRef kCTWritingDirectionAttributeName CT_AVAILABLE(10_8, 6_0);

/*!
    @abstract   Additional values for use with kCTWritingDirectionAttributeName
                in combination with kCTWritingDirectionLeftToRight or
                kCTWritingDirectionRightToLeft.

    @seealso    kCTWritingDirectionAttributeName
    @seealso    kCTWritingDirectionLeftToRight
    @seealso    kCTWritingDirectionRightToLeft
*/

enum {
    kCTWritingDirectionEmbedding = (0 << 1),
    kCTWritingDirectionOverride = (1 << 1)
};

/*!
    @const      kCTRubyAnnotationAttributeName
    @abstract   Key to reference a CTRubyAnnotation.

    @discussion Value must be a CTRubyAnnotationRef. See CTRubyAnnotation.h for
                more information.
 */

extern const CFStringRef kCTRubyAnnotationAttributeName CT_AVAILABLE(10_10, 8_0);

#if defined(__cplusplus)
}
#endif

#endif


text:
package org.apache.http.client.methods;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.http.HttpRequest;
import org.apache.http.client.utils.CloneUtilsHC4;
import org.apache.http.concurrent.Cancellable;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.message.AbstractHttpMessage;

@SuppressWarnings("deprecation")
public abstract class AbstractExecutionAwareRequest extends AbstractHttpMessage implements
        HttpExecutionAware, AbortableHttpRequest, Cloneable, HttpRequest {

    private final AtomicBoolean aborted;
    private final AtomicReference<Cancellable> cancellableRef;

    protected AbstractExecutionAwareRequest() {
        super();
        this.aborted = new AtomicBoolean(false);
        this.cancellableRef = new AtomicReference<Cancellable>(null);
    }

    @Deprecated
    public void setConnectionRequest(final ClientConnectionRequest connRequest) {
        setCancellable(new Cancellable() {

            public boolean cancel() {
                connRequest.abortRequest();
                return true;
            }

        });
    }

    @Deprecated
    public void setReleaseTrigger(final ConnectionReleaseTrigger releaseTrigger) {
        setCancellable(new Cancellable() {

            public boolean cancel() {
                try {
                    releaseTrigger.abortConnection();
                    return true;
                } catch (final IOException ex) {
                    return false;
                }
            }

        });
    }

    public void abort() {
        if (this.aborted.compareAndSet(false, true)) {
            final Cancellable cancellable = this.cancellableRef.getAndSet(null);
            if (cancellable != null) {
                cancellable.cancel();
            }
        }
    }

    public boolean isAborted() {
        return this.aborted.get();
    }

    /**
     * @since 4.2
     */
    public void setCancellable(final Cancellable cancellable) {
        if (!this.aborted.get()) {
            this.cancellableRef.set(cancellable);
        }
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        final AbstractExecutionAwareRequest clone = (AbstractExecutionAwareRequest) super.clone();
        clone.headergroup = CloneUtilsHC4.cloneObject(this.headergroup);
        clone.params = CloneUtilsHC4.cloneObject(this.params);
        return clone;
    }

    /**
     * @since 4.2
     */
    public void completed() {
        this.cancellableRef.set(null);
    }

    /**
     * Resets internal state of the request making it reusable.
     *
     * @since 4.2
     */
    public void reset() {
        final Cancellable cancellable = this.cancellableRef.getAndSet(null);
        if (cancellable != null) {
            cancellable.cancel();
        }
        this.aborted.set(false);
    }

}


text:
## Building ##

Serverwiz uses an ant build script.

To start a build:

    cd <repodir>
    ant -f build.xml clean compile jar

The jars are built in the ./build directory.

The OS specific jar can be ran directly.  In order to do this, there
must be a ./xml directory from where java is executed that contains
the library files.  So if you are in the repository directory, you
can run:

	java -jar build/serverwiz2_[OS].jar

where OS is linux64, macosx64, win32, or win64.

Important: The first time Serverwiz is ran, it will ask you for your
local git repository location.  It will look for common-mrw-xml repository
in that directory.  If it does not exist, it will clone the repository from:

	https://github.com/open-power/common-mrw-xml.git

This is the XML based library that contains attribute and target
definitions.   The library can be updated to latest by using
"Manage Library" button.

## Update mode in serverwiz ##
There is an update mode in the Serverwiz tool. It is used to update an MRW XML
with new attributes and target XMLs. This mode does not load the GUI. It only
takes the attributes, targets and parts XMLs. Opens the input MRW file, updates
it and saves it to output file.
In order to do this, there must be a ./xml directory from where java is executed
that contains the library files.  So if you are in the repository directory, you
can run:

	java -jar build/serverwiz2_[OS].jar -u -i <input MRW file name>
		-o <output MRW file name>

In update mode, it always looks for common-mrw-xml repository in the current
directory. If it does not exist, it will clone the repository from:

	https://github.com/open-power/common-mrw-xml.git

If additional libraries need to be added, then add repository details to the
serverwiz.preference file.

## Precompiled jars ##

There are precompiled binaries at:

	https://github.com/open-power/serverwiz/releases

Download serverwiz2.jar which is the main launcher application.  This
application checks the OS and downloads the proper OS specific jar from
the latest github release.  It will not use the jar that was built locally
unless using the -d flag is used.

To run:

	java -jar serverwiz2.jar


text:
#import <Foundation/Foundation.h>

# import <Parse/PFConstants.h>

typedef uint8_t PFLoggingTag;

@interface PFLogger : NSObject

@property (atomic, assign) PFLogLevel logLevel;

///--------------------------------------
/// @name Shared Logger
///--------------------------------------

/*!
A shared instance of `PFLogger` that should be used for all logging.

@returns An shared singleton instance of `PFLogger`.
*/
+ (instancetype)sharedLogger;

///--------------------------------------
/// @name Logging Messages
///--------------------------------------

/*!
 Logs a message at a specific level for a tag.
 If current logging level doesn't include this level - this method does nothing.

 @param level  Logging Level
 @param tag    Logging Tag
 @param format Format to use for the log message.
 */
- (void)logMessageWithLevel:(PFLogLevel)level
                        tag:(PFLoggingTag)tag
                     format:(NSString *)format, ... NS_FORMAT_FUNCTION(3, 4);

@end


text:
package com.ilya.sergeev.potlach.client;

import com.google.common.base.Objects;

public class UserInfo
{
	private long id;

	private String name;
	private String password;

	private int rating = 0;

	public UserInfo()
	{

	}

	public UserInfo(String name, String password)
	{
		this.name = name;
		this.password = password;
	}

	public long getId()
	{
		return id;
	}

	public void setId(long id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	@Override
	public int hashCode()
	{
		return Objects.hashCode(getName());
	}

	@Override
	public boolean equals(Object obj)
	{
		return (obj instanceof UserInfo) && Objects.equal(getName(), ((UserInfo) obj).getName());
	}

	public int getRating()
	{
		return rating;
	}

	public void setRating(int rating)
	{
		this.rating = rating;
	}
}


text:
This project aims at hosting tutorials, examples, discussions, research proposals, and other resources related to [fuzzing](https://en.wikipedia.org/wiki/Fuzzing).

External contributions are welcome, please
see [CONTRIBUTING](CONTRIBUTING) file for more info.

# Documentation

* [Why fuzz?](https://github.com/google/fuzzing/blob/master/docs/why-fuzz.md)
* [Introduction to fuzzing](https://github.com/google/fuzzing/blob/master/docs/intro-to-fuzzing.md)
* [What makes a good fuzz target](https://github.com/google/fuzzing/blob/master/docs/good-fuzz-target.md)
* [How to split a fuzzer-generated input into parts](https://github.com/google/fuzzing/blob/master/docs/split-inputs.md)
* [How to write structure-aware fuzzers with libFuzzer](https://github.com/google/fuzzing/blob/master/docs/structure-aware-fuzzing.md)
* [How to build fuzz targets](https://github.com/google/fuzzing/blob/master/docs/building-fuzz-targets.md)
* [Overview of AFL based fuzzers](https://github.com/google/fuzzing/blob/master/docs/afl-based-fuzzers-overview.md)
* [Fuzzing glossary](https://github.com/google/fuzzing/blob/master/docs/glossary.md)

# Related projects

* [OSS-Fuzz](https://github.com/google/oss-fuzz) - Continuous Fuzzing Service for Open Source Software
* [ClusterFuzz](https://github.com/google/clusterfuzz) - Scalable Fuzzing Infrastructure
* [FuzzBench](https://github.com/google/fuzzbench) - Fuzzer benchmarking as a service

# Disclaimer

This is not an official Google product.


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Interactable : MonoBehaviour {

    [HideInInspector]
    public Vector3 initialPosition;

    private void Start() {
        InputManager.ButtonClickDownDelegate += OnInteractionStart;
        InputManager.ButtonClickHoldDelegate += OnInteractionHold;
        InputManager.ButtonClickUpDelegate += OnInteractionEnd;

        initialPosition = transform.position;
        OnStart();
    }
    public virtual void OnStart(){}

    public abstract void OnInteractionStart(Vector3 position);
    public abstract void OnInteractionHold(Vector3 position);
    public abstract void OnInteractionEnd(Vector3 position);

    private void OnDestroy() {
        InputManager.ButtonClickDownDelegate -= OnInteractionStart;
        InputManager.ButtonClickHoldDelegate -= OnInteractionHold;
        InputManager.ButtonClickUpDelegate -= OnInteractionEnd;
    }

    protected Vector2 ScreenToWorldTouch(Vector3 position) {
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(position);
        return worldPos;
    }
}


text:
"""Model fields definition.
"""

__all__ = [
    'Field',
    'ForeignKeyField',
    'Expression',
    'ExpressionSet',
    'Ordering'
]

from d2om.exception import NoDataException
from d2om.config.model import OpCode, ExprConnector
#from d2om.config import DEBUG_MODE

OP_SEPARATOR = '__'

class FieldDescriptor(object):

    """FieldDescriptor class to store field's value (data container)."""

    def __init__(self, field):
        """
        Initialization.

        @param field: Field object.
        @param type: Field
        """
        self.field = field

    def __get__(self, instance, owner=None):
        """
        Get the attribute of the owner class or of an instance of that class.

        @param instance: Model object.
        @type instance: Model
        @param owner: Type of the Model object.
        @type owner: type
        @return: Field or its corresponding value.
        @rtype: Field/Field._column._py_type
        """
        if not instance:
            return self.field
        return instance._data.get(self.field.name)

    def __set__(self, instance, value):
        """
        Set the attribute of an instance of the owner class to a new value.

        @param instance: Model object.
        @type instance: Model
        @param value: Field's value.
        @type value: Field._column._py_type
        """
        instance._data[self.field.name] = self.field.py_value(value)

class RelatedObjectDescriptor(object):

    """RelatedObjectDescriptor class to store relations with other Models."""

    def __init__(self, field):
        """
        Initialization.

        @param field: Field object.
        @param type: Field
        """
        self.field = field

    def __get__(self, instance, owner=None):
        """
        Get the attribute of the owner class or of an instance of that class.

        @param instance: Model object.
        @type instance: Model
        @param owner: Type of the Model object.
        @type owner: type
        @return: Own Field or related object (Model object).
        @rtype: Field/Model
        @raise NoDataException: Exception if related object is not found.
        """
        if not instance:
            return self.field

        if not instance._data.get(self.field.related_name):
            related_object_id = instance._data.get(self.field.name)
            if related_object_id:
                try:
                    related_instance = self.field.related_field.model.get(
                        **{self.field.related_field.name: related_object_id})
                except NoDataException:
                    if not self.field.nullable:
                        raise
                else:
                    instance._data[self.field.related_name] = related_instance

        return instance._data.get(self.field.related_name)

    def __set__(self, instance, value):
        """
        Set the attribute on an instance of the owner class to a new value.

        @param instance: Model object.
        @type instance: Model
        @param value: Related object.
        @type value: Model/None
        """
        if value is None and self.field.nullable:
            instance._data.update({
                self.field.name: None,
                self.field.related_name: None})
        elif isinstance(value, self.field.related_field.model):
            instance._data.update({
                self.field.name: getattr(value, self.field.related_field.name),
                self.field.related_name: value})

class ReverseRelatedObjectDescriptor(object):

    """ReverseRelatedObjectDescriptor class to store reverse relations."""

    def __init__(self, field):
        """
        Initialization.

        @param field: Field object.
        @param type: Field
        """
        self.field = field

    def __get__(self, instance, owner=None):
        """
        Get the attribute of the owner class or of an instance of that class.

        @param instance: Model object.
        @type instance: Model
        @param owner: Type of the Model object.
        @type owner: type
        @return: Set of objects that are related with current one.
        @rtype: QueryResult
        @raise AttributeError: Exception if instance is not defined.
        """
        if not instance:
            raise AttributeError('[ReverseRelatedObjectDescriptor.__get__] '+
                                 'Accessible only via instances of the class')
        return self.field.model.select().filter(**{
            self.field.name: getattr(instance, self.field.related_field.name)
            }).all()

def set_expression(op):
    def inner(self, rhs):
        """Set up Expression object for the Field object."""
        if op not in OpCode.values:
            raise ValueError('Incorrect operation value for Expression')
        return Expression(self, op, rhs)
    return inner

def set_expressionset(connector):
    def inner(self, rhs):
        """Set up ExpressionSet object."""
        return ExpressionSet(connector, self, rhs)
    return inner

class Field(object):

    """Field class to describe Model attribute."""

    _field_counter = 0
    _order = 0

    def __init__(self, column_name, column_type=None, **kwargs):
        """
        Initialization.

        @param column_name: Name of the corresponding column.
        @type column_name: str
        @param column_type: Database column type.
        @type column_type: ColumnType
        @param kwargs: Column parameters (attributes).
        @type kwargs: dict
        """
        self.column_name = column_name.lower()

        self._column = None
        if isinstance(column_type, type):
            self._column = column_type(**kwargs)

        self._primary = False
        self._nullable = False
        self._default = None
        self._alias = None

        Field._field_counter += 1
        self._order = Field._field_counter

    def _add_to_class(self, model, attr_name):
        """
        Assign a Field instance to class Model with corrsponding name.

        @param model: Model class.
        @type model: type
        @param attr_name: Attribute name that corresponds to Field instance.
        @type attr_name: str
        """
        self.model = model
        self.name = attr_name
        setattr(self.model, self.name, FieldDescriptor(self))

    def primary(self, primary=True):
        """
        Set up flag "primary".

        @param primary: Flag for "primary key" field.
        @type primary: bool
        @return: Self instance.
        @rtype: Field
        """
        if self._nullable and primary:
            raise ValueError('[Field.primary] Primary key cannot be nullable')
        self._primary = bool(primary)
        return self

    def nullable(self, nullable=True):
        """
        Set up flag "nullable".

        @param nullable: Flag shows that field can have NULL value.
        @type nullable: bool
        @return: Self instance.
        @rtype: Field
        """
        if nullable and self._primary:
            raise ValueError('[Field.nullable] Primary key cannot be nullable')
        self._nullable = bool(nullable)
        return self

    def default(self, value):
        """
        Set up default value.

        @param value: Default value.
        @type value: any
        @return: Self instance.
        @rtype: Field
        """
        self._default = value
        return self

    def alias(self, alias):
        """
        Set up field alias.

        @param alias: Field alias.
        @type alias: str
        @return: Self instance.
        @rtype: Field
        """
        self._alias = alias
        return self

    __eq__ = set_expression(OpCode.EQ)
    __ne__ = set_expression(OpCode.NE)
    __lt__ = set_expression(OpCode.LT)
    __le__ = set_expression(OpCode.LE)
    __gt__ = set_expression(OpCode.GT)
    __ge__ = set_expression(OpCode.GE)
    __lshift__ = set_expression(OpCode.IN)
    __rshift__ = set_expression(OpCode.ISNULL)
    __mul__ = set_expression(OpCode.CONTAINS)
    __pow__ = set_expression(OpCode.ICONTAINS)
    __xor__ = set_expression(OpCode.ISTARTSWITH)

    def db_value(self, value):
        """
        Get correct value to store to database.

        @param value: Input value
        @type value: any
        @return: Converted value.
        @rtype: self._column.db_value(value)
        @raise ValueError: Column type is not defined.
        """
        if not self._column:
            raise ValueError('[Field.db_value] Column object is not defined')
        return self._column.db_value(value)

    def py_value(self, value):
        """
        Get correct value to operate in application.

        @param value: Input value
        @type value: any
        @return: Converted value.
        @rtype: self._column.py_value(value)
        @raise ValueError: Column type is not defined.
        """
        if not self._column:
            raise ValueError('[Field.py_value] Column object is not defined')
        return self._column.py_value(value)

    def asc(self):
        """
        Get instance of Ordering class (ASC).

        @return: Instance of Ordering class.
        @rtype: Ordering
        """
        return Ordering(self, True)

    def desc(self):
        """
        Get instance of Ordering class (DESC).

        @return: Instance of Ordering class.
        @rtype: Ordering
        """
        return Ordering(self, False)

class ForeignKeyField(Field):

    """ForeignKeyField class to describe Model FK attribute."""

    def __init__(self, column_name, related_field):
        """
        Initialization.

        @param column_name: Name of the corresponding column.
        @type column_name: str
        @param related_field: Corresponding field from connected Model.
        @type related_field: Field
        """
        super(ForeignKeyField, self).__init__(column_name)
        self._column = related_field._column

        self.related_field = related_field
        self.related_name = None
        self.reverse_related_name = None

    def _add_to_class(self, model, attr_name):
        """
        Assign a Field instance to class Model with corrsponding name.

        @param model: Model class.
        @type model: type
        @param attr_name: Attribute name that corresponds to Field object.
        @type attr_name: str
        """
        super(ForeignKeyField, self)._add_to_class(model, attr_name)

        if not self.related_name:
            self.related_name = self.related_field.model._meta.name.lower()
        if not self.reverse_related_name:
            self.reverse_related_name = '%s_set' % self.model._meta.name.lower()

        self.model._meta.relations.update({
            self.name: self.related_field.model})
        self.related_field.model._meta.reverse_relations.update({
            self.reverse_related_name: self.model})

        setattr(self.model, self.related_name, RelatedObjectDescriptor(self))
        setattr(self.related_field.model, self.reverse_related_name,
                ReverseRelatedObjectDescriptor(self))

    def with_related_name(self, name):
        """
        Set related name.

        @param name: Name that corresponds to related field.
        @type name: str
        @return: Self instance.
        @rtype: ForeignKeyField
        """
        self.related_name = name
        return self

    def with_reverse_related_name(self, name):
        """
        Set reverse related name.

        @param name: Related name for connected Model.
        @type name: str
        @return: Self instance.
        @rtype: ForeignKeyField
        """
        self.reverse_related_name = name
        return self

class Ordering(object):

    """Ordering class to represent direction of sorting."""

    def __init__(self, field, asc=True):
        """
        Initialization.

        @param field: Field object.
        @type field: Field
        @param asc: Flag to define direction of sorting (asc-True, desc-False).
        @type asc: bool
        """
        self.field = field
        self.asc = asc

    def to_string(self):
        """
        Get corresponding string.

        @return: SQL string.
        @rtype: str
        """
        if hasattr(self.field, 'model'):
            if self.asc:
                return self.field.model._meta.database.order_type.Asc
            return self.field.model._meta.database.order_type.Desc
        return ''

class BaseExpression(object):

    """BaseExpression class for SQL conditions representation."""

    def __init__(self, negated=False):
        """
        Initialization.

        @param negated: Negation for expression or expression set.
        @type negated: bool
        """
        self.negated = negated
        self._models_set = set()

    def __invert__(self):
        """
        Set attribute "negated" to opposite (equal to "~obj").

        @return: Self instance.
        @rtype: BaseExpression
        """
        self.negated = not self.negated
        return self

    def __and__(self, rhs):
        """
        The bitwise AND of self-instance and other BaseExpression.

        @param rhs: Any of BaseExpression objects.
        @type rhs: BaseExpression/Expression/ExpressionSet
        @return: ExpressionSet object (sub-class of BaseExpression).
        @rtype: ExpressionSet
        """
        return ExpressionSet(ExprConnector.AND, self, rhs)

    def __or__(self, rhs):
        """
        The bitwise OR of self-instance and other BaseExpression.

        @param rhs: Any of BaseExpression objects.
        @type rhs: BaseExpression/Expression/ExpressionSet
        @return: ExpressionSet object (sub-class of BaseExpression).
        @rtype: ExpressionSet
        """
        return ExpressionSet(ExprConnector.OR, self, rhs)

    def get_models(self):
        """
        Get utilized models.

        @return: Set of models.
        @rtype: set
        """
        return self._models_set

    def set_models(self, *args):
        """
        Add new models.

        @param args: List of models.
        @type args: list
        """
        self._models_set.update(args)

    def clone(self):
        """
        Clone instance (create a copy of instance).

        @raise NotImplementedError: Will be overridden.
        """
        raise NotImplementedError

class Expression(BaseExpression):

    """Expression class represent SQL condition for defined field."""

    _op_separator = OP_SEPARATOR

    def __init__(self, field, op, value, negated=False):
        """
        Initialization.

        @param field: Field object.
        @type field: Field
        @param op: Condition operation.
        @type op: str
        @param value: Condition value
        @type value: any
        @param negated: Negation for expression or expression set.
        @type negated: bool
        """
        super(Expression, self).__init__(negated=negated)
        self.field = field
        self.op = op
        self.value = value
        self.set_models(field.model)

    @classmethod
    def convert(cls, _model, **kwargs):
        """
        Convert key-value pairs into list of Expression objects.

        @param _model: Model class or object.
        @type _model: type/Model
        @param kwargs: Key-value pairs (dictionary of conditions).
        @type kwargs: dict
        @return: List of Expression objects.
        @rtype: list
        """
        expressions = []
        for name, value in kwargs.iteritems():

            items = name.rsplit(cls._op_separator, 1)
            if items[1:] and items[1] in OpCode.values:
                name, op = items
            else:
                op = OpCode.EQ

            field = _model.get_field(name)
            if not field:
                continue

            if op in [OpCode.ISNULL, OpCode.ISNOTNULL]:
                if not value and op == OpCode.ISNULL:
                    op = OpCode.ISNOTNULL
                elif not value:
                    op = OpCode.ISNULL
                value = None
            elif op in [OpCode.IS, OpCode.EQ] and value is None:
                op = OpCode.ISNULL
            elif op == OpCode.IS and value is not None:
                raise ValueError('[Expression.convert] ' +
                                 '__is lookups only accept None')

            expressions.append(cls(field, op, value))
        return expressions

    def clone(self):
        """
        Clone instance (create a copy of instance).

        @return: New object of Expression class.
        @rtype: Expression
        """
        return Expression(self.field, self.op, self.value, self.negated)

class ExpressionSet(BaseExpression):

    """ExpressionSet class represents a set of Expression instances."""

    def __init__(self, connector, *args):
        """
        Initialization.

        @param connector: ExprConnector value (and/or).
        @type connector:str
        @param args: Objects of BaseExpression/Expression/ExpressionSet.
        @type args: list
        """
        super(ExpressionSet, self).__init__()
        self.connector = connector
        self.children = []
        for a in args:
            if (isinstance(a, ExpressionSet)
                and self.connector == a.connector and not a.negated):
                self.children.extend(a.children)
            elif isinstance(a, BaseExpression):
                self.children.append(a)
            self.set_models(*a.get_models())

    def clone(self):
        """
        Clone instance (create a copy of instance).

        @return: New object of ExpressionSet class.
        @rtype: ExpressionSet
        """
        instance = ExpressionSet(self.connector)
        for child in self.children:
            instance.children.append(child.clone())
        instance.negated = self.negated
        return instance