text:
package org.wso2.es.ui.integration.test.store;

import org.openqa.selenium.By;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.extensions.selenium.BrowserManager;
import org.wso2.es.ui.integration.util.BaseUITestCase;
import org.wso2.es.ui.integration.util.ESWebDriver;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * Test appearance and behavior of Store Home page
 */
public class ESStoreAnonHomePageTestCase extends BaseUITestCase {

    private static final String LINE_CHART = "Line Chart";
    private static final String LINE_PLUS_BAR_CHART = "Line Plus Bar Chart";
    private static final String AMAZON = "Amazon";

    @BeforeClass(alwaysRun = true)
    public void setUp() throws Exception {
        super.init();
        driver = new ESWebDriver(BrowserManager.getWebDriver());
        baseUrl = getWebAppURL();
    }

    @Test(groups = "wso2.es.store", description = "Test Anonymous User Home Page")
    public void testAnonHomePage() throws Exception {
        //test appearance
        driver.get(baseUrl + STORE_URL);
        assertTrue(isElementPresent(By.cssSelector("a.brand")), "Home Page error: Logo missing");
        assertEquals("Sign in", driver.findElement(By.linkText("Sign in")).getText(),
                "Home Page error: Sign in button missing");
        assertTrue(isElementPresent(By.id("btn-register")), "Home Page error: Register button missing");
        assertEquals("Gadget", driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[1]/li"))
                .getText(), "Home Page error: Gadget menu missing");
        assertEquals("Site", driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[2]/li"))
                .getText(), "Home Page error: Site menu missing");
        assertEquals("Recent Gadgets", driver.findElement(By.linkText("Recent Gadgets")).getText(),
                "Home Page error: Recent Gadgets links missing");
        assertEquals("Recent Sites", driver.findElement(By.linkText("Recent Sites")).getText(),
                "Home Page error: Recent Sites links missing");
        assertTrue(isElementPresent(By.id("search")), "Home Page error: Search missing");
        assertTrue(isElementPresent(By.cssSelector("div.span3.store-right > div.row > div.span3")),
                "Home Page error: Recent Added side list missing");
    }

    @Test(groups = "wso2.es.store", description = "Test Anonymous User Recent sliding",
            enabled = false)
    public void testSliding() throws Exception {
        //TODO how to detect sliding is successful?
    }

    @Test(groups = "wso2.es.store", description = "Test Anonymous Navigation from top menu")
    public void testAnonNavigationTop() throws Exception {
        //test menu navigation
        driver.get(baseUrl + STORE_URL);
        driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[1]/li")).click();
        assertEquals(LINE_PLUS_BAR_CHART, driver.findElement(By.xpath("//h4[contains(.," + LINE_PLUS_BAR_CHART + "')]"))
                .getText(), "Gadgets Menu not working");
        driver.findElement(By.xpath("//div[@id='container-search']/div/div/div/div/a[2]/li")).click();
        assertEquals(AMAZON, driver.findElement(By.xpath("//h4[contains(.," + AMAZON + "')]")).getText(),
                "Sites Menu not working");
        driver.findElement(By.cssSelector("a.brand")).click();
    }

    @Test(groups = "wso2.es.store", description = "Test Anonymous Navigation page links")
    public void testAnonNavigationLinks() throws Exception {
        //test link navigation
        driver.get(baseUrl + STORE_URL);
        driver.findElement(By.cssSelector("a.brand")).click();
        driver.findElement(By.linkText("Recent Gadgets")).click();
        assertEquals(LINE_CHART, driver.findElement(By.xpath("//h4[contains(.,'" + LINE_CHART + "')]")).getText(),
                "Recent Gadgets link not working");
        driver.findElement(By.cssSelector("a.brand")).click();
        driver.findElement(By.linkText("Recent Sites")).click();
        assertEquals(AMAZON, driver.findElement(By.xpath("//h4[contains(.,'" + AMAZON + "')]")).getText(),
                "Recent Sites link not working");
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
        driver.quit();
    }

}


text:
/*
 * Copyright (c) 1982, 1986, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)ip_var.h	8.2 (Berkeley) 1/9/95
 */
/*
 * NOTICE: This file was modified by SPARTA, Inc. in 2007 to introduce
 * support for mandatory and extensible security protections.  This notice
 * is included in support of clause 2.2 (b) of the Apple Public License,
 * Version 2.0.
 */

#ifndef _NETINET_IP_VAR_H_
#define	_NETINET_IP_VAR_H_
#include <sys/appleapiopts.h>

/*
 * Overlay for ip header used by other protocols (tcp, udp).
 */
struct ipovly {
	u_char	ih_x1[9];		/* (unused) */
	u_char	ih_pr;			/* protocol */
	u_short	ih_len;			/* protocol length */
	struct	in_addr ih_src;		/* source internet address */
	struct	in_addr ih_dst;		/* destination internet address */
};

#define	MAX_IPOPTLEN	40

struct	ipstat {
	u_int32_t ips_total;		/* total packets received */
	u_int32_t ips_badsum;		/* checksum bad */
	u_int32_t ips_tooshort;		/* packet too short */
	u_int32_t ips_toosmall;		/* not enough data */
	u_int32_t ips_badhlen;		/* ip header length < data size */
	u_int32_t ips_badlen;		/* ip length < ip header length */
	u_int32_t ips_fragments;	/* fragments received */
	u_int32_t ips_fragdropped;	/* frags dropped (dups, out of space) */
	u_int32_t ips_fragtimeout;	/* fragments timed out */
	u_int32_t ips_forward;		/* packets forwarded */
	u_int32_t ips_fastforward;	/* packets fast forwarded */
	u_int32_t ips_cantforward;	/* packets rcvd for unreachable dest */
	u_int32_t ips_redirectsent;	/* packets forwarded on same net */
	u_int32_t ips_noproto;		/* unknown or unsupported protocol */
	u_int32_t ips_delivered;	/* datagrams delivered to upper level */
	u_int32_t ips_localout;		/* total ip packets generated here */
	u_int32_t ips_odropped;		/* lost packets due to nobufs, etc. */
	u_int32_t ips_reassembled;	/* total packets reassembled ok */
	u_int32_t ips_fragmented;	/* datagrams successfully fragmented */
	u_int32_t ips_ofragments;	/* output fragments created */
	u_int32_t ips_cantfrag;		/* don't fragment flag was set, etc. */
	u_int32_t ips_badoptions;	/* error in option processing */
	u_int32_t ips_noroute;		/* packets discarded due to no route */
	u_int32_t ips_badvers;		/* ip version != 4 */
	u_int32_t ips_rawout;		/* total raw ip packets generated */
	u_int32_t ips_toolong;		/* ip length > max ip packet size */
	u_int32_t ips_notmember;	/* multicasts for unregistered grps */
	u_int32_t ips_nogif;		/* no match gif found */
	u_int32_t ips_badaddr;		/* invalid address on header */
	u_int32_t ips_pktdropcntrl;	/* pkt dropped, no mbufs for ctl data */
	u_int32_t ips_rcv_swcsum;	/* ip hdr swcksum (inbound), packets */
	u_int32_t ips_rcv_swcsum_bytes;	/* ip hdr swcksum (inbound), bytes */
	u_int32_t ips_snd_swcsum;	/* ip hdr swcksum (outbound), packets */
	u_int32_t ips_snd_swcsum_bytes;	/* ip hdr swcksum (outbound), bytes */
	u_int32_t ips_adj;		/* total packets trimmed/adjusted */
	u_int32_t ips_adj_hwcsum_clr;	/* hwcksum discarded during adj */
	u_int32_t ips_rxc_collisions;	/* rx chaining collisions */
	u_int32_t ips_rxc_chained;	/* rx chains */
	u_int32_t ips_rxc_notchain;	/* rx bypassed chaining */
	u_int32_t ips_rxc_chainsz_gt2;	/* rx chain size greater than 2 */
	u_int32_t ips_rxc_chainsz_gt4;  /* rx chain size greater than 4 */
	u_int32_t ips_rxc_notlist;	/* count of pkts through ip_input */
	u_int32_t ips_raw_sappend_fail;	/* sock append failed */

};

struct ip_linklocal_stat {
	u_int32_t	iplls_in_total;
	u_int32_t	iplls_in_badttl;
	u_int32_t	iplls_out_total;
	u_int32_t	iplls_out_badttl;
};

/* forward declarations for ip_output() */
struct ip_out_args;
struct ip_moptions;

/* for PPP/PPTP */
extern int ip_gre_output(struct mbuf *);
typedef struct mbuf *(*gre_input_func_t)(struct mbuf *, int, int);
extern int ip_gre_register_input(gre_input_func_t);
#endif /* !_NETINET_IP_VAR_H_ */

redpajama_set_name: RedPajamaGithub


text:
package davidkellis.seven.domain

import davidkellis.seven.domain.CoreTypes.{Decimal, ShareQuantity, OrderQueue}
import java.time.ZonedDateTime

import scala.collection.mutable
import scala.util.Try

class BrokerageAccount(val broker: Broker,
                       val portfolio: Portfolio,
                       val openOrders: OrderQueue = mutable.Set.empty[Order],
                       val orderHistory: mutable.ListBuffer[Order] = mutable.ListBuffer.empty[Order]) {
  def marketBuyStock(security: Security, qty: ShareQuantity, time: ZonedDateTime): Try[Order] = {
    val order = Order.buildMarketBuy(this, Equity, security.id, qty, time)
    broker.placeOrder(order)
  }

  def marketSellStock(security: Security, qty: ShareQuantity, time: ZonedDateTime): Try[Order] = {
    val order = Order.buildMarketSell(this, Equity, security.id, qty, time)
    broker.placeOrder(order)
  }

  def limitBuyStock(security: Security, qty: ShareQuantity, limitPrice: Decimal, time: ZonedDateTime): Try[Order] = {
    val order = Order.buildLimitBuy(this, Equity, security.id, qty, limitPrice, time)
    broker.placeOrder(order)
  }

  def limitSellStock(security: Security, qty: ShareQuantity, limitPrice: Decimal, time: ZonedDateTime): Try[Order] = {
    val order = Order.buildLimitSell(this, Equity, security.id, qty, limitPrice, time)
    broker.placeOrder(order)
  }
}


text:
package com.amazonaws.services.pinpoint.model.transform;

import java.util.Map;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpoint.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * VoiceMessageMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class VoiceMessageMarshaller {

    private static final MarshallingInfo<String> BODY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Body").build();
    private static final MarshallingInfo<String> LANGUAGECODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LanguageCode").build();
    private static final MarshallingInfo<String> ORIGINATIONNUMBER_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OriginationNumber").build();
    private static final MarshallingInfo<Map> SUBSTITUTIONS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Substitutions").build();
    private static final MarshallingInfo<String> VOICEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("VoiceId").build();

    private static final VoiceMessageMarshaller instance = new VoiceMessageMarshaller();

    public static VoiceMessageMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(VoiceMessage voiceMessage, ProtocolMarshaller protocolMarshaller) {

        if (voiceMessage == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(voiceMessage.getBody(), BODY_BINDING);
            protocolMarshaller.marshall(voiceMessage.getLanguageCode(), LANGUAGECODE_BINDING);
            protocolMarshaller.marshall(voiceMessage.getOriginationNumber(), ORIGINATIONNUMBER_BINDING);
            protocolMarshaller.marshall(voiceMessage.getSubstitutions(), SUBSTITUTIONS_BINDING);
            protocolMarshaller.marshall(voiceMessage.getVoiceId(), VOICEID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
using Android.Widget;
using Flowers.Helpers;

namespace Flowers
{
    public partial class AddCommentActivity : ActivityBaseEx
    {
        private EditText _commentText;
        private Button _saveCommentButton;

        public EditText CommentText
        {
            get
            {
                return _commentText
                       ?? (_commentText = FindViewById<EditText>(Resource.Id.CommentText));
            }
        }

        public Button SaveCommentButton
        {
            get
            {
                return _saveCommentButton
                       ?? (_saveCommentButton = FindViewById<Button>(Resource.Id.SaveCommentButton));
            }
        }
    }
}


text:
namespace GreenPipes.Internals.Reflection
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Reflection.Emit;
    using Extensions;

    public class DynamicImplementationBuilder :
        IImplementationBuilder
    {
        const MethodAttributes PropertyAccessMethodAttributes = MethodAttributes.Public
            | MethodAttributes.SpecialName
            | MethodAttributes.HideBySig
            | MethodAttributes.Final
            | MethodAttributes.Virtual
            | MethodAttributes.VtableLayoutMask;

        readonly ConcurrentDictionary<string, ModuleBuilder> _moduleBuilders;
        readonly string _proxyNamespaceSuffix = "GreenPipes.DynamicInternal" + Guid.NewGuid().ToString("N");
        readonly ConcurrentDictionary<Type, Lazy<Type>> _proxyTypes;

        public DynamicImplementationBuilder()
        {
            _moduleBuilders = new ConcurrentDictionary<string, ModuleBuilder>();

            _proxyTypes = new ConcurrentDictionary<Type, Lazy<Type>>();
        }

        public Type GetImplementationType(Type interfaceType)
        {
            return _proxyTypes.GetOrAdd(interfaceType, x => new Lazy<Type>(() => CreateImplementation(x))).Value;
        }

        Type CreateImplementation(Type interfaceType)
        {
            if (!interfaceType.GetTypeInfo().IsInterface)
                throw new ArgumentException("Proxies can only be created for interfaces: " + interfaceType.Name, nameof(interfaceType));

            return GetModuleBuilderForType(interfaceType, moduleBuilder => CreateTypeFromInterface(moduleBuilder, interfaceType));
        }

        Type CreateTypeFromInterface(ModuleBuilder builder, Type interfaceType)
        {
            var typeName = "GreenPipes.DynamicInternal." +
                (interfaceType.IsNested && interfaceType.DeclaringType != null
                    ? $"{interfaceType.DeclaringType.Name}+{TypeCache.GetShortName(interfaceType)}"
                    : TypeCache.GetShortName(interfaceType));
            try
            {
                var typeBuilder = builder.DefineType(typeName,
                    TypeAttributes.Serializable | TypeAttributes.Class |
                    TypeAttributes.Public | TypeAttributes.Sealed,
                    typeof(object), new[] {interfaceType});

                typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);

                IEnumerable<PropertyInfo> properties = interfaceType.GetAllProperties();
                foreach (var property in properties)
                {
                    var fieldBuilder = typeBuilder.DefineField("field_" + property.Name, property.PropertyType,
                        FieldAttributes.Private);

                    var propertyBuilder = typeBuilder.DefineProperty(property.Name,
                        property.Attributes | PropertyAttributes.HasDefault, property.PropertyType, null);

                    var getMethod = GetGetMethodBuilder(property, typeBuilder, fieldBuilder);
                    var setMethod = GetSetMethodBuilder(property, typeBuilder, fieldBuilder);

                    propertyBuilder.SetGetMethod(getMethod);
                    propertyBuilder.SetSetMethod(setMethod);
                }

                return typeBuilder.CreateTypeInfo().AsType();
            }
            catch (Exception ex)
            {
                var message = $"Exception creating proxy ({typeName}) for {TypeCache.GetShortName(interfaceType)}";

                throw new InvalidOperationException(message, ex);
            }
        }

        MethodBuilder GetGetMethodBuilder(PropertyInfo propertyInfo, TypeBuilder typeBuilder,
            FieldBuilder fieldBuilder)
        {
            var getMethodBuilder = typeBuilder.DefineMethod("get_" + propertyInfo.Name,
                PropertyAccessMethodAttributes,
                propertyInfo.PropertyType,
                Type.EmptyTypes);

            var il = getMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, fieldBuilder);
            il.Emit(OpCodes.Ret);

            return getMethodBuilder;
        }

        MethodBuilder GetSetMethodBuilder(PropertyInfo propertyInfo, TypeBuilder typeBuilder,
            FieldBuilder fieldBuilder)
        {
            var setMethodBuilder = typeBuilder.DefineMethod("set_" + propertyInfo.Name,
                PropertyAccessMethodAttributes,
                null,
                new[] {propertyInfo.PropertyType});

            var il = setMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, fieldBuilder);
            il.Emit(OpCodes.Ret);

            return setMethodBuilder;
        }

        TResult GetModuleBuilderForType<TResult>(Type interfaceType, Func<ModuleBuilder, TResult> callback)
        {
            var assemblyName = interfaceType.Namespace + _proxyNamespaceSuffix;

            var builder = _moduleBuilders.GetOrAdd(assemblyName, name =>
            {
                const AssemblyBuilderAccess access = AssemblyBuilderAccess.RunAndCollect;

                var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(name), access);

                var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);

                return moduleBuilder;
            });

            return callback(builder);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Scyphophorus fibula Sommerf.

### Remarks
null


text:
package grpc_zap_test

import (
	"testing"

	"github.com/stretchr/testify/suite"
	"google.golang.org/grpc"

	"bytes"

	"encoding/json"
	"io"

	"fmt"

	"runtime"

	"github.com/mwitkow/go-grpc-middleware/logging"
	"github.com/mwitkow/go-grpc-middleware/logging/zap"
	"github.com/mwitkow/go-grpc-middleware/testing"
	pb_testproto "github.com/mwitkow/go-grpc-middleware/testing/testproto"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"golang.org/x/net/context"
	"google.golang.org/grpc/codes"
	"strings"
)

var (
	goodPing = &pb_testproto.PingRequest{Value: "something", SleepTimeMs: 9999}
)

type loggingPingService struct {
	pb_testproto.TestServiceServer
}

func customCodeToLevel(c codes.Code) zapcore.Level {
	if c == codes.Unauthenticated {
		// Make this a special case for tests, and an error.
		return zap.DPanicLevel
	}
	level := grpc_zap.DefaultCodeToLevel(c)
	return level
}

func (s *loggingPingService) Ping(ctx context.Context, ping *pb_testproto.PingRequest) (*pb_testproto.PingResponse, error) {
	grpc_zap.AddFields(ctx, zap.String("custom_string", "something"), zap.Int("custom_int", 1337))
	grpc_zap.Extract(ctx).Info("some ping")
	return s.TestServiceServer.Ping(ctx, ping)
}

func (s *loggingPingService) PingError(ctx context.Context, ping *pb_testproto.PingRequest) (*pb_testproto.Empty, error) {
	return s.TestServiceServer.PingError(ctx, ping)
}

func (s *loggingPingService) PingList(ping *pb_testproto.PingRequest, stream pb_testproto.TestService_PingListServer) error {
	grpc_zap.AddFields(stream.Context(), zap.String("custom_string", "something"), zap.Int("custom_int", 1337))
	grpc_zap.Extract(stream.Context()).Info("some pinglist")
	return s.TestServiceServer.PingList(ping, stream)
}

func (s *loggingPingService) PingEmpty(ctx context.Context, empty *pb_testproto.Empty) (*pb_testproto.PingResponse, error) {
	grpc_logging.ExtractMetadata(ctx).AddFieldsFromMiddleware(
		[]string{"middleware_1", "middleware_2"},
		[]interface{}{1410, "some_content"})
	return s.TestServiceServer.PingEmpty(ctx, empty)
}

type bufferWriteSyncer struct {
	*bytes.Buffer
}

func (*bufferWriteSyncer) Sync() error {
	return nil // no op
}

func TestZapLoggingSuite(t *testing.T) {
	if strings.HasPrefix(runtime.Version(), "go1.7") {
		t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7")
		return
	}
	b := &bufferWriteSyncer{&bytes.Buffer{}}
	zap.NewDevelopmentConfig()
	jsonEncoder := zapcore.NewJSONEncoder(zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.EpochTimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
	})
	core := zapcore.NewCore(jsonEncoder, b, zap.LevelEnablerFunc(func(zapcore.Level) bool { return true }))
	log := zap.New(core)
	opts := []grpc_zap.Option{
		grpc_zap.WithLevels(customCodeToLevel),
	}
	s := &ZapLoggingSuite{
		log:    log,
		buffer: b.Buffer,
		InterceptorTestSuite: &grpc_testing.InterceptorTestSuite{
			TestService: &loggingPingService{&grpc_testing.TestPingService{T: t}},
			ServerOpts: []grpc.ServerOption{
				grpc.StreamInterceptor(grpc_zap.StreamServerInterceptor(log, opts...)),
				grpc.UnaryInterceptor(grpc_zap.UnaryServerInterceptor(log, opts...)),
			},
		},
	}
	suite.Run(t, s)
}

type ZapLoggingSuite struct {
	*grpc_testing.InterceptorTestSuite
	buffer *bytes.Buffer
	log    *zap.Logger
}

func (s *ZapLoggingSuite) SetupTest() {
	s.buffer.Reset()
}

func (s *ZapLoggingSuite) getOutputJSONs() []string {
	ret := []string{}
	dec := json.NewDecoder(s.buffer)
	for {
		var val map[string]json.RawMessage
		err := dec.Decode(&val)
		if err == io.EOF {
			break
		}
		if err != nil {
			s.T().Fatalf("failed decoding output from ZAP JSON: %v", err)
		}
		out, _ := json.MarshalIndent(val, "", "  ")
		ret = append(ret, string(out))
	}
	return ret
}

func (s *ZapLoggingSuite) TestPing_WithCustomTags() {
	_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
	assert.NoError(s.T(), err, "there must be not be an on a successful call")
	msgs := s.getOutputJSONs()
	assert.Len(s.T(), msgs, 2, "two log statements should be logged")
	for _, m := range msgs {
		s.T()
		assert.Contains(s.T(), m, `"grpc_service": "mwitkow.testproto.TestService"`, "all lines must contain service name")
		assert.Contains(s.T(), m, `"grpc_method": "Ping"`, "all lines must contain method name")
		assert.Contains(s.T(), m, `"custom_string": "something"`, "all lines must contain `custom_string` set by AddFields")
		assert.Contains(s.T(), m, `"custom_int": 1337`, "all lines must contain `custom_int` set by AddFields")
		// request field extraction
		assert.Contains(s.T(), m, `"request.value": "something"`, "all lines must contain fields extracted from goodPing because of test.manual_extractfields.pb")
	}
	assert.Contains(s.T(), msgs[0], `"msg": "some ping"`, "handler's message must contain user message")
	assert.Contains(s.T(), msgs[1], `"msg": "finished unary call"`, "interceptor message must contain string")
	assert.Contains(s.T(), msgs[1], `"level": "info"`, "OK error codes must be logged on info level.")
	assert.Contains(s.T(), msgs[1], `"grpc_time_ns":`, "interceptor log statement should contain execution time")
}

func (s *ZapLoggingSuite) TestPingError_WithCustomLevels() {
	for _, tcase := range []struct {
		code  codes.Code
		level zapcore.Level
		msg   string
	}{
		{
			code:  codes.Internal,
			level: zap.ErrorLevel,
			msg:   "Internal must remap to ErrorLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.NotFound,
			level: zap.InfoLevel,
			msg:   "NotFound must remap to InfoLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.FailedPrecondition,
			level: zap.WarnLevel,
			msg:   "FailedPrecondition must remap to WarnLevel in DefaultCodeToLevel",
		},
		{
			code:  codes.Unauthenticated,
			level: zap.DPanicLevel,
			msg:   "Unauthenticated is overwritten to DPanicLevel with customCodeToLevel override, which probably didn't work",
		},
	} {
		s.buffer.Reset()
		_, err := s.Client.PingError(
			s.SimpleCtx(),
			&pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(tcase.code)})
		assert.Error(s.T(), err, "each call here must return an error")
		msgs := s.getOutputJSONs()
		require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingErr")
		m := msgs[0]
		assert.Contains(s.T(), m, `"grpc_service": "mwitkow.testproto.TestService"`, "all lines must contain service name")
		assert.Contains(s.T(), m, `"grpc_method": "PingError"`, "all lines must contain method name")
		assert.Contains(s.T(), m, fmt.Sprintf(`"grpc_code": "%s"`, tcase.code.String()), "all lines must contain method name")
		assert.Contains(s.T(), m, fmt.Sprintf(`"level": "%s"`, tcase.level.String()), tcase.msg)
	}
}

func (s *ZapLoggingSuite) TestPingList_WithCustomTags() {
	stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
	require.NoError(s.T(), err, "should not fail on establishing the stream")
	for {
		_, err := stream.Recv()
		if err == io.EOF {
			break
		}
		require.NoError(s.T(), err, "reading stream should not fail")
	}
	msgs := s.getOutputJSONs()
	assert.Len(s.T(), msgs, 2, "two log statements should be logged")
	for _, m := range msgs {
		s.T()
		assert.Contains(s.T(), m, `"grpc_service": "mwitkow.testproto.TestService"`, "all lines must contain service name")
		assert.Contains(s.T(), m, `"grpc_method": "PingList"`, "all lines must contain method name")
		assert.Contains(s.T(), m, `"custom_string": "something"`, "all lines must contain `custom_string` set by AddFields")
		assert.Contains(s.T(), m, `"custom_int": 1337`, "all lines must contain `custom_int` set by AddFields")
		// request field extraction
		assert.Contains(s.T(), m, `"request.value": "something"`, "all lines must contain fields extracted from goodPing because of test.manual_extractfields.pb")
	}
	assert.Contains(s.T(), msgs[0], `"msg": "some pinglist"`, "handler's message must contain user message")
	assert.Contains(s.T(), msgs[1], `"msg": "finished streaming call"`, "interceptor message must contain string")
	assert.Contains(s.T(), msgs[1], `"level": "info"`, "OK error codes must be logged on info level.")
	assert.Contains(s.T(), msgs[1], `"grpc_time_ns":`, "interceptor log statement should contain execution time")
}

func (s *ZapLoggingSuite) TestPingEmpty_WithMetadataTags() {
	_, err := s.Client.PingEmpty(s.SimpleCtx(), &pb_testproto.Empty{})
	assert.NoError(s.T(), err, "there must be not be an on a successful call")
	msgs := s.getOutputJSONs()
	require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingEmpty")
	m := msgs[0]
	assert.Contains(s.T(), m, `"middleware_1": 1410`, "the handler must contain fields from grpc_logging.Metadata calls")
	assert.Contains(s.T(), m, `"middleware_2": "some_content"`, "the handler must contain fields from grpc_logging.Metadata calls")
}


text: #include "hal/radio_vendor_hal.h"


text:
'use strict';

const _ = require('lodash'),
	chalk = require('chalk'),
	/**
	 * @type {Configuration}
	 */
	config = require('../config'),
	debugCreate = require('debug'),
	{ GitLabApi } = require('./lib/gitlabapi'),
	handlers = require('./handlers'),
	helpers = require('./lib/helpers'),
	bluebird = require('bluebird'),
	server = require('./lib/server');

const api = new GitLabApi(config.gitLab.baseUrl, config.gitLab.apiToken),
	debug = debugCreate('gitlab-slack:app');

let gitLabSlack;

process.on('uncaughtException', function (err) {
	debug(chalk`{red UNCAUGHT EXCEPTION} - ${err.message}${'\n'}${err.stack}`);
	process.exit(1);
});
process.on('SIGINT', function () {
	debug(chalk`{yellow SIGINT} received!`);
	return _terminate();
});
process.on('SIGTERM', function () {
	debug(chalk`{yellow SIGTERM} received!`);
	return _terminate();
});

bluebird.config({
	longStackTraces: true
});

(async function () {
	debug('Starting up...');

	if (!config.gitLab.projects || !config.gitLab.projects.length) {
		// Make sure this gets logged somehow.
		(debug.enabled ? debug : console.error)(chalk`{red ERROR} No projects defined in configuration. Terminating...`);
		process.exit(1);
	}

	// Be nice and add the # character to channels in project configuration if it's not there.
	for (const project of config.gitLab.projects) {
		if (project.channel && !project.channel.startsWith('#')) {
			project.channel = '#' + project.channel;
		}
	}

	const projectConfigs = new Map(_.map(config.gitLab.projects, p => [p.id, p])),
		{ labelColors, issueLabels } = await _buildIssueLabelCaches();

	gitLabSlack = server.createServer(
		data => handlers.handleMessage(
			projectConfigs,
			labelColors,
			issueLabels,
			api,
			data
		)
	);

	gitLabSlack.on('close', function () {
		// If the service closes for some other reason, make sure
		//  the process also exits.
		_terminate();
	});

	gitLabSlack.listen(config.port);

	debug('Startup complete.');
})()
	.catch(function (err) {
		// Make sure this gets logged somehow.
		(debug.enabled ? debug : console.error)(chalk`{red ERROR} Processing failure in main branch. ! {red %s}\n{blue Stack} %s`, err.message, err.stack);
		_terminate(1);
	});

// region ---- HELPER FUNCTIONS --------------------

/**
 * Caches project and issue labels for projects with label-tracking enabled.
 * @returns {Promise<{ labelColors: Map, issueLabels: Map }>} The issue and label caches.
 * @private
 */
async function _buildIssueLabelCaches() {
	const cachers = [],
		issueLabels = new Map(),
		labelColors = new Map();

	_.each(config.gitLab.projects, function (project) {
		// For the label patterns that aren't already regex, compile them.
		_.each(project.labels, function (label, index) {
			if (!_.isRegExp(label)) {
				project.labels[index] = new RegExp(label, 'i');
			}
		});

		if (_.size(project.labels)) {
			const cacher = async function buildProjectCache() {
				debug(chalk`{cyan CACHE}[{cyanBright %d}] Caching information for {blue %d} / {blue %s}...`, project.id, project.id, project.name || '<no-name>');

				// region ---- CACHE PROJECT LABEL COLORS --------------------

				const projectLabelColors = new Map(),
					projectLabels = await api.getLabels(project.id);

				let projectLabelsCached = 0;

				// In API requests, labels have a name.
				for (const label of helpers.matchingAnyPattern(projectLabels, project.labels, l => l.name)) {
					projectLabelColors.set(label.name, label.color);
					projectLabelsCached++;
				}

				debug(chalk`{cyan CACHE}[{cyanBright %d}] Cached {blue %d} project label colors.`, project.id, projectLabelsCached);

				// endregion ---- CACHE PROJECT LABEL COLORS --------------------

				// region ---- CACHE PROJECT ISSUE LABELS --------------------

				const projectIssueLabels = new Map();

				let issueLabelsCached = 0,
					currentIssuePage = 1,
					totalIssuePages = 0;

				while (!totalIssuePages || currentIssuePage < totalIssuePages) {
					const result = await api.getOpenIssues(project.id, currentIssuePage);

					if (!result.data.length) {
						break;
					}

					if (!totalIssuePages) {
						totalIssuePages = result.totalPages;
					}

					for (const issue of result.data) {
						// We cache if the issue has labels and they match any of our patterns.
						const matchingLabels = helpers.matchingAnyPattern(issue.labels, project.labels);

						if (issue.labels.length && matchingLabels.length) {
							projectIssueLabels.set(issue.id, matchingLabels);
							issueLabelsCached++;
						}
					}

					currentIssuePage++;
				}

				debug(chalk`{cyan CACHE}[{cyanBright %d}] Cached labels of {blue %d} issues.`, project.id, issueLabelsCached);

				// endregion ---- CACHE PROJECT ISSUE LABELS --------------------

				labelColors.set(project.id, projectLabelColors);
				issueLabels.set(project.id, projectIssueLabels);

				debug(chalk`{cyan CACHE}[{cyanBright %d}] Cached all issue and label information.`, project.id);
			};

			cachers.push(cacher());
		}
	});

	await Promise.all(cachers);

	return { labelColors, issueLabels };
}

/**
 * Terminates the service.
 * @param {Number} exitCode The exit code. (default = 0)
 */
function _terminate(exitCode = 0) {
	debug('Terminating...');
	if (gitLabSlack && gitLabSlack.listening) {
		gitLabSlack.close(function () {
			process.exit(exitCode);
		});
	} else {
		process.exit(exitCode);
	}
}

// endregion ---- HELPER FUNCTIONS --------------------


text:
package com.thaiopensource.relaxng.edit;

import java.util.Map;
import java.util.HashMap;

public class ValuePattern extends Pattern {
  private String datatypeLibrary;
  private String type;
  private String value;
  private final Map<String, String> prefixMap = new HashMap<String, String>();

  public ValuePattern(String datatypeLibrary, String type, String value) {
    this.datatypeLibrary = datatypeLibrary;
    this.type = type;
    this.value = value;
  }

  public String getDatatypeLibrary() {
    return datatypeLibrary;
  }

  public void setDatatypeLibrary(String datatypeLibrary) {
    this.datatypeLibrary = datatypeLibrary;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public boolean mayContainText() {
    return true;
  }

  public Map<String, String> getPrefixMap() {
    return prefixMap;
  }

  public <T> T accept(PatternVisitor<T> visitor) {
    return visitor.visitValue(this);
  }
}


text:
import { AggregateProjection } from '@resolve-js/core'
import {
  USER_REGISTERED,
  USER_PROFILE_UPDATED,
  USER_PROFILE_DELETED,
} from '../user-profile.events'

const projection: AggregateProjection = {
  Init: () => ({
    isRegistered: false,
    isDeleted: false,
  }),
  [USER_REGISTERED]: (
    state,
    { payload: { firstName, lastName, contacts } }
  ) => ({
    ...state,
    isRegistered: true,
    firstName,
    lastName,
    contacts,
  }),
  [USER_PROFILE_UPDATED]: (
    state,
    { payload: { firstName, lastName, contacts } }
  ) => ({
    ...state,
    firstName,
    lastName,
    contacts,
  }),
  [USER_PROFILE_DELETED]: (state) => ({
    ...state,
    isRegistered: false,
    isDeleted: true,
  }),
}

export default projection


text:
using Aliyun.MNS.Common;
using System;
using System.Linq;
using System.Threading;

namespace Aliyun.MNS.Sample.Consumer
{
    class Program
    {
        private static string Host = Environment.GetEnvironmentVariable("ALIYUN_MNS_HOST");
        private static string AccessKey = Environment.GetEnvironmentVariable("ALIYUN_MNS_ACCESSKEY");
        private static string AccessSecret = Environment.GetEnvironmentVariable("ALIYUN_MNS_ACCESSSECRET");

        static void Main(string[] args)
        {
            Console.WriteLine($"Host: {Host}");
            Console.WriteLine($"AccessKey: {AccessKey}");
            Console.WriteLine($"AccessSecret: {AccessSecret}");

            var Queue = MNS.Configure(Host, AccessKey, AccessSecret).Queue("aries-test");

            while (true)
            {
                try
                {
                    var message = Queue.BatchReceiveMessage();

                    Console.WriteLine("message [{0}]:", message.Messages.Count);
                    foreach (var msg in message.Messages)
                    {
                        Console.WriteLine("\t{0}: {1}", msg.MessageId, msg.MessageBody);
                    }
                    Console.WriteLine("message processing..");
                    Thread.Sleep(2000);

                    Console.WriteLine("message processed");

                    Queue.BatchDeleteMessage(message.Messages.Select(m => m.ReceiptHandle).ToList());

                    Console.WriteLine("message deleted.");
                }
                catch (Exception ex)
                {
                    if (ex is MessageNotExistException)
                        continue;
                    else
                        Console.WriteLine("{0}\n{1}", ex.Message, ex.StackTrace);
                }
            }
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import Grid from 'material-ui/Grid';

function GridColumn(props) {
  const { children, spacing, ...other } = props;
  return (
    <Grid container direction="column" spacing={spacing} {...other}>
      {React.Children.map(children, child =>
        (child
          ? <Grid item >
            {child}
          </Grid>
          : null))}
    </Grid>
  );
}

GridColumn.propTypes = {
  children: PropTypes.node,
  spacing: PropTypes.number,
};

GridColumn.defaultProps = {
  spacing: 24,
};

export default GridColumn;


text:
require 'battlenet/api/client'

require 'battlenet/modules/wow/character_profile'
require 'battlenet/modules/wow/guild_profile'
require 'battlenet/modules/wow/item'
require 'battlenet/modules/wow/item_set'
require 'battlenet/modules/wow/achievement'
require 'battlenet/modules/wow/auction'
require 'battlenet/modules/wow/pvp_leaderboard'
require 'battlenet/modules/wow/quest'
require 'battlenet/modules/wow/realm'
require 'battlenet/modules/wow/recipe'
require 'battlenet/modules/wow/spell'
require 'battlenet/modules/wow/data'

#Dir[File.expand_path('../modules/wow/*.rb', __FILE__)].each{|f| require f}

module Battlenet

  class WOWClient < Client

    def initialize(options = {})
      client_settings = { :endpoint => '/wow' }
      client_settings = client_settings.merge(options)

      super(client_settings)
    end

    def character_profile(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::CharacterProfile.new(opts)
    end

    def guild_profile(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::GuildProfile.new(opts)
    end

    def item(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Item.new(opts)
    end

    def item_set(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::ItemSet.new(opts)
    end

    def achievement(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Achievement.new(opts)
    end

    def auction(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Auction.new(opts)
    end

    def pvp_leaderboard(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::PVPLeaderboard.new(opts)
    end

    def quest(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Quest.new(opts)
    end

    def realm(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Realm.new(opts)
    end

    def recipe(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Recipe.new(opts)
    end

    def spell(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Spell.new(opts)
    end

    def data(options = {})
      opts = options.merge({:client => self})
      Battlenet::WOW::Data.new(opts)
    end

  end

end


text:
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-3.0.xsd">
    <http auto-config="true">
        <intercept-url pattern="/login.xhtml*" filters="none" />
        <intercept-url pattern="/resources/**" filters="none" />
        <intercept-url pattern="/primefaces_resource/**" filters="none" />
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <custom-filter ref="userPopulatorFilter" after="LAST"/>
        <form-login login-processing-url="/j_spring_security_check" login-page="/login.xhtml" default-target-url="/main.xhtml" always-use-default-target="true" />
        <access-denied-handler error-page="/login.xhtml"/>
    </http>
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin123" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="user" password="user123" authorities="ROLE_USER" />
                <user name="student" password="student123" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>


text:
#include <orc/orc.h>
#include <orc-test/orctest.h>
#include <orc/orcparse.h>

#include <stdio.h>
#include <stdlib.h>

static char * read_file (const char *filename);
void output_code (OrcProgram *p, FILE *output);
void output_code_header (OrcProgram *p, FILE *output);
void output_code_test (OrcProgram *p, FILE *output);

int error = FALSE;

int
main (int argc, char *argv[])
{
  char *code;
  int n;
  int i;
  OrcProgram **programs;
  const char *filename = NULL;

  orc_init ();
  orc_test_init ();

  if (argc >= 2) {
    filename = argv[1];
  }
  if (filename == NULL) {
    filename = getenv ("testfile");
  }
  if (filename == NULL) {
    filename = "test.orc";
  }
  code = read_file (filename);
  if (!code) {
    printf("compile_parse_test <file.orc>\n");
    exit(1);
  }

  n = orc_parse (code, &programs);

  for(i=0;i<n;i++){
    OrcTestResult ret;

    printf("%s:\n", programs[i]->name);
    ret = orc_test_gcc_compile_neon (programs[i]);
    if (ret == ORC_TEST_FAILED) {
      error = TRUE;
    }
  }

  if (error) return 1;
  return 0;
}

static char *
read_file (const char *filename)
{
  FILE *file = NULL;
  char *contents = NULL;
  long size;
  int ret;

  file = fopen (filename, "r");
  if (file == NULL) return NULL;

  ret = fseek (file, 0, SEEK_END);
  if (ret < 0) goto bail;

  size = ftell (file);
  if (size < 0) goto bail;

  ret = fseek (file, 0, SEEK_SET);
  if (ret < 0) goto bail;

  contents = malloc (size + 1);
  if (contents == NULL) goto bail;

  ret = fread (contents, size, 1, file);
  if (ret < 0) goto bail;

  contents[size] = 0;

  fclose (file);

  return contents;
bail:
  /* something failed */
  if (file) fclose (file);
  if (contents) free (contents);

  return NULL;
}


text:
#ifndef INCLUDE_fnmatch__compat_h__
#define INCLUDE_fnmatch__compat_h__

#include "common.h"

#define FNM_NOMATCH		1		/* Match failed. */
#define FNM_NOSYS		2		/* Function not supported (unused). */
#define	FNM_NORES		3		/* Out of resources */

#define FNM_NOESCAPE	0x01		/* Disable backslash escaping. */
#define FNM_PATHNAME	0x02		/* Slash must be matched by slash. */
#define FNM_PERIOD		0x04		/* Period must be matched by period. */
#define FNM_LEADING_DIR 0x08		/* Ignore /<tail> after Imatch. */
#define FNM_CASEFOLD	0x10		/* Case insensitive search. */

#define FNM_IGNORECASE	FNM_CASEFOLD
#define FNM_FILE_NAME	FNM_PATHNAME

extern int p_fnmatch(const char *pattern, const char *string, int flags);

#endif /* _FNMATCH_H */


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/fapi2/plat_hw_access.C $                              */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2022                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file plat_hw_access.C
///
/// @brief Implements hardware-access functions for the platform layer.
///

#include <stdint.h>
#include <errl/errlentry.H>
#include <devicefw/userif.H>
#include <return_code.H>
#include <buffer.H>
#include <target.H>
#include <target_types.H>
#include <hw_access_def.H>
#include <fapi2/plat_utils.H>
#include <hwpf_fapi2_reasoncodes.H>
#include <scom/scomreasoncodes.H>
#include <fapi2/plat_hw_access.H>
#include <scom/errlud_pib.H>

#include <hw_access_def.H>
#include <arch/ppc.H>

#include <multicast_group_defs.H>
#include <multicast_defs.H>
#include <return_code_defs.H>
#include <hbotcompid.H>

namespace fapi2
{

// Bits 7-15 are address portion
const uint32_t CFAM_ADDRESS_MASK = 0x1FF;

// Bits 0-6 are engine offset
const uint32_t CFAM_ENGINE_OFFSET = 0xFE00;

// Operational mode for scom operations (ignore errors, wakeup core, etc.)
#ifndef PLAT_NO_THREAD_LOCAL_STORAGE
thread_local OpModes opMode = NORMAL;
#else
OpModes opMode = NORMAL;
#endif

// Bitmap of PIB errors to ignore during a PIB oeration
#ifndef PLAT_NO_THREAD_LOCAL_STORAGE
thread_local uint8_t pib_err_mask = 0x00;
#else
uint8_t pib_err_mask = 0x00;
#endif

// Multicast address parts
enum MulticastMasks : uint32_t
{
    CORE_SELECT_MASK       = 0x0000F000,
    MULTICAST_GROUP_MASK   = 0x07000000,
    MULTICAST_OP_MASK      = 0x38000000,
    MULTICAST_BIT          = 0x40000000,
};

enum MulticastOffsets : uint8_t
{
    CORE_SELECT_OFFSET     = 12,
    MULTICAST_GROUP_OFFSET = 24,
    MULTICAST_OP_OFFSET    = 27,
    MULTICAST_BIT_OFFSET   = 30,
};

// The MulticastGroup to hwValue (bits in the multicast address) map.
// There are only 3 multicast group bits in the multicast address,
// so the right side of the map must be <= 7.
std::map<MulticastGroup, uint32_t> g_multicastGroupMap = {
        {MCGROUP_ALL,        0x7},
        {MCGROUP_GOOD_NO_TP, 0x1},
        {MCGROUP_GOOD_MC,    0x2},
        {MCGROUP_GOOD_IOHS,  0x3},
        {MCGROUP_GOOD_PAU,   0x4},
        {MCGROUP_GOOD_PCI,   0x5},
        {MCGROUP_GOOD_EQ,    0x6} };

//------------------------------------------------------------------------------
// HW Communication Functions to be implemented at the platform layer.
//------------------------------------------------------------------------------

/// @brief Platform-level implementation called by getScom()
ReturnCode platGetScom(const Target<TARGET_TYPE_ALL>& i_target,
                       const uint64_t i_address,
                       buffer<uint64_t>& o_data)
{
    ReturnCode l_rc = FAPI2_RC_SUCCESS;
    errlHndl_t l_err = nullptr;

    FAPI_DBG(ENTER_MRK "platGetScom");
    // Note: Trace is placed here in plat code because PPE doesn't support
    //       trace in common fapi2_hw_access.H
    bool l_traceit = platIsScanTraceEnabled();

    // Extract the component pointer
    TARGETING::Target* l_target = i_target.get();

    do
    {

    if (l_target == nullptr)
    {
        o_data = 0;

        /*@
         * @errortype
         * @moduleid     fapi2::MOD_FAPI2_PLAT_GET_SCOM
         * @reasoncode   fapi2::RC_INVALID_TARG_TARGET
         * @userdata1    SCOM address being read
         * @devdesc      NULL target pointer given to platGetScom
         * @custdesc     Internal firmware error
         */
        l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        fapi2::MOD_FAPI2_PLAT_GET_SCOM,
                                        fapi2::RC_INVALID_TARG_TARGET,
                                        i_address,
                                        0,
                                        ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
        addErrlPtrToReturnCode(l_rc, l_err);
        l_rc.setRC(fapi2::FAPI2_RC_INVALID_PARAMETER);
        break;
    }

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

     uint64_t l_scomAddr = i_address;
     if(i_target.get().isMulticast())
     {
         // Compose the multicast address based on multicast params
         l_scomAddr = fapi2::getMulticastAddr(l_scomAddr,
                                             i_target.get().getMulticastGroup(),
                                             i_target.get().getMulticastOp(),
                                             i_target.get().getCoreSelect());
     }

    // Perform SCOM read
    size_t l_size = sizeof(uint64_t);
    l_err = deviceRead(l_target,
                       &o_data(),
                       l_size,
                       DEVICE_SCOM_ADDRESS(l_scomAddr, opMode));

    //If an error occured durring the device read and a pib_err_mask is set,
    // then we will check if the err matches the mask, if it does we
    // ignore the error
    if(l_err && (pib_err_mask != 0x00))
    {
        checkPibMask(l_err);
    }

    if (l_err)
    {
        if(opMode & fapi2::IGNORE_HW_ERROR)
        {
            delete l_err;
            l_err = nullptr;
        }
        else
        {
            FAPI_ERR("platGetScom: deviceRead returns error!");
            FAPI_ERR("fapiGetScom failed - Target %s, Addr %.16llX",
                     l_targName, l_scomAddr);
            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            if(l_err->getErrorType() == SCOM::SCOM_MULTICAST_MISCOMPARE)
            {
                l_rc.setRC(fapi2::FAPI2_RC_PLAT_MISCOMPARE);
            }
        }
    }

    if (l_traceit)
    {
        uint64_t l_data = (uint64_t)o_data;
        FAPI_SCAN("TRACE : GETSCOM     :  %s : %.16llX %.16llX",
                  l_targName,
                  l_scomAddr,
                  l_data);
    }

    } while (false);

    FAPI_DBG(EXIT_MRK "platGetScom");
    return l_rc;
}

/// @brief Platform-level implementation called by putScom()
ReturnCode platPutScom(const Target<TARGET_TYPE_ALL>& i_target,
                       const uint64_t i_address,
                       const buffer<uint64_t> i_data)
{
    ReturnCode l_rc = FAPI2_RC_SUCCESS;
    errlHndl_t l_err = nullptr;

    FAPI_DBG(ENTER_MRK "platPutScom");
    // Note: Trace is placed here in plat code because PPE doesn't support
    //       trace in common fapi2_hw_access.H
    bool l_traceit = platIsScanTraceEnabled();

    // Extract the component pointer
    TARGETING::Target* l_target = i_target.get();

    do
    {

    if (l_target == nullptr)
    {
        /*@
         * @errortype
         * @moduleid     fapi2::MOD_FAPI2_PLAT_PUT_SCOM
         * @reasoncode   fapi2::RC_INVALID_TARG_TARGET
         * @userdata1    SCOM address being written
         * @devdesc      NULL target pointer given to platPutScom
         * @custdesc     Internal firmware error
         */
        l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        fapi2::MOD_FAPI2_PLAT_PUT_SCOM,
                                        fapi2::RC_INVALID_TARG_TARGET,
                                        i_address,
                                        0,
                                        ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
        addErrlPtrToReturnCode(l_rc, l_err);
        l_rc.setRC(fapi2::FAPI2_RC_INVALID_PARAMETER);
        break;
    }

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    uint64_t l_scomAddr = i_address;

    if(i_target.get().isMulticast())
    {
        // Compose the multicast address based on multicast params
        l_scomAddr = fapi2::getMulticastAddr(l_scomAddr,
                                             i_target.get().getMulticastGroup(),
                                             i_target.get().getMulticastOp(),
                                             i_target.get().getCoreSelect());
    }

    // Perform SCOM write
    size_t l_size = sizeof(uint64_t);
    uint64_t l_data  = static_cast<uint64_t>(i_data);
    l_err = deviceWrite(l_target,
                        &l_data,
                        l_size,
                        DEVICE_SCOM_ADDRESS(l_scomAddr, opMode));

    //If an error occured durring the device write and a pib_err_mask is set,
    // then we will check if the err matches the mask, if it does we
    // ignore the error
    if(l_err && (pib_err_mask != 0x00))
    {
        checkPibMask(l_err);
    }

    if (l_err)
    {
        if(opMode & fapi2::IGNORE_HW_ERROR)
        {
            delete l_err;
            l_err = nullptr;
        }
        else
        {
            FAPI_ERR("platPutScom: deviceWrite returns error!");
            FAPI_ERR("platPutScom failed - Target %s, Addr %.16llX",
                     l_targName, l_scomAddr);
            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
        }
    }

    if (l_traceit)
    {
        FAPI_SCAN("TRACE : PUTSCOM     :  %s : %.16llX %.16llX",
                  l_targName,
                  l_scomAddr,
                  l_data);
    }

    } while (false);

    FAPI_DBG(EXIT_MRK "platPutScom");
    return l_rc;
}

/// @brief Platform-level implementation called by putScomUnderMask()
ReturnCode platPutScomUnderMask(const Target<TARGET_TYPE_ALL>& i_target,
                                const uint64_t i_address,
                                const buffer<uint64_t> i_data,
                                const buffer<uint64_t> i_mask)
{
    ReturnCode l_rc = FAPI2_RC_SUCCESS;
    errlHndl_t l_err = nullptr;

    FAPI_DBG(ENTER_MRK "platPutScomUnderMask");
    // Note: Trace is placed here in plat code because PPE doesn't support
    //       trace in common fapi2_hw_access.H
    bool l_traceit = platIsScanTraceEnabled();

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    do
    {
        // Extract the component pointer
        TARGETING::Target* l_target = i_target.get();

        // Get current value from HW
        uint64_t l_data = 0;
        size_t l_size = sizeof(uint64_t);
        l_err = deviceRead(l_target,
                           &l_data,
                           l_size,
                           DEVICE_SCOM_ADDRESS(i_address,opMode));
        if (l_err && !(opMode & fapi2::IGNORE_HW_ERROR))
        {
            FAPI_ERR("platPutScomUnderMask: deviceRead returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }
        else if(l_err)
        {
            delete l_err;
            l_err = nullptr;
            break;
        }

        // Calculate new value to write to reg
        uint64_t l_inMaskInverted = ~i_mask;    // Write mask inverted
        uint64_t l_newMask = (i_data & i_mask);  // Retain set data bits

        // l_data = current data set bits
        l_data &= l_inMaskInverted;

        // l_data = current data set bit + set mask bits
        l_data |= l_newMask;

        // Write new value
        l_err = deviceWrite(l_target,
                            &l_data,
                            l_size,
                            DEVICE_SCOM_ADDRESS(i_address,opMode));
        if (l_err && !(opMode & fapi2::IGNORE_HW_ERROR))
        {
            FAPI_ERR("platPutScomUnderMask: deviceWrite returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }
        else if (l_err)
        {
            delete l_err;
            l_err = nullptr;
            break;

        }

    } while (0);

    if(l_err && (pib_err_mask != 0x00))
    {
        checkPibMask(l_err);
    }

    if (l_rc != fapi2::FAPI2_RC_SUCCESS)
    {
       FAPI_ERR("platPutScomUnderMask failed - Target %s, Addr %.16llX",
                l_targName, i_address);
    }

    if( l_traceit )
    {
        uint64_t l_data = i_data;
        uint64_t l_mask = i_mask;
        FAPI_SCAN( "TRACE : PUTSCOMMASK : %s : %.16llX %.16llX %.16llX",
                   l_targName,
                   i_address,
                   l_data,
                   l_mask);
    }

    FAPI_DBG(EXIT_MRK "platPutScomUnderMask");
    return l_rc;
}

/// @brief Verify target of a cfam access
errlHndl_t verifyCfamAccessTarget(const TARGETING::Target* i_target,
                                  const uint32_t i_address)
{
    errlHndl_t l_err = nullptr;

    // Can't access cfam engine on the master processor
    TARGETING::Target* l_pMasterProcChip = nullptr;
    TARGETING::targetService().
      masterProcChipTargetHandle( l_pMasterProcChip );

    if( l_pMasterProcChip == i_target )
    {
        FAPI_ERR("verifyCfamAccessTarget: Attempt to access CFAM register %.8X on the master processor chip",
                 i_address);
        /*@
         * @errortype
         * @moduleid     fapi2::MOD_FAPI2_VERIFYCFAMACCESSTARGET
         * @reasoncode   fapi2::RC_INVALID_TARG_TARGET
         * @userdata1    CFAM Address
         * @userdata2    HUID of input target
         * @devdesc      verifyCfamAccessTarget> Attempt to access CFAM
         *               on the master processor
         * @custdesc     Internal firmware error
         */
        l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                   fapi2::MOD_FAPI2_VERIFYCFAMACCESSTARGET,
                                   fapi2::RC_INVALID_TARG_TARGET,
                                   i_address,
                                   TARGETING::get_huid(i_target),
                                   ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
        l_err->collectTrace(FAPI_TRACE_NAME);
    }

    return l_err;
}

/// @brief takes in an error log and looks for user details sections
///        with a compId of SCOM_COMP_ID. If one of those is found and
///        the pib err attatched to it matches the pib_err_mask, then
///        we delete the err.
void checkPibMask(errlHndl_t& io_errLog )
{
    //Delete the error if the mask matches the pib err
    for(auto data : io_errLog->getUDSections(SCOM_COMP_ID, SCOM::SCOM_UDT_PIB))
    {
        //We get the raw data from the userdetails section, which in this
        //case is the pib_err itself so just check it.
        if(*reinterpret_cast<uint8_t *>(data) == pib_err_mask)
        {
            FAPI_ERR( "Ignoring error %.8X due to pib_err_mask=%.1X", io_errLog->plid(), pib_err_mask );
            delete io_errLog;
            io_errLog = nullptr;
            break;
        }
    }
    return;
}

/// @brief Internal function that gets the chip target for cfam access
errlHndl_t getCfamChipTarget(const TARGETING::Target* i_target,
                             TARGETING::Target*& o_chipTarget)
{
    errlHndl_t l_err = nullptr;

    // Default to input target
    o_chipTarget = const_cast<TARGETING::Target*>(i_target);

    // Check to see if this is a chiplet
    if (i_target->getAttr<TARGETING::ATTR_CLASS>() == TARGETING::CLASS_UNIT)
    {
        // Look for its chip parent
        TARGETING::PredicateCTM l_chipClass(TARGETING::CLASS_CHIP);
        TARGETING::TargetHandleList l_list;
        TARGETING::TargetService& l_targetService = TARGETING::targetService();
        (void) l_targetService.getAssociated(
                l_list,
                i_target,
                TARGETING::TargetService::PARENT,
                TARGETING::TargetService::ALL,
                &l_chipClass);

        if ( l_list.size() == 1 )
        {
            o_chipTarget = l_list[0];
        }
        else
        {
            // Something is wrong here, can't have more than one parent chip
            FAPI_ERR("getCfamChipTarget: Invalid number of parent chip for this target chiplet - # parent chips %d", l_list.size());
            /*@
            * @errortype
            * @moduleid     fapi2::MOD_FAPI2_GET_CHIP_CFAM_TARGET
            * @reasoncode   fapi2::RC_INVALID_PARENT_TARGET_FOUND
            * @userdata1    Number of parent proc chips found
            * @userdata2    HUID of input target
            * @devdesc      Detecting more than 1 parent proc targets
            * @custdesc     Internal firmware error
            */
            l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                            fapi2::MOD_FAPI2_GET_CHIP_CFAM_TARGET,
                                            fapi2::RC_INVALID_PARENT_TARGET_FOUND,
                                            l_list.size(),
                                            TARGETING::get_huid(i_target),
                                            ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
            l_err->collectTrace(FAPI_TRACE_NAME);
        }
    }

    return l_err;
}

/// @brief Platform-level implementation called by getCfamRegister()
ReturnCode platGetCfamRegister(const Target<TARGET_TYPE_ALL>& i_target,
                               const uint32_t i_address,
                               buffer<uint32_t>& o_data)
{
    FAPI_DBG(ENTER_MRK "platGetCfamRegister");
    ReturnCode l_rc;
    errlHndl_t l_err = nullptr;
    bool l_traceit = platIsScanTraceEnabled();

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    do
    {
        // Extract the target pointer
        TARGETING::Target* l_target = i_target.get();

        // Get the chip target if l_target is not a chip
        TARGETING::Target* l_myChipTarget = nullptr;
        l_err = getCfamChipTarget(l_target, l_myChipTarget);
        if (l_err)
        {
            FAPI_ERR("platGetCfamRegister: getCfamChipTarget returns error!");
            FAPI_ERR("fapiGetCfamRegister failed - Target %s, Addr %.8X",
                      l_targName, i_address);

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Can't access cfam engine on master processor
        l_err = verifyCfamAccessTarget(l_target,i_address);
        if (l_err)
        {
            FAPI_ERR("platGetCfamRegister: verifyCfamAccessTarget returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Perform CFAM read via FSI
        size_t l_size = sizeof(uint32_t);
        l_err = deviceRead(l_myChipTarget,
                           &o_data(),
                           l_size,
                           DEVICE_CFAM_ADDRESS(i_address));
        if (l_err)
        {
            FAPI_ERR("platGetCfamRegister: deviceRead returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

    } while(0);

    if (l_rc != fapi2::FAPI2_RC_SUCCESS)
    {
       FAPI_ERR("fapiGetCfamRegister failed - Target %s, Addr %.8X",
                 l_targName, i_address);
    }

    if( l_traceit )
    {
        uint32_t l_data = (uint32_t)o_data;
        FAPI_SCAN( "TRACE : GETCFAMREG  : %s : %.8X %.8X",
                   l_targName,
                   i_address,
                   l_data);
    }

    FAPI_DBG(EXIT_MRK "platGetCfamRegister");
    return l_rc;
}

/// @brief Platform-level implementation called by putCfamRegister()
ReturnCode platPutCfamRegister(const Target<TARGET_TYPE_ALL>& i_target,
                               const uint32_t i_address,
                               const buffer<uint32_t> i_data)
{
    FAPI_DBG(ENTER_MRK "platPutCfamRegister");
    ReturnCode l_rc;
    errlHndl_t l_err = nullptr;
    bool l_traceit = platIsScanTraceEnabled();

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    do
    {
        // Extract the component pointer
        TARGETING::Target* l_target = i_target.get();

        // Get the chip target if l_target is not a chip
        TARGETING::Target* l_myChipTarget = nullptr;
        l_err = getCfamChipTarget(l_target, l_myChipTarget);
        if (l_err)
        {
            FAPI_ERR("platPutCfamRegister: getCfamChipTarget returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Can't access cfam engine on master processor
        l_err = verifyCfamAccessTarget(l_target,i_address);
        if (l_err)
        {
            FAPI_ERR("platPutCfamRegister: verifyCfamAccessTarget returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Perform CFAM write via FSI
        size_t l_size = sizeof(uint32_t);
        uint32_t l_data  = static_cast<uint32_t>(i_data);
        l_err = deviceWrite(l_myChipTarget,
                            &l_data,
                            l_size,
                            DEVICE_CFAM_ADDRESS(i_address));
        if (l_err)
        {
            FAPI_ERR("platPutCfamRegister: deviceWrite returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

    } while (0);

    if (l_rc != fapi2::FAPI2_RC_SUCCESS)
    {
        FAPI_ERR("platPutCfamRegister failed - Target %s, Addr %.8X",
                 l_targName, i_address);
    }

    if( l_traceit )
    {
        uint32_t l_data = i_data;
        FAPI_SCAN( "TRACE : PUTCFAMREG  : %s : %.8X %.8X",
                   l_targName,
                   i_address,
                   l_data);
    }

    FAPI_DBG(EXIT_MRK "platPutCfamRegister");
    return l_rc;
}

/// @brief   Modifying input 32-bit data with the specified mode
void platProcess32BitModifyMode( const ChipOpModifyMode i_modifyMode,
                                 const buffer<uint32_t> i_origDataBuf,
                                 buffer<uint32_t>& io_modifiedData )
{
    switch( i_modifyMode )
    {
            // OR operation
        case( fapi2::CHIP_OP_MODIFY_MODE_OR ):
            io_modifiedData |= i_origDataBuf;
            break;
            // AND operation
        case( fapi2::CHIP_OP_MODIFY_MODE_AND ):
            io_modifiedData &= i_origDataBuf;
            break;
            // XOR operation
        case( fapi2::CHIP_OP_MODIFY_MODE_XOR ):
            io_modifiedData ^= i_origDataBuf;
            break;

            // deliberately have no default case to catch new modes
            //  at compile time
    }
    return;
}

/// @brief   String translation for modify mode
const char* platModeString( const ChipOpModifyMode i_modifyMode )
{
    const char* l_modString = "???";
    switch( i_modifyMode )
    {
            // OR operation
        case( fapi2::CHIP_OP_MODIFY_MODE_OR ):
            l_modString = "OR";
            break;
            // AND operation
        case( fapi2::CHIP_OP_MODIFY_MODE_AND ):
            l_modString = "AND";
            break;
            // XOR operation
        case( fapi2::CHIP_OP_MODIFY_MODE_XOR ):
            l_modString = "XOR";
            break;

            // deliberately have no default case to catch new modes
            //  at compile time
    }
    return l_modString;
}

/// @brief Platform-level implementation of modifyCfamRegister()
ReturnCode platModifyCfamRegister(const Target<TARGET_TYPE_ALL>& i_target,
                                  const uint32_t i_address,
                                  const buffer<uint32_t> i_data,
                                  const ChipOpModifyMode i_modifyMode)
{
    FAPI_DBG(ENTER_MRK "platModifyCfamRegister");
    ReturnCode l_rc;
    errlHndl_t l_err = nullptr;
    bool l_traceit = platIsScanTraceEnabled();
    const char* l_modeString = platModeString(i_modifyMode);

    // Grab the name of the target
    TARGETING::ATTR_FAPI_NAME_type l_targName = {0};
    fapi2::toString(i_target, l_targName, sizeof(l_targName));

    do
    {
        // Extract the component pointer
        TARGETING::Target* l_target = i_target.get();

        // Can't access cfam engine on master processor
        l_err = verifyCfamAccessTarget(l_target,i_address);
        if (l_err)
        {
            FAPI_ERR("platModifyCfamRegister: verifyCfamAccessTarget returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Get the chip target if l_target is not a chip
        TARGETING::Target* l_myChipTarget = nullptr;
        l_err = getCfamChipTarget(l_target, l_myChipTarget);
        if (l_err)
        {
            FAPI_ERR("platModifyCfamRegister: getCfamChipTarget returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Read current value
        size_t l_size = sizeof(uint32_t);
        buffer<uint32_t> l_data = 0;
        l_err = deviceRead(l_myChipTarget,
                           &l_data(),
                           l_size,
                           DEVICE_CFAM_ADDRESS(i_address));
        if (l_err)
        {
            FAPI_ERR("platModifyCfamRegister: deviceRead returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

        // Applying modification
        platProcess32BitModifyMode(i_modifyMode, i_data, l_data);

        // Write back
        l_err = deviceWrite(l_target,
                            &l_data(),
                            l_size,
                            DEVICE_CFAM_ADDRESS(i_address));
        if (l_err)
        {
            FAPI_ERR("platModifyCfamRegister: deviceWrite returns error!");

            // Add the error log pointer as data to the ReturnCode
            addErrlPtrToReturnCode(l_rc, l_err);
            break;
        }

    } while (0);

    if (l_rc != fapi2::FAPI2_RC_SUCCESS)
    {
        FAPI_ERR("platModifyCfamRegister failed - Target %s, Addr %.8X",
                  l_targName, i_address);
    }

    if( l_traceit )
    {
        uint32_t l_data = (uint32_t)i_data;
        FAPI_SCAN( "TRACE : MODCFAMREG  : %s : %.8X %.8X %s",
                   l_targName,
                   i_address,
                   l_data,
                   l_modeString );
    }

    FAPI_DBG(EXIT_MRK "platModifyCfamRegister");
    return l_rc;
}

//--------------------------------------------------------------------------
// Operational Mode Error Functions
//--------------------------------------------------------------------------

void platSetOpMode(const OpModes i_mode)
{
    FAPI_INF("Setting fapi2::opMode to be 0x%x", i_mode);
    opMode = static_cast<OpModes>(
            static_cast<uint8_t>(opMode) | static_cast<uint8_t>(i_mode)
            );
    return;
}

OpModes platGetOpMode(void)
{
    return opMode;
}

//--------------------------------------------------------------------------
// PIB Error Mask Functions
//--------------------------------------------------------------------------

void platSetPIBErrorMask(const uint8_t i_mask)
{
    assert(i_mask <= 7, "PIB Err Mask must be between 0 and 7");
    pib_err_mask = i_mask;
    return;
}

uint8_t platGetPIBErrorMask(void)
{
    return pib_err_mask;
}

// --------------------------------------------------------------------------
// NOTE:
// No spy access interface as HB doesn't allow spy access.
// --------------------------------------------------------------------------

/**
 * @brief Determine if a given target is on the boot proc chip
 * @param[in]  i_Target   TARGETING::Target which op is being called on
 * @param[out] i_isMaster True if on boot proc chip, false if not
 * @return errlHndl_t
 */
errlHndl_t isOnBootProc(TARGETING::Target * i_target, bool & o_isBootProc)
{
    errlHndl_t l_errl = nullptr;
    assert(i_target != nullptr, "isOnBootProc:: Cannot pass nullptr target to isOnBootProc");
    TARGETING::Target* l_pBootProcChip = nullptr;
    TARGETING::Target* l_pParentProcChip = nullptr;
    TARGETING::targetService().masterProcChipTargetHandle( l_pBootProcChip );
    assert(l_pBootProcChip != nullptr, "isOnBootProc:: Unable to find the system's boot proc chip target handle");
    o_isBootProc = false;

    // Target can be a chiplet or a proc, get the parent proc in case it's a chiplet
    l_errl = getCfamChipTarget(i_target, l_pParentProcChip);
    if(l_errl == nullptr)
    {
        if(l_pBootProcChip == l_pParentProcChip)
        {
            o_isBootProc = true;
        }
    }
    return l_errl;
}

uint32_t getPlatMCGroup(const MulticastGroup i_group)
{
    assert(i_group < MCGROUP_COUNT, "getPlatMCGroup: invalid i_group");
    auto l_iterator = g_multicastGroupMap.find(i_group);
    assert(l_iterator != g_multicastGroupMap.end(),
          "getPlatMCGroup: could not find Multicast Group mapping for group %d",
          i_group);
    return l_iterator->second;
}

uint64_t getMulticastAddr(uint64_t i_addr,
                          const MulticastGroup i_group,
                          const MulticastType i_op,
                          const MulticastCoreSelect i_coreSelect)
{
    uint64_t l_resultingAddress = i_addr;
    // Set the mulitcast bit (bit 1)
    l_resultingAddress |= MULTICAST_BIT;
    // Copy in the op (bits 2, 3, 4)
    l_resultingAddress &= ~MULTICAST_OP_MASK;
    l_resultingAddress |= (i_op << MULTICAST_OP_OFFSET);
    // Copy in the group (bits 5, 6, 7)
    l_resultingAddress &= ~MULTICAST_GROUP_MASK;
    l_resultingAddress |= (getPlatMCGroup(i_group) << MULTICAST_GROUP_OFFSET);

    if(i_coreSelect != MCCORE_NONE)
    {
        // Copy in the core select (bits 16, 17, 18, 19)
        l_resultingAddress &= ~CORE_SELECT_MASK;
        l_resultingAddress |= (i_coreSelect << CORE_SELECT_OFFSET);
    }
    return l_resultingAddress;
}

bool isMulticastBitSet(const uint32_t i_scomAddr)
{
    return ((i_scomAddr & MULTICAST_BIT) >> MULTICAST_BIT_OFFSET);
}

MulticastGroup getMulticastGroup(const uint32_t i_multicastScomAddr)
{
    return static_cast<MulticastGroup>(
                ((i_multicastScomAddr & MULTICAST_GROUP_MASK) >>
                    MULTICAST_GROUP_OFFSET));
}

MulticastType getMulticastOp(const uint32_t i_multicastScomAddr)
{
    return static_cast<MulticastType>(
                ((i_multicastScomAddr & MULTICAST_OP_MASK) >>
                    MULTICAST_OP_OFFSET));
}

MulticastCoreSelect getCoreSelect(const uint32_t i_multicastScomAddr)
{
    return static_cast<MulticastCoreSelect>(
                ((i_multicastScomAddr & CORE_SELECT_MASK) >>
                    CORE_SELECT_OFFSET));
}

} // End namespace


text:
package com.tomgibara.chess;

import java.util.List;

import junit.framework.TestCase;

public class MoveTest extends TestCase {

	public void testAllMoves() {
		for (Move move : Move.allMoves()) {
			assertNotNull(move);
			assert(move.reverse().reverse() == move);
		}
	}

	public void testPossibleMoves() {
		for (Move move : Move.possibleMoves()) {
			assertTrue(move.isPossible());
		}
	}

	public void testMovesToAndFromSquare() {
		Square sqr = Square.at(File.FL_B, Rank.RK_7);
		{
			List<Move> moves = Move.possibleMovesFrom(sqr);
			assertFalse(moves.isEmpty());
			moves.forEach( m-> assertTrue(Move.possibleMovesTo(sqr).contains(m.reverse())) );
		}
		{
			List<Move> moves = Move.possibleMovesTo(sqr);
			assertFalse(moves.isEmpty());
			moves.forEach( m-> assertTrue(Move.possibleMovesFrom(sqr).contains(m.reverse())) );
		}
	}

	public void testNoKnightOverlap() {
		for (Move move : Move.possibleMoves()) {
			assertFalse( move.isPossibleFor(PieceType.KNIGHT) && move.isPossibleFor(PieceType.QUEEN) );
		}
	}

}


text:
[![Build Status](https://travis-ci.org/udzura/middleman-scrub.svg?branch=master)](https://travis-ci.org/udzura/middleman-scrub)

Scrub the invalid letters which source file contains.

## Usage

```ruby
activate :scrub
```

### Config

```
activate :scrub,
  scrub_regexp: /[あ-お]/, # To add target letters
  target_filename: /\.html$/, # To specify target files
  verbose: true # Debug
```

## License

[MIT.](https://udzura.mit-license.org/)


text:
package android.support.wearable.complications;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.LocaleSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Displays one or more ComplicationText objects in a template.
 *
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
@SuppressLint("BanParcelableUsage")
public final class ComplicationTextTemplate implements Parcelable, TimeDependentText {

    private static final String KEY_TIME_DEPENDENT_TEXTS = "KEY_TIME_DEPENDENT_TEXTS";
    private static final String KEY_SURROUNDING_STRING = "KEY_SURROUNDING_STRING";

    public static final Creator<ComplicationTextTemplate> CREATOR =
            new Creator<ComplicationTextTemplate>() {
                @Override
                @NonNull
                @SuppressLint("SyntheticAccessor")
                public ComplicationTextTemplate createFromParcel(@NonNull Parcel in) {
                    return new ComplicationTextTemplate(in);
                }

                @Override
                @NonNull
                public ComplicationTextTemplate[] newArray(int size) {
                    return new ComplicationTextTemplate[size];
                }
            };

    /**
     * The plain-text part of the complication text. See {@link Builder#setSurroundingText} for
     * details.
     */
    private final CharSequence mSurroundingText;

    /** The time-dependent parts of the complication text. */
    private final ComplicationText[] mComplicationTexts;

    ComplicationTextTemplate(
            @Nullable CharSequence surroundingText,
            @NonNull ComplicationText[] complicationTexts) {
        mSurroundingText = surroundingText;
        mComplicationTexts = complicationTexts;
        checkFields();
    }

    private ComplicationTextTemplate(@NonNull Parcel in) {
        this(in.readBundle(ComplicationTextTemplate.class.getClassLoader()));
    }

    @SuppressWarnings("deprecation")
    private ComplicationTextTemplate(@NonNull Bundle rootBundle) {
        mSurroundingText = rootBundle.getCharSequence(KEY_SURROUNDING_STRING);

        Parcelable[] texts = rootBundle.getParcelableArray(KEY_TIME_DEPENDENT_TEXTS);
        assert texts != null;
        mComplicationTexts = new ComplicationText[texts.length];
        for (int i = 0; i < texts.length; i++) {
            mComplicationTexts[i] = (ComplicationText) texts[i];
        }

        checkFields();
    }

    private static class SerializedForm implements Serializable {
        @Nullable CharSequence mSurroundingText;
        @NonNull ComplicationText[] mComplicationTexts;

        SerializedForm(
                @Nullable CharSequence surroundingText,
                @NonNull ComplicationText[] complicationTexts) {
            mSurroundingText = surroundingText;
            mComplicationTexts = complicationTexts;
        }

        private void writeObject(ObjectOutputStream oos) throws IOException {
            CharSequenceSerializableHelper.writeToStream(mSurroundingText, oos);
            oos.writeObject(mComplicationTexts);
        }

        private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
            mSurroundingText = CharSequenceSerializableHelper.readFromStream(ois);
            mComplicationTexts = (ComplicationText[]) ois.readObject();
        }

        Object readResolve() {
            return new ComplicationTextTemplate(mSurroundingText, mComplicationTexts);
        }
    }

    Object writeReplace() {
        return new SerializedForm(mSurroundingText, mComplicationTexts);
    }

    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
        throw new InvalidObjectException("Use SerializedForm");
    }

    private void checkFields() {
        if (mSurroundingText == null && mComplicationTexts.length == 0) {
            throw new IllegalStateException(
                    "One of mSurroundingText and mTimeDependentText must be non-null");
        }
    }

    @Override
    public void writeToParcel(@NonNull Parcel out, int flags) {
        Bundle bundle = new Bundle();
        bundle.putCharSequence(KEY_SURROUNDING_STRING, mSurroundingText);
        bundle.putParcelableArray(KEY_TIME_DEPENDENT_TEXTS, mComplicationTexts);
        out.writeBundle(bundle);
    }

    @NonNull
    @Override
    public CharSequence getTextAt(@NonNull Resources resources, long dateTimeMillis) {
        final int len = mComplicationTexts.length;
        if (len == 0) {
            return mSurroundingText;
        }
        CharSequence[] timeDependentParts = new CharSequence[len];
        for (int i = 0; i < len; i++) {
            timeDependentParts[i] = mComplicationTexts[i].getTextAt(resources, dateTimeMillis);
        }

        if (mSurroundingText == null) {
            return TextUtils.join(" ", timeDependentParts);
        }

        return TextUtils.expandTemplate(mSurroundingText, timeDependentParts);
    }

    @Override
    public boolean returnsSameText(long firstDateTimeMillis, long secondDateTimeMillis) {
        for (TimeDependentText text : mComplicationTexts) {
            if (!text.returnsSameText(firstDateTimeMillis, secondDateTimeMillis)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public long getNextChangeTime(long fromTime) {
        long result = Long.MAX_VALUE;
        for (TimeDependentText text : mComplicationTexts) {
            result = Math.min(result, text.getNextChangeTime(fromTime));
        }
        return result;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    /**
     * Builder for a ComplicationTextTemplate object that displays one or more {@link
     * ComplicationText} objects, within a format string if specified.
     */
    public static final class Builder {
        private CharSequence mSurroundingText;
        private final List<ComplicationText> mTexts = new ArrayList<>(2);

        /** Adds a ComplicationText to be applied to the {@link #setSurroundingText} template. */
        @NonNull
        public Builder addComplicationText(@NonNull ComplicationText text) {
            mTexts.add(text);
            return this;
        }

        /**
         * Sets the string within which the texts will be displayed. This is optional.
         *
         *
Within the text, {@code ^1} will be replaced with the first ComplicationText, {@code
         * ^2} will be replaced with the second, and so on. So for example to show a result like
         * {@code "8 of 10 minutes"} the surrounding text would be {@code "^1 of ^2 minutes"}.
         *
         *
To use the {@code ^} character within the text, escape it as {@code ^^}.
         *
         *
If not specified, the texts will be concatenated together, separated by spaces.
         *
         *
If the text contains spans, some of them may not be rendered by
         * {@link ComplicationDrawable}. Supported spans are {@link ForegroundColorSpan},
         * {@link LocaleSpan}, {@link SubscriptSpan}, {@link SuperscriptSpan}, {@link StyleSpan},
         * {@link StrikethroughSpan}, {@link TypefaceSpan} and {@link UnderlineSpan}.
         *
         * @param surroundingText string template
         * @return this builder for chaining
         */
        @NonNull
        public Builder setSurroundingText(@Nullable CharSequence surroundingText) {
            mSurroundingText = surroundingText;
            return this;
        }

        /**
         * Returns {@link ComplicationTextTemplate} including the ComplicationText objects formatted
         * as specified.
         */
        @NonNull
        @SuppressLint("SyntheticAccessor")
        public ComplicationTextTemplate build() {
            if (mTexts.isEmpty()) {
                throw new IllegalStateException("At least one text must be specified.");
            }

            return new ComplicationTextTemplate(
                    mSurroundingText, mTexts.toArray(new ComplicationText[mTexts.size()]));
        }
    }
}


text:
package cn.xdean.jex.lang.function.type;

import java.util.function.BiFunction;

@FunctionalInterface
public interface Func2<A, B, R> extends BiFunction<A, B, R> {
  R call(A a, B b);

  @Override
  default R apply(A a, B b) {
    return call(a, b);
  }
}


text:
from django.apps import AppConfig

class TprojectConfig(AppConfig):
    name = 'tproject'
    verbose_name = "项目"


text:
<?php

namespace Vicious;

class Vicious
{

	protected $router;
	protected $route;
	protected $request;
	protected $config;
	protected $before = array();

	protected $error_handler = false;
	protected $not_found_handler = false;
	protected $error_shown = false;

	protected $config_handlers = array();

	/*
   * PSR-0 autoloader
   */
	public static function autoload($class_name) {
		static $base_dir;
		if (!$base_dir) {
			$this_class = str_replace(__NAMESPACE__.'\\', '', __CLASS__);
			$base_dir = __DIR__;
			if (substr($base_dir, -strlen($this_class)) === $this_class) {
				$base_dir = substr($base_dir, 0, -strlen($this_class));
			}
		}
		$class_name = ltrim($class_name, '\\');
		$file_name  = $base_dir;
		$namespace = '';
		if ($last_pos = strripos($class_name, '\\')) {
			$namespace = substr($class_name, 0, $last_pos);
			$class_name = substr($class_name, $last_pos + 1);
			$file_name  .= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
		}
		$file_name .= $class_name . '.php';
		if (file_exists($file_name)) require $file_name;
	}

	public static function RegisterAutoloader() {
		spl_autoload_register(__NAMESPACE__ . "\\Vicious::autoload");
	}

	public static function Free() {
		require(__DIR__ . DIRECTORY_SEPARATOR . 'Free.php');
	}

	public static function Autorun() {
		$s = self::instance();
		register_shutdown_function(array($s, 'run'));
	}

	public function run() {
		try {
			$this->request = new Request(false, false, $this->config->methodoverride);
			$this->dispatch($this->request);
		} catch (\Exception $e) {
			$this->handle_error($e);
		}
	}

	public function __construct() {
		# handle errors our way
		set_error_handler(array(&$this, 'default_error_handler'));
		set_exception_handler(array(&$this, 'default_exception_handler'));

		# need a router instance
		$this->router = new Router();
		$this->config = new Config();
	}

	/**
	 * Singleton instance method
	 */
	public static function instance() {
		static $instance;
		if (!$instance) {
			$instance = new Vicious;
		}
		return $instance;
	}

	/**
	 * Dispatch is the main point of execution.
	 */
	public function dispatch($uri, $verb=false) {
		if ($uri instanceof Request) {
			if ($verb === false) $verb = $uri->method;
			$uri = $uri->uri;
		}

		if ($verb === false) $verb = $this->request->method;

		# first run configs
		$this->config_run();

		# find the right route
		$this->route = $this->router->route_for_request($verb, $uri);

		# run filters and catch output
		ob_start();
		foreach($this->before as $filter) {
			call_user_func($filter);
		}
		$filter_output = ob_get_clean();

		# exec the method
		$out = $this->route->execute($this->config->routes);

		# show the results
		if ($out != null) {
			if (is_string($out)) {
				echo $filter_output;
				echo $out;
			} else if ($out instanceof View\Renderable) {
				$out->template_dir = $this->config->templates;
				$out->send_content_type_header();
				echo $filter_output;
				$out->render();
			}
		}

	}

	public function get($pattern, $handler)			{ return $this->router->get($pattern, $handler); }
	public function put($pattern, $handler)			{ return $this->router->put($pattern, $handler); }
	public function post($pattern, $handler)		{ return $this->router->post($pattern, $handler); }
	public function delete($pattern, $handler)	{ return $this->router->delete($pattern, $handler); }

	/**
	 * Add a filter before
	 */
	public function before($handler)	{ $this->before[] = $handler; }

	/**
	 * Set a function to be called as setup depending on the environment
	 */
	public function configure($environment, $handler=false) {
		if ($handler == false) {
			$handler = $environment;
			$environment = 'ALL';
		}
		$this->config_handlers[$environment][] = $handler;
	}

	/**
	 * Run config setup
	 */
	public function config_run() {
		if (isset($this->config_handlers[$this->config->environment]) && is_array($this->config_handlers[$this->config->environment])) {
			foreach($this->config_handlers[$this->config->environment] as $handler) {
				call_user_func($handler, $this->config);
			}
		}

		if (isset($this->config_handlers['ALL']) && is_array($this->config_handlers['ALL'])) {
			foreach($this->config_handlers['ALL'] as $handler) {
				call_user_func($handler, $this->config);
			}
		}
	}

	/**
	 * Errors
	 */
	public function error($e) { $this->error_handler = $e;	}
	public function not_found($h) { $this->not_found_handler = $h;	}

	public function handle_error($e) {
		if ($this->error_shown) return;
		$this->error_shown = true;
		$logo = 'data:image/png;base64,' . base64_encode(file_get_contents(__DIR__.'/images/vicious.png'));
		if (!($e instanceof ViciousException)) $e = ViciousException::fromException($e);
		if ($e instanceof NotFound) {
			$this->status(404);
			if ($this->config->environment != Config::PRODUCTION) {
				if ($this->config->error_style == Config::JSON_ERROR_STYLE) {
					$out = json_encode(array('error' => $this->request->uri . ' Not Found'));
				} else {
					$out = "<!DOCTYPE html>
					<title>404 Not Found</title>

I dunno what you’re after.

Try this:

get('".$this->request->uri."', function() {
	return 'Hello World';
	});

					";
				}
			} else if ($this->not_found_handler) {
				$out = call_user_func($this->not_found_handler, $e);
			} else {
				# standard apache 404 page
				$out = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><title>404 Not Found</title>
Not Found

The requested URL '.$this->request->uri.' was not found on this server.
';
			}

		} else {
			$this->status(500);
			if ($this->config->environment != Config::PRODUCTION) {
				if ($this->config->error_style == Config::JSON_ERROR_STYLE) {
					$out = json_encode(array('error' => array(
						'class' 	=> substr(get_class($e), strrpos(get_class($e), "\\") + 1),
						'file' 		=> pathinfo($e->file(), PATHINFO_BASENAME) . ':' . $e->line(),
						'message' => $e->message(),
						'uri' 		=> $this->request->uri,
					)));
				} else {
					$t = $e->trace();
					$backtrace = explode("\n", $e->trace_as_string());
					array_shift($backtrace);
					foreach($backtrace as $k => $v) {
						$i = strpos($v, ':');
						$backtrace[$k] = substr_replace($v, '
  ', $i, 1);
					}
					$backtrace = join('

', $backtrace);

					$vars = array('GET' => $_GET, 'POST' => $_POST, 'SESSION' => isset($_SESSION) ? $_SESSION : array(), 'SERVER' => $_SERVER);

					# make server path prettier
					$vars['SERVER'] = str_replace(':', '
', $vars['SERVER']);

					foreach($vars as $type => $sg) {
						//$html = "";
						$html = "
$type

";
						if (empty($sg)) {
							$html .= "
No $type data.

";
						} else {
							foreach($sg as $k => $v) {
								if (is_array($v)) {
									ob_start();
									var_export($v);
									$v = nl2br(ob_get_clean());
								}
								$html .= "
$k	".wordwrap($v, 150, "
\n", true)."
";
							}
							$html .= '
';
						}
						$vars[$type] = $html;
					}

					$out = sprintf("<!DOCTYPE html>
					<title>500 Internal Server Error</title>

%s

file: %s(%s)

uri: %s

%s

BACKTRACE

%s

					%s
					%s
					%s
					%s

",
						substr(get_class($e), strrpos(get_class($e), "\\") + 1),
						pathinfo($e->file(), PATHINFO_BASENAME),
						$e->line(),
						$this->request->uri,
						$e->message(),
						$backtrace,
						$vars['GET'],
						$vars['POST'],
						$vars['SESSION'],
						$vars['SERVER']
					);
				}
			} else if ($this->error_handler) {
				$out = call_user_func($this->error_handler, $e);
			} else {
				# standard default 500 page
				$out = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><title>500 Internal Server Error</title>
Internal Server Error

Please try again later.
';
			}
		}

		if ($out != null) {
			if (is_string($out)) {
				die($out);
			} else if ($out instanceof View\Renderable) {
				$out->template_dir = $this->config->templates;
				$out->send_content_type_header();
				$out->render();
			}
		}
	}

	public function default_error_handler($errno, $errstr, $errfile, $errline) {
		if (libxml_use_internal_errors()) {
			$err = libxml_get_last_error();
			if ($err) {
				$exp = LibXMLException::fromLibXMLError($err);
				libxml_clear_errors();
				$this->default_exception_handler($exp);
				return;
			}
		}
		$this->default_exception_handler(new InvalidStatement($errstr, $errno, $errfile, $errline));
	}

	public function default_exception_handler($e) {
		$l = ob_get_level();
		while($l--) ob_end_clean();
		$this->handle_error($e);
		exit;
	}

	public function params($p=false) {
		if (!$this->route) return false;
		$params = $this->route->params();
		if ($p === false) return $params;
		if (isset($params[$p])) {
			return $params[$p];
		} else {
			return false;
		}
	}

	public function route() {
		return $this->route;
	}

	public function request() {
		return $this->request;
	}

	public function config() {
		return $this->config;
	}

	// ===========================================================
	// - RESPONSE HELPERS
	// ===========================================================
	public function status($s) {
		if (is_numeric($s))	{
			switch($s) {
				case 404:
					header("HTTP/1.0 404 Not Found");
					header("Status: 404 Not Found");
					return;

				case 500:
					header('HTTP/1.1 500 Internal Server Error');
					header("Status: 500 Internal Server Error");
					return;

				default:
					header("Status: $s");
					return;
			}
		}
	}

	public function redirect($loc=false, $code=false) {
		if ($code !== false) status($code);
		$loc = $loc ? $loc : '/';
		header("Location: $loc");
		exit();
	}

}


text:
[![npm](https://nodei.co/npm/herror.png)](https://nodei.co/npm/herror/)

# herror

[![Dependency Status][david-badge]][david]

Simple HTTP error constructor, as if this problem is still open.

[david]: https://david-dm.org/eush77/herror
[david-badge]: https://david-dm.org/eush77/herror.png

## Example

```js
var err = herror(403);

err.code
//=> 403

err.message
//=> "403 Forbidden"

err.toString()
//=> "Error: 403 Forbidden"
```

## API

### `err = herror(code)`

Make new error from HTTP status code.

## Install

```
npm install herror
```

## License

MIT