text:
template<typename T, typename... Ts>
String concatStrings(T t, Ts... ts)
{
    return t + concatStrings(ts...);
}

template<>
String concatStrings<String>(String s)
{
    return s;
}

TEST_CASE("Observable::combineLatest",
          "[Observable][Observable::combineLatest]")
{
    Array<String> values;
    OwnedArray<Observable<String>> os;
    for (int i = 0; i < 8; i++)
        os.add(new Observable<String>(Observable<String>::just(String(i) + " ")));

    IT("works with arity 1")
    {
        const auto f = concatStrings<String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1]), values);
        ReaX_RequireValues(values, "0 1 ");
    }

    IT("works with arity 2")
    {
        const auto f = concatStrings<String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2]), values);
        ReaX_RequireValues(values, "0 1 2 ");
    }

    IT("works with arity 3")
    {
        const auto f = concatStrings<String, String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2], *os[3]), values);
        ReaX_RequireValues(values, "0 1 2 3 ");
    }

    IT("works with arity 4")
    {
        const auto f = concatStrings<String, String, String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2], *os[3], *os[4]), values);
        ReaX_RequireValues(values, "0 1 2 3 4 ");
    }

    IT("works with arity 5")
    {
        const auto f = concatStrings<String, String, String, String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2], *os[3], *os[4], *os[5]), values);
        ReaX_RequireValues(values, "0 1 2 3 4 5 ");
    }

    IT("works with arity 6")
    {
        const auto f = concatStrings<String, String, String, String, String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2], *os[3], *os[4], *os[5], *os[6]), values);
        ReaX_RequireValues(values, "0 1 2 3 4 5 6 ");
    }

    IT("works with arity 7")
    {
        const auto f = concatStrings<String, String, String, String, String, String, String, String>;
        ReaX_CollectValues(os[0]->combineLatest(f, *os[1], *os[2], *os[3], *os[4], *os[5], *os[6], *os[7]), values);
        ReaX_RequireValues(values, "0 1 2 3 4 5 6 7 ");
    }

    IT("combines elements into a tuple when no function is given")
    {
        auto o1 = Observable<bool>::just(true);
        auto o2 = Observable<String>::from({ "Hello", "World" });
        auto o3 = Observable<long long>::range(4, 6);
        auto combined = o1.combineLatest(o2, o3);
        static_assert(std::is_same<decltype(combined), Observable<std::tuple<bool, String, long long>>>::value, "Combined Observable has wrong type.");

        Array<std::tuple<bool, String, int>> values;
        ReaX_CollectValues(combined, values);

        CHECK(values.size() == 3);

        ReaX_RequireValues(values,
                         std::make_tuple(true, "World", 4),
                         std::make_tuple(true, "World", 5),
                         std::make_tuple(true, "World", 6));
    }
}

TEST_CASE("Observable::concat",
          "[Observable][Observable::concat]")
{
    Array<var> values;

    IT("concatenates the values emitted by the source Observables")
    {
        auto observable = Observable<var>::from({ "Hello", "World" });
        auto another = Observable<var>::from({ 1.5, 2.32, 5.6 });
        ReaX_CollectValues(observable.concat({another}), values);

        ReaX_RequireValues(values, var("Hello"), var("World"), var(1.5), var(2.32), var(5.6));
    }
}

TEST_CASE("Observable::distinctUntilChanged",
          "[Observable][Observable::distinctUntilChanged]")
{
    IT("doesn't emit consecutive duplicate integers")
    {
        Array<var> originalValues;
        Array<var> filteredValues;
        PublishSubject<var> subject;

        ReaX_CollectValues(subject, originalValues);
        ReaX_CollectValues(subject.distinctUntilChanged(), filteredValues);

        subject.onNext(3);
        subject.onNext(3);
        subject.onNext("3"); // Is equal to 3, due to how juce::var defines operator==
        subject.onNext(3);
        subject.onNext(3);
        subject.onNext(5);
        subject.onNext(3);

        ReaX_RequireValues(originalValues, var(3), var(3), var("3"), var(3), var(3), var(5), var(3));
        ReaX_RequireValues(filteredValues, var(3), var(5), var(3));
    }

    IT("doesn't emit consecutive duplicate Point<int>s")
    {
        Array<Point<int>> values;
        PublishSubject<Point<int>> subject;

        // Declare Point<int> as the type parameter, to use Point<int>::operator== for comparison:
        ReaX_CollectValues(subject.distinctUntilChanged(), values);

        subject.onNext(Point<int>(27, 12));
        subject.onNext(Point<int>(27, 12));
        subject.onNext(Point<int>(27, 14));

        ReaX_RequireValues(values, Point<int>(27, 12), Point<int>(27, 14));
    }
}

TEST_CASE("Observable::elementAt",
          "[Observable][Observable::elementAt]")
{
    auto observable = Observable<float>::from({ 17.4, 3.0, 1.5, 6.77 });
    Array<double> values;

    IT("emits only the value at the given index")
    {
        ReaX_CollectValues(observable.elementAt(2), values);

        ReaX_RequireValues(values, 1.5);
    }
}

TEST_CASE("Observable::filter",
          "[Observable][Observable::filter]")
{
    IT("filters ints")
    {
        Array<int> values;
        auto source = Observable<int>::range(4, 9, 1);
        auto filtered = source.filter([](int i) {
            return (i % 2 == 0);
        });
        ReaX_CollectValues(filtered, values);

        ReaX_RequireValues(values, 4, 6, 8);
    }

    IT("filters Strings")
    {
        Array<String> values;
        auto source = Observable<String>::from({ "Hello", "Great", "World", "Hey" });
        auto filtered = source.filter([](String s) {
            return s[0] == 'H';
        });
        ReaX_CollectValues(filtered, values);

        ReaX_RequireValues(values, "Hello", "Hey");
    }

    IT("filters an Observable which emits different types")
    {
        Array<var> values;
        auto source = Observable<var>::from({ 3, "Hello", 5.43 });
        auto filtered = source.filter([](var v) {
            return v.isDouble();
        });
        ReaX_CollectValues(filtered, values);

        ReaX_RequireValues(values, 5.43);
    }

    IT("works with std::bind")
    {
        Array<int> values;
        auto source = Observable<int>::range(14, 19);

        struct Test
        {
            bool test(int value) { return value < 17; }
        };

        Test t;
        auto predicate = std::bind(&Test::test, &t, std::placeholders::_1);
        auto filtered = source.filter(predicate);

        ReaX_CollectValues(filtered, values);
        ReaX_RequireValues(values, 14, 15, 16);
    }
}

TEST_CASE("Observable::flatMap",
          "[Observable][Observable::flatMap]")
{
    Array<String> values;

    IT("merges the values emitted by the returned Observables")
    {
        auto o = Observable<String>::from({ "Hello", "World" }).flatMap([](String s) {
            return Observable<String>::from({ s.toLowerCase(), s.toUpperCase() + "!" });
        });
        ReaX_CollectValues(o, values);

        ReaX_RequireValues(values, "hello", "HELLO!", "world", "WORLD!");
    }
}

TEST_CASE("Observable::map",
          "[Observable][Observable::map]")
{
    Array<long long> values;
    auto source = Observable<long>::range(4, 7, 2);

    IT("emits values synchronously")
    {
        auto mapped = source.map([](long l) { return l * 1.5; });
        ReaX_CollectValues(mapped, values);

        ReaX_RequireValues(values, 6.0, 9.0, 10.5);
    }
}

TEST_CASE("Interaction between Observable::map and Observable::switchOnNext",
          "[Observable][Observable::map][Observable::switchOnNext]")
{
    IT("supports returning Observables in map, even nested twice")
    {
        Array<String> values;
        auto source = Observable<int>::just(1);
        auto nested = source.map([](int i) {
            return Observable<String>::just("Hello").map([i](String s) {
                return Observable<var>::just(String(i) + " " + s);
            });
        });

        // Unwrap twice
        auto unwrapped = nested.switchOnNext().switchOnNext();
        ReaX_CollectValues(unwrapped, values);

        ReaX_RequireValues(values, "1 Hello");
    }

    IT("continues to emit values after the source Observable is gone")
    {
        Array<int> values;
        auto source = std::make_shared<Observable<int>>(Observable<int>::just(17));
        auto mapped = source->map([](int next) {
            return Observable<int>::create([next](Observer<int> observer) {
                MessageManager::getInstance()->callAsync([observer, next]() {
                    observer.onNext(next * 3);
                });
            });
        });
        auto unwrapped = mapped.switchOnNext();
        ReaX_CollectValues(unwrapped, values);

        // There should be no values before running dispatch loop
        CHECK(values.isEmpty());

        source.reset();
        ReaX_RunDispatchLoopUntil(!values.isEmpty());

        // The value should be emitted, although there's no reference to the source anymore
        ReaX_RequireValues(values, 17 * 3);
    }
}

TEST_CASE("Observable::merge",
          "[Observable][Observable::merge]")
{
    Array<int> values;

    IT("works with arity 8")
    {
        Array<Observable<int>> os;

        for (int i = 0; i < 8; ++i)
            os.add(Observable<int>::range(-i, 1));

        auto merged = os[0].merge({os[1], os[2], os[3], os[4], os[5], os[6], os[7]});
        ReaX_CollectValues(merged, values);

        CHECK(values.size() == 44);
        ReaX_RequireValues(values, 0, 1, -1, 0, 1, -2, -1, 0, 1, -3, -2, -1, 0, 1, -4, -3, -2, -1, 0, 1, -5, -4, -3, -2, -1, 0, 1, -6, -5, -4, -3, -2, -1, 0, 1, -7, -6, -5, -4, -3, -2, -1, 0, 1);
    }
}

TEST_CASE("Observable::reduce",
          "[Observable][Observable::reduce]")
{
    Array<int> values;

    IT("reduces emitted values")
    {
        auto observable = Observable<int>::from({ 10, 100, 1000 }).reduce(2, [](int accum, int next) {
            return accum + next;
        });

        ReaX_CollectValues(observable, values);

        ReaX_RequireValues(values, 1112);
    }
}

TEST_CASE("Observable::scan",
          "[Observable][Observable::scan]")
{
    Array<int> values;

    IT("applies the function to the inputs")
    {
        auto o = Observable<int>::range(1, 5).scan(10, [](int accum, int currentValue) {
            return accum + currentValue;
        });
        ReaX_CollectValues(o, values);

        ReaX_RequireValues(values, 11, 13, 16, 20, 25);
    }
}

TEST_CASE("Observable::skip",
          "[Observable][Observable::skip]")
{
    Array<int> values;

    IT("skips the first 4 values")
    {
        auto o = Observable<int>::from({ 4, 7, 2, 1, 19, 1, 33, 4 }).skip(4);
        ReaX_CollectValues(o, values);

        ReaX_RequireValues(values, 19, 1, 33, 4);
    }
}

TEST_CASE("Observable::skipUntil",
          "[Observable][Observable::skipUntil]")
{
    Array<String> values;

    IT("skips until another Observable emits a value")
    {
        PublishSubject<String> subject;
        PublishSubject<var> trigger;

        ReaX_CollectValues(subject.skipUntil(trigger), values);

        // Emit some values, these should NOT be received
        subject.onNext("Not");
        subject.onNext("Getting");
        subject.onNext("This");

        // Trigger
        trigger.onNext(var::undefined());

        // Emit more values, these should be received
        subject.onNext("These");
        subject.onNext("Are");
        subject.onNext("Received");

        ReaX_RequireValues(values, "These", "Are", "Received");
    }
}

TEST_CASE("Observable::startWith",
          "[Observable][Observable::startWith]")
{
    Array<int> values;
    auto observable = Observable<int>::from({ 17, 3 });

    IT("prepends values to an existing Observable")
    {
        ReaX_CollectValues(observable.startWith({6, 4, 7, 2}), values);

        ReaX_RequireValues(values, 6, 4, 7, 2, 17, 3);
    }
}

TEST_CASE("Observable::takeLast",
          "[Observable][Observable::takeLast]")
{
    Array<String> values;
    auto observable = Observable<String>::from({ "First", "Another", "And one more", "Last value" });

    IT("takes the last 2 emitted values")
    {
        ReaX_CollectValues(observable.takeLast(2), values);

        ReaX_RequireValues(values, "And one more", "Last value");
    }
}

TEST_CASE("Observable::takeUntil",
          "[Observable][Observable::takeUntil]")
{
    Array<String> values;

    IT("emits until another Observable emits a value")
    {
        PublishSubject<String> subject;
        PublishSubject<String> trigger;

        ReaX_CollectValues(subject.takeUntil(trigger), values);

        // Emit some values, these should be received
        subject.onNext("These");
        subject.onNext("Are");
        subject.onNext("Received");

        // Trigger
        trigger.onNext("Hey stop!");

        // Emit more values, these should NOT be received
        subject.onNext("Not");
        subject.onNext("Getting");
        subject.onNext("This");

        ReaX_RequireValues(values, "These", "Are", "Received");
    }
}

TEST_CASE("Observable::takeWhile",
          "[Observable][Observable::takeWhile]")
{
    Array<int> values;

    IT("emits values as long as the predicate returns true")
    {
        PublishSubject<int> subject;
        const auto predicate = [](int i) {
            return i <= 10;
        };

        ReaX_CollectValues(subject.takeWhile(predicate), values);

        // These should be emitted
        subject.onNext(4);
        subject.onNext(7);
        subject.onNext(10);

        // These shouldn't be emitted, because predicate(11) == false
        subject.onNext(11);
        subject.onNext(3);
        subject.onNext(7);

        ReaX_RequireValues(values, 4, 7, 10);
    }
}

TEST_CASE("Observable::withLatestFrom",
          "[Observable][Observable::withLatestFrom]")
{
    Array<String> values;
    PublishSubject<String> s1;
    PublishSubject<String> s2;

    IT("only emits when the first Observable emits")
    {
        const auto f = concatStrings<String, String>;
        ReaX_CollectValues(s1.withLatestFrom(f, s2), values);
        CHECK(values.isEmpty());
        s2.onNext("World!");
        CHECK(values.isEmpty());
        s1.onNext("Hello ");

        ReaX_RequireValues(values, "Hello World!");
    }
}

TEST_CASE("Observable::zip",
          "[Observable][Observable::zip]")
{
    Array<String> values;

    IT("zips three Observables together")
    {
        PublishSubject<String> strings;
        PublishSubject<int> ints;
        PublishSubject<double> doubles;
        const auto combine = [](String s, int i, double d) {
            return "s=" + s + "; i=" + String(i) + "; d=" + String(d);
        };

        ReaX_CollectValues(strings.zip(combine, ints, doubles), values);

        // First value should be emitted when all three Observables have emitted once
        strings.onNext("a");
        CHECK(values.isEmpty());
        ints.onNext(1);
        CHECK(values.isEmpty());
        doubles.onNext(0.1);
        ReaX_CheckValues(values, "s=a; i=1; d=0.1");

        // Second value should be emitted when all three Observables have emitted twice
        doubles.onNext(0.25);
        CHECK(values.size() == 1);
        ints.onNext(57);
        CHECK(values.size() == 1);
        strings.onNext("x");
        ReaX_RequireValues(values, "s=a; i=1; d=0.1", "s=x; i=57; d=0.25");
    }
}


text:
[Castiel](http://va.mu/cUmX) was written to rescue me from hell every time I have to write any kind
of script that must deal with dates and times to be parsed on command line.

It is common to me to write summarization daemons that must accept command lines like:

`sales-count yesterday`

or

`hit-count yesterday today 11..17`

## Installation

Add this line to your application's Gemfile:

    gem 'castiel'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install castiel

## Usage

````ruby
Castiel.parse 'yesterday today 1977-04-13'
# => [2013-04-21 00:00:00 -0300, 2013-04-22 00:00:00 -0300, 1977-04-13 00:00:00 -0300]
````

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

SDFset


text:
package com.huawei.esdk.fusionmanager.local.model.vm;

import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;

/**
 *
 * 删除虚拟机模板返回信息。
 * <p>
 * @since eSDK Cloud V100R003C30
 */
public class DeleteVMTemplateResp extends FMSDKResponse
{

}


text:
package order

import (
	"fmt"
)

// HigherLowerError represents an error for values (a & b) where a cannot be lower than b
type HigherLowerError struct {
	higher, lower float64
}

func (e *HigherLowerError) Error() string {
	return fmt.Sprintf("%f - cannot be lower than %f", e.higher, e.lower)
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_add_52b.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-52b.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

/* bad function declaration */
void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_badSink(unsigned int data);

void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52b_badSink(unsigned int data)
{
    CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_goodG2BSink(unsigned int data);

void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52b_goodG2BSink(unsigned int data)
{
    CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_goodG2BSink(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_goodB2GSink(unsigned int data);

void CWE190_Integer_Overflow__unsigned_int_fscanf_add_52b_goodB2GSink(unsigned int data)
{
    CWE190_Integer_Overflow__unsigned_int_fscanf_add_52c_goodB2GSink(data);
}

#endif /* OMITGOOD */


text:
Marshal and unmarshal request/response, so that it can be persisted or replayed any time.

## Usage

```go
package main

import (
    "io/ioutil"
    "github.com/ddliu/go-httpreplay"
)

func main() {
    resp, err := http.Get("http://google.com/")

    // marshal and cache the response
    data, err := httpreplay.Marshal(resp)
    ioutil.WriteFile("/tmp/cache.data", data, 0777)

    // unmarshal the response
    data, err := ioutil.ReadFile("/tmp/cache.data")
    resp, err := httpreplay.Unmarshal(data)
}
```


text:
@interface CordovaBoilerPlatePlugin : CDVPlugin

- (void)pluginInitialize;
- (void)doSomethingNoArgs:(CDVInvokedUrlCommand*)command;
- (void)doSomethingOneArg:(CDVInvokedUrlCommand*)command;
- (void)doSomethingMultipleArgs:(CDVInvokedUrlCommand*)command;

@end


text:
package client

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/chzyer/flow"
	"github.com/chzyer/logex"
)

type Config struct {
	Debug      bool
	DebugStack bool `default:"true"`
	DebugFlow  bool

	DevId     int
	UserName  string
	Password  string
	AesKey    string `name:"key"`
	RouteFile string `default:"routes.conf"`
	Pprof     string `default:":10060"`

	Sock string `desc:"unixsock for interactive with" default:"/tmp/next.sock"`

	Host2 string `name:"host"`
	Host  string `type:"[0]"`
}

func (c *Config) GetHostName() string {
	u, err := url.Parse(c.Host)
	if err != nil {
		panic(err)
	}
	idx := strings.Index(u.Host, ":")
	if idx > 0 {
		u.Host = u.Host[:idx]
	}
	return u.Host
}

func FixHost(host string) string {
	if !strings.Contains(host, ":") {
		host += ":11311"
	}
	if !strings.HasPrefix(host, "http") {
		host = "http://" + host
	}
	return host
}

func (c *Config) FlaglyVerify() error {
	if c.Host == "" {
		c.Host = c.Host2
	}
	if c.Host == "" {
		return fmt.Errorf("host is empty")
	}
	c.Host = FixHost(c.Host)

	if c.AesKey == "" {
		return fmt.Errorf("aeskey is required")
	}
	if c.UserName == "" {
		return fmt.Errorf("username is missing")
	}
	if c.Password == "" {
		return fmt.Errorf("password is missing")
	}

	flow.DefaultDebug = c.DebugFlow
	logex.ShowCode = c.DebugStack
	return nil
}

func (c *Config) FlaglyHandle(f *flow.Flow) error {
	New(c, f).Run()
	return nil
}

func (c *Config) FlaglyDesc() string {
	return "client mode"
}


text:
DECLARE_bool(force);
DECLARE_int64(timeout_ms);
DECLARE_string(columns);

using kudu::master::ConnectToMasterRequestPB;
using kudu::master::ConnectToMasterResponsePB;
using kudu::master::ListMastersRequestPB;
using kudu::master::ListMastersResponsePB;
using kudu::master::Master;
using kudu::master::MasterServiceProxy;
using kudu::master::MasterServiceProxy;
using kudu::master::ResetAuthzCacheRequestPB;
using kudu::master::ResetAuthzCacheResponsePB;
using kudu::rpc::RpcController;
using std::cout;
using std::map;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;

namespace kudu {
namespace tools {
namespace {

const char* const kMasterAddressArg = "master_address";
const char* const kMasterAddressDesc = "Address of a Kudu Master of form "
    "'hostname:port'. Port may be omitted if the Master is bound to the "
    "default port.";
const char* const kFlagArg = "flag";
const char* const kValueArg = "value";

Status MasterGetFlags(const RunnerContext& context) {
  const string& address = FindOrDie(context.required_args, kMasterAddressArg);
  return PrintServerFlags(address, Master::kDefaultPort);
}

Status MasterSetFlag(const RunnerContext& context) {
  const string& address = FindOrDie(context.required_args, kMasterAddressArg);
  const string& flag = FindOrDie(context.required_args, kFlagArg);
  const string& value = FindOrDie(context.required_args, kValueArg);
  return SetServerFlag(address, Master::kDefaultPort, flag, value);
}

Status MasterStatus(const RunnerContext& context) {
  const string& address = FindOrDie(context.required_args, kMasterAddressArg);
  return PrintServerStatus(address, Master::kDefaultPort);
}

Status MasterTimestamp(const RunnerContext& context) {
  const string& address = FindOrDie(context.required_args, kMasterAddressArg);
  return PrintServerTimestamp(address, Master::kDefaultPort);
}

Status ListMasters(const RunnerContext& context) {
  LeaderMasterProxy proxy;
  RETURN_NOT_OK(proxy.Init(context));

  ListMastersRequestPB req;
  ListMastersResponsePB resp;

  proxy.SyncRpc<ListMastersRequestPB, ListMastersResponsePB>(
      req, &resp, "ListMasters", &MasterServiceProxy::ListMastersAsync);

  if (resp.has_error()) {
    return StatusFromPB(resp.error().status());
  }

  DataTable table({});

  vector<ServerEntryPB> masters;
  std::copy_if(resp.masters().begin(), resp.masters().end(), std::back_inserter(masters),
               [](const ServerEntryPB& master) {
                 if (master.has_error()) {
                   LOG(WARNING) << "Failed to retrieve info for master: "
                                << StatusFromPB(master.error()).ToString();
                   return false;
                 }
                 return true;
               });

  auto hostport_to_string = [] (const HostPortPB& hostport) {
    return Substitute("$0:$1", hostport.host(), hostport.port());
  };

  for (const auto& column : strings::Split(FLAGS_columns, ",", strings::SkipEmpty())) {
    vector<string> values;
    if (boost::iequals(column, "uuid")) {
      for (const auto& master : masters) {
        values.push_back(master.instance_id().permanent_uuid());
      }
    } else if (boost::iequals(column, "seqno")) {
      for (const auto& master : masters) {
        values.push_back(std::to_string(master.instance_id().instance_seqno()));
      }
    } else if (boost::iequals(column, "rpc-addresses") ||
               boost::iequals(column, "rpc_addresses")) {
      for (const auto& master : masters) {
        values.push_back(JoinMapped(master.registration().rpc_addresses(),
                         hostport_to_string, ","));
      }
    } else if (boost::iequals(column, "http-addresses") ||
               boost::iequals(column, "http_addresses")) {
      for (const auto& master : masters) {
        values.push_back(JoinMapped(master.registration().http_addresses(),
                                    hostport_to_string, ","));
      }
    } else if (boost::iequals(column, "version")) {
      for (const auto& master : masters) {
        values.push_back(master.registration().software_version());
      }
    } else if (boost::iequals(column, "start_time")) {
      for (const auto& master : masters) {
        values.emplace_back(StartTimeToString(master.registration()));
      }
    }else if (boost::iequals(column, "role")) {
    for (const auto& master : masters) {
        std::string master_role = "";
        switch(master.role()){
            case RaftPeerPB_Role::RaftPeerPB_Role_UNKNOWN_ROLE:
                master_role="unknowrole";
            case RaftPeerPB_Role::RaftPeerPB_Role_FOLLOWER:
                master_role="follower";
            case RaftPeerPB_Role::RaftPeerPB_Role_LEADER:
                master_role="leader";
            case RaftPeerPB_Role::RaftPeerPB_Role_LEARNER:
                master_role="learner";
            case RaftPeerPB_Role::RaftPeerPB_Role_NON_PARTICIPANT:
                master_role="nonparticipant";
            default:
                master_role="unknowrole";
            }
        values.push_back(master_role);
        }
      } else {
      return Status::InvalidArgument("unknown column (--columns)", column);
    }
    table.AddColumn(column.ToString(), std::move(values));
  }

  RETURN_NOT_OK(table.PrintTo(cout));
  return Status::OK();
}

Status MasterDumpMemTrackers(const RunnerContext& context) {
  const auto& address = FindOrDie(context.required_args, kMasterAddressArg);
  return DumpMemTrackers(address, Master::kDefaultPort);
}

// Make sure the list of master addresses specified in 'master_addresses'
// corresponds to the actual list of masters addresses in the cluster,
// as reported in ConnectToMasterResponsePB::master_addrs.
Status VerifyMasterAddressList(const vector<string>& master_addresses) {
  map<string, set<string>> addresses_per_master;
  for (const auto& address : master_addresses) {
    unique_ptr<MasterServiceProxy> proxy;
    RETURN_NOT_OK(BuildProxy(address, Master::kDefaultPort, &proxy));

    RpcController ctl;
    ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms));
    ConnectToMasterRequestPB req;
    ConnectToMasterResponsePB resp;
    RETURN_NOT_OK(proxy->ConnectToMaster(req, &resp, &ctl));
    const auto& resp_master_addrs = resp.master_addrs();
    if (resp_master_addrs.size() != master_addresses.size()) {
      const auto addresses_provided = JoinStrings(master_addresses, ",");
      const auto addresses_cluster_config = JoinMapped(
          resp_master_addrs,
          [](const HostPortPB& pb) {
            return Substitute("$0:$1", pb.host(), pb.port());
          }, ",");
      return Status::InvalidArgument(Substitute(
          "list of master addresses provided ($0) "
          "does not match the actual cluster configuration ($1) ",
          addresses_provided, addresses_cluster_config));
    }
    set<string> addr_set;
    for (const auto& hp : resp_master_addrs) {
      addr_set.emplace(Substitute("$0:$1", hp.host(), hp.port()));
    }
    addresses_per_master.emplace(address, std::move(addr_set));
  }

  bool mismatch = false;
  if (addresses_per_master.size() > 1) {
    const auto it_0 = addresses_per_master.cbegin();
    auto it_1 = addresses_per_master.begin();
    ++it_1;
    for (auto it = it_1; it != addresses_per_master.end(); ++it) {
      if (it->second != it_0->second) {
        mismatch = true;
        break;
      }
    }
  }

  if (mismatch) {
    string err_msg = Substitute("specified: ($0);",
                                JoinStrings(master_addresses, ","));
    for (const auto& e : addresses_per_master) {
      err_msg += Substitute(" from master $0: ($1);",
                            e.first, JoinStrings(e.second, ","));
    }
    return Status::ConfigurationError(
        Substitute("master address lists mismatch: $0", err_msg));
  }

  return Status::OK();
}

Status ResetAuthzCacheAtMaster(const string& master_address) {
  unique_ptr<MasterServiceProxy> proxy;
  RETURN_NOT_OK(BuildProxy(master_address, Master::kDefaultPort, &proxy));

  RpcController ctl;
  ctl.set_timeout(MonoDelta::FromMilliseconds(FLAGS_timeout_ms));

  ResetAuthzCacheRequestPB req;
  ResetAuthzCacheResponsePB resp;
  RETURN_NOT_OK(proxy->ResetAuthzCache(req, &resp, &ctl));
  if (resp.has_error()) {
    return StatusFromPB(resp.error().status());
  }
  return Status::OK();
}

Status ResetAuthzCache(const RunnerContext& context) {
  const string& master_addresses_str =
      FindOrDie(context.required_args, kMasterAddressesArg);
  const vector<string>& master_addresses =
      strings::Split(master_addresses_str, ",");

  if (!FLAGS_force) {
    // Make sure the list of master addresses specified for the command
    // matches the actual list of masters in the cluster.
    RETURN_NOT_OK(VerifyMasterAddressList(master_addresses));
  }

  // It makes sense to reset privileges cache at every master in the cluster.
  // Otherwise, SentryAuthzProvider might return inconsistent results for authz
  // requests upon master leadership change.
  vector<Status> statuses;
  statuses.reserve(master_addresses.size());
  for (const auto& address : master_addresses) {
    auto status = ResetAuthzCacheAtMaster(address);
    statuses.emplace_back(std::move(status));
  }
  DCHECK_EQ(master_addresses.size(), statuses.size());
  string err_str;
  for (auto i = 0; i < statuses.size(); ++i) {
    const auto& s = statuses[i];
    if (s.ok()) {
      continue;
    }
    err_str += Substitute(" error from master at $0: $1",
                          master_addresses[i], s.ToString());
  }
  if (err_str.empty()) {
    return Status::OK();
  }
  return Status::Incomplete(err_str);
}

} // anonymous namespace

unique_ptr<Mode> BuildMasterMode() {
  ModeBuilder builder("master");
  builder.Description("Operate on a Kudu Master");

  {
    unique_ptr<Action> action_reset =
        ActionBuilder("reset", &ResetAuthzCache)
        .Description("Reset the privileges cache")
        .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
        .AddOptionalParameter(
            "force",
            boost::none,
            string("Ignore mismatches of the specified and the actual lists "
                   "of master addresses in the cluster"))
        .Build();

    unique_ptr<Mode> mode_authz_cache = ModeBuilder("authz_cache")
        .Description("Operate on the authz cache of a Kudu Master")
        .AddAction(std::move(action_reset))
        .Build();
    builder.AddMode(std::move(mode_authz_cache));
  }
  {
    unique_ptr<Action> dump_memtrackers =
        ActionBuilder("dump_memtrackers", &MasterDumpMemTrackers)
        .Description("Dump the memtrackers from a Kudu Master")
        .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc })
        .AddOptionalParameter("format")
        .AddOptionalParameter("memtracker_output")
        .AddOptionalParameter("timeout_ms")
        .Build();
    builder.AddAction(std::move(dump_memtrackers));
  }
  {
    unique_ptr<Action> get_flags =
        ActionBuilder("get_flags", &MasterGetFlags)
        .Description("Get the gflags for a Kudu Master")
        .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc })
        .AddOptionalParameter("all_flags")
        .AddOptionalParameter("flag_tags")
        .Build();
    builder.AddAction(std::move(get_flags));
  }
  {
    unique_ptr<Action> set_flag =
        ActionBuilder("set_flag", &MasterSetFlag)
        .Description("Change a gflag value on a Kudu Master")
        .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc })
        .AddRequiredParameter({ kFlagArg, "Name of the gflag" })
        .AddRequiredParameter({ kValueArg, "New value for the gflag" })
        .AddOptionalParameter("force")
        .Build();
    builder.AddAction(std::move(set_flag));
  }
  {
    unique_ptr<Action> status =
        ActionBuilder("status", &MasterStatus)
        .Description("Get the status of a Kudu Master")
        .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc })
        .Build();
    builder.AddAction(std::move(status));
  }
  {
    unique_ptr<Action> timestamp =
        ActionBuilder("timestamp", &MasterTimestamp)
        .Description("Get the current timestamp of a Kudu Master")
        .AddRequiredParameter({ kMasterAddressArg, kMasterAddressDesc })
        .Build();
    builder.AddAction(std::move(timestamp));
  }
  {
    unique_ptr<Action> list_masters =
        ActionBuilder("list", &ListMasters)
        .Description("List masters in a Kudu cluster")
        .AddRequiredParameter({ kMasterAddressesArg, kMasterAddressesArgDesc })
        .AddOptionalParameter(
            "columns",
            string("uuid,rpc-addresses"),
            string("Comma-separated list of master info fields to "
                   "include in output.\nPossible values: uuid, "
                   "rpc-addresses, http-addresses, version, seqno "
                   "and start_time"))
        .AddOptionalParameter("format")
        .AddOptionalParameter("timeout_ms")
        .Build();
    builder.AddAction(std::move(list_masters));
  }

  return builder.Build();
}

} // namespace tools
} // namespace kudu


text:
<!doctype html>

  <meta charset="utf-8">

<title>Markdown Features Test · Nice Day</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="description" content="Indented Code Blocks">

<link rel="alternate" href="/feed.xml" type="application/atom+xml">

  <link rel="icon" href="/favicon.ico">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">

<link rel="mask-icon" href="/favicon.svg" color="#ff00b4">

<link rel="stylesheet" href="/assets/themes/curtana/css/app.css?assets-inline">

<link rel="canonical" href="http:www.niceday.me/markdown-features-test.html">

<meta property="og:type" content="article">
<meta property="og:site_name" content="Nice Day">
<meta property="og:title" content="Markdown Features Test">
<meta property="og:url" content="http:www.niceday.me/markdown-features-test.html">
<meta property="og:description" content="Indented Code Blocks">

<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Markdown Features Test">
<meta name="twitter:url" content="http:www.niceday.me/markdown-features-test.html">
<meta name="twitter:description" content="Indented Code Blocks">

  <meta property="article:published_time" content="2014-06-06T00:00:00-07:00">
  <meta property="article:modified_time" content="1969-12-31T16:00:00-08:00">

  <meta name="twitter:label1" value="Words">
  <meta name="twitter:data1" value="430 words">
  <meta name="twitter:label2" value="Reading time">
  <meta name="twitter:data2" value="2 mins">

  <meta name="twitter:site" content="@sparanoid">

            Nice Day

            Work

            Note

            Life

    Markdown Features Test

        By Day
        on <time datetime="2014-06-06T00:00:00-07:00">Jun 6, 2014</time>

Indented Code Blocks

def show
  @widget = Widget(params[:id])
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @widget }
  end
end

Liquid Tag with linenos Support

1
2
3
4
5
6
7

def show
  @widget = Widget(params[:id])
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @widget }
  end
end

GFM Code Blocks (fenced_code_blocks)

/* Background color function */
.code-bg (@v) when (lightness(@v) >= 50%) {
  @return-bg: mix(#000, lighten(@v, 30%), 10%);
}
.code-bg (@v) when (lightness(@v) < 50%) {
  @return-bg: mix(#fff, darken(@v, 10%), 70%);
}

SmartyPants

"Aha! What's up, man?" – Jony said.

Tables

      Name
      Upvotes
      Downvotes
      Abstentions

      Alice
      10
      11
      2

      Bob
      4
      3
      1

      Charlie
      7
      9
      4

      Totals
      21
      23
      7

Intra-emphasis

foo_bar_baz

Auto-link

http://sparanoid.com/

Strikethroughs

This is good bad.

Space after Headers

###This is not a header.

Superscripts

This is the 2^(nd) time.

Footnotes

This1 is2 a sentence3.

ID 日本語タイトル

Expected id should be id-ri-ben-yu-taitoru.

ID 中文標題

Expected id should be id-zhong-wen-biao-ti.

Lorem lean startup ipsum product market fit customer development acquihire technical cofounder. User engagement A/B testing shrink a market venture capital pitch deck. Social bookmarking group buying crowded market pivot onboarding freemium prototype ping pong. Early stage disruptive ecosystem community outreach dynamic location based strategic investor. ↩

An Important Announcement by Richard Ziade at Readability ↩

Good afterble constanoon, this sweet hongi is as bung as a stuffed morepork. Mean while, in the marae, Dr Ropata and Hairy Maclary from Donaldson's Dairy were up to no good with a bunch of bloody troties. ↩

Nice Day

github

Email

Weibo


text:
<?php

namespace SM\Factory;

use SM\SMException;
use SM\StateMachine\StateMachineInterface;

abstract class AbstractFactory implements ClearableFactoryInterface
{
    /** @var array */
    protected $configs = [];

    /** @var StateMachineInterface[] */
    protected $stateMachines = [];

    /**
     * @param array $configs Array of configs for the available state machines
     *
     * @throws SMException
     */
    public function __construct(array $configs)
    {
        foreach ($configs as $graph => $config) {
            $this->addConfig($config, $graph);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function get($object, string $graph = 'default'): StateMachineInterface
    {
        $hash = spl_object_hash($object);

        if (isset($this->stateMachines[$hash][$graph])) {
            return $this->stateMachines[$hash][$graph];
        }

        foreach ($this->configs as $config) {
            if ($config['graph'] === $graph && $object instanceof $config['class']) {
                return $this->stateMachines[$hash][$graph] = $this->createStateMachine($object, $config);
            }
        }

        throw new SMException(sprintf(
            'Cannot create a state machine because the configuration for object "%s" with graph "%s" does not exist.',
            get_class($object),
            $graph
        ));
    }

    /**
     * {@inheritDoc}
     */
    public function clear(): void
    {
        $this->stateMachines = array();
    }

    /**
     * Adds a new config
     *
     * @param array  $config
     * @param string $graph
     *
     * @throws SMException If the index "class" is not configured
     */
    public function addConfig(array $config, string $graph = 'default'): void
    {
        if (!isset($config['graph'])) {
            $config['graph'] = $graph;
        }

        if (!isset($config['class'])) {
            throw new SMException(sprintf(
               'Index "class" needed for the state machine configuration of graph "%s"',
                $config['graph']
            ));
        }

        $this->configs[] = $config;
    }

    /**
     * Create a state machine for the given object and config
     *
     * @param       $object
     * @param array $config
     *
     * @return StateMachineInterface
     *
     * @throws SMException
     */
    abstract protected function createStateMachine($object, array $config): StateMachineInterface;
}


text:
package example.service;

import example.repo.Customer1024Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer1024Service {
	public Customer1024Service(Customer1024Repository repo) {}
}


text:
require 'require_all'
require 'logger'

require 'cyclid/config'
require 'cyclid/plugin_registry'

# Top level module for the core Cyclid code.
module Cyclid
  class << self
    attr_accessor :config, :controllers, :plugins, :dispatcher, :builder, :logger

    config_path = ENV['CYCLID_CONFIG'] || File.join(%w(/ etc cyclid config))
    Cyclid.config = API::Config.new(config_path)

    Cyclid.controllers = []
    Cyclid.plugins = API::Plugins::Registry.new

    begin
      Cyclid.logger = if Cyclid.config.log.casecmp('stderr').zero?
                        Logger.new(STDERR)
                      else
                        Logger.new(Cyclid.config.log)
                      end

      original_formatter = Logger::Formatter.new
      Cyclid.logger.formatter = proc { |severity, datetime, progname, msg|
        original_formatter.call(severity, datetime, progname, "#{Thread.current.object_id}: #{msg}")
      }

    rescue StandardError => ex
      abort "Failed to initialize: #{ex}"
    end
  end
end

require_relative 'db'

require 'cyclid/monkey_patches'
require 'cyclid/constants'
require 'cyclid/errors'
require 'cyclid/models'
require 'cyclid/hmac'
require 'cyclid/plugins'
require 'cyclid/job'
require 'cyclid/controllers'

dispatcher = Cyclid.plugins.find(Cyclid.config.dispatcher, Cyclid::API::Plugins::Dispatcher)
abort "Could not find dispatcher '#{Cyclid.config.dispatcher}'" if dispatcher.nil?
Cyclid.dispatcher = dispatcher.new

Cyclid.builder = Cyclid.plugins.find(Cyclid.config.builder, Cyclid::API::Plugins::Builder)
abort "Could not find builder '#{Cyclid.config.builder}'" if Cyclid.builder.nil?


text:
"""
Created on Sat Sep 16 15:24:28 2017

@author: andrewsmac
"""

import tensorflow as tf

# Model parameters
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
# Model input and output
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)

# loss
loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training data
x_train = [1, 2, 3, 4]
y_train = [0, -1, -2, -3]
# training loop
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init) # reset values to wrong
for i in range(1000):
  sess.run(train, {x: x_train, y: y_train})

# evaluate training accuracy
curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train})
print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))


text:
#include "linux_table_container_ipc.h"

#include <fcntl.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syscall.h>
#include <syslog.h>
#include <unistd.h>

#include <chrono>
#include <cstdlib>
#include <iostream>

#include <osquery/core/flags.h>
#include <osquery/core/tables.h>
#include <osquery/logger/logger.h>
#include <osquery/worker/ipc/posix/pipe_channel_factory.h>
#include <osquery/worker/ipc/table_ipc_json_converter.h>

#include "osquery/worker/logging/glog/glog_logger.h"

namespace osquery {

DECLARE_bool(verbose);

CLI_FLAG(bool,
         keep_container_worker_open,
         false,
         "Keep the container worker running to be reused instead of closing it "
         "after each query");

namespace {

const std::string kProc = "/proc";
const std::string kMountNamespace = "/ns/mnt";

/*
 * A namespace id as read from the pseudo link /proc/<pid>/ns/mnt
 * has the format mnt:[<id>] where <id> is an unsigned int representing
 * the namespace id; the max value of an unsigned int has 10 digits
 * and the rest of the string are 6 characters, so the content
 * of the link is max 16 characters.
 */
const int kMaxNamespaceIdLinkChars = 16;

PlatformProcess current_running_process;

Status extractMountNamespaceId(const std::string& mount_namespace_path,
                               std::string& mount_namespace_id) {
  std::string mnt_namespace_id_source(kMaxNamespaceIdLinkChars, 0);
  auto chars_read = readlink(mount_namespace_path.data(),
                             &mnt_namespace_id_source[0],
                             mnt_namespace_id_source.size());

  if (chars_read < 0) {
    return Status::failure("Could not read the mount namespace id from " +
                           mount_namespace_path +
                           ", error: " + std::to_string(errno));
  }

  mnt_namespace_id_source.resize(static_cast<size_t>(chars_read));

  if (mnt_namespace_id_source.empty()) {
    return Status::failure(
        "Failed to parse the mount namespace id, string is empty");
  }

  auto start = mnt_namespace_id_source.find('[');

  if (start == std::string::npos) {
    return Status::failure(
        "Failed to find the start of the mount namespace id in \"" +
        mnt_namespace_id_source + "\"");
  }

  auto end = mnt_namespace_id_source.find(']', start);

  if (end == std::string::npos) {
    return Status::failure(
        "Failed to find the end of the mount namespace id in \"" +
        mnt_namespace_id_source + "\"");
  }

  size_t namespace_id_size = end - start - 1;

  if (namespace_id_size == 0) {
    return Status::failure(
        "Failed to parse the mount namespace id, no id found");
  }

  mount_namespace_id =
      mnt_namespace_id_source.substr(start + 1, namespace_id_size);

  return Status::success();
}

ProcessState checkProcessStateAndLog(const PlatformProcess& process,
                                     const std::string& table_name) {
  int child_exit_status = 0;

  ProcessState process_state = process.checkStatus(child_exit_status);

  if (process_state == ProcessState::PROCESS_ERROR) {
    LOG(ERROR)
        << "Failed to get the process state of container worker of table "
        << table_name << " with pid " << process.pid();
  } else if (process_state == ProcessState::PROCESS_EXITED &&
             child_exit_status != 0) {
    std::string message =
        "Container worker of table " + table_name +
        " exited with exit status: " + std::to_string(child_exit_status);
    if (child_exit_status == 2 && FLAGS_verbose) {
      syslog(LOG_NOTICE, "%s", message.c_str());
    } else {
      LOG(ERROR) << message;
    }
  }

  return process_state;
}
} // namespace

extern template std::set<int> ConstraintList::getAll<int>(
    ConstraintOperator) const;

LinuxTableContainerIPC::LinuxTableContainerIPC(PipeChannelFactory& factory)
    : ipc_(factory, *this) {}

LinuxTableContainerIPC::~LinuxTableContainerIPC() {
  close(original_mnt_fd_);
}

Status LinuxTableContainerIPC::connectToContainer(
    const std::string& table_name,
    bool keep_process_open,
    TableGeneratePtr function_ptr) {
  keep_process_open_ = keep_process_open;

  auto current_pid = getpid();
  std::string original_mnt_path =
      kProc + "/" + std::to_string(current_pid) + kMountNamespace;

  if (original_mnt_fd_ > 0) {
    close(original_mnt_fd_);
  }

  original_mnt_fd_ = open(original_mnt_path.c_str(), O_RDONLY);

  if (original_mnt_fd_ < 0) {
    return Status::failure(
        "Failed to open the original mount namespace of the worker");
  }

  bool is_open = ipc_.setActiveChannelIfOpen(table_name);

  if (!is_open) {
    // This will stop any worker connected to another table,
    // so that we only have one open each time
    if (keep_process_open_) {
      stopContainerWorker();
    }

    PipeChannelTicket channel_ticket = ipc_.createChannelTicket();

    auto process_group = getpgrp();
    table_generate_ptr_ = function_ptr;

    pid_t pid = fork();

    if (pid == 0) {
      auto result = setpgid(0, process_group);

      if (result < 0) {
        std::_Exit(1);
      }

      try {
        ipc_.connectToParent(table_name, std::move(channel_ticket));
      } catch (const std::exception& e) {
        syslog(LOG_NOTICE, "Failed to connect to parent: %s", e.what());
        std::_Exit(1);
      }

      executeQueryJobs();
    } else if (pid == -1) {
      return Status::failure("Failed to start container worker to table " +
                             table_name);
    } else {
      current_running_process = PlatformProcess(pid);
      ipc_.connectToChild(table_name, std::move(channel_ticket), pid);
    }
  }

  return Status::success();
}
void LinuxTableContainerIPC::stopContainerWorker() {
  PlatformProcess child_process(std::move(current_running_process));

  if (child_process.pid() == kInvalidPid) {
    return;
  }

  std::string table_name = ipc_.isChannelOpen()
                               ? ipc_.getTableName()
                               : ipc_.getTableNameFromPid(child_process.pid());

  ipc_.setActiveChannelIfOpen(table_name);
  ipc_.closeActiveChannel();

  ProcessState process_state =
      checkProcessStateAndLog(child_process, table_name);

  if (process_state == ProcessState::PROCESS_STILL_ALIVE) {
    // Wait for the process to close on a separate thread.
    // If it doesn't close in a timely fashion it will be forcefully terminated.
    auto wait_and_kill = [](PlatformProcess process, std::string table_name) {
      auto time_passed = std::chrono::milliseconds(0);
      auto interval = std::chrono::milliseconds(500);
      auto max_delay = std::chrono::milliseconds(2000);

      ProcessState process_state = ProcessState::PROCESS_STILL_ALIVE;
      while (time_passed < max_delay) {
        sleepFor(static_cast<size_t>(interval.count()));
        time_passed += interval;

        process_state = checkProcessStateAndLog(process, table_name);

        if (process_state == ProcessState::PROCESS_ERROR ||
            process_state == ProcessState::PROCESS_EXITED) {
          break;
        }
      }

      if (process_state == ProcessState::PROCESS_STILL_ALIVE) {
        LOG(ERROR) << "Container worker to table " << table_name << " and pid "
                   << process.pid()
                   << " did not stop in a timely fashion, so it will be "
                      "forcefully terminated";
        process.kill();
        process.cleanup();
      }
    };

    auto wait_and_kill_thread =
        std::thread(wait_and_kill, std::move(child_process), table_name);
    wait_and_kill_thread.detach();
  }
}

Status LinuxTableContainerIPC::handleLog(GLOGLogType log_type,
                                         int priority,
                                         const std::string& message) {
  auto logger = GLOGLogger::instance();
  switch (log_type) {
  case GLOGLogType::LOG: {
    logger.log(priority, message);
    break;
  }
  case GLOGLogType::VLOG: {
    logger.vlog(priority, message);
    break;
  }
  default: {
    return Status::failure("Unknown log message type " +
                           std::to_string(static_cast<int>(log_type)));
  }
  }

  return Status::success();
}

Status LinuxTableContainerIPC::handleJob(QueryContext& context) {
  QueryData query_data;
  auto pids_with_namespace =
      context.constraints.at("pid_with_namespace").getAll<int>(EQUALS);

  if (pids_with_namespace.empty()) {
    return Status::failure(
        "Column constraint pid_with_namespace has been passed but there's no "
        "value in it");
  }

  for (const auto pid : pids_with_namespace) {
    std::string path = kProc + "/" + std::to_string(pid) + kMountNamespace;
    auto fd = open(path.c_str(), O_RDONLY);

    if (fd < 0) {
      logger_.vlog(1,
                   "Could not open mount namespace of pid " +
                       std::to_string(pid) +
                       ", error: " + std::to_string(errno));
      continue;
    }

    std::string mount_namespace_id;
    auto status = extractMountNamespaceId(path, mount_namespace_id);

    if (!status.ok()) {
      logger_.vlog(1, status.getMessage());
      close(fd);
      continue;
    }

    // We call the syscall directly because setns() has been added as a function
    // from glibc 2.14 and on only.
    int result = static_cast<int>(syscall(SYS_setns, fd, 0));

    close(fd);

    if (result < 0) {
      logger_.vlog(1,
                   "Could not switch namespace of pid " + std::to_string(pid) +
                       ", error: " + std::to_string(errno));
      continue;
    }

    QueryData namespace_query_data = table_generate_ptr_(context, logger_);
    for (auto& row : namespace_query_data) {
      row["pid_with_namespace"] = INTEGER(pid);
      row["mount_namespace_id"] = mount_namespace_id;
    }

    query_data.insert(query_data.end(),
                      std::make_move_iterator(namespace_query_data.begin()),
                      std::make_move_iterator(namespace_query_data.end()));
  }

  /*
    While we still want to return results to the parent,
    but not being able to restore the original namespace means that
    if the child is kept around, it won't be able to be reused.
    So after delivering the results, we return with an error so
    that the process will be always closed.
  */
  auto write_status = ipc_.sendQueryData(query_data);

  if (keep_process_open_) {
    int result = static_cast<int>(syscall(SYS_setns, original_mnt_fd_, 0));

    if (result < 0) {
      auto status = Status::failure(
          "Failed to restore the original mount namespace, due to error: " +
          std::to_string(errno));
      logger_.vlog(1, status.getMessage());
      return status;
    }
  }

  return write_status;
}

void LinuxTableContainerIPC::executeQueryJobs() {
  int exit_status_code = 0;
  if (keep_process_open_) {
    while (true) {
      JSONMessageType message_type;
      auto status = ipc_.processOneMessage(nullptr, message_type);

      if (!status.ok()) {
        exit_status_code = status.getCode();

        if (exit_status_code != 2 || FLAGS_verbose) {
          syslog(LOG_NOTICE, "%s", status.getMessage().c_str());
        }
        break;
      }
    }
  } else {
    JSONMessageType message_type;
    auto status = ipc_.processOneMessage(nullptr, message_type);

    if (!status.ok()) {
      exit_status_code = status.getCode();

      if (exit_status_code != 2 || FLAGS_verbose) {
        syslog(LOG_NOTICE, "%s", status.getMessage().c_str());
      }
    }
  }

  std::_Exit(exit_status_code);
}

Status LinuxTableContainerIPC::retrieveQueryDataFromContainer(
    const QueryContext& context, QueryData& result) {
  CleanupWorkerOnError cleanupOnError(*this);
  auto status = ipc_.sendJob(context);

  if (!status.ok()) {
    return status;
  }

  bool child_has_result = false;
  while (!child_has_result) {
    JSONMessageType message_type;
    auto status = ipc_.processOneMessage(&result, message_type);

    if (!status.ok())
      return status;

    if (message_type == JSONMessageType::QueryData) {
      child_has_result = true;
    }
  }

  cleanupOnError.dismiss();
  return status;
}

QueryData generateInNamespace(const QueryContext& context,
                              const std::string& table_name,
                              TableGeneratePtr generate_ptr) {
  bool keep_container_worker_open = FLAGS_keep_container_worker_open;
  QueryData results;

  static PipeChannelFactory factory;

  try {
    LinuxTableContainerIPC ipc(factory);
    auto status = ipc.connectToContainer(
        table_name, keep_container_worker_open, generate_ptr);

    if (!status.ok()) {
      LOG(ERROR) << "Table " << table_name
                 << " failed to connect to the container: "
                 << status.getMessage();
      return results;
    }

    status = ipc.retrieveQueryDataFromContainer(context, results);

    if (!status.ok()) {
      LOG(ERROR) << "Table " << table_name
                 << " failed to retrieve QueryData from the container: "
                 << status.getMessage();
    }

    if (!keep_container_worker_open)
      ipc.stopContainerWorker();
  } catch (const std::exception& e) {
    LOG(ERROR) << "Table " << table_name
               << " failed to run query in the container: " << e.what();
  }

  return results;
}

}; // namespace osquery


text:
import os

import pytest
import six

from verta._internal_utils import _artifact_utils

class TestArtifacts:
    def test_log_path(self, experiment_run, strs):
        strs, holdout = strs[:-1], strs[-1]  # reserve last key

        for key, artifact_path in zip(strs, strs):
            experiment_run.log_artifact_path(key, artifact_path)

        for key, artifact_path in zip(strs, strs):
            assert experiment_run.get_artifact(key) == artifact_path

        with pytest.raises(KeyError):
            experiment_run.get_artifact(holdout)

    def test_clientside_storage(self, experiment_run, strs, in_tempdir, random_data):
        key = strs[0]
        filename = strs[1]
        FILE_CONTENTS = random_data

        # TODO: be able to use existing env var for debugging
        # NOTE: there is an assertion of `== 1` artifact that would need to be changed
        VERTA_ARTIFACT_DIR_KEY = 'VERTA_ARTIFACT_DIR'
        PREV_VERTA_ARTIFACT_DIR = os.environ.pop(VERTA_ARTIFACT_DIR_KEY, None)
        try:
            VERTA_ARTIFACT_DIR = os.path.join(in_tempdir, "artifact-store")
            os.environ[VERTA_ARTIFACT_DIR_KEY] = VERTA_ARTIFACT_DIR

            # create file
            with open(filename, 'wb') as f:
                f.write(FILE_CONTENTS)
            # log artifact and delete file
            experiment_run.log_artifact(key, filename)
            os.remove(filename)
            # and then there was one
            assert len(os.listdir(VERTA_ARTIFACT_DIR)) == 1

            # artifact retrievable
            artifact = experiment_run.get_artifact(key)
            assert artifact.read() == FILE_CONTENTS

            # artifact downloadable
            filepath = experiment_run.download_artifact(key, filename)
            with open(filepath, 'rb') as f:
                assert f.read() == FILE_CONTENTS

            # object as well
            obj = {'some': ["arbitrary", "object"]}
            experiment_run.log_artifact(key, obj, overwrite=True)
            assert experiment_run.get_artifact(key) == obj
        finally:
            if PREV_VERTA_ARTIFACT_DIR is not None:
                os.environ[VERTA_ARTIFACT_DIR_KEY] = PREV_VERTA_ARTIFACT_DIR
            else:
                del os.environ[VERTA_ARTIFACT_DIR_KEY]

    def test_download_path_only_error(self, experiment_run, strs, in_tempdir):
        key = strs[0]
        path = strs[1]

        experiment_run.log_artifact_path(key, path)
        with pytest.raises(ValueError):
            experiment_run.download_artifact(key, path)

    def test_blocklisted_key_error(self, experiment_run, all_values):
        all_values = (value  # log_artifact treats str value as filepath to open
                      for value in all_values if not isinstance(value, str))

        for key, artifact in zip(_artifact_utils.BLOCKLISTED_KEYS, all_values):
            with pytest.raises(ValueError, match="please use a different key$"):
                experiment_run.log_image(key, artifact)
            with pytest.raises(ValueError, match="please use a different key$"):
                experiment_run.log_image_path(key, artifact)

class TestImages:
    @staticmethod
    def matplotlib_to_pil(fig):
        Image = pytest.importorskip("PIL.Image")

        bytestream = six.BytesIO()
        fig.savefig(bytestream)
        return Image.open(bytestream)

    def test_log_path(self, experiment_run, strs):
        strs, holdout = strs[:-1], strs[-1]  # reserve last key

        for key, image_path in zip(strs, strs):
            experiment_run.log_image_path(key, image_path)

        for key, image_path in zip(strs, strs):
            assert experiment_run.get_image(key) == image_path

        with pytest.raises(KeyError):
            experiment_run.get_image(holdout)

    def test_upload_blank_warning(self, experiment_run, strs):
        Image = pytest.importorskip("PIL.Image")

        key = strs[0]
        img = Image.new('RGB', (64, 64), 'white')

        with pytest.warns(UserWarning):
            experiment_run.log_image(key, img)

    def test_upload_plt(self, experiment_run, strs):
        np = pytest.importorskip("numpy")
        matplotlib = pytest.importorskip("matplotlib")
        matplotlib.use("Agg")  # https://stackoverflow.com/a/37605654
        import matplotlib.pyplot as plt

        key = strs[0]
        plt.scatter(*np.random.random((2, 10)))

        experiment_run.log_image(key, plt)
        assert np.array_equal(np.asarray(experiment_run.get_image(key).getdata()),
                              np.asarray(self.matplotlib_to_pil(plt).getdata()))

    def test_upload_fig(self, experiment_run, strs):
        np = pytest.importorskip("numpy")
        matplotlib = pytest.importorskip("matplotlib")
        matplotlib.use("Agg")  # https://stackoverflow.com/a/37605654
        import matplotlib.pyplot as plt

        key = strs[0]
        fig, ax = plt.subplots()
        ax.scatter(*np.random.random((2, 10)))

        experiment_run.log_image(key, fig)
        assert np.array_equal(np.asarray(experiment_run.get_image(key).getdata()),
                              np.asarray(self.matplotlib_to_pil(fig).getdata()))

    def test_upload_pil(self, experiment_run, strs):
        np = pytest.importorskip("numpy")
        Image = pytest.importorskip("PIL.Image")
        ImageDraw = pytest.importorskip("PIL.ImageDraw")

        key = strs[0]
        img = Image.new('RGB', (64, 64), 'gray')
        ImageDraw.Draw(img).arc(np.r_[np.random.randint(32, size=(2)),
                                          np.random.randint(32, 64, size=(2))].tolist(),
                                    np.random.randint(360), np.random.randint(360),
                                    'white')

        experiment_run.log_image(key, img)
        assert(np.array_equal(np.asarray(experiment_run.get_image(key).getdata()),
                              np.asarray(img.getdata())))

    def test_conflict(self, experiment_run, strs):
        Image = pytest.importorskip("PIL.Image")

        images = dict(zip(strs, [Image.new('RGB', (64, 64), 'gray')]*3))

        for key, image in six.viewitems(images):
            experiment_run.log_image(key, image)
            with pytest.raises(ValueError):
                experiment_run.log_image(key, image)

        for key, image in reversed(list(six.viewitems(images))):
            with pytest.raises(ValueError):
                experiment_run.log_image(key, image)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Host-to-realm interface (hostrealm) — MIT Kerberos Documentation</title>

    <link rel="stylesheet" href="../_static/agogo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/kerb.css" type="text/css" />

    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="MIT Kerberos Documentation" href="../index.html" />
    <link rel="up" title="For plugin module developers" href="index.html" />
    <link rel="next" title="Local authorization interface (localauth)" href="localauth.html" />
    <link rel="prev" title="kadmin authorization interface (kadm5_auth)" href="kadm5_auth.html" />

MIT Kerberos Documentation

        Contents |
        previous |
        next |
        index |
        Search |
    feedback

Host-to-realm interface (hostrealm)¶

The host-to-realm interface was first introduced in release 1.12.  It
allows modules to control the local mapping of hostnames to realm
names as well as the default realm.  For a detailed description of the
hostrealm interface, see the header file
<tt class="docutils literal"><krb5/hostrealm_plugin.h></tt>.

Although the mapping methods in the hostrealm interface return a list
of one or more realms, only the first realm in the list is currently
used by callers.  Callers may begin using later responses in the
future.

Any mapping method may return KRB5_PLUGIN_NO_HANDLE to defer
processing to a later module.

A module can create and destroy per-library-context state objects
using the init and fini methods.  If the module does not need
any state, it does not need to implement these methods.

The optional host_realm method allows a module to determine
authoritative realm mappings for a hostname.  The first authoritative
mapping is used in preference to KDC referrals when getting service
credentials.

The optional fallback_realm method allows a module to determine
fallback mappings for a hostname.  The first fallback mapping is tried
if there is no authoritative mapping for a realm, and KDC referrals
failed to produce a successful result.

The optional default_realm method allows a module to determine the
local default realm.

If a module implements any of the above methods, it must also
implement free_list to ensure that memory is allocated and
deallocated consistently.

On this page

Host-to-realm interface (hostrealm)

Table of contents

For users

For administrators

For application developers

For plugin module developers

General plugin concepts

Client preauthentication interface (clpreauth)

KDC preauthentication interface (kdcpreauth)

Credential cache selection interface (ccselect)

Password quality interface (pwqual)

KADM5 hook interface (kadm5_hook)

kadmin authorization interface (kadm5_auth)

Host-to-realm interface (hostrealm)

Local authorization interface (localauth)

Server location interface (locate)

Configuration interface (profile)

GSSAPI mechanism interface

Internal pluggable interfaces

PKINIT certificate authorization interface (certauth)

KDC policy interface (kdcpolicy)

Building Kerberos V5

Kerberos V5 concepts

Protocols and file formats

MIT Kerberos features

How to build this documentation from the source

Contributing to the MIT Kerberos Documentation

Resources

Full Table of Contents

Search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Release: 1.16

                © Copyright 1985-2017, MIT.

        Contents |
        previous |
        next |
        index |
        Search |
    feedback


text:
SPK_NAME = haproxy
SPK_VERS = 1.5.8
SPK_REV = 16
SPK_ICON = src/haproxy.png
DSM_UI_DIR = app

DEPENDS = cross/$(SPK_NAME)
SPK_DEPENDS = "python>2.7.3-3"

MAINTAINER = SynoCommunity
DESCRIPTION = HAProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications.
DESCRIPTION_FRE = HAProxy est un produit libre, performant et fiable qui permet la haute disponibilité, la répartition de charge et le proxy de services TCP ou HTTP.
ADMIN_PORT = 8280
RELOAD_UI = yes
DISPLAY_NAME = HAProxy
CHANGELOG = "1. Update to 1.5.8<br>2. Improve SSL security"

HOMEPAGE   = http://haproxy.1wt.eu/
LICENSE    = GNU GPL 2
HELPURL    = http://synocommunity.com/help/haproxy

WIZARDS_DIR = src/wizard/

INSTALLER_SCRIPT = src/installer.sh
SSS_SCRIPT       = src/dsm-control.sh
FWPORTS          = src/${SPK_NAME}.sc

INSTALL_PREFIX = /usr/local/$(SPK_NAME)

POST_STRIP_TARGET = haproxy_extra_install

include ../../mk/spksrc.spk.mk

.PHONY: haproxy_extra_install
haproxy_extra_install: $(STAGING_DIR)/share/requirements.pybundle
	install -m 755 -d $(STAGING_DIR)/var
	install -m 755 -d $(STAGING_DIR)/var/crt
	install -m 755 -d $(STAGING_DIR)/app
	install -m 644 src/haproxy.cfg $(STAGING_DIR)/var/haproxy.cfg.tpl
	install -m 644 src/app/config $(STAGING_DIR)/app/config
	install -m 644 src/app/style.css $(STAGING_DIR)/app/style.css
	install -m 644 src/app/haproxy.js $(STAGING_DIR)/app/haproxy.js
	install -m 755 src/app/setup.py $(STAGING_DIR)/app/setup.py
	install -m 755 src/app/haproxy.cgi.py $(STAGING_DIR)/app/haproxy.cgi
	install -m 755 -d $(STAGING_DIR)/app/application
	install -m 644 src/app/application/* $(STAGING_DIR)/app/application/
	install -m 755 -d $(STAGING_DIR)/app/texts
	for language in enu fre; do \
		install -m 755 -d $(STAGING_DIR)/app/texts/$${language}; \
		install -m 644 src/app/texts/$${language}/strings $(STAGING_DIR)/app/texts/$${language}/strings; \
	done
	install -m 755 -d $(STAGING_DIR)/app/images
	install -m 644 src/app/images/*.png $(STAGING_DIR)/app/images/
	for size in 16 24 32 48 72; do \
		convert $(SPK_ICON) -thumbnail $${size}x$${size} \
		        $(STAGING_DIR)/app/images/$(SPK_NAME)-$${size}.png ; \
	done

$(STAGING_DIR)/share/requirements.pybundle:
	@$(MSG) "Bundling requirements"
	install -m 755 -d $(STAGING_DIR)/share
	@cd $(WORK_DIR) && $(PIP) bundle $@ pyextdirect==0.3.1 flask


text:
/**
 * angular-strap
 * @version v2.3.1 - 2015-07-19
 * @link http://mgcrea.github.io/angular-strap
 * @author Olivier Louvignes <olivier@mg-crea.com> (https://github.com/mgcrea)
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
'use strict';

angular.module('mgcrea.ngStrap.popover', [ 'mgcrea.ngStrap.tooltip' ]).provider('$popover', function() {
  var defaults = this.defaults = {
    animation: 'am-fade',
    customClass: '',
    container: false,
    target: false,
    placement: 'right',
    templateUrl: 'popover/popover.tpl.html',
    contentTemplate: false,
    trigger: 'click',
    keyboard: true,
    html: false,
    title: '',
    content: '',
    delay: 0,
    autoClose: false
  };
  this.$get = [ '$tooltip', function($tooltip) {
    function PopoverFactory(element, config) {
      var options = angular.extend({}, defaults, config);
      var $popover = $tooltip(element, options);
      if (options.content) {
        $popover.$scope.content = options.content;
      }
      return $popover;
    }
    return PopoverFactory;
  } ];
}).directive('bsPopover', [ '$window', '$sce', '$popover', function($window, $sce, $popover) {
  var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout;
  return {
    restrict: 'EAC',
    scope: true,
    link: function postLink(scope, element, attr) {
      var options = {
        scope: scope
      };
      angular.forEach([ 'template', 'templateUrl', 'controller', 'controllerAs', 'contentTemplate', 'placement', 'container', 'delay', 'trigger', 'html', 'animation', 'customClass', 'autoClose', 'id', 'prefixClass', 'prefixEvent' ], function(key) {
        if (angular.isDefined(attr[key])) options[key] = attr[key];
      });
      var falseValueRegExp = /^(false|0|)$/i;
      angular.forEach([ 'html', 'container', 'autoClose' ], function(key) {
        if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false;
      });
      var dataTarget = element.attr('data-target');
      if (angular.isDefined(dataTarget)) {
        if (falseValueRegExp.test(dataTarget)) options.target = false; else options.target = dataTarget;
      }
      angular.forEach([ 'title', 'content' ], function(key) {
        attr[key] && attr.$observe(key, function(newValue, oldValue) {
          scope[key] = $sce.trustAsHtml(newValue);
          angular.isDefined(oldValue) && requestAnimationFrame(function() {
            popover && popover.$applyPlacement();
          });
        });
      });
      attr.bsPopover && scope.$watch(attr.bsPopover, function(newValue, oldValue) {
        if (angular.isObject(newValue)) {
          angular.extend(scope, newValue);
        } else {
          scope.content = newValue;
        }
        angular.isDefined(oldValue) && requestAnimationFrame(function() {
          popover && popover.$applyPlacement();
        });
      }, true);
      attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) {
        if (!popover || !angular.isDefined(newValue)) return;
        if (angular.isString(newValue)) newValue = !!newValue.match(/true|,?(popover),?/i);
        newValue === true ? popover.show() : popover.hide();
      });
      attr.viewport && scope.$watch(attr.viewport, function(newValue) {
        if (!popover || !angular.isDefined(newValue)) return;
        popover.setViewport(newValue);
      });
      var popover = $popover(element, options);
      scope.$on('$destroy', function() {
        if (popover) popover.destroy();
        options = null;
        popover = null;
      });
    }
  };
} ]);


text:
package cc.zkteam.juediqiusheng.base;

import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by wustor
 * 日期  2017-10-30.
 * 邮箱  fat_chao@163.com
 */
public abstract class RvHolder<T> extends RecyclerView.ViewHolder {
    protected RvListener mListener;

    public RvHolder(View itemView, int type, RvListener listener) {
        super(itemView);
        this.mListener = listener;
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onItemClick(v.getId(), getAdapterPosition());
            }
        });
    }

    public abstract void bindHolder(T t, int position);

}


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

public class BellController : MonoBehaviour {

    public float maxSpeed;
    public float gravityForce;
    public float aggroRange;
    public float maxAggroRange;
    public GameObject target;
    public AudioClip sfxDefeat;

    private Vector3 moveDirection;
    private bool aggro;
    private Vector3 velocity;
    Rigidbody rb;
    SpriteRenderer spriteRenderer;
    Animator animator;

    void Start() {
        aggro = false;

        rb = GetComponent<Rigidbody>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
    }

    void FixedUpdate() {
        // Flip enemy horizontally based on x relative to player
        if (transform.position.x < target.transform.position.x) {
            spriteRenderer.flipX = false;
        }
        else if (transform.position.x > target.transform.position.x) {
            spriteRenderer.flipX = true;
        }

        // Calculate player's position
        Vector3 direction = target.transform.position - transform.position;
        float magnitude = direction.magnitude;
        direction.Normalize();

        velocity = direction * maxSpeed;

        if (aggro == false && magnitude < aggroRange) {
            // Become aggressive when player is in range
            aggro = true;
        }

        if (aggro == true && magnitude > maxAggroRange) {
            // Become passive when player is out of chasing range
            aggro = false;
        }

        if (aggro) {
            // Move towards player when in aggro range
            rb.AddForce(new Vector3(velocity.x, rb.velocity.y, velocity.z), ForceMode.Force);
        }

        // Idle & Walk animation aggro
        if (aggro == false) {
            // Idle animation when not aggro'd, standing around
            if (!animator.GetCurrentAnimatorStateInfo(0).IsName("BellIdle")) {
                animator.Play("BellIdle", -1, 0.0f);
            }
        } else {
            // Walk animation when aggro'd, chasing player
            if (!animator.GetCurrentAnimatorStateInfo(0).IsName("BellWalk")) {
                animator.Play("BellWalk", -1, 0.0f);
            }
        }
    }

    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.tag == "Player") {
            // Rebound off player when colliding with them
    		rb.AddForce(new Vector3(-velocity.x / 2, rb.velocity.y, -velocity.z / 2), ForceMode.Impulse);
        }

        if (collision.gameObject.tag == "Umbrella Attack") {
            // Rebound further while player is blocking
            rb.AddForce(new Vector3(-velocity.x, rb.velocity.y, -velocity.z), ForceMode.Impulse);

            //target.GetComponent<AudioSource>().pitch = (Random.Range(0.9f, 1.1f));
            target.GetComponent<AudioSource>().PlayOneShot(target.GetComponent<PlayerController>().sfxUmbrella, 0.25f);
        }
    }

    private void OnTriggerEnter(Collider other) {
        if (other.gameObject.tag == "Player Attack") {
            // Create smoke effect
            MakeSmoke();

            // Enemy hit by key attack, destroy
            Destroy(gameObject);
        }

        if (other.gameObject.tag == "Feet Attack") {
            // Create smoke effect
            MakeSmoke();

            // Enemy hit by key attack, destroy
            Destroy(gameObject);
        }

        if (other.tag == "Cactus") {
            // Create smoke effect
            MakeSmoke();

            // Enemy hit by cactus, destroy
            Destroy(gameObject);
        }

        if (other.tag == "Gumball") {
        	if (other.transform.parent.gameObject.GetComponent<Rigidbody>().velocity.magnitude > 0.0f) {
	            // Create smoke effect
	            MakeSmoke();

	            // Enemy hit by key attack, destroy
	            Destroy(gameObject);
	        }
        }
    }

    /*
    private void OnTriggerStay(Collider other) {
		if (other.gameObject.tag == "Player Attack") {
			// Create smoke effect
            MakeSmoke();

            // Enemy hit by key attack, destroy
            Destroy(gameObject);
		}

        if (other.tag == "Cactus") {
            // Create smoke effect
            MakeSmoke();

            // Enemy hit by key attack, destroy
            Destroy(gameObject);
        }
    }
    */

    public void MakeSmoke() {
        // Create smoke effect
        Transform smoke = this.gameObject.transform.GetChild(0);
        smoke.gameObject.SetActive(true);
        smoke.gameObject.GetComponent<SmokeController>().enabled = true;
        smoke.parent = null;

        target.GetComponent<AudioSource>().pitch = (Random.Range(0.9f, 1.1f));
        target.GetComponent<AudioSource>().PlayOneShot(sfxDefeat, 1f);
    }
}


text:
.. _conan-qbs-toolchain:

conan.tools.qbs
===============

QbsProfile
------------

.. warning::

    This is an **experimental** feature subject to breaking changes in future releases.

Available since: `1.33.0 <https://github.com/conan-io/conan/releases/tag/1.33.0>`_

The ``QbsProfile`` can be used in the ``generate()`` method:

.. code:: python

    from conan import ConanFile
    from conan.tools.qbs import QbsProfile

    class App(ConanFile):
        settings = "os", "arch", "compiler", "build_type"
        requires = "hello/0.1"
        options = {"shared": [True, False]}
        default_options = {"shared": False}

        def generate(self):
            tc = QbsProfile(self)
            tc.generate()

The ``QbsProfile`` will generate the following file during :command:`conan install`
command (or before calling the ``build()`` method when the package is being
built in the cache): *conan_toolchain_profile.qbs*. This file will contain a qbs profile
named *conan_toolchain_profile*.

*conan_toolchain_profile.qbs* will contain the definitions of all the Qbs properties
related to the Conan options and settings for the current package, platform,
etc. This includes the following:

  * Detection of compiler.

  * Based on the compiler set in environment variable ``CC``.

  * Uses detected system compiler based on Conan setting ``compiler`` if environment variable ``CC`` is not set.

* Detection of compiler flags from environment (as defined at https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html):

  * ``ASFLAGS``

  * ``CFLAGS``

  * ``CPPFLAGS``

  * ``CXXFLAGS``

  * ``LDFLAGS``

* Detection of sysroot from environment.

* Detection of ``build_type`` from Conan settings.

* Detection of ``arch`` from Conan settings.

* Detection of ``compiler.cxxstd`` from Conan settings.

* Detection of ``fPIC`` based on the existence of such option in the recipe.

Qbs
---

Available since: `1.33.0 <https://github.com/conan-io/conan/releases/tag/1.33.0>`_

If you are using **Qbs** as your build system, you can use the **Qbs** build helper.

.. code-block:: python

    from conan import ConanFile
    from conan.tools.qbs import Qbs

    class ConanFileToolsTest(ConanFile):
        ...

        def build(self):
            qbs = Qbs(self)
            qbs.build()

Constructor
+++++++++++

.. code-block:: python

    class Qbs(object):

        def __init__(self, conanfile, project_file=None)

Parameters:
    - **conanfile** (Required): Use ``self`` inside a ``conanfile.py``.
    - **project_file** (Optional, Defaulted to ``None``): Path to the root project file.

Attributes
++++++++++

profile
*********************

**Defaulted to**: ``conan_toolchain_profile``

Specifies the qbs profile to build the project for.

Methods
+++++++

add_configuration()
*********************

.. code-block:: python

    def add_configuration(self, name, values)

Add a build configuration to use.

Parameters:
    - **name** (Required): Specifies build configuration name.
    - **values** (Required): A dict of properties set for this build configuration.

build()
*******

.. code-block:: python

    def build(self, products=None)

Build Qbs project.

Parameters:
    - **products** (Optional, Defaulted to ``None``): Specifies a list of products to build. If ``None`` build all products which have the qbs property ``buildByDefault`` set to ``true``.

build_all()
***********

.. code-block:: python

    def build_all(self)

Build all products of Qbs project, even products which set the qbs property ``buildByDefault`` set to ``false``

install()
*********

.. code-block:: python

    def install(self)

Install products.

Example
*******

A typical usage of the Qbs build helper, if you want to be able to both execute :command:`conan create` and also build your package for a
library locally (in your user folder, not in the local cache), could be:

.. code-block:: python

    from conan import ConanFile
    from conan.tools.qbs import Qbs

    class HelloConan(ConanFile):
        name = "hello"
        version = "0.1"
        settings = "os", "compiler", "build_type", "arch"
        generators = "qbs"
        exports_sources = "src/*", "*.qbs"
        no_copy_source = True
        requires = "zlib/1.2.11"

        def build(self):
            qbs = Qbs(self)
            qbs.add_configuration("default", {
                "project.conanBuildInfo", self.build_folder + "/conanbuildinfo.qbs"
            })
            qbs.build()

        def package(self):
            self.copy("*.h", dst="include", src="src")
            self.copy("*.lib", dst="lib", keep_path=False)
            self.copy("*.dll", dst="bin", keep_path=False)
            self.copy("*.dylib*", dst="lib", keep_path=False)
            self.copy("*.so", dst="lib", keep_path=False)
            self.copy("*.a", dst="lib", keep_path=False)

        def package_info(self):
            self.cpp_info.libs = ["hello"]

Note the ``qbs`` generator, which generates the *conanbuildinfo.qbs* file, to process
dependencies information. Setting ``no_copy_source = True`` helps qbs to pick the right project file
and not get confused by the generated files.

The *hello.qbs* could be as simple as:

.. code-block:: text

    Project {
        readonly property path conanBuildInfo

        references: conanBuildInfo

        DynamicLibrary {
            name: "hello"
            version: "0.1.0"
            files: "src/hello.cpp"
            cpp.cxxLanguageVersion: "c++11"

            Depends { name: "cpp" }
            Depends { name: "zlib" }
        }
    }


text:
<?php

namespace PHPCensor\Model\Build;

use Exception;
use PHPCensor\Builder;
use PHPCensor\ConfigurationInterface;
use PHPCensor\Model\Build;
use PHPCensor\StoreRegistry;
use Psr\Log\LogLevel;

/**
 * Remote Git Build Model
 *
 * @package    PHP Censor
 * @subpackage Application
 *
 * @author Dan Cryer <dan@block8.co.uk>
 * @author Dmitry Khomutov <poisoncorpsee@gmail.com>
 */
class GitBuild extends Build
{
    protected ConfigurationInterface $configuration;

    public function __construct(
        ConfigurationInterface $configuration,
        StoreRegistry $storeRegistry,
        array $initialData = []
    ) {
        parent::__construct($storeRegistry, $initialData);

        $this->configuration = $configuration;
    }

    /**
     * Get the URL to be used to clone this remote repository.
     *
     * @return string
     */
    protected function getCloneUrl()
    {
        return $this->getProject()->getReference();
    }

    /**
     * Create a working copy by cloning, copying, or similar.
     *
     * @param string $buildPath
     *
     * @return bool
     *
     * @throws Exception
     */
    public function createWorkingCopy(Builder $builder, $buildPath)
    {
        $key = \trim($this->getProject()->getSshPrivateKey());

        if (!empty($key)) {
            $success = $this->cloneBySsh($builder, $buildPath);
        } else {
            $success = $this->cloneByHttp($builder, $buildPath);
        }

        if ($success) {
            $success = $this->mergeBranches($builder, $buildPath);
        }

        if (!$success) {
            $builder->logFailure('Failed to clone remote git repository.');

            return false;
        }

        return $this->handleConfig($builder, $buildPath);
    }

    /**
     * @param string $buildPath
     *
     * @return bool
     */
    protected function mergeBranches(Builder $builder, $buildPath)
    {
        $branches = $this->getExtra('branches');
        if (!empty($branches)) {
            $cmd = 'cd "%s" && git merge --quiet origin/%s';
            foreach ($branches as $branch) {
                $success = $builder->executeCommand($cmd, $buildPath, $branch);
                if (!$success) {
                    $builder->log('Fail merge branch origin/' . $branch, LogLevel::ERROR);

                    return false;
                }
                $builder->log('Merged branch origin/' . $branch, LogLevel::INFO);
            }
        }

        return true;
    }

    /**
     * Use an HTTP-based git clone.
     *
     * @param string $cloneTo
     *
     * @return bool
     */
    protected function cloneByHttp(Builder $builder, $cloneTo)
    {
        $cmd = 'cd .. && git clone --recursive ';

        $buildSettings = $builder->getConfig('build_settings');
        if ($buildSettings && isset($buildSettings['clone_depth']) && (0 < (int)$buildSettings['clone_depth'])) {
            $cmd .= ' --depth ' . \intval($buildSettings['clone_depth']) . ' ';
        }

        $cmd .= ' -b "%s" "%s" "%s"';
        $success = $builder->executeCommand($cmd, $this->getBranch(), $this->getCloneUrl(), $cloneTo);

        if ($success) {
            $success = $this->postCloneSetup($builder, $cloneTo);
        }

        return $success;
    }

    /**
     * Use an SSH-based git clone.
     *
     * @param string $cloneTo
     *
     * @return bool
     */
    protected function cloneBySsh(Builder $builder, $cloneTo)
    {
        $keyFile       = $this->writeSshKey();
        $gitSshWrapper = $this->writeSshWrapper($keyFile);

        // Do the git clone:
        $cmd = 'cd .. && git clone --recursive ';

        $buildSettings = $builder->getConfig('build_settings');
        if ($buildSettings && isset($buildSettings['clone_depth']) && (0 < (int)$buildSettings['clone_depth'])) {
            $cmd .= ' --depth ' . \intval($buildSettings['clone_depth']) . ' ';
        }

        $cmd .= ' -b "%s" "%s" "%s"';
        $cmd = 'export GIT_SSH="' . $gitSshWrapper . '" && ' . $cmd;

        $success = $builder->executeCommand($cmd, $this->getBranch(), $this->getCloneUrl(), $cloneTo);

        if ($success) {
            $extra = [
                'git_ssh_wrapper' => $gitSshWrapper
            ];

            $success = $this->postCloneSetup($builder, $cloneTo, $extra);
        }

        // Remove the key file and git wrapper:
        \unlink($keyFile);
        \unlink($gitSshWrapper);

        return $success;
    }

    /**
     * Handle any post-clone tasks, like switching branches.
     *
     * @param string $cloneTo
     * @param array  $extra
     *
     * @return bool
     */
    protected function postCloneSetup(Builder $builder, $cloneTo, array $extra = null)
    {
        $success  = true;
        $commitId = $this->getCommitId();
        $chdir    = 'cd "%s"';

        if (empty($this->getEnvironmentId()) && !empty($commitId)) {
            $cmd     = $chdir . ' && git checkout %s --quiet';
            $success = $builder->executeCommand($cmd, $cloneTo, $commitId);
        }

        // Always update the commit hash with the actual HEAD hash
        if ($builder->executeCommand($chdir . ' && git rev-parse HEAD', $cloneTo)) {
            $commitId = \trim($builder->getLastOutput());

            $this->setCommitId($commitId);

            if ($builder->executeCommand($chdir . ' && git log -1 --pretty=format:%%s %s', $cloneTo, $commitId)) {
                $this->setCommitMessage(\trim($builder->getLastOutput()));
            }

            if ($builder->executeCommand($chdir . ' && git log -1 --pretty=format:%%ae %s', $cloneTo, $commitId)) {
                $this->setCommitterEmail(\trim($builder->getLastOutput()));
            }
        }

        return $success;
    }
}


text:
#include <aws/es/model/CreateOutboundCrossClusterSearchConnectionResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::ElasticsearchService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

CreateOutboundCrossClusterSearchConnectionResult::CreateOutboundCrossClusterSearchConnectionResult()
{
}

CreateOutboundCrossClusterSearchConnectionResult::CreateOutboundCrossClusterSearchConnectionResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

CreateOutboundCrossClusterSearchConnectionResult& CreateOutboundCrossClusterSearchConnectionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("SourceDomainInfo"))
  {
    m_sourceDomainInfo = jsonValue.GetObject("SourceDomainInfo");

  }

  if(jsonValue.ValueExists("DestinationDomainInfo"))
  {
    m_destinationDomainInfo = jsonValue.GetObject("DestinationDomainInfo");

  }

  if(jsonValue.ValueExists("ConnectionAlias"))
  {
    m_connectionAlias = jsonValue.GetString("ConnectionAlias");

  }

  if(jsonValue.ValueExists("ConnectionStatus"))
  {
    m_connectionStatus = jsonValue.GetObject("ConnectionStatus");

  }

  if(jsonValue.ValueExists("CrossClusterSearchConnectionId"))
  {
    m_crossClusterSearchConnectionId = jsonValue.GetString("CrossClusterSearchConnectionId");

  }

  return *this;
}


text:
package ca.corefacility.bioinformatics.irida.exceptions;

/**
 * Thrown web there is an error parsing the webpack assets-manifest file.
 */
public class WebpackParserException extends RuntimeException {
	public WebpackParserException(String message) {
		super(message);

	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Jint.Marshal;

namespace Jint.Native
{
    /// <summary>
    /// Represent a set of native overloads to set and get values using indexers.
    /// </summary>
    public class NativeIndexer : INativeIndexer
    {
        NativeOverloadImpl<MethodInfo, JsIndexerGetter> m_getOverload;
        NativeOverloadImpl<MethodInfo, JsIndexerSetter> m_setOverload;

        public NativeIndexer(Marshaller marshaller, MethodInfo[] getters, MethodInfo[] setters)
        {
            m_getOverload = new NativeOverloadImpl<MethodInfo, JsIndexerGetter>(
                marshaller,
                delegate(Type[] genericArgs, int Length)
                {
                    return Array.FindAll<MethodInfo>(getters, mi => mi.GetParameters().Length == Length);
                },
                new NativeOverloadImpl<MethodInfo, JsIndexerGetter>.WrapMmemberDelegate(marshaller.WrapIndexerGetter)
            );
            m_setOverload = new NativeOverloadImpl<MethodInfo, JsIndexerSetter>(
                marshaller,
                delegate(Type[] genericArgs, int Length)
                {
                    return Array.FindAll<MethodInfo>(setters, mi => mi.GetParameters().Length == Length);
                },
                new NativeOverloadImpl<MethodInfo,JsIndexerSetter>.WrapMmemberDelegate(marshaller.WrapIndexerSetter)
            );
        }

        public JsInstance get(JsInstance that, JsInstance index)
        {
            JsIndexerGetter getter = m_getOverload.ResolveOverload(new JsInstance[] { index }, null);
            if (getter == null)
                throw new JintException("No matching overload found");
            return getter(that, index);
        }

        public void set(JsInstance that, JsInstance index, JsInstance value)
        {
            JsIndexerSetter setter = m_setOverload.ResolveOverload(new JsInstance[] { index, value }, null);
            if (setter == null)
                throw new JintException("No matching overload found");

            setter(that, index, value);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="commonltr.css"/>
<title>Beeswax</title>

DB Query

      A brand new application that enables viewing data in MySQL, PostgreSQL, Oracle and Sqlite has been committed.

 Inspired from the Beeswax application, it allows you to query a relational database and view it in a table.


text:
package io.katharsis.queryParams;

import io.katharsis.queryParams.params.*;

import java.util.Map;

/**
 * Contains a set of parameters passed along with the request.
 */
public class QueryParams {
    private TypedParams<FilterParams> filters;
    private TypedParams<SortingParams> sorting;
    private TypedParams<GroupingParams> grouping;
    private TypedParams<IncludedFieldsParams> includedFields;
    private TypedParams<IncludedRelationsParams> includedRelations;
    private Map<RestrictedPaginationKeys, Integer> pagination;

    public TypedParams<FilterParams> getFilters() {
        return filters;
    }
    void setFilters(TypedParams<FilterParams> filters) {
        this.filters = filters;
    }

    public TypedParams<SortingParams> getSorting() {
        return sorting;
    }
    void setSorting(TypedParams<SortingParams> sorting) {
        this.sorting = sorting;
    }

    public TypedParams<GroupingParams> getGrouping() {
        return grouping;
    }
    void setGrouping(TypedParams<GroupingParams> grouping) {
        this.grouping = grouping;
    }

    public Map<RestrictedPaginationKeys, Integer> getPagination() {
        return pagination;
    }
    void setPagination(Map<RestrictedPaginationKeys, Integer> pagination) {
        this.pagination = pagination;
    }

    public TypedParams<IncludedFieldsParams> getIncludedFields() {
        return includedFields;
    }
    void setIncludedFields(TypedParams<IncludedFieldsParams> includedFields) {
        this.includedFields = includedFields;
    }

    public TypedParams<IncludedRelationsParams> getIncludedRelations() {
        return includedRelations;
    }
    void setIncludedRelations(TypedParams<IncludedRelationsParams> includedRelations) {
        this.includedRelations = includedRelations;
    }

    @Override
    public String toString() {
        return "QueryParams{" +
            "filters=" + filters +
            ", sorting=" + sorting +
            ", grouping=" + grouping +
            ", includedFields=" + includedFields +
            ", includedRelations=" + includedRelations +
            ", pagination=" + pagination +
            '}';
    }
}