text:
// Copyright 2014 The Cockroach Authors.
//
// 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. See the AUTHORS file
// for names of contributors.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)

package gossip

import (
	"bytes"
	"fmt"
	"math"
	"net"
	"reflect"
	"regexp"
	"sync"
	"time"

	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
)

// callback holds regexp pattern match and GossipCallback method.
type callback struct {
	pattern *regexp.Regexp
	method  Callback
}

// infoStore objects manage maps of Info and maps of Info Group
// objects. They maintain a sequence number generator which they use
// to allocate new info objects.
//
// infoStores can be queried for incremental updates occurring since a
// specified sequence number.
//
// infoStores can be combined using deltas from peer nodes.
//
// infoStores are not thread safe.
type infoStore struct {
	Infos     infoMap  `json:"infos,omitempty"`  // Map from key to info
	Groups    groupMap `json:"groups,omitempty"` // Map from key prefix to groups of infos
	NodeAddr  net.Addr `json:"-"`                // Address of node owning this info store: "host:port"
	MaxSeq    int64    `json:"-"`                // Maximum sequence number inserted
	seqGen    int64    // Sequence generator incremented each time info is added
	callbacks []callback
}

// monotonicUnixNano returns a monotonically increasing value for
// nanoseconds in Unix time. Since equal times are ignored with
// updates to infos, we're careful to avoid incorrectly ignoring a
// newly created value in the event one is created within the same
// nanosecond. Really unlikely except for the case of unittests, but
// better safe than sorry.
func monotonicUnixNano() int64 {
	monoTimeMu.Lock()
	defer monoTimeMu.Unlock()

	now := time.Now().UnixNano()
	if now == lastTime {
		now = lastTime + 1
	}
	lastTime = now
	return now
}

// String returns a string representation of an infostore.
func (is *infoStore) String() string {
	buf := bytes.Buffer{}
	prepend := ""
	if count := is.infoCount(); count > 0 {
		buf.WriteString(fmt.Sprintf("infostore contains %d info(s)", count))
	} else {
		buf.WriteString("infostore is empty")
	}
	// Compute delta of groups and infos.
	is.visitInfos(func(g *group) error {
		buf.WriteString(prepend)
		prepend = ", "
		buf.WriteString(fmt.Sprintf("group %q", g.Prefix))
		return nil
	}, func(i *info) error {
		buf.WriteString(prepend)
		prepend = ", "
		buf.WriteString(fmt.Sprintf("info %q: %+v", i.Key, i.Val))
		return nil
	})
	return buf.String()
}

// Returns true if the info belongs to a group registered with
// the info store; false otherwise.
func (is *infoStore) belongsToGroup(key string) *group {
	if g, ok := is.Groups[infoPrefix(key)]; ok {
		return g
	}
	return nil
}

var (
	monoTimeMu sync.Mutex
	lastTime   int64
)

// newInfoStore allocates and returns a new infoStore.
// "NodeAddr" is the address of the node owning the infostore
// in "host:port" format.
func newInfoStore(nodeAddr net.Addr) *infoStore {
	return &infoStore{
		Infos:    infoMap{},
		Groups:   groupMap{},
		NodeAddr: nodeAddr,
	}
}

// newInfo allocates and returns a new info object using specified key,
// value, and time-to-live.
func (is *infoStore) newInfo(key string, val interface{}, ttl time.Duration) *info {
	is.seqGen++
	now := monotonicUnixNano()
	ttlStamp := now + int64(ttl)
	if ttl == 0*time.Second {
		ttlStamp = math.MaxInt64
	}
	return &info{
		Key:       key,
		Val:       val,
		Timestamp: now,
		TTLStamp:  ttlStamp,
		NodeAddr:  is.NodeAddr,
		peerAddr:  is.NodeAddr,
		seq:       is.seqGen,
	}
}

// getInfo returns an info object by key or nil if it doesn't exist.
func (is *infoStore) getInfo(key string) *info {
	if group := is.belongsToGroup(key); group != nil {
		return group.getInfo(key)
	}
	if info, ok := is.Infos[key]; ok {
		// Check TTL and discard if too old.
		if info.expired(time.Now().UnixNano()) {
			delete(is.Infos, key)
			return nil
		}
		return info
	}
	return nil
}

// getGroupInfos returns an array of info objects from specified group.
// Returns nil if group is not registered.
func (is *infoStore) getGroupInfos(prefix string) infoSlice {
	if group, ok := is.Groups[prefix]; ok {
		return group.infosAsSlice()
	}
	return nil
}

// registerGroup registers a new group with info store. Subsequent
// additions of infos will first check whether the info prefix matches
// a group. On match, the info will be added to the group instead of
// to the info map.
//
// REQUIRES: group.prefix is not already in the info store's groups map.
func (is *infoStore) registerGroup(g *group) error {
	if g2, ok := is.Groups[g.Prefix]; ok {
		if g.Prefix != g2.Prefix || g.Limit != g2.Limit || g.TypeOf != g2.TypeOf {
			return util.Errorf("group %q already in group map with different settings %v vs. %v",
				g.Prefix, g, g2)
		}
		return nil
	}
	is.Groups[g.Prefix] = g
	return nil
}

// addInfo adds or updates an info in the infos or groups maps. If the
// prefix of the info is a key of the info store's groups map, then the
// info is added to that group (prefix is defined by prefix of string up
// until last period '.'). Otherwise, the info is added to the infos map.
//
// Returns nil if info was added; error otherwise.
func (is *infoStore) addInfo(i *info) error {
	// If the prefix matches a group, add to group.
	if group := is.belongsToGroup(i.Key); group != nil {
		contentsChanged, err := group.addInfo(i)
		if err != nil {
			return err
		}
		if i.seq > is.MaxSeq {
			is.MaxSeq = i.seq
		}
		is.processCallbacks(i.Key, contentsChanged)
		return nil
	}
	// Only replace an existing info if new timestamp is greater, or if
	// timestamps are equal, but new hops is smaller.
	var contentsChanged bool
	if existingInfo, ok := is.Infos[i.Key]; ok {
		if i.Timestamp < existingInfo.Timestamp ||
			(i.Timestamp == existingInfo.Timestamp && i.Hops >= existingInfo.Hops) {
			return util.Errorf("info %+v older than current info %+v", i, existingInfo)
		}
		contentsChanged = !reflect.DeepEqual(existingInfo.Val, i.Val)
	} else {
		// No preexisting info means contentsChanged is true.
		contentsChanged = true
	}
	// Update info map.
	is.Infos[i.Key] = i
	if i.seq > is.MaxSeq {
		is.MaxSeq = i.seq
	}
	is.processCallbacks(i.Key, contentsChanged)
	return nil
}

// infoCount returns the count of infos stored in groups and the
// non-group infos map. This is really just an approximation as
// we don't check whether infos are expired.
func (is *infoStore) infoCount() uint32 {
	count := uint32(len(is.Infos))
	for _, group := range is.Groups {
		count += uint32(len(group.Infos))
	}
	return count
}

// maxHops returns the maximum hops across all infos in the store.
// This is the maximum number of gossip exchanges between any
// originator and this node.
func (is *infoStore) maxHops() uint32 {
	var maxHops uint32
	is.visitInfos(nil, func(i *info) error {
		if i.Hops > maxHops {
			maxHops = i.Hops
		}
		return nil
	})
	return maxHops
}

// registerCallback compiles a regexp for pattern and adds it to
// the callbacks slice.
func (is *infoStore) registerCallback(pattern string, method Callback) {
	re := regexp.MustCompile(pattern)
	is.callbacks = append(is.callbacks, callback{pattern: re, method: method})
	var infos []*info
	if err := is.visitInfos(nil, func(i *info) error {
		if re.MatchString(i.Key) {
			infos = append(infos, i)
		}
		return nil
	}); err != nil {
		log.Errorf("failed to properly run registered callback while visiting pre-existing info: %s", err)
	}
	// Run callbacks in a goroutine to avoid mutex reentry.
	go func() {
		for _, i := range infos {
			method(i.Key, true /* contentsChanged */)
		}
	}()
}

// processCallbacks processes callbacks for the specified key by
// matching callback regular expression against the key and invoking
// the corresponding callback method on a match.
func (is *infoStore) processCallbacks(key string, contentsChanged bool) {
	var matches []callback
	for _, cb := range is.callbacks {
		if cb.pattern.MatchString(key) {
			matches = append(matches, cb)
		}
	}
	// Run callbacks in a goroutine to avoid mutex reentry.
	go func() {
		for _, cb := range matches {
			cb.method(key, contentsChanged)
		}
	}()
}

// visitInfos implements a visitor pattern to run two methods in the
// course of visiting all groups, all group infos, and all non-group
// infos. The visitGroup function is run against each group in
// turn. After each group is visited, the visitInfo function is run
// against each of its infos. Finally, after all groups have been
// visitied, the visitInfo function is run against each non-group info
// in turn. Be sure to skip over any expired infos.
func (is *infoStore) visitInfos(visitGroup func(*group) error, visitInfo func(*info) error) error {
	now := time.Now().UnixNano()
	for _, g := range is.Groups {
		if visitGroup != nil {
			if err := visitGroup(g); err != nil {
				return err
			}
		}
		if visitInfo != nil {
			for _, i := range g.Infos {
				if i.expired(now) {
					delete(g.Infos, i.Key)
					continue
				}
				if err := visitInfo(i); err != nil {
					return err
				}
			}
		}
	}

	if visitInfo != nil {
		for _, i := range is.Infos {
			if i.expired(now) {
				delete(is.Infos, i.Key)
				continue
			}
			if err := visitInfo(i); err != nil {
				return err
			}
		}
	}

	return nil
}

// combine combines an incremental delta with the current infoStore.
// The sequence numbers on all info objects are reset using the info
// store's sequence generator. All hop distances on infos are
// incremented to indicate they've arrived from an external source.
// Returns the count of "fresh" infos in the provided delta.
func (is *infoStore) combine(delta *infoStore) int {
	// combine group info. If the group doesn't yet exist, register
	// it. Extract the infos from the group and combine them
	// one-by-one using addInfo.
	var freshCount int
	delta.visitInfos(func(g *group) error {
		if _, ok := is.Groups[g.Prefix]; !ok {
			// Make a copy of the group.
			gCopy := newGroup(g.Prefix, g.Limit, g.TypeOf)
			is.registerGroup(gCopy)
		}
		return nil
	}, func(i *info) error {
		is.seqGen++
		i.seq = is.seqGen
		i.Hops++
		i.peerAddr = delta.NodeAddr
		if is.addInfo(i) == nil {
			freshCount++
		}
		return nil
	})
	return freshCount
}

// delta returns an incremental delta of infos added to the info store
// since (not including) the specified sequence number. These deltas
// are intended for efficiently updating peer nodes. Any infos passed
// from node requesting delta are ignored.
//
// Returns nil if there are no deltas.
func (is *infoStore) delta(addr net.Addr, seq int64) *infoStore {
	if seq >= is.MaxSeq {
		return nil
	}

	delta := newInfoStore(is.NodeAddr)

	// Compute delta of groups and infos.
	is.visitInfos(func(g *group) error {
		gDelta := newGroup(g.Prefix, g.Limit, g.TypeOf)
		delta.registerGroup(gDelta)
		return nil
	}, func(i *info) error {
		if i.isFresh(addr, seq) {
			delta.addInfo(i)
		}
		return nil
	})

	delta.MaxSeq = is.MaxSeq
	return delta
}

// distant returns an addrSet of node addresses for gossip peers which
// originated infos with info.Hops > maxHops.
func (is *infoStore) distant(maxHops uint32) *addrSet {
	addrMap := make(map[string]net.Addr)
	is.visitInfos(nil, func(i *info) error {
		if i.Hops > maxHops {
			addrMap[i.NodeAddr.String()] = i.NodeAddr
		}
		return nil
	})

	// Build and return array of addresses.
	addrs := newAddrSet(len(addrMap))
	for _, addr := range addrMap {
		addrs.addAddr(addr)
	}
	return addrs
}

// leastUseful determines which node from amongst the node addresses
// listed in addrs is currently contributing the least. Returns nil
// if addrs is empty.
func (is *infoStore) leastUseful(addrs *addrSet) net.Addr {
	contrib := make(map[string]int, addrs.len())
	for key := range addrs.addrs {
		contrib[key] = 0
	}
	is.visitInfos(nil, func(i *info) error {
		if addrs.hasAddr(i.peerAddr) {
			contrib[i.peerAddr.String()]++
		}
		return nil
	})

	least := math.MaxInt32
	var leastKey string
	for key, count := range contrib {
		if count < least {
			least = count
			leastKey = key
		}
	}

	if least == math.MaxInt32 {
		return nil
	}
	return addrs.addrs[leastKey]
}


text:
from django.test import TestCase
from django.contrib.auth.models import User

from djangobb_forum.models import Post
from djangobb_forum.templatetags.forum_extras import profile_link, link, lofi_link

class TestLinkTags(TestCase):
    fixtures = ['test_forum.json']

    def setUp(self):
        self.user = User.objects.get(pk=1)
        self.post = Post.objects.get(pk=1)

    def test_profile_link(self):
        plink = profile_link(self.user)
        self.assertEqual(plink, "djangobb")

    def test_link(self):
        l = link(self.post)
        self.assertEqual(l, "Test Body")

    def test_lofi_link(self):
        l = lofi_link(self.post)
        self.assertEqual(l, "Test Body")

redpajama_set_name: RedPajamaGithub


text:
package io.druid.indexing.overlord;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Inject;
import io.druid.java.util.emitter.EmittingLogger;
import io.druid.java.util.emitter.service.ServiceEmitter;
import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.concurrent.Execs;
import io.druid.concurrent.TaskThreadPriority;
import io.druid.guice.annotations.Self;
import io.druid.indexer.TaskLocation;
import io.druid.indexing.common.TaskStatus;
import io.druid.indexing.common.TaskToolbox;
import io.druid.indexing.common.TaskToolboxFactory;
import io.druid.indexing.common.config.TaskConfig;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.autoscaling.ScalingStats;
import io.druid.java.util.common.DateTimes;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.Pair;
import io.druid.java.util.common.lifecycle.LifecycleStop;
import io.druid.query.NoopQueryRunner;
import io.druid.query.Query;
import io.druid.query.QueryRunner;
import io.druid.query.QuerySegmentWalker;
import io.druid.query.SegmentDescriptor;
import io.druid.server.DruidNode;
import io.druid.server.SetAndVerifyContextQueryRunner;
import io.druid.server.initialization.ServerConfig;
import org.joda.time.Interval;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * Runs tasks in a JVM thread using an ExecutorService.
 */
public class ThreadPoolTaskRunner implements TaskRunner, QuerySegmentWalker
{
  private static final EmittingLogger log = new EmittingLogger(ThreadPoolTaskRunner.class);

  private final TaskToolboxFactory toolboxFactory;
  private final TaskConfig taskConfig;
  private final ConcurrentMap<Integer, ListeningExecutorService> exec = new ConcurrentHashMap<>();
  private final Set<ThreadPoolTaskRunnerWorkItem> runningItems = new ConcurrentSkipListSet<>(
      ThreadPoolTaskRunnerWorkItem.COMPARATOR
  );
  private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
  private final ServiceEmitter emitter;
  private final TaskLocation location;
  private final ServerConfig serverConfig;

  private volatile boolean stopping = false;

  @Inject
  public ThreadPoolTaskRunner(
      TaskToolboxFactory toolboxFactory,
      TaskConfig taskConfig,
      ServiceEmitter emitter,
      @Self DruidNode node,
      ServerConfig serverConfig
  )
  {
    this.toolboxFactory = Preconditions.checkNotNull(toolboxFactory, "toolboxFactory");
    this.taskConfig = taskConfig;
    this.emitter = Preconditions.checkNotNull(emitter, "emitter");
    this.location = TaskLocation.create(node.getHost(), node.getPlaintextPort(), node.getTlsPort());
    this.serverConfig = serverConfig;
  }

  @Override
  public List<Pair<Task, ListenableFuture<TaskStatus>>> restore()
  {
    return ImmutableList.of();
  }

  @Override
  public void registerListener(TaskRunnerListener listener, Executor executor)
  {
    for (Pair<TaskRunnerListener, Executor> pair : listeners) {
      if (pair.lhs.getListenerId().equals(listener.getListenerId())) {
        throw new ISE("Listener [%s] already registered", listener.getListenerId());
      }
    }

    final Pair<TaskRunnerListener, Executor> listenerPair = Pair.of(listener, executor);

    // Location never changes for an existing task, so it's ok to add the listener first and then issue bootstrap
    // callbacks without any special synchronization.

    listeners.add(listenerPair);
    log.info("Registered listener [%s]", listener.getListenerId());
    for (ThreadPoolTaskRunnerWorkItem item : runningItems) {
      TaskRunnerUtils.notifyLocationChanged(ImmutableList.of(listenerPair), item.getTaskId(), item.getLocation());
    }
  }

  @Override
  public void unregisterListener(String listenerId)
  {
    for (Pair<TaskRunnerListener, Executor> pair : listeners) {
      if (pair.lhs.getListenerId().equals(listenerId)) {
        listeners.remove(pair);
        log.info("Unregistered listener [%s]", listenerId);
        return;
      }
    }
  }

  private static ListeningExecutorService buildExecutorService(int priority)
  {
    return MoreExecutors.listeningDecorator(
        Execs.singleThreaded(
            "task-runner-%d-priority-" + priority,
            TaskThreadPriority.getThreadPriorityFromTaskPriority(priority)
        )
    );
  }

  @Override
  @LifecycleStop
  public void stop()
  {
    stopping = true;

    for (Map.Entry<Integer, ListeningExecutorService> entry : exec.entrySet()) {
      try {
        entry.getValue().shutdown();
      }
      catch (SecurityException ex) {
        log.wtf(ex, "I can't control my own threads!");
      }
    }

    for (ThreadPoolTaskRunnerWorkItem item : runningItems) {
      final Task task = item.getTask();
      final long start = System.currentTimeMillis();
      final boolean graceful;
      final long elapsed;
      boolean error = false;

      if (taskConfig.isRestoreTasksOnRestart() && task.canRestore()) {
        // Attempt graceful shutdown.
        graceful = true;
        log.info("Starting graceful shutdown of task[%s].", task.getId());

        try {
          task.stopGracefully();
          final TaskStatus taskStatus = item.getResult().get(
              new Interval(DateTimes.utc(start), taskConfig.getGracefulShutdownTimeout()).toDurationMillis(),
              TimeUnit.MILLISECONDS
          );

          // Ignore status, it doesn't matter for graceful shutdowns.
          log.info(
              "Graceful shutdown of task[%s] finished in %,dms.",
              task.getId(),
              System.currentTimeMillis() - start
          );

          TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), taskStatus);
        }
        catch (Exception e) {
          log.makeAlert(e, "Graceful task shutdown failed: %s", task.getDataSource())
             .addData("taskId", task.getId())
             .addData("dataSource", task.getDataSource())
             .emit();
          log.warn(e, "Graceful shutdown of task[%s] aborted with exception.", task.getId());
          error = true;
          TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.failure(task.getId()));
        }
      } else {
        graceful = false;
        TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.failure(task.getId()));
      }

      elapsed = System.currentTimeMillis() - start;

      final ServiceMetricEvent.Builder metricBuilder = ServiceMetricEvent
          .builder()
          .setDimension("task", task.getId())
          .setDimension("dataSource", task.getDataSource())
          .setDimension("graceful", String.valueOf(graceful))
          .setDimension("error", String.valueOf(error));

      emitter.emit(metricBuilder.build("task/interrupt/count", 1L));
      emitter.emit(metricBuilder.build("task/interrupt/elapsed", elapsed));
    }

    // Ok, now interrupt everything.
    for (Map.Entry<Integer, ListeningExecutorService> entry : exec.entrySet()) {
      try {
        entry.getValue().shutdownNow();
      }
      catch (SecurityException ex) {
        log.wtf(ex, "I can't control my own threads!");
      }
    }
  }

  @Override
  public ListenableFuture<TaskStatus> run(final Task task)
  {
    final TaskToolbox toolbox = toolboxFactory.build(task);
    final Object taskPriorityObj = task.getContextValue(TaskThreadPriority.CONTEXT_KEY);
    int taskPriority = 0;
    if (taskPriorityObj != null) {
      if (taskPriorityObj instanceof Number) {
        taskPriority = ((Number) taskPriorityObj).intValue();
      } else if (taskPriorityObj instanceof String) {
        try {
          taskPriority = Integer.parseInt(taskPriorityObj.toString());
        }
        catch (NumberFormatException e) {
          log.error(e, "Error parsing task priority [%s] for task [%s]", taskPriorityObj, task.getId());
        }
      }
    }
    // Ensure an executor for that priority exists
    if (!exec.containsKey(taskPriority)) {
      final ListeningExecutorService executorService = buildExecutorService(taskPriority);
      if (exec.putIfAbsent(taskPriority, executorService) != null) {
        // favor prior service
        executorService.shutdownNow();
      }
    }
    final ListenableFuture<TaskStatus> statusFuture = exec.get(taskPriority)
                                                          .submit(new ThreadPoolTaskRunnerCallable(
                                                              task,
                                                              location,
                                                              toolbox
                                                          ));
    final ThreadPoolTaskRunnerWorkItem taskRunnerWorkItem = new ThreadPoolTaskRunnerWorkItem(
        task,
        location,
        statusFuture
    );
    runningItems.add(taskRunnerWorkItem);
    Futures.addCallback(
        statusFuture, new FutureCallback<TaskStatus>()
        {
          @Override
          public void onSuccess(TaskStatus result)
          {
            runningItems.remove(taskRunnerWorkItem);
          }

          @Override
          public void onFailure(Throwable t)
          {
            runningItems.remove(taskRunnerWorkItem);
          }
        }
    );

    return statusFuture;
  }

  @Override
  public void shutdown(final String taskid)
  {
    for (final TaskRunnerWorkItem runningItem : runningItems) {
      if (runningItem.getTaskId().equals(taskid)) {
        runningItem.getResult().cancel(true);
      }
    }
  }

  @Override
  public Collection<TaskRunnerWorkItem> getRunningTasks()
  {
    return ImmutableList.<TaskRunnerWorkItem>copyOf(runningItems);
  }

  @Override
  public Collection<TaskRunnerWorkItem> getPendingTasks()
  {
    return ImmutableList.of();
  }

  @Override
  public Collection<TaskRunnerWorkItem> getKnownTasks()
  {
    return ImmutableList.<TaskRunnerWorkItem>copyOf(runningItems);
  }

  @Override
  public Optional<ScalingStats> getScalingStats()
  {
    return Optional.absent();
  }

  @Override
  public void start()
  {
    // No state startup required
  }

  @Override
  public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
  {
    return getQueryRunnerImpl(query);
  }

  @Override
  public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
  {
    return getQueryRunnerImpl(query);
  }

  private <T> QueryRunner<T> getQueryRunnerImpl(Query<T> query)
  {
    QueryRunner<T> queryRunner = null;
    final String queryDataSource = Iterables.getOnlyElement(query.getDataSource().getNames());

    for (final ThreadPoolTaskRunnerWorkItem taskRunnerWorkItem : ImmutableList.copyOf(runningItems)) {
      final Task task = taskRunnerWorkItem.getTask();
      if (task.getDataSource().equals(queryDataSource)) {
        final QueryRunner<T> taskQueryRunner = task.getQueryRunner(query);

        if (taskQueryRunner != null) {
          if (queryRunner == null) {
            queryRunner = taskQueryRunner;
          } else {
            log.makeAlert("Found too many query runners for datasource")
               .addData("dataSource", queryDataSource)
               .emit();
          }
        }
      }
    }

    return new SetAndVerifyContextQueryRunner(
        serverConfig,
        queryRunner == null ? new NoopQueryRunner<T>() : queryRunner
    );
  }

  private static class ThreadPoolTaskRunnerWorkItem extends TaskRunnerWorkItem
  {
    private static final Comparator<ThreadPoolTaskRunnerWorkItem> COMPARATOR = new Comparator<ThreadPoolTaskRunnerWorkItem>()
    {
      @Override
      public int compare(
          ThreadPoolTaskRunnerWorkItem lhs,
          ThreadPoolTaskRunnerWorkItem rhs
      )
      {
        return lhs.getTaskId().compareTo(rhs.getTaskId());
      }
    };

    private final Task task;
    private final TaskLocation location;

    private ThreadPoolTaskRunnerWorkItem(
        Task task,
        TaskLocation location,
        ListenableFuture<TaskStatus> result
    )
    {
      super(task.getId(), result);
      this.task = task;
      this.location = location;
    }

    public Task getTask()
    {
      return task;
    }

    @Override
    public TaskLocation getLocation()
    {
      return location;
    }
  }

  private class ThreadPoolTaskRunnerCallable implements Callable<TaskStatus>
  {
    private final Task task;
    private final TaskLocation location;
    private final TaskToolbox toolbox;

    public ThreadPoolTaskRunnerCallable(Task task, TaskLocation location, TaskToolbox toolbox)
    {
      this.task = task;
      this.location = location;
      this.toolbox = toolbox;
    }

    @Override
    public TaskStatus call()
    {
      final long startTime = System.currentTimeMillis();

      TaskStatus status;

      try {
        log.info("Running task: %s", task.getId());
        TaskRunnerUtils.notifyLocationChanged(
            listeners,
            task.getId(),
            location
        );
        TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), TaskStatus.running(task.getId()));
        status = task.run(toolbox);
      }
      catch (InterruptedException e) {
        // Don't reset the interrupt flag of the thread, as we do want to continue to the end of this callable.
        if (stopping) {
          // Tasks may interrupt their own run threads to stop themselves gracefully; don't be too scary about this.
          log.debug(e, "Interrupted while running task[%s] during graceful shutdown.", task);
        } else {
          // Not stopping, this is definitely unexpected.
          log.warn(e, "Interrupted while running task[%s]", task);
        }

        status = TaskStatus.failure(task.getId());
      }
      catch (Exception e) {
        log.error(e, "Exception while running task[%s]", task);
        status = TaskStatus.failure(task.getId());
      }
      catch (Throwable t) {
        log.error(t, "Uncaught Throwable while running task[%s]", task);
        throw t;
      }

      status = status.withDuration(System.currentTimeMillis() - startTime);
      TaskRunnerUtils.notifyStatusChanged(listeners, task.getId(), status);
      return status;
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using renderdoc;

namespace renderdocui.Code
{
    class TimedUpdate
    {
        public delegate void UpdateMethod();

        public TimedUpdate(int msCount, UpdateMethod up)
        {
            m_Rate = msCount;
            m_Update = up;
            Start();
        }

        private int m_Rate;
        private UpdateMethod m_Update = null;
        private System.Threading.Timer m_CameraTick = null;

        private static void TickCB(object state)
        {
            if (!(state is TimedUpdate)) return;

            var me = (TimedUpdate)state;

            if (me.m_Update != null) me.m_Update();
            if (me.m_CameraTick != null) me.m_CameraTick.Change(me.m_Rate, System.Threading.Timeout.Infinite);
        }

        public void Start()
        {
            m_CameraTick = new System.Threading.Timer(TickCB, this as object, m_Rate, System.Threading.Timeout.Infinite);
        }

        public void Stop()
        {
            m_CameraTick.Dispose();
            m_CameraTick = null;
        }
    }

    abstract class CameraControls
    {
        protected CameraControls()
        {
        }

        abstract public bool Update();

        abstract public Camera Camera { get; }

        abstract public void MouseWheel(object sender, MouseEventArgs e);

        virtual public void MouseClick(object sender, MouseEventArgs e)
        {
            m_DragStartPos = e.Location;
        }

        virtual public void MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.None)
            {
                m_DragStartPos = new Point(-1, -1);
            }
            else
            {
                if (m_DragStartPos.X < 0)
                {
                    m_DragStartPos = e.Location;
                }

                m_DragStartPos = e.Location;
            }
        }

        virtual public void KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A || e.KeyCode == Keys.D)
                m_CurrentMove[0] = 0;
            if (e.KeyCode == Keys.Q || e.KeyCode == Keys.E)
                m_CurrentMove[1] = 0;
            if (e.KeyCode == Keys.W || e.KeyCode == Keys.S)
                m_CurrentMove[2] = 0;

            if (e.Shift)
                m_CurrentSpeed = 3.0f;
            else
                m_CurrentSpeed = 1.0f;
        }

        virtual public void KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.W)
                m_CurrentMove[2] = 1;
            if (e.KeyCode == Keys.S)
                m_CurrentMove[2] = -1;
            if (e.KeyCode == Keys.Q)
                m_CurrentMove[1] = 1;
            if (e.KeyCode == Keys.E)
                m_CurrentMove[1] = -1;
            if (e.KeyCode == Keys.D)
                m_CurrentMove[0] = 1;
            if (e.KeyCode == Keys.A)
                m_CurrentMove[0] = -1;

            if (e.Shift)
                m_CurrentSpeed = 3.0f;
            else
                m_CurrentSpeed = 1.0f;
        }

        private float m_CurrentSpeed = 1.0f;
        private int[] m_CurrentMove = new int[3] { 0, 0, 0 };

        public float SpeedMultiplier = 0.05f;

        protected int[] CurrentMove { get { return m_CurrentMove; } }
        protected float CurrentSpeed { get { return m_CurrentSpeed * SpeedMultiplier; } }

        private Point m_DragStartPos = new Point(-1, -1);
        protected Point DragStartPos { get { return m_DragStartPos; } }
    }

    class ArcballCamera : CameraControls
    {
        private Camera m_Camera = null;

        public override Camera Camera { get { return m_Camera; } }

        public ArcballCamera()
        {
            m_Camera = Camera.InitArcball();
        }

        public void Reset(Vec3f pos, float dist)
        {
            m_LookAt = pos;
            m_Distance = Math.Abs(dist);

            m_Camera.ResetArcball();
            m_Camera.SetPosition(m_LookAt);
            m_Camera.SetArcballDistance(m_Distance);
        }

        public void SetDistance(float dist)
        {
            m_Distance = Math.Abs(dist);
            m_Camera.SetArcballDistance(m_Distance);
        }

        public override bool Update()
        {
            return false;
        }

        public override void MouseWheel(object sender, MouseEventArgs e)
        {
            float mod = (1.0f - (float)e.Delta / 2500.0f);

            m_Distance = Math.Max(1e-6f, m_Distance * mod);

            m_Camera.SetArcballDistance(m_Distance);

            ((HandledMouseEventArgs)e).Handled = true;
        }

        public override void MouseMove(object sender, MouseEventArgs e)
        {
            if (DragStartPos.X > 0)
            {
                if (e.Button == MouseButtons.Middle ||
                    (e.Button == MouseButtons.Left && (Control.ModifierKeys & Keys.Alt) == Keys.Alt)
                    )
                {
                    float xdelta = (float)(e.X - DragStartPos.X) / 300.0f;
                    float ydelta = (float)(e.Y - DragStartPos.Y) / 300.0f;

                    xdelta *= Math.Max(1.0f, m_Distance);
                    ydelta *= Math.Max(1.0f, m_Distance);

                    Vec3f pos, fwd, right, up;
                    m_Camera.GetBasis(out pos, out fwd, out right, out up);

                    m_LookAt.x -= right.x * xdelta;
                    m_LookAt.y -= right.y * xdelta;
                    m_LookAt.z -= right.z * xdelta;

                    m_LookAt.x += up.x * ydelta;
                    m_LookAt.y += up.y * ydelta;
                    m_LookAt.z += up.z * ydelta;

                    m_Camera.SetPosition(m_LookAt);
                }
                else if (e.Button == MouseButtons.Left)
                {
                    Control c = sender as Control;
                    if (c != null)
                        m_Camera.RotateArcball(DragStartPos, e.Location, c.ClientRectangle.Size);
                }
            }

            base.MouseMove(sender, e);
        }

        private float m_Distance = 10.0f;
        private Vec3f m_LookAt = new Vec3f();
        public Vec3f LookAtPos
        {
            get { return m_LookAt; }
            set { m_LookAt = value; m_Camera.SetPosition(m_LookAt); }
        }
    }

    class FlyCamera : CameraControls
    {
        private Camera m_Camera = null;

        public override Camera Camera { get { return m_Camera; } }

        public FlyCamera()
        {
            m_Camera = Camera.InitFPSLook();
        }

        public void Reset(Vec3f position)
        {
            m_Position = position;
            m_Rotation = new Vec3f();

            Camera.SetPosition(m_Position);
            Camera.SetFPSRotation(m_Rotation);
        }

        public override bool Update()
        {
            Vec3f pos, fwd, right, up;
            m_Camera.GetBasis(out pos, out fwd, out right, out up);

            if (CurrentMove[0] != 0)
            {
                Vec3f dir = right;
                dir.Mul((float)CurrentMove[0]);

                m_Position.x += dir.x * CurrentSpeed;
                m_Position.y += dir.y * CurrentSpeed;
                m_Position.z += dir.z * CurrentSpeed;
            }
            if (CurrentMove[1] != 0)
            {
                Vec3f dir = new Vec3f(0.0f, 1.0f, 0.0f);
                //dir = up;
                dir.Mul((float)CurrentMove[1]);

                m_Position.x += dir.x * CurrentSpeed;
                m_Position.y += dir.y * CurrentSpeed;
                m_Position.z += dir.z * CurrentSpeed;
            }
            if (CurrentMove[2] != 0)
            {
                Vec3f dir = fwd;
                dir.Mul((float)CurrentMove[2]);

                m_Position.x += dir.x * CurrentSpeed;
                m_Position.y += dir.y * CurrentSpeed;
                m_Position.z += dir.z * CurrentSpeed;
            }

            if (CurrentMove[0] != 0 || CurrentMove[1] != 0 || CurrentMove[2] != 0)
            {
                Camera.SetPosition(m_Position);
                return true;
            }

            return false;
        }

        public override void MouseWheel(object sender, MouseEventArgs e)
        {
        }

        public override void MouseMove(object sender, MouseEventArgs e)
        {
            if (DragStartPos.X > 0 && e.Button == MouseButtons.Left)
            {
                m_Rotation.y -= (float)(e.X - DragStartPos.X) / 300.0f;
                m_Rotation.x -= (float)(e.Y - DragStartPos.Y) / 300.0f;

                Camera.SetFPSRotation(m_Rotation);
            }

            base.MouseMove(sender, e);
        }

        private Vec3f m_Position = new Vec3f();
        private Vec3f m_Rotation = new Vec3f();
    }
}


text:
var tooltipSlider = document.getElementById('slider-tooltip');

noUiSlider.create(tooltipSlider, {
	start: [60],
	range: {
		'min': 0,
		'max': 100
	}
});

var tipHandle = tooltipSlider.getElementsByClassName('noUi-handle')[0]
var tooltip = [];

var value;

tooltip = document.createElement('div');
tipHandle.appendChild(tooltip);

// Add a class for styling
tooltip.className += 'tooltip-slider';
// Add additional markup
tooltip.innerHTML = 'Silliness: ';
// Replace the tooltip reference with the span we just added
tooltip = tooltip.getElementsByTagName('span')[0];

// When the slider changes, write the value to the tooltips.
tooltipSlider.noUiSlider.on('update', function( values, handle ){
	value = Math.round(values[handle]);
	tooltip.innerHTML = value;
});


text:
<app-menu-bar></app-menu-bar>

There was an error executing the application.

Products

      {{product.id}}
      {{product.description}}


text:
// -----------------------------------------------------------------------
// <copyright file="ITranscriptsContract.cs" company="Spardo, LLC">
// Copyright (c) 2011 SPardo, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// -----------------------------------------------------------------------

namespace DotNet37Signals.Client.Campfire.Contracts
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using DotNet37Signals.Client.Campfire.Models;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    [ServiceContract]
    public interface ITranscriptsContract : ICampfireContract
    {
        [OperationContract]
        [WebGet(UriTemplate = "/room/{roomId}/transcript.xml")]
        Messages GetToday(string roomid);

        [OperationContract]
        [WebGet(UriTemplate = "/room/{roomId}/transcript/{year}/{month}/{day}.xml")]
        Messages Get(string roomid, string year, string month, string day);
    }

    public static class TranscriptsContractExtensions
    {
        public static Messages Get(this ITranscriptsContract contract, string roomId, DateTime asOf)
        {
            return contract.Get(roomId, asOf.Year.ToString(), asOf.Month.ToString(), asOf.Day.ToString());
        }
    }
}


text:
<?

namespace Helper\Image;

abstract class Image
{

	/**
	 * Creates an object instance and reads image file if it is defined.
	 *
	 * @abstract
	 * @access protected
	 * @param string $file The image file path to read.
	 */
	abstract protected function __construct($file = null);

	/**
	 * Reads image file into object.
	 *
	 * @abstract
	 * @access public
	 * @param string $file The file path.
	 */
	abstract public function load($file);

	/**
	 * Saves image into $file, if not defined saves into file where it has been loaded.
	 *
	 * @abstract
	 * @access public
	 * @param string $file The file path.
	 */
	abstract public function save($file = null);

	/**
	 * Resizes image to defined resolution.
	 *
	 * @abstract
	 * @access public
	 * @param integer $width The width of resized image.
	 * @param integer $height The height of resized image.
	 * @param boolean $adaptive If TRUE uses current gravity to crop or fit image,
	 * 	if FALSE just resizes image as it is without propotions.
	 * @return boolean TRUE on success, FALSE on failure.
	 */
	abstract public function resize($width, $height, $adaptive = false);

	/**
	 * Returns image geometry [width, height] in associated array.
	 *
	 * @abstract
	 * @access public
	 * @return array The geometry.
	 */
	abstract public function getGeometry();

	/**
	 * Returns image width.
	 *
	 * @abstract
	 * @access public
	 * @return integer The width in pixels.
	 */
	abstract public function getWidth();

	/**
	 * Returns image height.
	 *
	 * @abstract
	 * @access public
	 * @return integer The height in pixels.
	 */
	abstract public function getHeight();

	const NorthWest = 'NorthWest',
		North = 'North',
		NorthEast = 'NorthEast',
		West = 'West',
		Center = 'Center',
		East = 'East',
		SouthWest = 'SouthWest',
		South = 'South',
		SouthEast = 'SouthEast',
		Fit = 'Fit';

	const GD = 1, Imagick = 2, Gmagick = 3, None = 0;

	private static $lib;

	private $gravity = self::Fit, $compressionQuality = 75;

	/**
	 * Returns gravity option.
	 *
	 * @access public
	 * @return integer The gravity option.
	 */
	public function getGravity()
	{
		return $this->gravity;
	}

	/**
	 * Sets gravity option.
	 *
	 * @access public
	 * @param integer $gravity The new gravity option.
	 */
	public function setGravity($gravity)
	{
		return $this->gravity = $gravity;
	}

	/**
	 * Returns image compression quality from 0 to 100.
	 *
	 * @access public
	 * @return integer The quality value.
	 */
	public function getCompressionQuality()
	{
		return $this->compressionQuality;
	}

	/**
	 * Sets image compression quality from 0 to 100.
	 *
	 * @access public
	 * @param integer $quality The quality value.
	 */
	public function setCompressionQuality($quality)
	{
		$this->compressionQuality = $quality;
	}

	/**
	 * Returns width, heigt and position of new image which
	 * 	must be resized into defined $width:$height.
	 *
	 * @access protected
	 * @param integer $width The width of new image.
	 * @param integer $height The height of new image.
	 * @return array The associatred array [width, height, left, top].
	 */
	protected function getAdaptiveGeometry($width, $height)
	{
		$result = [
			'width' => $width,
			'height' => $height,
			'left' => 0,
			'top' => 0,
		];
		if (!$width || !$height)
		{
			throw new Exception("Incorrect new resoltion [{$width}x{$height}]");
		}
		$w = $this->getWidth();
		$h = $this->getHeight();
		$scale = $w / $width < $h / $height ? $w / $width : $h / $height;
		if (self::Fit === $this->gravity)
		{
			$scale = $w / $width < $h / $height ? $h / $height : $w / $width;
		}
		if (0 == $scale)
		{
			return $result;
		}
		$w = intval($w / $scale);
		$h = intval($h / $scale);
		$left = 0;
		$top = 0;

		switch ($this->gravity)
		{
			case self::Fit:
				break;

			case self::South:
				$top = $h - $height;
			case self::North:
				$left = intval(($w - $width) / 2);
				break;

			case self::East:
				$left = $w - $width;
			case self::West:
				$top = intval(($h - $height) / 2);
				break;

			case self::Center:
				$left = intval(($w - $width) / 2);
				$top = intval(($h - $height) / 2);
				break;

			case self::NorthEast:
				$left = $w - $width;
				break;

			case self::SouthEast:
				$left = $w - $width;
			case self::SouthWest:
				$top = $h - $height;
				break;
		}
		$result = [
			'width' => $w,
			'height' => $h,
			'left' => $left,
			'top' => $top
		];
		return $result;
	}

	/**
	 * Sets default library without detecting.
	 *
	 * @static
	 * @access public
	 * @param integer $lib The lib constant.
	 */
	public static function useLib($lib = null)
	{
		self::$lib = $lib;
	}

	/**
	 * Detects image library to use.
	 *
	 * @static
	 * @access protected
	 */
	protected static function detectLib()
	{
		if (null !== self::$lib)
		{
			return false;
		}
		if (class_exists("\\Imagick"))
		{
			self::$lib = self::Imagick;
		}
		else if (class_exists("\\Gmagick"))
		{
			self::$lib = self::Gmagick;
		}
		else if (function_exists('gd_info'))
		{
			self::$lib = self::GD;
		}
		else
		{
			self::$lib = self::None;
		}
		return true;
	}

	/**
	 * Creates an instance of image object depending on used library.
	 *
	 * @static
	 * @access public
	 * @param string $file The image
	 */
	public static function create($file = null)
	{
		self::detectLib();
		switch (self::$lib)
		{
			case self::Imagick:
				return new \Helpers\Image\Imagick($file);

			case self::Gmagick:
				return new \Helpers\Image\Gmagick($file);

			case self::GD:
				return new \Helpers\Image\GD($file);
		}

		throw new Exception('Cannot find any supported Image processing library on server');
	}

}


text:
// Template Source: BaseEntityCollectionRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.ReportRoot;
import com.microsoft.graph.models.PrintUsageByPrinter;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseEntityCollectionRequest;
import com.microsoft.graph.requests.PrintUsageByPrinterCollectionResponse;
import com.microsoft.graph.requests.PrintUsageByPrinterCollectionRequestBuilder;
import com.microsoft.graph.requests.PrintUsageByPrinterCollectionRequest;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Print Usage By Printer Collection Request.
 */
public class PrintUsageByPrinterCollectionRequest extends BaseEntityCollectionRequest<PrintUsageByPrinter, PrintUsageByPrinterCollectionResponse, PrintUsageByPrinterCollectionPage> {

    /**
     * The request builder for this collection of PrintUsageByPrinter
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public PrintUsageByPrinterCollectionRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions, PrintUsageByPrinterCollectionResponse.class, PrintUsageByPrinterCollectionPage.class, PrintUsageByPrinterCollectionRequestBuilder.class);
    }

    /**
     * Creates a new PrintUsageByPrinter
     * @param newPrintUsageByPrinter the PrintUsageByPrinter to create
     * @return a future with the created object
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PrintUsageByPrinter> postAsync(@Nonnull final PrintUsageByPrinter newPrintUsageByPrinter) {
        final String requestUrl = getBaseRequest().getRequestUrl().toString();
        return new PrintUsageByPrinterRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
            .buildRequest(getBaseRequest().getHeaders())
            .postAsync(newPrintUsageByPrinter);
    }

    /**
     * Creates a new PrintUsageByPrinter
     * @param newPrintUsageByPrinter the PrintUsageByPrinter to create
     * @return the newly created object
     */
    @Nonnull
    public PrintUsageByPrinter post(@Nonnull final PrintUsageByPrinter newPrintUsageByPrinter) throws ClientException {
        final String requestUrl = getBaseRequest().getRequestUrl().toString();
        return new PrintUsageByPrinterRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null)
            .buildRequest(getBaseRequest().getHeaders())
            .post(newPrintUsageByPrinter);
    }

    /**
     * Sets the expand clause for the request
     *
     * @param value the expand clause
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest expand(@Nonnull final String value) {
        addExpandOption(value);
        return this;
    }

    /**
     * Sets the filter clause for the request
     *
     * @param value the filter clause
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest filter(@Nonnull final String value) {
        addFilterOption(value);
        return this;
    }

    /**
     * Sets the order by clause for the request
     *
     * @param value the order by clause
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest orderBy(@Nonnull final String value) {
        addOrderByOption(value);
        return this;
    }

    /**
     * Sets the select clause for the request
     *
     * @param value the select clause
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest select(@Nonnull final String value) {
        addSelectOption(value);
        return this;
    }

    /**
     * Sets the top value for the request
     *
     * @param value the max number of items to return
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest top(final int value) {
        addTopOption(value);
        return this;
    }

    /**
     * Sets the count value for the request
     *
     * @param value whether or not to return the count of objects with the request
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest count(final boolean value) {
        addCountOption(value);
        return this;
    }
    /**
     * Sets the count value to true for the request
     *
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest count() {
        addCountOption(true);
        return this;
    }
    /**
     * Sets the skip value for the request
     *
     * @param value of the number of items to skip
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest skip(final int value) {
        addSkipOption(value);
        return this;
    }

    /**
     * Add Skip token for pagination
     * @param skipToken - Token for pagination
     * @return the updated request
     */
    @Nonnull
    public PrintUsageByPrinterCollectionRequest skipToken(@Nonnull final String skipToken) {
    	addSkipTokenOption(skipToken);
        return this;
    }
}


text:
<?php  namespace Palmabit\Catalog\ModelMultilanguage\Decorators;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use L;
use Exception;
use Palmabit\Catalog\ModelMultilanguage\Interfaces\DecoratorInterface;
use Palmabit\Catalog\ModelMultilanguage\Interfaces\EditableLanguageDescriptionInterface;

abstract class AbstractLanguageDescriptionsDecorator implements DecoratorInterface
{

    protected $null_resource_name = '';
    protected $descriptions_relation_name = '';
    protected $resource;
    protected $null_resource;
    protected $current_lang;
    protected $default_lang;

    public function __construct(EditableLanguageDescriptionInterface $resource, $current_lang = null)
    {
        if(empty($this->descriptions_relation_name))
        {
            throw new Exception("You cannot instantiate this class without setting descriptions_relation_name field.");
        }

        if(empty($this->null_resource_name))
        {
            throw new Exception("You cannot instantiate this class without setting null_resource_name field.");
        }

        $this->getAppLanguages();
        $this->current_lang = $current_lang ? : $this->current_lang;
        $this->resource = $resource;
        $this->initializeLanguageDescriptions();
        $this->null_resource = new $this->null_resource_name($this, $this->current_lang);
    }

    private function initializeLanguageDescriptions()
    {
        $this->resource->language_descriptions = $this->resource->{$this->descriptions_relation_name}()->get();
    }

    /**
     * @param mixed $resource
     */
    public function setResource($resource)
    {
        $this->resource = $resource;
    }

    /**
     * @return mixed
     */
    public function getResource()
    {
        return $this->resource;
    }

    /**
     * @return mixed
     */
    public function getDescriptionRelationName()
    {
        return $this->descriptions_relation_name;
    }

    /**
     * @param $key
     * @param $value
     * @return mixed
     */
    protected function setAttribute($key, $value)
    {
        if(!$this->isDescriptionField($key))
        {
            return $this->resource->$key = $value;
        }

        $this->setDescriptionValue($key, $value);
    }

    public function __get($key)
    {
        return $this->getAttribute($key);
    }

    public function __set($key, $value)
    {
        return $this->setAttribute($key, $value);
    }

    /**
     * @param $key
     * @return mixed
     */
    protected function getAttribute($key)
    {
        if(!$this->isDescriptionField($key))
        {
            return $this->resource->$key;
        }

        $current_description = $this->findCurrentDescription();

        return $current_description->$key;
    }

    /**
     * @param $current_lang
     * @return null
     */
    public function findCurrentDescription()
    {
        $current_description = $this->findDescriptionForLang($this->current_lang);
        if(!$current_description) $current_description = $this->findDescriptionForLang($this->default_lang);
        $description_object = $current_description ? : $this->null_resource;

        return $description_object;
    }

    /**
     * @param $lang
     * @return mixed
     */
    protected function findDescriptionForLang($lang)
    {
        return $this->resource->language_descriptions->filter(function ($language_description) use ($lang)
        {
            return ($language_description->lang == $lang) ? true : false;
        })->first();
    }

    /**
     * @param $key
     * @param $value
     * @return null
     */
    protected function setDescriptionValue($key, $value)
    {
        $current_description = $this->findDescriptionForLang($this->current_lang);
        $description_object = $current_description ? : $this->null_resource;

        return $description_object->$key = $value;
    }

    /**
     * @param       $method
     * @param array $params
     * @return mixed
     */
    public function __call($method, array $params = [])
    {
        // Calls method on resource if exists
        if(method_exists($this->resource, $method))
        {
            return call_user_func_array([$this->resource, $method], $params);
        }
    }

    /**
     * @param $key
     * @return bool
     */
    private function isDescriptionField($key)
    {
        return in_array($key, $this->resource->getDescriptionAttributes());
    }

    /**
     * @return mixed
     */
    public function getDescriptionObjects()
    {
        return $this->resource->getLanguageDescriptionsAttribute();
    }

    private function getAppLanguages()
    {
        $this->current_lang = L::get();
        $this->default_lang = L::getDefault();
    }

    public function removeLanguageDescription($lang)
    {
        foreach($this->resource->language_descriptions as $key => $language_description)
        {
            if($language_description->lang == $lang) unset($this->resource->language_descriptions[$key]);
        }
    }

    public function fill(array $attributes)
    {
        foreach($attributes as $key => $value)
        {
            if($this->isFillable($key)) $this->setAttribute($key, $value);
        }

        return $this;
    }

    /**
     * @return mixed
     */
    public function getCurrentLang()
    {
        return $this->current_lang;
    }

    /**
     * @return mixed
     */
    public function getDefaultLang()
    {
        return $this->default_lang;
    }

    /**
     * @param mixed $current_lang
     */
    public function setCurrentLang($current_lang)
    {
        $this->current_lang = $current_lang;
    }

    /**
     * @param $key
     * @return bool
     */
    protected function isFillable($key)
    {
        return in_array($key, $this->resource->getFillable())||in_array($key, $this->resource->getDescriptionAttributes());
    }
}


text:
import Testing

main :: IO ()
main = do
    -- print (testResults)
    print "[]"

-- testResults :: [Failure]
-- testResults = runTests allTests
-- testResults = []


text:
package org.hoteia.cas.home;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.security.Principal;

@Controller
public class HomeController {

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Principal principal) {
		return principal != null ? "homeSignedIn" : "homeNotSignedIn";
	}
}


text:
"""Python helper for loading Ignite ops and kernels."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.util import loader
from tensorflow.python.platform import resource_loader

_dataset_ops = loader.load_op_library(
    resource_loader.get_path_to_datafile("../../_dataset_ops.so"))


text:
import io
import os
import sys
import time
import threading

from IOST_Basic                     import *
from IOST_Config                    import *
from IOST_Terminal                  import *
from IOST_Terminal                  import IOST_NPS

import gtk
import gobject
import pango
import gtk.glade
import vte

class IOST_RunTest_LogFile():
    """
    This is a class procces log-file when run the IOST program
    """
    def __init__(self):
        ""
        self.RunTest_TimeStart = time.strftime("%Y-%m-%d_%Hh%Mm%Ss")
        print self.RunTest_TimeStart


text:
WidgetRegistration DropDownWidget::s_DropDownWidgetRegistration("DropDown", &DropDownWidget::CreateWidget, &DropDownWidget::CreateWidgetXML);

//===========================================================================================================
///----------------------------------------------------------------------------------------------------------
///constructors

DropDownWidget::DropDownWidget(){
	//do nothing

}

DropDownWidget::DropDownWidget(const std::string& name) : GroupWidget(name){

}

DropDownWidget::DropDownWidget(const XMLNode& node) : GroupWidget(node){
	m_resizeToFitChildren = true;
}

DropDownWidget::~DropDownWidget(){
	//do nothing
}

///----------------------------------------------------------------------------------------------------------
///virtual overrides

void DropDownWidget::StartUp() {
	BaseWidget::StartUp();

	CreateAllChildren();

	//DoResizeToFitChildren();

	m_currentOption = m_children[0];
	m_currentOption->ShowWidget();

	//set components
	SetRenderComponent();
	SetUICollider2DComponent();

}

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

void DropDownWidget::CreateAllChildren() {

	Vector2 currentOffset = Vector2::ZERO;
	BaseWidget* newChild;
	BaseWidget* prevChild = NULL;

	AABB2 dropDownBounds = GetRenderBounds();

	for (ChildDefinition& childDef : m_childDefs) {

		std::string childName = childDef.name;
		Vector2 childOffset = childDef.offset;
		UIAnchorID childAnchor = UI_ANCHOR_TOP_CENTER;
		std::string childText = childDef.text;

		//create a new one and stuff it in m_children

		//adjust based on prev child
		if (prevChild) {
			float yAdjustment = prevChild->GetRenderBounds().CalcLengthOfSides().y;
			currentOffset.y -= yAdjustment;
		}
		newChild = theUISystem->CreateWidget(childName, currentOffset);
		newChild->SetParent(this);
		newChild->SetAnchorID(childAnchor);

		dropDownBounds.StretchToIncludePoint(newChild->GetPosition());

		//override text attrib
		if (childText != "") {

			for (int i = 0; i < NUM_WIDGET_STATES; i++) {
				WidgetStateID stateID = (WidgetStateID)i;

				WidgetStateProperties& myStateProperties = newChild->GetWidgetStateProperties(stateID);

				if (myStateProperties.m_defaultProperties->HasProperty("text")) {
					myStateProperties.m_defaultProperties->Set("text", childText);
				}
			}
		}

		newChild->HideWidget();

		m_children.push_back(newChild);

		prevChild = newChild;
	}

	//this stuff with the drop down still doesn't work :(
// 	float boxYpadding = abs(currentOffset.y);
//
// 	dropDownBounds.AddPadding(0.0f, boxYpadding);

	Vector2 myResizedDimensions = dropDownBounds.CalcLengthOfSides();

	Vector2 myResizedOffset = dropDownBounds.CalcCenter();

	m_widgetDefaultProperties.Set("offset", myResizedOffset);

	m_widgetDefaultProperties.Set("dimensions", myResizedDimensions);

}

void DropDownWidget::SetDefaultPropertiesFromXML(const XMLNode& node) {
	GroupWidget::SetDefaultPropertiesFromXML(node);
}

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

void DropDownWidget::LoadBaseAttributesFromXML(const XMLNode& node) {
	GroupWidget::LoadBaseAttributesFromXML(node);
}

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

void DropDownWidget::ProcessInput(double deltaSeconds) {

	m_currentOption->ProcessInput(deltaSeconds);

	UICollider2DComponent& currentOptionUICollider = m_currentOption->GetUICollider2DComponent();

	if (!m_UIColliderComponent.OnHover()) {
		HideDropDownOptions();
	}
	else {
		if (currentOptionUICollider.OnHover()) {
			ShowDropDownOptions();
		}//end of outer if

		for (BaseWidget* child : m_children) {
			child->ProcessInput(deltaSeconds);

			UICollider2DComponent& childUICollider = child->GetUICollider2DComponent();
			if (childUICollider.OnHover()) {
				if (child->GetUICollider2DComponent().OnClick(MOUSE_BUTTON_LEFT)) {

					m_currentOption = child;

					break;
				}//end of nested if
			}
		}//end of for

	}//end of outer if/else

}

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

void DropDownWidget::UpdateRenderComponent(double deltaSeconds) {

	if (!m_currentOption)
		return;

	Vector2 currentOffset = Vector2::ZERO;

	m_currentOption->SetOffset(currentOffset);
	m_currentOption->UpdateRenderComponent(deltaSeconds);

	BaseWidget* prevChild = m_currentOption;

	for (BaseWidget* child : m_children) {
		if (child != m_currentOption) {

			//adjust based on prev child
			if (prevChild) {
				float yAdjustment = prevChild->GetRenderBounds().CalcLengthOfSides().y;
				currentOffset.y -= yAdjustment;
			}

			child->SetOffset(currentOffset);
			child->UpdateRenderComponent(deltaSeconds);

			prevChild = child;
		}
	}

	GroupWidget::UpdateRenderComponent(deltaSeconds);

}

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

//upkeep
void DropDownWidget::Update(double deltaSeconds) {

	GroupWidget::Update(deltaSeconds);

}

//render
void DropDownWidget::Render(OpenGLRenderer* renderer) {

	BaseWidget::Render(renderer);

	m_currentOption->Render(renderer);

	for (BaseWidget* child : m_children) {
		if(child != m_currentOption)
		   child->Render(renderer);
	}

}

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

void DropDownWidget::ShowDropDownOptions() {
	for (BaseWidget* child : m_children) {
		if(m_currentOption != child)
			child->ShowWidget();
	}
}

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

void DropDownWidget::HideDropDownOptions() {
	for (BaseWidget* child : m_children) {
		if (m_currentOption != child)
			child->HideWidget();
	}
}

//===========================================================================================================


text:
declare function getSpecifier(): string;
declare var whatToLoad: boolean;
declare const directory: string;
declare const moduleFile: number;

import(getSpecifier());

var p0 = import(`${directory}\${moduleFile}`);
var p1 = import(getSpecifier());
const p2 = import(whatToLoad ? getSpecifier() : "defaulPath")

function returnDynamicLoad(path: string) {
    return import(path);
}

//// [importCallExpressionDeclarationEmit1.js]
Promise.resolve().then(() => require(getSpecifier()));
var p0 = Promise.resolve().then(() => require(`${directory}\${moduleFile}`));
var p1 = Promise.resolve().then(() => require(getSpecifier()));
const p2 = Promise.resolve().then(() => require(whatToLoad ? getSpecifier() : "defaulPath"));
function returnDynamicLoad(path) {
    return Promise.resolve().then(() => require(path));
}

//// [importCallExpressionDeclarationEmit1.d.ts]
declare function getSpecifier(): string;
declare var whatToLoad: boolean;
declare const directory: string;
declare const moduleFile: number;
declare var p0: Promise<any>;
declare var p1: Promise<any>;
declare const p2: Promise<any>;
declare function returnDynamicLoad(path: string): Promise<any>;


text:
layout: page
title: About Me
description: This is what I do.
background: '/img/bg-about1.jpg'
---

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed quisquam ut perspiciatis, repudiandae nulla animi iste vel, praesentium repellendus molestias aliquid consequatur, earum rem qui error voluptates eius enim consequuntur!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex alias, earum consectetur quia natus ducimus voluptate explicabo, hic porro reprehenderit, quasi? Tenetur ipsum distinctio laboriosam perspiciatis officiis dolore, architecto id.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam inventore aspernatur repellendus incidunt adipisci modi voluptates recusandae iste eligendi, repudiandae corporis quod aut, optio! Explicabo quaerat unde voluptatem! Itaque, eum!


text:
namespace Pyrite3D
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Extensions;
    using UnityEngine;

    public class IsRendered : MonoBehaviour
    {
        private readonly List<GameObject> _childDetectors = new List<GameObject>();
        private readonly List<GameObject> _cubes = new List<GameObject>();
        private Cube _cube;
        private CubeLoader _cubeLoader;
        private int _lod;
        private PyriteLoader _manager;
        private MeshRenderer _meshRenderer;
        private PyriteQuery _pyriteQuery;
        private Renderer _render;
        private int _x, _y, _z;
        private LoadCubeRequest _loadCubeRequest;

        private bool Upgradable
        {
            get
            {
                return _manager != null && _childDetectors.Count == 0 && _pyriteQuery.DetailLevels.ContainsKey(_lod - 1);
            }
        }

        public void SetCubePosition(int x, int y, int z, int lod, PyriteQuery query, PyriteLoader manager)
        {
            _x = x;
            _y = y;
            _z = z;
            _lod = lod;
            _pyriteQuery = query;
            _manager = manager;
            name = string.Format("PH_L{3}:{0}_{1}_{2}", x, y, z, lod);
        }

        public void SetCubePosition(int x, int y, int z, int lod, PyriteQuery query, CubeLoader manager)
        {
            _x = x;
            _y = y;
            _z = z;
            _lod = lod;
            _pyriteQuery = query;
            _cubeLoader = manager;
            name = string.Format("PH_L{3}:{0}_{1}_{2}", x, y, z, lod);
        }

        // Use this for initialization
        private void Start()
        {
            _render = GetComponent<Renderer>();
            _meshRenderer = GetComponent<MeshRenderer>();
        }

        private void OnWillRenderObject()
        {
            if (Camera.current == Camera.main)
            {
                if (_cubes.Count == 0 && _childDetectors.Count == 0)
                {
                    _meshRenderer.enabled = false;
                    StartCoroutine(OnRenderRoutine());
                }
            }
        }

        private IEnumerator OnRenderRoutine()
        {
            if (_manager != null)
            {
                _loadCubeRequest = new LoadCubeRequest(_x, _y, _z, _lod, _pyriteQuery, createdObjects =>
                        {
                            if (!_loadCubeRequest.Cancelled)
                            {
                                _cubes.AddRange(createdObjects);
                                StartCoroutine(StopRenderCheck(Camera.main));
                            }
                            else
                            {
                                foreach (var createdObject in createdObjects)
                                {
                                    Destroy(createdObject);
                                }
                            }
                        });

                _manager.EnqueueLoadCubeRequest(_loadCubeRequest);
            }
            else if (_cubeLoader != null)
            {
                _cube = new Cube {MapPosition = new Vector3(_x, _y, _z), Query = _pyriteQuery, Lod = _lod};
                _cubeLoader.AddToQueue(_cube);
                while (_cube.GameObject == null)
                {
                    yield return null;
                }
                _cubes.AddRange(new[] {_cube.GameObject});
                yield return StartCoroutine(StopRenderCheck(Camera.main));
            }
        }

        private bool ShouldUpgrade(Component camera)
        {
            return Vector3.Distance(transform.position, camera.transform.position) < 500 &&
                   Math.Abs(transform.position.y - camera.transform.position.y) < 120;
        }

        public void DestroyChildren()
        {
            if (_loadCubeRequest != null)
            {
                _loadCubeRequest.Cancelled = true;
            }

            if (_cubes != null)
            {
                foreach (var cube in _cubes)
                {
                    Destroy(cube);
                }
                _cubes.Clear();
            }

            if (_cube != null)
            {
                _cube.GameObject = null;
                _cube = null;
            }

            foreach (var detector in _childDetectors)
            {
                detector.GetComponent<IsRendered>().DestroyChildren();
                Destroy(detector);
            }
            _childDetectors.Clear();
        }

        public override string ToString()
        {
            return string.Format("ph L{0}:{1},{2},{3}", _lod, _x, _y, _z);
        }

        private IEnumerator StopRenderCheck(Camera camera)
        {
            while (true)
            {
                if (!_render.IsVisibleFrom(camera))
                {
                    _meshRenderer.enabled = true;
                    DestroyChildren();
                    break;
                }
                if (Upgradable && ShouldUpgrade(camera))
                {
                    yield return
                        StartCoroutine(_manager.AddUpgradedDetectorCubes(_pyriteQuery, _x, _y, _z, _lod,
                            addedDetectors =>
                            {
                                DestroyChildren();
                                _childDetectors.AddRange(addedDetectors);
                            }));
                }

                yield return null;
            }
        }
    }
}


text:
RxJava is a Java VM implementation of [ReactiveX (Reactive Extensions)](https://reactivex.io): a library for composing asynchronous and event-based programs by using observable sequences.

For more information about ReactiveX, see the [Introduction to ReactiveX](http://reactivex.io/intro.html) page.

### RxJava is Lightweight

RxJava tries to be very lightweight. It is implemented as a single JAR that is focused on just the Observable abstraction and related higher-order functions.

### RxJava is a Polyglot Implementation

RxJava supports Java 6 or higher and JVM-based languages such as [Groovy](https://github.com/ReactiveX/RxGroovy), [Clojure](https://github.com/ReactiveX/RxClojure), [JRuby](https://github.com/ReactiveX/RxJRuby), [Kotlin](https://github.com/ReactiveX/RxKotlin) and [Scala](https://github.com/ReactiveX/RxScala).

RxJava is meant for a more polyglot environment than just Java/Scala, and it is being designed to respect the idioms of each JVM-based language. (This is something we're still working on.)

### RxJava Libraries

The following external libraries can work with RxJava:

* [Hystrix](https://github.com/Netflix/Hystrix/wiki/How-To-Use#wiki-Reactive-Execution) latency and fault tolerance bulkheading library.
* [Camel RX](http://camel.apache.org/rx.html) provides an easy way to reuse any of the [Apache Camel components, protocols, transports and data formats](http://camel.apache.org/components.html) with the RxJava API
* [rxjava-http-tail](https://github.com/myfreeweb/rxjava-http-tail) allows you to follow logs over HTTP, like `tail -f`
* [mod-rxvertx - Extension for VertX](https://github.com/vert-x/mod-rxvertx) that provides support for Reactive Extensions (RX) using the RxJava library
* [rxjava-jdbc](https://github.com/davidmoten/rxjava-jdbc) - use RxJava with jdbc connections to stream ResultSets and do functional composition of statements
* [rtree](https://github.com/davidmoten/rtree) - immutable in-memory R-tree and R*-tree with RxJava api including backpressure


text: A list application that uses Dropbox to sync across devices.


text:
#ifndef CRC_HELPER_H
#define	CRC_HELPER_H

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Compute CRC word for a byte string.
 */
uint16_t MakeCrc(const uint8_t *data, int count);

/* Update a CRC accumulation with one data byte.
 */
uint16_t ByteUpdateCrc(uint16_t crc, uint8_t data);

/* Update a CRC accumulation with several data bytes.
 */
uint16_t ArrayUpdateCrc(uint16_t crc, const uint8_t *data, int count);

#ifdef __cplusplus
}
#endif // __cplusplus

#endif


text:
{% extends "layout.html" %}

{% block content %}

About

This is an About page for the INtro to flask

{% endblock %}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<!-- Description of the project -->
	<groupId>org.ow2.chameleon.rose.demo</groupId>
	<artifactId>demo.service.implementation</artifactId>
	<name>demo service implementation</name>
	<version>0.1.0-SNAPSHOT</version>
	<packaging>bundle</packaging>

	<properties>
		<!-- Dependencies version -->
		<ipojo.version>1.8.0</ipojo.version>
		<osgi.version>4.2.0</osgi.version>

		<!-- Plugins version -->
		<bundle.plugin.version>2.3.4</bundle.plugin.version>
		<compiler.plugin.version>2.1</compiler.plugin.version>
		<ipojo.plugin.version>1.8.0</ipojo.plugin.version>

		<!-- Encoding -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<!-- Project dependencies -->
	<dependencies>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>org.osgi.compendium</artifactId>
			<version>${osgi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.ipojo.annotations</artifactId>
			<version>${ipojo.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.ipojo</artifactId>
			<version>${ipojo.version}</version>
		</dependency>
		<dependency>
			<groupId>org.ow2.chameleon.rose.demo</groupId>
			<artifactId>demo.service.api</artifactId>
			<version>0.1.0-SNAPSHOT</version>
		</dependency>
	</dependencies>

	<!-- Build configuration -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<version>${bundle.plugin.version}</version>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>
							${project.artifactId}
						</Bundle-SymbolicName>
						<Import-Package>org.ow2.chameleon.rose.demo.api,*</Import-Package>
						<Private-Package>org.ow2.chameleon.rose.demo.service</Private-Package>
						<Expport-Package />

					</instructions>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-ipojo-plugin</artifactId>
				<version>${ipojo.plugin.version}</version>
				<executions>
					<execution>
						<goals>
							<goal>ipojo-bundle</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${compiler.plugin.version}</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
var common     = require('../common');
var assert     = require('assert');

assert.equal(
	common.Remove().from('table1').build(),
	"DELETE FROM `table1`"
);

assert.equal(
	common.Remove().from('table1').where({ col: 1 }).build(),
	"DELETE FROM `table1` WHERE `col` = 1"
);

assert.equal(
	common.Remove().from('table1').where({ col1: 1 }, { col2: 2 }).build(),
	"DELETE FROM `table1` WHERE (`col1` = 1) AND (`col2` = 2)"
);

assert.equal(
	common.Remove().from('table1').where({ or: [{ col: 1 }, { col: 2 }] }).build(),
	"DELETE FROM `table1` WHERE ((`col` = 1) OR (`col` = 2))"
);

assert.equal(
	common.Remove().from('table1').limit(10).build(),
	"DELETE FROM `table1` LIMIT 10"
);

assert.equal(
	common.Remove().from('table1').limit(10).offset(3).build(),
	"DELETE FROM `table1` LIMIT 10 OFFSET 3"
);

assert.equal(
	common.Remove().from('table1').order('col').limit(5).build(),
	"DELETE FROM `table1` ORDER BY `col` ASC LIMIT 5"
);

assert.equal(
	common.Remove().from('table1').order('col1', 'A').order('col2', 'Z').limit(5).build(),
	"DELETE FROM `table1` ORDER BY `col1` ASC, `col2` DESC LIMIT 5"
);


text:
<?php

use CachetHQ\Cachet\Facades\Setting;
use Illuminate\Support\Facades\Request;
use Jenssegers\Date\Date;

if (!function_exists('set_active')) {

    /**
     * Set active class if request is in path.
     *
     * @param string $path
     * @param array  $classes
     * @param string $active
     *
     * @return string
     */
    function set_active($path, array $classes = [], $active = 'active')
    {
        if (Request::is($path)) {
            $classes[] = $active;
        }

        $class = e(implode(' ', $classes));

        return empty($classes) ? '' : "class=\"{$class}\"";
    }
}

if (!function_exists('segment_identify')) {
    /**
     * Identifies the user for Segment.com.
     *
     * @return bool
     */
    function segment_identify()
    {
        if (Config::get('segment.write_key')) {
            try {
                if (Setting::get('app_track')) {
                    return app('segment')->identify([
                        'anonymousId' => Config::get('app.key'),
                        'context'     => [
                            'locale'         => Config::get('app.locale'),
                            'timezone'       => Setting::get('app_timezone'),
                            'DB_DRIVER'      => getenv('DB_DRIVER'),
                            'CACHE_DRIVER'   => getenv('CACHE_DRIVER'),
                            'SESSION_DRIVER' => getenv('SESSION_DRIVER'),
                        ],
                    ]);
                } else {
                    return false;
                }
            } catch (Exception $e) {
                return false;
            }
        }
    }
}

if (!function_exists('segment_track')) {
    /**
     * Tracks events in Segment.com.
     *
     * @param string $event
     * @param array  $properties
     *
     * @return bool
     */
    function segment_track($event, array $properties = [])
    {
        if (Config::get('segment.write_key')) {
            try {
                if (Setting::get('app_track')) {
                    return app('segment')->track([
                        'anonymousId' => Config::get('app.key'),
                        'event'       => $event,
                        'properties'  => $properties,
                        'context'     => [
                            'locale'         => Config::get('app.locale'),
                            'timezone'       => Setting::get('app_timezone'),
                            'DB_DRIVER'      => getenv('DB_DRIVER'),
                            'CACHE_DRIVER'   => getenv('CACHE_DRIVER'),
                            'SESSION_DRIVER' => getenv('SESSION_DRIVER'),
                        ],
                    ]);
                } else {
                    return false;
                }
            } catch (Exception $e) {
                return false;
            }
        }
    }
}

if (!function_exists('segment_page')) {
    /**
     * Tracks pages in Segment.com.
     *
     * @param string $page
     *
     * @return bool
     */
    function segment_page($page)
    {
        if (Config::get('segment.write_key')) {
            try {
                if (Setting::get('app_track')) {
                    return app('segment')->page([
                        'anonymousId' => Config::get('app.key'),
                        'name'        => $page,
                        'context'     => [
                            'locale'         => Config::get('app.locale'),
                            'timezone'       => Setting::get('app_timezone'),
                            'DB_DRIVER'      => getenv('DB_DRIVER'),
                            'CACHE_DRIVER'   => getenv('CACHE_DRIVER'),
                            'SESSION_DRIVER' => getenv('SESSION_DRIVER'),
                        ],
                    ]);
                } else {
                    return false;
                }
            } catch (Exception $e) {
                return false;
            }
        }
    }
}

if (!function_exists('formatted_date')) {
    /**
     * Formats a date with the user timezone and the selected format.
     *
     * @param string $date
     *
     * @return \Jenssegers\Date\Date
     */
    function formatted_date($date)
    {
        $dateFormat = Setting::get('date_format', 'jS F Y');

        return (new Date($date))->format($dateFormat);
    }
}

if (!function_exists('subscribers_enabled')) {
    /**
     * Is the subscriber functionality enabled and configured.
     *
     * @return bool
     */
    function subscribers_enabled()
    {
        $isEnabled = Setting::get('enable_subscribers', false);
        $mailAddress = env('MAIL_ADDRESS', false);
        $mailFrom = env('MAIL_NAME', false);

        return $isEnabled && $mailAddress && $mailFrom;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Jard. Bot. Nat. Belg. 58(3-4): 542 (1988)

#### Original name
Micropsalliota campestroides var. brevipes Heinem.

### Remarks
null


text:
import * as React from "react";
import { useAllAppPermissions } from "components/AuthorisationManager/api/appPermission";
import CheckboxSeries from "components/CheckboxSeries";

interface Props {
  value: string[];
  addPermission: (permissionName: string) => void;
  removePermission: (permissionName: string) => void;
}

export const AppPermissionPicker: React.FunctionComponent<Props> = ({
  value,
  addPermission,
  removePermission,
}) => {
  const allAppPermissions = useAllAppPermissions();

  return (
    <CheckboxSeries
      allValues={allAppPermissions}
      includedValues={value}
      addValue={addPermission}
      removeValue={removePermission}
    />
  );
};

export default AppPermissionPicker;


text:
module DbCharmer
  module ActiveRecord
    module ClassAttributes
      @@db_charmer_opts = {}
      def db_charmer_opts=(opts)
        @@db_charmer_opts[self.name] = opts
      end

      def db_charmer_opts
        @@db_charmer_opts[self.name] || {}
      end

      #---------------------------------------------------------------------------------------------
      @@db_charmer_default_connections = {}
      def db_charmer_default_connection=(conn)
        @@db_charmer_default_connections[self.name] = conn
      end

      def db_charmer_default_connection
        @@db_charmer_default_connections[self.name]
      end

      #---------------------------------------------------------------------------------------------
      @@db_charmer_slaves = {}
      def db_charmer_slaves=(slaves)
        @@db_charmer_slaves[self.name] = slaves
      end

      def db_charmer_slaves
        @@db_charmer_slaves[self.name] || []
      end

      # Returns a random connection from the list of slaves configured for this AR class
      def db_charmer_random_slave
        return nil unless db_charmer_slaves.any?
        db_charmer_slaves[rand(db_charmer_slaves.size)]
      end

      #---------------------------------------------------------------------------------------------
      def db_charmer_connection_proxies
        Thread.current[:db_charmer_connection_proxies] ||= {}
      end

      def db_charmer_connection_proxy=(proxy)
        db_charmer_connection_proxies[self.name] = proxy
      end

      def db_charmer_connection_proxy
        db_charmer_connection_proxies[self.name]
      end

      #---------------------------------------------------------------------------------------------
      def db_charmer_force_slave_reads_flags
        Thread.current[:db_charmer_force_slave_reads] ||= {}
      end

      def db_charmer_force_slave_reads=(force)
        db_charmer_force_slave_reads_flags[self.name] = force
      end

      def db_charmer_force_slave_reads
        db_charmer_force_slave_reads_flags[self.name]
      end

      # Slave reads are used in two cases:
      #  - per-model slave reads are enabled (see db_magic method for more details)
      #  - global slave reads enforcing is enabled (in a controller action)
      def db_charmer_force_slave_reads?
        db_charmer_force_slave_reads || DbCharmer.force_slave_reads?
      end

      #---------------------------------------------------------------------------------------------
      def db_charmer_connection_levels
        Thread.current[:db_charmer_connection_levels] ||= Hash.new(0)
      end

      def db_charmer_connection_level=(level)
        db_charmer_connection_levels[self.name] = level
      end

      def db_charmer_connection_level
        db_charmer_connection_levels[self.name] || 0
      end

      def db_charmer_top_level_connection?
        db_charmer_connection_level.zero?
      end

      #---------------------------------------------------------------------------------------------
      def db_charmer_remapped_connection
        return nil unless db_charmer_top_level_connection?
        name = :master
        proxy = db_charmer_model_connection_proxy
        name = proxy.db_charmer_connection_name.to_sym if proxy

        remapped = db_charmer_database_remappings[name]
        remapped ? DbCharmer::ConnectionFactory.connect(remapped, true) : nil
      end

      def db_charmer_database_remappings
        Thread.current[:db_charmer_database_remappings] ||= Hash.new
      end

      def db_charmer_database_remappings=(mappings)
        raise "Mappings must be nil or respond to []" if mappings && (! mappings.respond_to?(:[]))
        Thread.current[:db_charmer_database_remappings] = mappings || {}
      end

      #---------------------------------------------------------------------------------------------
      # Returns model-specific connection proxy, ignoring any global connection remappings
      def db_charmer_model_connection_proxy
        db_charmer_connection_proxy || db_charmer_default_connection
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using NConfig;

namespace NConfigMvc.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            var testSection = NConfigurator.Default.GetSection<TestConfigSection>();

            var configManagerTestSection = ConfigurationManager.GetSection("TestConfigSection") as TestConfigSection;

            var namedTestSection = NConfigurator.UsingFile(@"Config\Custom.config").GetSection<TestConfigSection>("NamedSection");

            ViewBag.NConfigDefault = testSection.TestValue;
            ViewBag.ConfigurationManager = configManagerTestSection.TestValue;
            ViewBag.NConfigNamed = namedTestSection.TestValue;

            ViewBag.AppSettings = new List<string>();
            foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            {
                ViewBag.AppSettings.Add(key + " : " + ConfigurationManager.AppSettings[key]);
            }

            ViewBag.ConnectionStrings = new List<string>();
            foreach (ConnectionStringSettings connectionString in ConfigurationManager.ConnectionStrings)
            {
                ViewBag.ConnectionStrings.Add(connectionString.Name + " : " + connectionString.ConnectionString);
            }

            return View();
        }
    }

    static class StringExtensions
    {
        public static string F(this string format, params object[] args)
        {
            return string.Format(format, args);
        }
    }

}


text:
"""Example of using an initial condition with a fixed amount.

With the amount of free F fixed, most of the free A will be able to bind and
form the A-F complex before equilibrium is reached. If free F were not fixed,
its lower initial amount would severely restrict how much complex could form.
See run_fixed_initial.py for a demonstration of this behavior.

"""

from __future__ import print_function
from pysb import *

Model()

Monomer('A', ['b'])
Monomer('F', ['b'])

Parameter('kf', 1.0)
Parameter('kr', 1.0)
Parameter('A_0', 100)
Parameter('F_0', 20)

Rule('A_bind_F', A(b=None) + F(b=None) | A(b=1) % F(b=1), kf, kr)

Initial(A(b=None), A_0)
Initial(F(b=None), F_0, fixed=True)

Observable('A_free', A(b=None))
Observable('F_free', F(b=None))
Observable('AF_complex', A(b=1) % F(b=1))

if __name__ == '__main__':
    print(__doc__, "\n", model)
    print("""
NOTE: This model code is designed to be imported and programatically
manipulated, not executed directly. The above output is merely a
diagnostic aid.""")


text:
A tiny frontend for monitoring and cancelling transcoding jobs.

To use with https://github.com/dietervanhoof/transcoder-backend


text:
namespace app.catalogDetail {
    'use strict';

    import IWebDataService = services.IWebDataService;
    import ICatalog = models.ICatalog;

    interface ICatalogDetailStateParams extends ng.ui.IStateParamsService {
        id: number;
    }

    export class CatalogDetail {
        static $inject: Array<string> = ['$stateParams', 'webDataService'];

        catalog: ICatalog;

        constructor(
            $stateParams: ICatalogDetailStateParams,
            webDataService: IWebDataService
        ) {
            webDataService.getCatalog($stateParams.id).then(
                (success: ng.IHttpPromiseCallbackArg<ICatalog>) => {
                    this.catalog = success.data;
                });
        }
    }

    angular
        .module('app.catalogDetail', [])
        .controller('catalogDetail', CatalogDetail)
        .config(['$stateProvider', ($stateProvider: angular.ui.IStateProvider) => {
            $stateProvider.state('catalogDetail', {
                controller: CatalogDetail,
                controllerAs: 'cat',
                templateUrl: 'components/catalogDetail/catalogDetail.html',
                url: '/catalog/{id:int}'
            });
        }]);
}


text:
Board.scheme_primitive_functions = (function ($) {
  var m_canvas = null;
  var m_context = null;

  var m_main_frame = null;
  var m_board_main = Board.board_main;
  var m_editor = Board.editor;
  var m_div_repl = Board.div_repl;

  var JS_functions = {
    'set-painter-frame': function(args){
      // (make-frame)
      console.log(args);
      var x, y, width;
      x = car(args).value;
      y = cadr(args).value;
      width = caddr(args).value;
      m_main_frame = new PainterFrame(x, y, width);
      return T;
    },
    'set-color': function(args) {
      console.log(args);
      var x, y, colors;
      x = car(args).value;
      y = cadr(args).value;
      colors = caddr(args);
      var r = car(colors).value;
      var g = cadr(colors).value;
      var b = caddr(colors).value;
      m_board_main.set_color(x, y, r, g, b);
      return T;
    },
    'draw-line': function(args){
      console.log(args);
      var x1, y1, x2, y2;
      x1 = car(args).value;
      y1 = cadr(args).value;

      x2 = car(cddr(args)).value;
      y2 = cadr(cddr(args)).value;

      m_board_main.draw_line(x1, y1, x2, y2);
      return T;
    },
    'board-reset': function(){
      m_board_main.reset();
      return T;
    },
    'draw-x': function(){
      return T;
    },
    'load': function(args){
      console.log('load');
      console.log('(begin ' + m_editor.get_val() + ')');
      m_div_repl.output_eval_result('(begin ' + m_editor.get_val() + ')');
      return T;
    }
  };

  return {
    init: function(){
      m_canvas = $('#canvas_main').get(0);
      m_context = m_canvas.getContext('2d');
      m_editor = Board.editor;
    },
    install_JS_functions: function(result){
      var createBind = function (variable, value) {
        var result = {};
        result.variable = variable;
        result.value = value;
        return result;
      };
      var builtinFunc = function (variable, value) {
        result.push(createBind(variable, new LPrimitiveFunc(value)));
      };
      console.log(JS_functions);
      for(key in JS_functions) {
        console.log(key);
        console.log(JS_functions[key]);
        builtinFunc(String(key), JS_functions[key]);
      }
      return result;
    }
  };
})(jQuery);