text:
// Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, George Kurian, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.

// FIXME: This list could probably be trimmed down a lot.
#include "simulator.h"
#include "core_manager.h"
#include "config.h"
#include "core.h"
#include "thread.h"
#include "syscall_model.h"
#include "thread_manager.h"
#include "hooks_manager.h"
#include "trace_manager.h"
#include "config_file.hpp"
#include "handle_args.h"
#include "log.h"
#include "instruction_modeling.h"
#include "magic_client.h"
#include "sampling_manager.h"
#include "sampling_provider.h"
#include "performance_model.h"
#include "timer.h"
#include "logmem.h"
#include "circular_log.h"

#include "codecache_trace.h"
#include "local_storage.h"
#include "toolreg.h"
#include "pin_exceptions.h"
#include "trace_rtn.h"

// lite directories
#include "lite/routine_replace.h"
#include "lite/handle_syscalls.h"

#include "sim_api.h"

#include "pin.H"
#include "inst_mode_macros.h"
#ifdef PINPLAY_SUPPORTED
# include "pinplay.H"
#endif

#include <iostream>
#include <assert.h>
#include <set>
#include <sys/syscall.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>

#include <typeinfo>

// ---------------------------------------------------------------
// FIXME:
// There should be a better place to keep these globals
// -- a PinSimulator class or smthg
bool done_app_initialization = false;
config::ConfigFile *cfg;

// clone stuff
extern int *parent_tidptr;
#ifdef TARGET_IA32
extern struct user_desc *newtls;
#endif
extern int *child_tidptr;

bool forkedInChild = false;

// ---------------------------------------------------------------

map <ADDRINT, string> rtn_map;
PIN_LOCK rtn_map_lock;

#ifdef PINPLAY_SUPPORTED
PINPLAY_ENGINE pinplay_engine;
#endif

void applicationMemCopy(void *dest, const void *src, size_t n)
{
   PIN_SafeCopy(dest, src, n);
}

void printRtn (ADDRINT rtn_addr, bool enter)
{
   PIN_GetLock (&rtn_map_lock, 1);
   map<ADDRINT, string>::iterator it = rtn_map.find (rtn_addr);

   string point = enter ? "Enter" : "Exit";
   if (it != rtn_map.end())
   {
      LOG_PRINT ("Stack trace : %s %s", point.c_str(), (it->second).c_str());
   }
   else
   {
      LOG_PRINT ("Stack trace : %s UNKNOWN", point.c_str());
   }

   PIN_ReleaseLock (&rtn_map_lock);
}

VOID printInsInfo(CONTEXT* ctxt)
{
   __attribute__((__unused__)) ADDRINT reg_inst_ptr = PIN_GetContextReg(ctxt, REG_INST_PTR);
   __attribute__((__unused__)) ADDRINT reg_stack_ptr = PIN_GetContextReg(ctxt, REG_STACK_PTR);

   LOG_PRINT("eip = %#llx, esp = %#llx", reg_inst_ptr, reg_stack_ptr);
}

void showInstructionInfo(INS ins)
{
   printf("\t");
   if (INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins))
      printf("* ");
   else
      printf("  ");
//   printf("%d - %s ", INS_Category(ins), CATEGORY_StringShort(INS_Category(ins)).c_str());
   printf("%x - %s ", INS_Opcode(ins), OPCODE_StringShort(INS_Opcode(ins)).c_str());
   printf(" %s ", INS_Disassemble(ins).c_str());
   printf("\n");
}

VOID instructionCallback(TRACE trace, INS ins, InstMode::inst_mode_t inst_mode)
{
   // Debugging Functions
   // showInstructionInfo(ins);
   if (Log::getSingleton()->isLoggingEnabled())
   {
      INS_InsertPredicatedCall(ins, IPOINT_BEFORE,
            AFUNPTR(printInsInfo),
            IARG_CALL_ORDER, CALL_ORDER_FIRST,
            IARG_CONTEXT,
            IARG_END);
   }

   // Core Performance Modeling

}

void handleCheckScheduled(THREADID threadIndex)
{
   Thread* thread = localStore[threadIndex].thread;
   Core* core = thread->getCore();

   if (core == NULL)
   {
      // This thread isn't scheduled. Normally it shouldn't execute any code,
      // but just after thread start we do get here.
      // Wait here until we're scheduled on one of the cores.
      SubsecondTime time = SubsecondTime::Zero();
      thread->reschedule(time, core);

      // We should be on a core now, set its performance model to our local time
      core = thread->getCore();
      // If the core already has a later time, we have to wait
      time = std::max(time, core->getPerformanceModel()->getElapsedTime());
      core->getPerformanceModel()->queueDynamicInstruction(new SpawnInstruction(time));
   }
}

VOID addCheckScheduled(TRACE trace, INS ins_head)
{
   INS_InsertCall(ins_head, IPOINT_BEFORE, AFUNPTR(handleCheckScheduled), IARG_THREAD_ID, IARG_END);
}

static int getInstMode()
{
   return Sim()->getInstrumentationMode();
}

VOID traceCallback(TRACE trace, void *v)
{
   InstMode::inst_mode_t inst_mode = INSTR_GET_MODE(trace);

   BBL bbl_head = TRACE_BblHead(trace);
   INS ins_head = BBL_InsHead(bbl_head);

   #ifdef PINPLAY_SUPPORTED
   // Make sure all version switches happen before any PinPlay instrumentation, to avoid PinPlay seeing some instructions twice
   CALL_ORDER call_order = (CALL_ORDER)(pinplay_engine.PinPlayFirstBeforeCallOrder() - 1);
   #else
   CALL_ORDER call_order = CALL_ORDER_DEFAULT;
   #endif

   // Write the resulting mode to REG_INST_Gx for use by INS_InsertVersionCase
   INS_InsertCall(ins_head, IPOINT_BEFORE, (AFUNPTR)getInstMode, IARG_RETURN_REGS, g_toolregs[TOOLREG_TEMP], IARG_CALL_ORDER, call_order, IARG_END);

   // Add version switch cases for all possible target versions (no test to switch to self)
   #define SWITCH_VERSION(v) if (inst_mode != (v)) INS_InsertVersionCase(ins_head, g_toolregs[TOOLREG_TEMP], v, v, IARG_CALL_ORDER, call_order, IARG_END);
   SWITCH_VERSION(InstMode::DETAILED)
   SWITCH_VERSION(InstMode::CACHE_ONLY)
   SWITCH_VERSION(InstMode::FAST_FORWARD)

   // Version 0 is only for startup / amnesia, don't do anything else there
   if (TRACE_Version(trace) == 0)
      return;

   addCheckScheduled(trace, ins_head);

   addRtnTracer(trace);

   // Routine replacement
   RTN rtn = TRACE_Rtn(trace);
   if (RTN_Valid(rtn)
      && RTN_Address(rtn) == TRACE_Address(trace))
   {
      lite::routineStartCallback(rtn, ins_head);
   }

   // Select per-basicblock instrumentation level.
   // In fast-forward mode, this is the only instrumentation (except for some rare stuff like magic, syscall),
   //   so using a lighter version here significantly speeds up simulation

   InstrumentLevel::Level instr_level;
   if (Sim()->getConfig()->getBBVsEnabled()) {
      // Someone (a Python script) has requested BBVs to be enabled.
      instr_level = InstrumentLevel::INSTR_WITH_BBVS;
   } else if (Sim()->getSamplingManager()->getSamplingProvider()) {
      // Ask the sampling provider what mode they need
      instr_level = Sim()->getSamplingManager()->getSamplingProvider()->requestedInstrumentation();
   } else {
      instr_level = InstrumentLevel::INSTR;
   }

   for (BBL bbl = bbl_head; BBL_Valid(bbl); bbl = BBL_Next(bbl))
   {
      switch (instr_level) {
         case (InstrumentLevel::INSTR):
         case (InstrumentLevel::INSTR_WITH_BBVS):
            BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)InstructionModeling::countInstructions, IARG_THREAD_ID, IARG_ADDRINT, BBL_Address(bbl), IARG_UINT32, BBL_NumIns(bbl), IARG_END);
            break;
         case (InstrumentLevel::NONE):
            break;
         default:
            LOG_PRINT_ERROR("Unexpected enum value '%d'", instr_level);
            break;
      }

      // I-cache modeling during warmup
      if (Sim()->getConfig()->getEnableICacheModeling()) {
         INSTRUMENT(
            INSTR_IF_CACHEONLY(inst_mode),
            trace, BBL_InsHead(bbl), IPOINT_BEFORE,
            AFUNPTR(InstructionModeling::accessInstructionCacheWarmup),
            IARG_THREAD_ID,
            IARG_ADDRINT, BBL_Address(bbl),
            IARG_UINT32, BBL_Size(bbl),
            IARG_END);
      }

      UINT32 icount = 0;

      for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
      {
         // Instruction modelling
         InstructionModeling::addInstructionModeling(trace, ins, inst_mode);

         if (INSTR_IF_DETAILED(inst_mode) && !INS_IsSyscall(ins))
         {
            Instruction *inst = InstructionModeling::decodeInstruction(ins);
            INSTRUMENT(INSTR_IF_DETAILED(inst_mode), trace, ins, IPOINT_BEFORE, AFUNPTR(InstructionModeling::handleInstruction), IARG_THREAD_ID, IARG_PTR, inst, IARG_END);
         }
         ++icount;

         if (ins == BBL_InsTail(bbl) || icount >= 32 || INS_HasRealRep(ins))
         {
            if (INS_HasFallThrough(ins))
               INSTRUMENT(INSTR_IF_DETAILED(inst_mode), trace, ins, IPOINT_AFTER, AFUNPTR(InstructionModeling::handleBasicBlock), IARG_THREAD_ID, IARG_END);
            if (INS_IsBranch(ins))
               INSTRUMENT(INSTR_IF_DETAILED(inst_mode), trace, ins, IPOINT_TAKEN_BRANCH, AFUNPTR(InstructionModeling::handleBasicBlock), IARG_THREAD_ID, IARG_END);
            icount = 0;
         }

         if (ins == BBL_InsTail(bbl))
            break;
      }
   }
}

VOID traceInvalidate(ADDRINT orig_pc, ADDRINT cache_pc, BOOL success)
{
   if (!Sim()->getConfig()->getEnableSMCSupport())
   {
      // It should be safe to turn on SMC support at runtime
      // (which means: stop using caches for basic blocks and decoded instruction from now on).
      // Just in case enabling this half-way through isn't reliable, keep the warning for now.
      LOG_PRINT_WARNING_ONCE("Trace invalidation orig_pc(%p) cache_pc(%p) success(%d)\n\n"
                             "Self-modifying code (SMC) support now enabled.\n"
                             "Use general/enable_smc_support=true to enable manually.\n", orig_pc, cache_pc, success);
      Sim()->getConfig()->forceEnableSMCSupport();
   }
}

void ApplicationStart()
{
}

void ApplicationExit(int, void*)
{
   if (forkedInChild)
      return;

   LOG_PRINT("Application exit.");
   Simulator::release();

   delete cfg;
}

void ApplicationDetach(void*)
{
   ApplicationExit(0, NULL);
}

void PinDetach(void)
{
   //PIN_Detach();
}

VOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v)
{
   if (! done_app_initialization)
   {
      // Spawn the main() thread
      Sim()->getThreadManager()->spawnThread(INVALID_THREAD_ID, 0, NULL, NULL);

      // Start the trace manager, if any
      if (Sim()->getTraceManager())
         Sim()->getTraceManager()->start();

      // All the real initialization is done in
      // replacement_start at the moment
      done_app_initialization = true;
   }

   SubsecondTime time;
   thread_id_t thread_id = Sim()->getThreadManager()->getThreadToSpawn(time);

   // Set thread name for Sniper-in-Sniper simulations
   String threadName = String("app-") + itostr(thread_id);
   SimSetThreadName(threadName.c_str());

   Sim()->getThreadManager()->onThreadStart(thread_id, time);

   // Don't resize this vector at runtime as it's shared and we don't want it to be reallocated while someone uses it
   LOG_ASSERT_ERROR(localStore.size() > threadIndex, "Ran out of thread_id slots, increase MAX_PIN_THREADS");

   memset(&localStore[threadIndex], 0, sizeof(localStore[threadIndex]));
   localStore[threadIndex].thread = Sim()->getThreadManager()->getThreadFromID(thread_id);
   localStore[threadIndex].thread->m_os_info.tid = syscall(__NR_gettid);
   if (Sim()->getConfig()->getEnableSpinLoopDetection())
      localStore[threadIndex].sld.sld = new SpinLoopDetector(localStore[threadIndex].thread);
}

VOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v)
{
   if (forkedInChild)
      return;

   Sim()->getThreadManager()->onThreadExit(localStore[threadIndex].thread->getId());

   if (localStore[threadIndex].thread->getId() == 0)
      if (Sim()->getTraceManager())
         Sim()->getTraceManager()->stop();
}

bool handleSigUsr1(THREADID threadIndex, INT32 signal, CONTEXT *ctx, BOOL hasHandler, const EXCEPTION_INFO *pExceptInfo, void* v)
{
   Sim()->getHooksManager()->callHooks(HookType::HOOK_SIGUSR1, 0);
   return false;
}

VOID forkAfterChild(THREADID threadid, const CONTEXT *ctxt, VOID *v)
{
   // Application has fork()ed. We don't want to track child processes, but Pin will attempt to do cleanups.
   // Make sure that these don't trigger any simulator code.
   forkedInChild = true;
}

int main(int argc, char *argv[])
{
   // ---------------------------------------------------------------
   // FIXME:
   PIN_InitLock (&rtn_map_lock);
   // ---------------------------------------------------------------

   // Global initialization
   PIN_InitSymbols();
   PIN_Init(argc,argv);

   initToolregs();

   // To make sure output shows up immediately, make stdout and stderr line buffered
   // (if we're writing into a pipe to run-graphite, or redirected to a file by the job runner, the default will be block buffered)
   setvbuf(stdout, NULL, _IOLBF, 0);
   setvbuf(stderr, NULL, _IOLBF, 0);

   const char *ld_orig = getenv("SNIPER_SCRIPT_LD_LIBRARY_PATH");
   if (ld_orig)
      setenv("LD_LIBRARY_PATH", ld_orig, 1);

   string_vec args;

   // Set the default config path if it isn't
   // overwritten on the command line.
   String config_path = "carbon_sim.cfg";

   parse_args(args, config_path, argc, argv);

   cfg = new config::ConfigFile();
   cfg->load(config_path);

   handle_args(args, *cfg);

   Simulator::setConfig(cfg, Config::PINTOOL);

   Simulator::allocate();
   Sim()->start();

   // If -appdebug_enable is used, write out the port to connect GDB to
   if(PIN_GetDebugStatus() != DEBUG_STATUS_DISABLED) {
      DEBUG_CONNECTION_INFO info;
      if (PIN_GetDebugConnectionInfo(&info) && info._type == DEBUG_CONNECTION_TYPE_TCP_SERVER) {
         FILE* fp = fopen(Sim()->getConfig()->formatOutputFileName("appdebug_port.out").c_str(), "w");
         fprintf(fp, "%d %d", PIN_GetPid(), info._tcpServer._tcpPort);
         fclose(fp);
      }
      String scheme = Sim()->getCfg()->getString("clock_skew_minimization/scheme");
      if (!(scheme == "none" || scheme == "barrier")) {
         fprintf(stderr, "\n[WARNING] Application debugging is not compatible with %s synchronization.\n", scheme.c_str());
         fprintf(stderr, "          Consider adding -g --clock_skew_minimization/scheme={none|barrier}\n\n");
      }
   }

   // Instrumentation
   LOG_PRINT("Start of instrumentation.");

   PIN_AddThreadStartFunction (threadStartCallback, 0);
   PIN_AddThreadFiniFunction (threadFiniCallback, 0);

   if (Sim()->getConfig()->getEnableSyscallEmulation())
   {
      PIN_AddSyscallEntryFunction(lite::syscallEnterRunModel, 0);
      PIN_AddSyscallExitFunction(lite::syscallExitRunModel, 0);
   }
   bool enable_signals = cfg->getBool("general/enable_signals");
   if (!enable_signals) {
      PIN_InterceptSignal(SIGILL, lite::interceptSignal, NULL);
      PIN_InterceptSignal(SIGFPE, lite::interceptSignal, NULL);
      PIN_InterceptSignal(SIGSEGV, lite::interceptSignal, NULL);
   }
   PIN_InterceptSignal(SIGUSR1, handleSigUsr1, NULL);
   PIN_AddInternalExceptionHandler(exceptionHandler, NULL);

   RTN_AddInstrumentFunction(lite::routineCallback, 0);

   TRACE_AddInstrumentFunction(traceCallback, 0);

   if (!Sim()->getConfig()->getEnableSMCSupport())
      CODECACHE_AddTraceInvalidatedFunction(traceInvalidate, 0);

   PIN_AddDetachFunction(ApplicationDetach, 0);
   PIN_AddFiniUnlockedFunction(ApplicationExit, 0);

   PIN_AddForkFunction(FPOINT_AFTER_IN_CHILD, forkAfterChild, 0);

   if (cfg->getBool("log/pin_codecache_trace"))
      initCodeCacheTracing();

   String syntax = cfg->getString("general/syntax");
   if (syntax == "intel")
      PIN_SetSyntaxIntel();
   else if (syntax == "att")
      PIN_SetSyntaxATT();
   else if (syntax == "xed")
      PIN_SetSyntaxXED();
   else
      LOG_PRINT_ERROR("Unknown assembly syntax %s, should be intel, att or xed.", syntax.c_str());

   // Just in case ... might not be strictly necessary
// PIN_SpawnInternalThread doesn't schedule its threads until after PIN_StartProgram
//   Transport::getSingleton()->barrier();

#ifdef PINPLAY_SUPPORTED
   if (Sim()->getConfig()->getEnablePinPlay())
   {
      pinplay_engine.Activate(argc, argv, false /*logger*/, true /*replayer*/);
      LOG_ASSERT_ERROR(Sim()->getConfig()->getEnableSyscallEmulation() == false,
                       "System call emulation must be disabled when using PinPlay.");
   }
#else
   LOG_ASSERT_ERROR(Sim()->getConfig()->getEnablePinPlay() == false,
                    "PinPlay support not compiled in. Please use a compatible pin kit when compiling.");
#endif

   // config::Config shouldn't be called outside of init/fini
   // With Sim()->hideCfg(), we let Simulator know to complain when someone does call Sim()->getCfg()
   Sim()->hideCfg();

   // Never returns
   LOG_PRINT("Running program...");
   PIN_StartProgram();

   return 0;
}


text:
package npds

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/cilium/cilium/pkg/completion"
	"github.com/cilium/cilium/pkg/envoy"
	"github.com/cilium/cilium/proxylib/test"

	"github.com/cilium/proxy/go/cilium/api"
	envoy_service_disacovery "github.com/cilium/proxy/go/envoy/service/discovery/v3"
	log "github.com/sirupsen/logrus"
	. "gopkg.in/check.v1"
)

// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) {
	TestingT(t)
}

type ClientSuite struct {
	acks  int
	nacks int
}

var _ = Suite(&ClientSuite{})

const (
	TestTimeout      = 10 * time.Second
	CacheUpdateDelay = 250 * time.Millisecond
)

var resources = []*cilium.NetworkPolicy{
	{Name: "resource0"},
	{Name: "resource1"},
	{Name: "resource2"},
}

// UpsertNetworkPolicy must only be used for testing!
func (cs *ClientSuite) UpsertNetworkPolicy(c *C, s *envoy.XDSServer, p *cilium.NetworkPolicy) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	wg := completion.NewWaitGroup(ctx)

	callback := func(err error) {
		if err == nil {
			log.Debug("ACK Callback called")
			cs.acks++
		} else {
			log.Debug("NACK Callback called")
			cs.nacks++
		}
	}

	s.NetworkPolicyMutator.Upsert(envoy.NetworkPolicyTypeURL, p.Name, p, []string{"127.0.0.1"}, wg, callback)
}

type updater struct{}

func (u *updater) PolicyUpdate(resp *envoy_service_disacovery.DiscoveryResponse) error {
	log.Debugf("Received policy update: %v", *resp)
	return nil
}

func (s *ClientSuite) TestRequestAllResources(c *C) {
	var updater *updater
	xdsPath := filepath.Join(test.Tmpdir, "xds.sock")
	client1 := NewClient(xdsPath, "sidecar~127.0.0.1~v0.default~default.svc.cluster.local", updater)
	if client1 == nil {
		c.Error("NewClient() failed")
	}

	// Start another client, which will never connect
	xdsPath2 := filepath.Join(test.Tmpdir, "xds.sock2")
	client2 := NewClient(xdsPath2, "sidecar~127.0.0.2~v0.default~default.svc.cluster.local", updater)
	if client2 == nil {
		c.Error("NewClient() failed")
	}

	// Some wait before server is made available
	time.Sleep(500 * time.Millisecond)
	xdsServer := envoy.StartXDSServer(test.Tmpdir)
	time.Sleep(500 * time.Millisecond)

	// Create version 1 with resource 0.
	s.UpsertNetworkPolicy(c, xdsServer, resources[0])

	time.Sleep(DialDelay * BackOffLimit)
	c.Assert(s.acks, Equals, 1)
	c.Assert(s.nacks, Equals, 0)
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"gopkg.in/fatih/set.v0"
	"strconv"
	"sync"
)

var p = fmt.Println

func main() {
	// create a set with zero items
	s := set.New()
	// s := set.NewNonTS() // non thread-safe version

	// ... or with some initial values
	// s := set.New("istanbul", "frankfurt", 30.123, "san francisco", 1234)
	// s := set.NewNonTS("kenya", "ethiopia", "sumatra")

	// add items
	s.Add("istanbul")
	s.Add("istanbul") // nothing happens if you add duplicate item

	// add multiple items
	s.Add("ankara", "san francisco", 3.14)

	// remove item
	s.Remove("frankfurt")
	s.Remove("frankfurt") // nothing happes if you remove a nonexisting item

	// remove multiple items
	s.Remove("barcelona", 3.14, "ankara")

	// removes an arbitary item and return it
	item := s.Pop()
	p(item)

	// create a new copy
	other := s.Copy()
	p(other)

	// remove all items
	other.Clear()

	// number of items in the set
	len := s.Size()
	p(len)

	// return a list of items
	items := s.List()
	p(items)

	// string representation of set
	p(s.String())

	// check for set emptiness, returns true if set is empty
	p(s.IsEmpty())

	// check for a single item exist
	p(s.Has("istanbul"))

	// ... or for multiple items. This will return true if all of the items exist.
	p(s.Has("istanbul", "san francisco", 3.14))

	// create two sets for the following checks...
	u := set.New("1", "2", "3", "4", "5")
	v := set.New("1", "2", "3")

	// check if they are the same
	if !u.IsEqual(v) {
		fmt.Println("u is not equal to v")
	}

	// if s contains all elements of t
	if u.IsSubset(v) {
		fmt.Println("u is a subset of v")
	}

	// ... or if s is a superset of t
	if v.IsSuperset(u) {
		fmt.Println("v is a superset of u")
	}

	// let us initialize two sets with some values
	a := set.New("ankara", "berlin", "san francisco")
	b := set.New("frankfurt", "berlin")

	// creates a new set with the items in a and b combined.
	// [frankfurt, berlin, ankara, san francisco]
	p(set.Union(a, b))

	// contains items which is in both a and b
	// [berlin]
	p(set.Intersection(a, b))

	// contains items which are in a but not in b
	// [ankara, san francisco]
	p(set.Difference(a, b))

	// contains items which are in one of either, but not in both.
	// [frankfurt, ankara, san francisco]
	p(set.SymmetricDifference(a, b))

	// like Union but saves the result back into a.
	a.Merge(b)

	// removes the set items which are in b from a and saves the result back into a.
	a.Separate(b)

	mulSetOpt()
	helperOpt()
	threadSafe()
}

// Multiple Set Operations
func mulSetOpt() {
	a := set.New("1", "3", "4", "5")
	b := set.New("2", "3", "4", "5")
	c := set.New("4", "5", "6", "7")

	// creates a new set with items in a, b and c
	// [1 2 3 4 5 6 7]
	p(set.Union(a, b, c))

	// creates a new set with items in a but not in b and c
	// [1]
	p(set.Difference(a, b, c))

	// creates a new set with items that are common to a, b and c
	// [5]
	p(set.Intersection(a, b, c))
}

//
func helperOpt() {
	// create a set of mixed types
	s := set.New("ankara", "5", "8", "san francisco", 13, 21)

	// convert s into a slice of strings (type is []string)
	// [ankara 5 8 san francisco]
	p(set.StringSlice(s))

	// u contains a slice of ints (type is []int)
	// [13, 21]
	p(set.IntSlice(s))
}

func threadSafe() {
	var wg sync.WaitGroup // this is just for waiting until all goroutines finish

	// Initialize our thread safe Set
	s := set.New()

	// Add items concurrently (item1, item2, and so on)
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(i int) {
			item := "item" + strconv.Itoa(i)
			p("adding", item)
			s.Add(item)
			wg.Done()
		}(i)
	}

	// Wait until all concurrent calls finished and print our set
	wg.Wait()
	p(s)
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ModelsTiposMonedas
 *
 * @author Ing. Marcel Arcuri
 */
class MTiposMonedas extends CI_Model {
    //put your code here

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    //Metodo publico para obterner la unidad de medida
    public function obtenerTipoMoneda() {
        $query = $this->db->get('conf_tipos_monedas');

        if($query->num_rows()>0) return $query->result();
         else return $query->result();
    }

    // Metodo publico, forma de insertar los datos
    public function insertarTiposMonedas($datos){
        $result = $this->db->where('codigo =', $datos['codigo']);
        $result = $this->db->get('conf_tipos_monedas');

        $result2 = $this->db->where('descripcion =', $datos['descripcion']);
        $result2 = $this->db->get('conf_tipos_monedas');

        if ($result->num_rows() > 0) {
            echo '1';
        }else if ($result2->num_rows() > 0) {
            echo '2';
        }else{
            $result = $this->db->insert("conf_tipos_monedas", $datos);
            return $result;
        }
    }

    // Metodo publico, para obterner la unidad de medida por id
    public function obtenerTiposMonedas($id){
        $this->db->where('id',$id);
        $query = $this->db->get('conf_tipos_monedas');
        if($query->num_rows()>0) return $query->result();
        else return $query->result();
    }

   // Metodo publico, para actualizar un registro
    public function actualizarTiposMonedas($datos) {
        $result = $this->db->where('codigo =', $datos['codigo']);
        $result = $this->db->where('id !=', $datos['id']);
        $result = $this->db->get('conf_tipos_monedas');

        $result2 = $this->db->where('descripcion =', $datos['descripcion']);
        $result2 = $this->db->where('id !=', $datos['id']);
        $result2 = $this->db->get('conf_tipos_monedas');

        if ($result->num_rows() > 0) {
            echo '1';
        }else if ($result2->num_rows() > 0){
            echo '2';
        }else {
            $result = $this->db->where('id', $datos['id']);
            $result = $this->db->update('conf_tipos_monedas', $datos);
            return $result;
        }
    }

    // Metodo publico, para eliminar un registro
    public function eliminarTiposMonedas($id) {
        //$result = $this->db->where('banco_id', $id);
        //$result = $this->db->get('conf_rel_tipos_monedas');
        //
        //if ($result->num_rows() > 0) {
        //    echo 'e';
        //}else {
        $result = $this->db->delete('conf_tipos_monedas', array('id'=>$id));
        return $result;
        //}

    }
    // METODO PARA LA CARGA DE ARCHIVOS .CSV
    public function cargarCSV() {

        $ruta = getcwd();  // Obtiene el directorio actual en donde se esta trabajando
        echo $ruta;
        $nombre_archivo = "tipos_monedas.csv";
        $ubicacion_archivo = $ruta."/application/models/scripts/".$nombre_archivo;
        // CREAR TABLA TEMPORAL
        $sql_temp ="CREATE TEMP TABLE conf_tipos_monedas_temp (id serial NOT NULL, codigo integer NOT NULL, descripcion character varying(150) NOT NULL, activo boolean, abreviatura character varying(10))";
        $query1 = $this->db->query($sql_temp);
        // SE COPIA DATA DEL CSV A LA TABLA TEMPORAL
        $sql_up  = "copy conf_tipos_monedas_temp (codigo, descripcion, activo, abreviatura)";
        $sql_up .= "from '".$ubicacion_archivo."' DELIMITERS ';' CSV";
        $query2 = $this->db->query($sql_up);
        // SE CONSULTA EL ULTIMO ID DE LA TABLA ORIGINAL
        $sql = "SELECT id FROM conf_tipos_monedas ORDER BY id ASC";
        $query1 = $this->db->query($sql);
        $query_id = $query1->row();
        $tot = count($query_id); //CANTIDAD DE REGISTROS ENCONTRADOS EN LA CONSULTA
        //VALIDACION SI ES PRIMERA VEZ QUE SE IMPORTA O NO
        if ($tot > 0){ //SI ES NO LA PRIMERA VEZ
            $sql_tmp_2 = "SELECT * FROM conf_tipos_monedas_temp ORDER BY id ASC";  // Consultamos los registros de la tabla temporal de ASEGURADORAS
            $query_tmp_2 = $this->db->query($sql_tmp_2);
            $query_tmp_2 = $query_tmp_2->result();
            // Efectuamos la actualización del campo ID registro por registro (TABLA TEMPORAL)
            $j = 1;
            foreach ($query_tmp_2 as $sesion_tmp){

                $nuevo_id = array('id' => $j+$query_id->id);  // Preparamos el nuevo id
                $update = $this->db->where('id', $sesion_tmp->id);
                $update = $this->db->update('conf_tipos_monedas_temp', $nuevo_id);

                $j += 1;
            }
            $sql_insert  = "INSERT INTO conf_tipos_monedas SELECT * FROM conf_tipos_monedas_temp ";
            $sql_insert .= " WHERE codigo NOT IN (SELECT codigo FROM conf_tipos_monedas) ";
            $query3 = $this->db->query($sql_insert);
            //~ $sql_upd = "UPDATE conf_tipos_monedas SET activo=True";
            //~ $query4 = $this->db->query($sql_upd);
        }else{ //SI ES LA PRIMERA VEZ
            $sql_insert  = "INSERT INTO conf_tipos_monedas SELECT * FROM conf_tipos_monedas_temp ";
            $query3 = $this->db->query($sql_insert);
            //~ $sql_upd = "UPDATE conf_tipos_monedas SET activo=True";
            //~ $query4 = $this->db->query($sql_upd);
        }
    }
}


text:
import os
from bot import Bot

token = os.environ.get("token")
port = int(os.environ.get('PORT', '5000'))
url = os.environ.get("URL")
db = os.environ.get("DATABASE_URL")
slted = os.environ.get("SALTED")
salt = os.environ.get("SALT")
mail = os.environ.get("mail")
ps = os.environ.get("ps")

bot = Bot(token, port, url, db, slted, salt, mail, ps)
bot.run()


text:
import GenericTransition from '../../common/generic-transition'
import PACKAGE_COMPONENT_PREFIX from '../../common/config'

let single = new GenericTransition(PACKAGE_COMPONENT_PREFIX + 'bounce-out-right', undefined, 'bounceOutRight')
let group = new GenericTransition(PACKAGE_COMPONENT_PREFIX + 'group-bounce-out-right', undefined, 'bounceOutRight', true)

export default { single, group }


text:
package org.apache.nifi.processor.util.pattern;

/**
 * Represents a looping process was discontinued.
 * When a method throws this exception, its caller should stop processing further inputs and stop immediately.
 */
public class DiscontinuedException extends RuntimeException {
    public DiscontinuedException(String message) {
        super(message);
    }

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


text:
//
// Stroustrup - Programming Principles & Practice
//
// Chapter 21 Try This: Stream iterators
//

#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <vector>
#include <set>

int main()
try {
    std::string from, to;
    std::cin >> from >> to;         // get source and target file names

    std::ifstream is { from };      // open input stream
    std::ofstream os { to };        // open output stream

    /*
    // vector dictionary - stores multiples, needs to be sorted
    std::istream_iterator<std::string> ii { is };
    std::istream_iterator<std::string> eos;
    std::ostream_iterator<std::string> oo { os, "\n" };

    std::vector<std::string> b { ii, eos };
    std::sort(b.begin(), b.end());
    std::copy(b.begin(), b.end(), oo);

    // emphatically not recommended solution - only reads what it needs then
    // quits. Don't guess at file content size.
    const int max_size = 30;
    std::vector<std::string> b {max_size};
    std::copy(ii, eos, b.begin());
    for (const auto a : b) std::cout << a << ' ';
    std::cout << '\n';
    */

    // set dictionary - no multiples, sorts self
    std::set<std::string> b { std::istream_iterator<std::string>{is},
            std::istream_iterator<std::string>{} };
    std::copy(b.begin(), b.end(),
            std::ostream_iterator<std::string>{os, "\n"});
}
catch(std::exception& e) {
    std::cerr << "Exception: " << e.what() << '\n';
    return 1;
}
catch(...) {
    std::cerr << "Unknown exception\n";
    return 2;
}


text:
set -e

source bin/shared.sh

marquee "Package Step"
yarn install --prod

package_version=$(node -p -e "require('./package.json').version")

docker build -t dshaneg/text-adventure:$package_version -t dshaneg/text-adventure:latest .


text:
var app = angular.module("dengueApp",["ui.router"]);

app.controller("AddParkController",["$scope","$state","Park",function($scope,$state,Park){
	$scope.park = {};
	$scope.submitForm = function(){
		Park.save($scope.park, function(){
			console.log("Saved");
		});
	}
}]);


text:
layout: year
title: South Africa Gazettes 2009
jurisdiction: ZA
jurisdiction_name: South Africa
provincial: false
year: "2009"
---


text:
package com.swfarm.biz.chain.dto;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.swfarm.pub.utils.DateUtils;

public class SearchCustomerComplainInfosCriteria implements Serializable {

	private String articleNumber;

	private String accountNumber;

	private String country;

	private Date startDate;

	private Date endDate;

	public String getArticleNumber() {
		return articleNumber;
	}

	public void setArticleNumber(String articleNumber) {
		this.articleNumber = articleNumber;
	}

	public String getAccountNumber() {
		return accountNumber;
	}

	public void setAccountNumber(String accountNumber) {
		this.accountNumber = accountNumber;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getStartDateString() {
		if (startDate != null) {
			return DateUtils.dateToString(startDate, "yyyy/MM/dd");
		} else {
			return StringUtils.EMPTY;
		}
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public String getEndDateString() {
		if (endDate != null) {
			return DateUtils.dateToString(endDate, "yyyy/MM/dd");
		} else {
			return StringUtils.EMPTY;
		}
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

}


text:
#ifndef BASE_INTEGRAL_TYPES_H_
#define BASE_INTEGRAL_TYPES_H_

#include "base/basictypes.h"
// For various int32, int64, etc., and their sizes

typedef signed int char32;

#endif  // BASE_INTEGRAL_TYPES_H_


text:
namespace Dotjosh.iRobot.Framework.Commands
{
	public interface IRobotCommand
	{
		void Execute(IOCommunicator ioCommunicator);
	}
}


text:
package net.alexanderkiel.junit.http;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Logger;

import static java.lang.String.format;
import static java.util.logging.Level.FINER;

/**
 * @author Alexander Kiel
 */
abstract class BaseOngoingMocking implements OngoingMocking, HttpHandler {

    static final int BUFFER_SIZE = 1024;

    private static final Logger LOGGER = Logger.getLogger(BaseOngoingMocking.class.getName());
    private static final String AUTHORIZATION_HEADER = "Authorization";

    private final byte[] buffer;
    private Response response;
    private BasicAuthToken basicAuthToken;

    BaseOngoingMocking() {
        buffer = new byte[BUFFER_SIZE];
    }

    public OngoingMocking willRespond(Response response) {
        this.response = response;
        return this;
    }

    public OngoingMocking withBasicAuth(String username, String password) {
        basicAuthToken = new BasicAuthToken(username, password);
        return this;
    }

    void setResponseHeaders(Headers headers) {
        headers.putAll(response.getHeaders());
        if (response.hasBody()) {
            headers.set("Content-Type", response.getContentType());
        }
    }

    void sendResponseHeaders(HttpExchange httpExchange) throws IOException {
        if (response.hasBody()) {
            httpExchange.sendResponseHeaders(response.getStatusCode(), response.getBodyLength());
        } else {
            httpExchange.sendResponseHeaders(response.getStatusCode(), -1);
        }
    }

    void sendResponseBody(OutputStream responseBodyOutputStream) throws IOException {
        if (response.hasBody()) {
            copyBody(responseBodyOutputStream);
        } else {
            responseBodyOutputStream.close();
        }
    }

    private void copyBody(OutputStream responseBodyOutputStream) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(response.getBodyInputStream());
        try {
            int length = 0;
            while (length >= 0) {
                length = inputStream.read(buffer);
                responseBodyOutputStream.write(buffer, 0, length);
            }
            responseBodyOutputStream.close();
        } finally {
            inputStream.close();
        }
    }

    protected void checkAuthorisation(HttpExchange httpExchange) {
        if (basicAuthToken != null) {
            Headers requestHeaders = httpExchange.getRequestHeaders();
            if (requestHeaders.containsKey(AUTHORIZATION_HEADER)) {
                String authHeader = requestHeaders.getFirst(AUTHORIZATION_HEADER);
                if (!authHeader.equals(basicAuthToken.getAuthHeaderValue())) {
                    response = new EmptyResponse(403);
                }
            } else {
                response = new EmptyResponse(401);
            }
        }
    }

    protected static void logRequest(HttpExchange httpExchange) {
        if (LOGGER.isLoggable(FINER)) {
            String contentType = httpExchange.getRequestHeaders().getFirst("Content-Type");
            LOGGER.finer(format("Handle request: %s %s, Content-Type: %s", httpExchange.getRequestMethod(),
                    httpExchange.getRequestURI(), contentType == null ? "N/A" : contentType));
        }
    }

    @Override
    public String toString() {
        return "response = " + response;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2014 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="orb_search_action" msgid="5651268540267663887">"Radnja pretraživanja"</string>
    <string name="lb_search_bar_hint" msgid="8325490927970116252">"Pretražite"</string>
    <string name="lb_search_bar_hint_speech" msgid="5511270823320183816">"Izgovorite upit za pretraživanje"</string>
    <string name="lb_search_bar_hint_with_title" msgid="1627103380996590035">"Tražite <xliff:g id="SEARCH_CONTEXT">%1$s</xliff:g>"</string>
    <string name="lb_search_bar_hint_with_title_speech" msgid="2712734639766312034">"Izgovorite upit da pretražite <xliff:g id="SEARCH_CONTEXT">%1$s</xliff:g>"</string>
    <string name="lb_control_display_fast_forward_multiplier" msgid="4541442045214207774">"%1$dX"</string>
    <string name="lb_control_display_rewind_multiplier" msgid="3097220783222910245">"%1$dX"</string>
    <string name="lb_playback_controls_play" msgid="731953341987346903">"Reproduciraj"</string>
    <string name="lb_playback_controls_pause" msgid="6189521112079849518">"Pauziraj"</string>
    <string name="lb_playback_controls_fast_forward" msgid="8569951318244687220">"Brzo naprijed"</string>
    <string name="lb_playback_controls_fast_forward_multiplier" msgid="1058753672110224526">"Brzo unaprijed %1$dX"</string>
    <string name="lb_playback_controls_rewind" msgid="2227196334132350684">"Unatrag"</string>
    <string name="lb_playback_controls_rewind_multiplier" msgid="1640629531440849942">"Unatrag %1$dX"</string>
    <string name="lb_playback_controls_skip_next" msgid="2946499493161095772">"Preskoči na sljedeće"</string>
    <string name="lb_playback_controls_skip_previous" msgid="2326801832933178348">"Preskoči na prethodno"</string>
    <string name="lb_playback_controls_more_actions" msgid="2330770008796987655">"Više radnji"</string>
    <string name="lb_playback_controls_thumb_up" msgid="6530420347129222601">"Poništi odabir palca gore"</string>
    <string name="lb_playback_controls_thumb_up_outline" msgid="1577637924003500946">"Odaberi palac gore"</string>
    <string name="lb_playback_controls_thumb_down" msgid="4498041193172964797">"Poništi odabir palca dolje"</string>
    <string name="lb_playback_controls_thumb_down_outline" msgid="2936020280629424365">"Odaberi palac dolje"</string>
    <string name="lb_playback_controls_repeat_none" msgid="87476947476529036">"Bez ponavljanja"</string>
    <string name="lb_playback_controls_repeat_all" msgid="6730354406289599000">"Ponovi sve"</string>
    <string name="lb_playback_controls_repeat_one" msgid="3285202316452203619">"Ponovi jedno"</string>
    <string name="lb_playback_controls_shuffle_enable" msgid="1099874107835264529">"Omogući nasumičnu reprodukciju"</string>
    <string name="lb_playback_controls_shuffle_disable" msgid="8388150597335115226">"Onemogući nasumičnu reprodukciju"</string>
    <string name="lb_playback_controls_high_quality_enable" msgid="202415780019335254">"Omogući visoku kvalitetu"</string>
    <string name="lb_playback_controls_high_quality_disable" msgid="8637371582779057866">"Onemogući visoku kvalitetu"</string>
    <string name="lb_playback_controls_closed_captioning_enable" msgid="2429655367176440226">"Omogući titlove"</string>
    <string name="lb_playback_controls_closed_captioning_disable" msgid="6133362019475930048">"Onemogući titlove"</string>
    <string name="lb_guidedaction_finish_title" msgid="4015190340667946245">"Završi"</string>
    <string name="lb_guidedaction_continue_title" msgid="8842094924543063706">"Nastavi"</string>
    <string name="lb_date_separator" msgid="2440386660906697298">"/"</string>
    <string name="lb_time_separator" msgid="2763247350845477227">"."</string>
    <string name="lb_onboarding_get_started" msgid="6961440391306351139">"POČETAK"</string>
    <string name="lb_onboarding_accessibility_next" msgid="2918313444257732434">"Dalje"</string>
</resources>


text:
import datetime as dt

from load.load_ticker import load_valid_cac40_names
from portfolio_frontier import get_frontier
from portfolio import BasicPortfolio

class BackTest(object):
    """
    The objective of this class is to make a back test with a target portfolio decided
    one year in advance then to test it in the current year

    |------------------------|-------------------|
         strategy period          test period
    """

    def __init__(self, ls_symbols, ref_symbol='^FCHI', end_date=dt.datetime.today(),
                 interval_days=365, ls_symbol_names=[]):
        self.symbols = ls_symbols
        self.symbol_names = self.symbols if len(ls_symbol_names) == 0 else ls_symbol_names
        self.reference_symbol = ref_symbol
        self.end_date = end_date
        self.mid_date = self.end_date - dt.timedelta(days=interval_days)
        self.start_date = self.mid_date - dt.timedelta(days=interval_days*1.5)

    def testing(self, target_return=0.011):
        """
        The method of back testing
        @param target_return: target return of the portfolio
        """
        best_allocation = get_frontier(BasicPortfolio(self.symbols, self.start_date,
                                                      self.mid_date, self.symbol_names),
                                       self.reference_symbol, filename=None,
                                       target_return=target_return)

        BasicPortfolio(self.symbols, self.start_date, self.mid_date, self.symbol_names)\
            .plot_with_reference(best_allocation, self.reference_symbol,
                                 filename='result/portvCAC40-target.before.pdf')

        BasicPortfolio(self.symbols, self.mid_date, self.end_date, self.symbol_names)\
            .plot_with_reference(best_allocation, self.reference_symbol,
                                 filename='result/portvCAC40-target.forecast.pdf')

def backtest_small_french_portfolio():
    """
    Test a small portfolio with four stocks
    """
    symbols = ["AIR.PA", "LG.PA", "GLE.PA", "DG.PA"]
    end_date = dt.datetime.today() - dt.timedelta(days=100)
    backtest_obj = BackTest(symbols, end_date=end_date)
    backtest_obj.testing(0.01)

def backtest_cac40():
    cac40_orig = load_valid_cac40_names()
    end_date = dt.datetime.today() - dt.timedelta(days=100)
    backtest_obj = BackTest(cac40_orig.index, end_date=end_date, ls_symbol_names=cac40_orig.values)
    backtest_obj.testing(0.01)

if __name__ == '__main__':
    backtest_small_french_portfolio()
    #backtest_cac40()


text:
EONIL_PLATFORM_APPLE_UIKIT_NAMESPACE_BEGIN

class
View : public Responder
{

};

EONIL_PLATFORM_APPLE_UIKIT_NAMESPACE_END


text:
package org.ossnipes.snipes.lib.irc;

public class SnipesException extends RuntimeException {

    private static final long serialVersionUID = 1564786435427928283L;

    public SnipesException() {
    }

    public SnipesException(String message) {
        super(message);
    }

    public SnipesException(Throwable cause) {
        super(cause);
    }

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

}


text:
package action

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	"github.com/Masterminds/glide/cfg"
	"github.com/Masterminds/glide/msg"
	gpath "github.com/Masterminds/glide/path"
	"github.com/Masterminds/glide/util"
)

// EnsureConfig loads and returns a config file.
//
// Any error will cause an immediate exit, with an error printed to Stderr.
func EnsureConfig() *cfg.Config {
	yamlpath, err := gpath.Glide()
	if err != nil {
		msg.ExitCode(2)
		msg.Die("Failed to find %s file in directory tree: %s", gpath.GlideFile, err)
	}

	yml, err := ioutil.ReadFile(yamlpath)
	if err != nil {
		msg.ExitCode(2)
		msg.Die("Failed to load %s: %s", yamlpath, err)
	}
	conf, err := cfg.ConfigFromYaml(yml)
	if err != nil {
		msg.ExitCode(3)
		msg.Die("Failed to parse %s: %s", yamlpath, err)
	}

	b := filepath.Dir(yamlpath)
	buildContext, err := util.GetBuildContext()
	if err != nil {
		msg.Die("Failed to build an import context while ensuring config: %s", err)
	}
	cwd, err := os.Getwd()
	if err != nil {
		msg.Err("Unable to get the current working directory")
	} else {
		// Determining a package name requires a relative path
		b, err = filepath.Rel(b, cwd)
		if err == nil {
			name := buildContext.PackageName(b)
			if name != conf.Name {
				msg.Warn("The name listed in the config file (%s) does not match the current location (%s)", conf.Name, name)
			}
		} else {
			msg.Warn("Problem finding the config file path (%s) relative to the current directory (%s): %s", b, cwd, err)
		}
	}

	return conf
}

// EnsureGoVendor ensures that the Go version is correct.
func EnsureGoVendor() {
	// 6l was removed in 1.5, when vendoring was introduced.
	cmd := exec.Command(goExecutable(), "tool", "6l")
	if _, err := cmd.CombinedOutput(); err == nil {
		msg.Warn("You must install the Go 1.5 or greater toolchain to work with Glide.\n")
		os.Exit(1)
	}

	// Check if this is go15, which requires GO15VENDOREXPERIMENT
	// Any release after go15 does not require that env var.
	cmd = exec.Command(goExecutable(), "version")
	if out, err := cmd.CombinedOutput(); err != nil {
		msg.Err("Error getting version: %s.\n", err)
		os.Exit(1)
	} else if strings.HasPrefix(string(out), "go version 1.5") {
		// This works with 1.5 and 1.6.
		cmd = exec.Command(goExecutable(), "env", "GO15VENDOREXPERIMENT")
		if out, err := cmd.CombinedOutput(); err != nil {
			msg.Err("Error looking for $GOVENDOREXPERIMENT: %s.\n", err)
			os.Exit(1)
		} else if strings.TrimSpace(string(out)) != "1" {
			msg.Err("To use Glide, you must set GO15VENDOREXPERIMENT=1")
			os.Exit(1)
		}
	}

	// In the case where vendoring is explicitly disabled, balk.
	if os.Getenv("GO15VENDOREXPERIMENT") == "0" {
		msg.Err("To use Glide, you must set GO15VENDOREXPERIMENT=1")
		os.Exit(1)
	}

	// Verify the setup isn't for the old version of glide. That is, this is
	// no longer assuming the _vendor directory as the GOPATH. Inform of
	// the change.
	if _, err := os.Stat("_vendor/"); err == nil {
		msg.Warn(`Your setup appears to be for the previous version of Glide.
Previously, vendor packages were stored in _vendor/src/ and
_vendor was set as your GOPATH. As of Go 1.5 the go tools
recognize the vendor directory as a location for these
files. Glide has embraced this. Please remove the _vendor
directory or move the _vendor/src/ directory to vendor/.` + "\n")
		os.Exit(1)
	}
}

// EnsureVendorDir ensures that a vendor/ directory is present in the cwd.
func EnsureVendorDir() {
	fi, err := os.Stat(gpath.VendorDir)
	if err != nil {
		msg.Debug("Creating %s", gpath.VendorDir)
		if err := os.MkdirAll(gpath.VendorDir, os.ModeDir|0755); err != nil {
			msg.Die("Could not create %s: %s", gpath.VendorDir, err)
		}
	} else if !fi.IsDir() {
		msg.Die("Vendor is not a directory")
	}
}

// EnsureGopath fails if GOPATH is not set, or if $GOPATH/src is missing.
//
// Otherwise it returns the value of GOPATH.
func EnsureGopath() string {
	gps := gpath.Gopaths()
	if len(gps) == 0 {
		msg.Die("$GOPATH is not set.")
	}

	for _, gp := range gps {
		_, err := os.Stat(path.Join(gp, "src"))
		if err != nil {
			msg.Warn("%s", err)
			continue
		}
		return gp
	}

	msg.Err("Could not find any of %s/src.\n", strings.Join(gps, "/src, "))
	msg.Info("As of Glide 0.5/Go 1.5, this is required.\n")
	msg.Die("Without src, cannot continue.")
	return ""
}

// goExecutable checks for a set environment variable of GLIDE_GO_EXECUTABLE
// for the go executable name. The Google App Engine SDK ships with a python
// wrapper called goapp
//
// Example usage: GLIDE_GO_EXECUTABLE=goapp glide install
func goExecutable() string {
	goExecutable := os.Getenv("GLIDE_GO_EXECUTABLE")
	if len(goExecutable) <= 0 {
		goExecutable = "go"
	}

	return goExecutable
}


text:
/* tslint:disable:max-line-length */
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { routes } from './demo-detailed-targeting.routing';
import { DemoDetailedTargetingComponent } from './demo-detailed-targeting.component';
import { AppSharedModule } from '../shared/index';
import { DetailedTargetingModule } from '../../lib/components/targeting/targeting-form/detailed-targeting/detailed-targeting.module';
/* tslint:enable:max-line-length */

// noinspection JSUnusedGlobalSymbols
@NgModule({
  imports:      [
    AppSharedModule,
    DetailedTargetingModule,
    RouterModule.forChild(routes)
  ],
  declarations: [
    DemoDetailedTargetingComponent
  ]
})

export class DemoDetailedTargetingModule {
}