text:
package com.facebook.thrift.type;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.reflect.ClassPath;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class TypeRegistry {
  private static final Logger LOGGER = LoggerFactory.getLogger(TypeRegistry.class);

  /** Sorted map for universal name hash to Type */
  private static final ConcurrentSkipListMap<ByteBuf, Type> hashMap = new ConcurrentSkipListMap<>();

  /** Local cache for sorted map. */
  private static final Map<ByteBuf, Type> cache = new ConcurrentHashMap<>();

  /** Hash map for class name to Type */
  private static final Map<Class, Type> classMap = new ConcurrentHashMap<>();

  /** Sorted map for pre registered universal name hash to class name */
  private static final ConcurrentSkipListMap<ByteBuf, String> hashList =
      new ConcurrentSkipListMap<>();

  private static final String TYPE_LIST_PREFIX = "__fbthrift_TypeList_";

  private TypeRegistry() {}

  static {
    initialize();
  }

  /**
   * Check if the prefix is already in the pre-loaded hash list. If it is in the list, mapped
   * classname is loaded. This will register the type to the TypeRegistry.
   *
   * @param prefix prefix as byte array
   * @return True if prefix is already in pre-loaded hash list, false if otherwise.
   * @throws AmbiguousUniversalNameException if the prefix return more than one entry.
   */
  private static boolean registered(ByteBuf prefix) {
    ByteBuf key = hashList.ceilingKey(prefix);
    if (key == null || !startsWith(key, prefix)) {
      return false;
    }

    ByteBuf nextKey = hashList.higherKey(key);
    if (nextKey == null || !startsWith(nextKey, prefix)) {
      String className = hashList.get(key);
      if (className != null) {
        try {
          Class.forName(className);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
      return true;
    }

    throw new AmbiguousUniversalNameException(ByteBufUtil.hexDump(prefix));
  }

  /**
   * Find all _TypeList_<hash-code> classes from classpath and pre-load all type mapping into
   * hashList - TreeMap
   */
  private static void initialize() {
    try {
      ClassPath.from(ClassLoader.getSystemClassLoader()).getAllClasses().stream()
          .filter(c -> c.getName().contains(TYPE_LIST_PREFIX))
          .forEach(
              c -> {
                try {
                  Class clazz = Class.forName(c.getName());
                  Object o = clazz.getDeclaredConstructor().newInstance();
                  if (o instanceof TypeList) {
                    TypeList typeList = (TypeList) o;
                    for (TypeList.TypeMapping m : typeList.getTypes()) {
                      UniversalName un = new UniversalName(m.getUri());
                      hashList.put(un.getHashBytes(), m.getClassName());
                    }
                  }
                } catch (Exception e) {
                  LOGGER.warn("Can not load class: " + c.getName(), e);
                }
              });
    } catch (Exception e) {
      throw new RuntimeException("Can not read classes", e);
    }
  }

  /**
   * Validate given universal name and the class. They should not be associated with another object.
   * If universal name or class is already associated with another entry, IllegalArgumentException
   * is thrown.
   *
   * @param type
   */
  private static void validate(Type type) {
    Class clazz = type.getClazz();
    UniversalName universalName = type.getUniversalName();

    if (exist(universalName) && hashMap.get(universalName.getHashBytes()).getClazz() != clazz) {
      String msg =
          "Universal name already registered with another class "
              + hashMap.get(universalName.getHashBytes()).getClazz().getCanonicalName();
      LOGGER.error(msg);
      throw new IllegalArgumentException(msg);
    }
    if (exist(clazz)
        && !classMap
            .get(clazz)
            .getUniversalName()
            .getHashBytes()
            .equals(universalName.getHashBytes())) {
      String msg =
          "Class name already registered with another universal name "
              + classMap.get(clazz).getUniversalName().getUri();
      LOGGER.error(msg);
      throw new IllegalArgumentException(msg);
    }
  }

  /**
   * Validate and add the type.
   *
   * @param type Type info containing universal name, class name and other metadata.
   */
  private static synchronized void addType(Type type) {
    validate(type);

    hashMap.put(type.getUniversalName().getHashBytes(), type);
    classMap.put(type.getClazz(), type);

    cache.clear();
  }

  /**
   * Add the given type to the registry. If universal name or class is already associated with
   * another entry, IllegalArgumentException is thrown.
   *
   * @param type Type info containing universal name, class name and other metadata.
   * @return Hash bytes as hexadecimal value.
   */
  public static String add(Type type) {
    LOGGER.debug("Adding type to the registry: {}", type);
    addType(type);

    return type.getUniversalName().getHash();
  }

  private static boolean startsWith(ByteBuf bytes, ByteBuf prefix) {
    for (int i = 0; i < Math.min(prefix.capacity(), bytes.capacity()); i++) {
      if (prefix.getByte(i) != bytes.getByte(i)) {
        return false;
      }
    }
    return prefix.capacity() <= bytes.capacity();
  }

  /**
   * Find Type by given hash prefix. For example, if a Type is registered with a hash
   * "af420267bd92e0cb", it can be returned by providing any hash prefix, like "af42", "af4202" etc
   * if they return exactly one Type.
   *
   * @param prefix prefix as byte array
   * @return Type
   * @throws AmbiguousUniversalNameException if the prefix return more than one Type.
   * @throws IllegalArgumentException if the prefix is empty or null
   */
  public static Type findByHashPrefix(ByteBuf prefix) {
    if (!Objects.requireNonNull(prefix).isReadable()) {
      throw new IllegalArgumentException("Prefix must be at least one byte, it is empty or null");
    }

    if (cache.containsKey(prefix)) {
      return cache.get(prefix);
    }

    ByteBuf key = hashMap.ceilingKey(prefix);
    if (key == null || !startsWith(key, prefix)) {
      if (registered(prefix)) {
        return findByHashPrefix(prefix);
      }
      return null;
    }

    ByteBuf nextKey = hashMap.higherKey(key);
    if (nextKey == null || !startsWith(nextKey, prefix)) {
      Type type = hashMap.get(key);
      cache.put(prefix, type);
      return type;
    }

    throw new AmbiguousUniversalNameException(ByteBufUtil.hexDump(prefix));
  }

  /**
   * Find Type by given hash prefix. Same as the {@link #findByHashPrefix(ByteBuf) findByHashPrefix}
   * but taking prefix as hexadecimal String.
   *
   * @param hexPrefix as hexadecimal string
   * @return Type
   * @throws AmbiguousUniversalNameException if the prefix return more than one Type.
   * @throws IllegalArgumentException if the prefix is empty or null
   */
  public static Type findByHashPrefix(String hexPrefix) {
    return findByHashPrefix(Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hexPrefix)));
  }

  /**
   * Find Type by given class name.
   *
   * @param clazz
   * @return Type
   */
  public static Type findByClass(Class clazz) {
    return classMap.get(clazz);
  }

  /**
   * Find Type by given universal name.
   *
   * @param universalName Universal name
   * @return Type
   */
  public static Type findByUniversalName(UniversalName universalName) {
    return hashMap.get(universalName.getHashBytes());
  }

  /**
   * Check if the class is already in the registry.
   *
   * @param clazz Name of the class
   * @return True if already in the registry, false otherwise
   */
  public static boolean exist(Class clazz) {
    return classMap.containsKey(clazz);
  }

  /**
   * Check if the universal name is already in the registry.
   *
   * @param universalName Universal name
   * @return True if already in the registry, false otherwise
   */
  public static boolean exist(UniversalName universalName) {
    return hashMap.containsKey(universalName.getHashBytes());
  }

  @VisibleForTesting
  public static int size() {
    return hashMap.size();
  }

  @VisibleForTesting
  public static void clear() {
    LOGGER.info("Clearing type registry");
    hashMap.clear();
    classMap.clear();
  }

  @VisibleForTesting
  public static void print() {
    for (ByteBuf key : hashMap.keySet()) {
      System.out.println(
          ByteBufUtil.hexDump(key) + " " + hashMap.get(key).getUniversalName().getUri());
    }
  }
}


text:
<?php

class Twocheckout_Company extends Twocheckout
{

    public static function retrieve()
    {
        $request = new Twocheckout_Api_Requester();
        $urlSuffix = '/api/acct/detail_company_info';
        $result = $request->doCall($urlSuffix);
        return Twocheckout_Util::returnResponse($result);
    }
}

class Twocheckout_Contact extends Twocheckout
{

    public static function retrieve()
    {
        $request = new Twocheckout_Api_Requester();
        $urlSuffix = '/api/acct/detail_contact_info';
        $result = $request->doCall($urlSuffix);
        return Twocheckout_Util::returnResponse($result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
  <hawkular-subtab ng-controller="Subtab.SubtabController">

Availability

          Response Time

  </hawkular-subtab>

    <hk-alert-notification></hk-alert-notification>

Response Time Status

        {{vm.endTimeStamp | date:'HH:mm:ss'}}

                = 0">{{vm.average}} ms
                = 0">n/a
                Average

                = 0">{{vm.median}} ms
                = 0">n/a
                Median

            = 0">{{vm.percentile95th}} ms
                = 0">n/a
                95th percentile

Metrics

            <button class="btn btn-link hk-chart-update" tooltip-trigger tooltip-placement="top"
                    tooltip-append-to-body="true" tooltip="Update chart"
                    ng-click="vm.refreshChartDataNow(vm.getMetricId())">

            </button>

= 0">

Response Time

            <hawkular-chart
              data="vm.chartData.dataPoints"
              chart-type="hawkularmetric"
              alert-value="{{vm.threshold}}"
              use-zero-min-value="true"
              y-axis-units="Response Time (ms)"
              chart-height="250">
            </hawkular-chart>

            Response Time
            Threshold
            Interval above the threshold

        <div class="panel panel-default hk-graph" ng-if="vm.average < 0">

Response Time

The server hasn't been reachable for this time range.

        <hk-alert-info list="vm.alertList" limit="(vm.showAllAlerts ? 100000 : 3)"
                       resource-id="vm.$routeParams.resourceId" title="Url">
        </hk-alert-info>


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

	<title itemprop="name" content="Twitter / Javascript | Seven">Twitter / Javascript | Seven | Handpicked lists for Front Ender.</title>
	<meta property="og:title" content="Twitter / Javascript | Seven">
	<meta property="og:type" content="article">
	<meta property="og:url" content="http://seven.studiomohawk.com//javascript/2012/05/12/twitter-javascript/">
  <meta itemprop="description" name="description" property="og:description" content="Addy Osmani

Nicholas C. Zakas

Richard D. Worth

Scott Jehl

John Resig

JavaScript Daily

GitHub JavaScript
">

  <meta property="og:image" content="http://seven.studiomohawk.com/fb-icon-200.png">
  <meta property="og:site_name" content="Seven | Handpicked lists for Front Ender.">

  <meta name="viewport" content="width=device-width">
  <link href="http://seven.studiomohawk.com/atom.xml" rel="alternate" title="Seven | Handpicked lists for Front Ender." type="application/atom+xml">
  <link rel="stylesheet" href="/style/style.css">

Seven

Handpicked lists for Front Ender.

Twitter / Javascript

							<time class="date-pub" title="Liquid error: undefined method `xmlschema' for nil:NilClass">
								12
								05
								12
							</time>
							javascript

Addy Osmani

Nicholas C. Zakas

Richard D. Worth

Scott Jehl

John Resig

JavaScript Daily

GitHub JavaScript

						← View previous article

						View next article →

 Home

Questions?

      	Ask Me on Github

About

				現役フロントエンドデベロッパ/ウェブデザイナ、斉藤祐也がフロントエンドにまつわる情報やTipsを紹介。2〜3年は遅れているという日本のウェブをアップデートしたい。そんな思いで更新していきます。

Elsewhere

CSS Radar / フロントエンダのためのミニブック

cssradar@twitter / 1日5件以内でフロントエンド関連情報をつぶやきます

en.ja / フロントエンダのための翻訳記事

Pinboard / カオスにならないようきちんと管理

500px / 趣味は写真。Nikon D90ユーザ


text:
module Admin::AdminHelper
  def admin_menu_links(links)
    links.map { |text, path| admin_menu_link(text, path) }.join.html_safe
  end

  def admin_menu_link(text, path)
    content_tag(
      :li,
      link_to(text, path, class: "nav-link"),
      current_page?(path) ? {class: "nav-item active"} : {class: "nav-item"}
    )
  end

  def page_header(title)
    content_tag(:div, content_tag(:h1, title), class: "page-header")
  end

  def breadcrumbs(crumbs, heading)
    content_tag(
      :nav,
      content_tag(
        :ol,
        crumbs.map { |k, v| content_tag(:li, link_to(k, v), class: "breadcrumb-item") }.join.html_safe +
        content_tag(:li, heading, class: "breadcrumb-item active"),
        class: "breadcrumb"
      ),
      "aria-label" => "breadcrumb"
    )
  end

  def editor(form, attribute, mode)
    textarea_id = "##{form.object_name}_#{attribute}"
    editor_id = "editor_#{attribute}"
    form_classes = ".new_#{form.object_name}, .edit_#{form.object_name}"
    form.text_area(attribute, class: "editor-textarea") +
      content_tag(
        "div", form.object.send(attribute), id: editor_id, class: "editor"
      ) + editor_javascript_tag(editor_id, form_classes, textarea_id, mode)
  end

  def editor_javascript_tag(editor_id, form_classes, textarea_id, mode)
    javascript_tag(
      "const #{editor_id} = ace.edit('#{editor_id}');
  #{editor_id}.getSession().setUseWorker(false);
  #{editor_id}.setTheme('ace/theme/github');
  #{editor_id}.setShowPrintMargin(false);
  #{editor_id}.getSession().setMode('ace/mode/#{mode}');
  #{editor_id}.getSession().setTabSize(2);
  #{editor_id}.getSession().setUseSoftTabs(true);
  #{editor_id}.getSession().setUseWrapMode(true);
  document.querySelector('#{form_classes}').addEventListener('submit', function() {
    const textarea = document.querySelector('#{textarea_id}');
    textarea.value = #{editor_id}.getSession().getValue();
  });
  "
    )
  end

  def dismissable_error_message(&block)
    render(
      partial: "admin/shared/dismissable_error_message",
      locals: {body: capture(&block)}
    )
  end

  protected

  def object_title(object)
    object.instance_of?(Array) ? object.last : object
  end
end


text:
package mpg.biochem.de.interbase.task;

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;

public class DownloadNCBIMappingsTasklet implements Tasklet{

	private Logger logger = Logger.getLogger(DownloadNCBIMappingsTasklet.class);

	@Value("${ftp.proxy.url}")
	private String ftpProxy;

	@Value("${ftp.proxy.port}")
	private String ftpPort;

	@Value("${mapping.ncbi.url}")
	private String url;

	@Value("${path}")
	private String downloadPath;

	@Value("${mapping.ncbi.download}")
	private boolean download;

	@Value("${ncbi.ftp}")
	private String ftp;

	@Value("${ncbi.username}")
	private String username;

	@Value("${ncbi.password}")
	private String password;

	public DownloadNCBIMappingsTasklet(){
		if(password == null)
			password = "";

		downloadPath += "/mapping/gene2accession.gz";
	}

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

		boolean index = false;
		DateTime ftpModDate = getLastModifiedDate();
		if(download){

			File mappings = new File(downloadPath);
			if(mappings.exists() && FileUtils.isFileNewer(mappings, ftpModDate.toDate())){
				logger.info("Mappings file is up to date");
				//Do nothing
			}else{
				//Download the file
				logger.info("Downloading ncbi mapping file");
				FileUtils.copyURLToFile(new URL(url), mappings);
				index = true;
			}

		}else{
			logger.info("Download disabled, mapping.download = false");
		}

		chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("STEP", "create_index");
		chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("INDEX", index);
		return RepeatStatus.FINISHED;
	}

	public DateTime getLastModifiedDate() throws SocketException, IOException{

		FTPClient ftpClient = new FTPClient();
		if(ftpProxy.equals("") || ftpPort.equals("")){
			ftpClient.connect(ftp);
			ftpClient.login(username, password);
		}else{
			ftpClient.connect(ftpProxy, Integer.parseInt(ftpPort));
			ftpClient.login(username+"@"+ftp, password);
		}

		DateTime date = null;
		/*if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
			logger.warn("Uniprot FTP server refused connection.");
		}else{*/
			String mDate = ftpClient.getModificationTime(url.substring(url.lastIndexOf(ftp)+ftp.length(), url.length()));
			mDate = mDate.substring(mDate.indexOf(" "), mDate.length()).trim();

			DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMddHHmmss");
			date = fmt.parseDateTime(mDate);
		//}
		ftpClient.disconnect();

		return date;
	}
}


text:
var solution = new Solution("kfx");
var project = new Project("kfx");

solution.cmd = true;

project.addExclude(".git/**");
project.addExclude("build/**");

project.addFile("Sources/**");
project.addFile("glsl2agal/src/**");
project.addFile("glsl2agal/agalassembler/**");
project.addFile("glsl2agal/swc/**");
project.addExclude("glsl2agal/src/glsl/main.cpp");
project.addExclude("glsl2agal/src/glsl/*.ll");
project.addExclude("glsl2agal/src/glsl/*.yy");
project.addExclude("glsl2agal/src/glsl/*.sh");
project.addExclude("glsl2agal/src/glsl/glcpp/tests/**");
project.addExclude("glsl2agal/src/glsl/glcpp/glcpp.c");
project.addExclude("glsl2agal/src/glsl/builtin_stubs.cpp");

project.addIncludeDir("glsl2agal/src/glsl");
project.addIncludeDir("glsl2agal/src/mesa");
project.addIncludeDir("glsl2agal/include");
if (platform === Platform.Windows) {
	project.addIncludeDir("glsl2agal/msinttypes-r26");
}

project.addDefine("GLSL2AGAL_LIB");

if (platform === Platform.Windows) {
	project.addIncludeDir("Libraries/DirectX/Include");
	project.addLibFor("Win32", "d3d11");
	project.addLibFor("Win32", "d3dcompiler");
}

project.addSubProject(Solution.createProject("angleproject"));

solution.addProject(project);

return solution;


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using SS.Integration.Common.Extensions;

namespace SS.Integration.Adapter.Model
{
    /// <summary>
    /// This class represents a selection as it comes
    /// within a delta/full snapshot.
    ///
    /// As some information are only present in a full snapshot
    /// (i.e. tag section) not all the properties have valid
    /// value when the object is created from a delta snapshot.
    /// </summary>
    [Serializable]
    public class Selection
    {
        private readonly Dictionary<string, string> _tags;
        private string _OverridenName;

        public Selection()
        {
            _tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
            _OverridenName = null;
        }

        /// <summary>
        /// Selection's Id
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Selection's price when present
        /// within the snapshot
        /// </summary>
        public double? Price { get; set; }

        /// <summary>
        /// Selections' status.
        /// See SelectionStatus for a list of valid values.
        /// </summary>
        public string Status { get; set; }

        /// <summary>
        /// Selection's tradability when present
        /// within the snapshot
        /// </summary>
        public bool? Tradable { get; set; }

        /// <summary>
        /// The selection's name.
        ///
        /// The selection's name can be overwritten by manually setting it, but
        /// it is only valid for the current object. If another snapshot arrives,
        /// the Selection object is re-created with the information contained within
        /// the snapshot.
        ///
        /// If not manually set, this field is only valid when the object
        /// is created from a full snapshot.
        /// </summary>
        [IgnoreDataMember]
        public string Name
        {
            get
            {
                return string.IsNullOrEmpty(_OverridenName) ? GetTagValue("name") : _OverridenName;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                    _OverridenName = value;
            }
        }

        /// <summary>
        /// Returns true if the selection is suspended.
        ///
        /// This is currently computed by checking the
        /// tradability value. If the tradability is present
        /// and its value if false, then the selection is
        /// considered as suspended.
        /// </summary>
        [IgnoreDataMember]
        public bool IsSuspended
        {
            get
            {
                return this.Tradable.HasValue && !this.Tradable.Value;
            }
        }

        [IgnoreDataMember]
        public bool? IsActive
        {
            get
            {
                if (string.IsNullOrEmpty(Status))
                    return null;

                return Status == SelectionStatus.Active;
            }
        }

        public Result Result { get; set; }

        public Result PlaceResult { get; set; }

        #region Tags

        [IgnoreDataMember]
        public IEnumerable<string> TagKeys
        {
            get
            {
                return _tags.Keys;
            }
        }

        public bool HasTag(string tagKey) => HasTag(tagKey, true);
        public bool HasTag(string tagKey, bool keyCaseSensitive) => !string.IsNullOrEmpty(tagKey) && _tags.FindKey(tagKey, keyCaseSensitive) != null;

        public void AddOrUpdateTagValue(string tagKey, string tagValue) => AddOrUpdateTagValue(tagKey, tagValue, true);
        public void AddOrUpdateTagValue(string tagKey, string tagValue, bool keyCaseSensitive) => _tags.AddOrUpdateValue(tagKey, tagValue, keyCaseSensitive);

        public string GetTagValue(string tagKey) => GetTagValue(tagKey, true);
        public string GetTagValue(string tagKey, bool keyCaseSensitive) => _tags.GetValue(tagKey, keyCaseSensitive);

        public bool IsTagValueMatch(string tagKey, string value, bool valueCaseSensitive = false, bool keyCaseSensitive = true)
            => _tags.IsValueMatch(tagKey, value, valueCaseSensitive, keyCaseSensitive);

        [IgnoreDataMember]
        public int TagsCount
        {
            get
            {
                return _tags.Count;
            }
        }

        /// <summary>
        /// Deprecated, use the API interface to deal with tags
        /// </summary>
        public Dictionary<string, string> Tags
        {
            get
            {
                return _tags;
            }
        }

        #endregion

        public override string ToString()
        {
            var format = "Selection with selectionId={0}";
            if (this.Name != null)
            {
                format += " selectionName=\"{1}\"";
                return string.Format(format, Id, Name);
            }

            return string.Format(format, Id);
        }
    }
}


text:
using System;
using System.Windows;
using ElephantBookStore.Client.Converters;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ElephantBookStore.Client.UnitTests.InvertedBooleanToVisibilityConverterTests
{
	[TestClass]
	public class ConvertBackShould
	{
		[TestMethod]
		[ExpectedException(typeof(NotSupportedException))]
		public void Throw_NotSupportedException_WhenCalled()
		{
			var converter = new InvertedBooleanToVisibilityConverter();

			converter.ConvertBack(Visibility.Visible, null, null, null);
		}
	}
}


text: export declare function OnChange(defaultValue?: any): any;


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	"strings"

	"secondbit.org/gifs/api"

	"github.com/coreos/go-etcd/etcd"
	"github.com/gorilla/mux"
)

var (
	etcdAddrs = StringArray{}
)

type StringArray []string

func (a *StringArray) Set(s string) error {
	*a = append(*a, s)
	return nil
}

func (a *StringArray) String() string {
	return strings.Join(*a, ",")
}

func main() {
	flag.Var(&etcdAddrs, "etcd-address", "address to the etcd server (may be specified more than once)")
	flag.Parse()
	if len(etcdAddrs) < 1 {
		fmt.Println("Must set at least once etcd address.")
		return
	}
	client := etcd.NewClient(etcdAddrs)
	resp, err := client.Get("/", false, true)
	if err != nil {
		fmt.Println(err)
		return
	}
	context, err := getEtcdContext(resp.Node)
	if err != nil {
		fmt.Println(err)
		return
	}
	listenAddr := api.DefaultListenAddr
	for _, node := range resp.Node.Nodes {
		fmt.Println(node.Key)
		if node.Key == "/listen_addr" {
			listenAddr = node.Value
			fmt.Println("Set listenAddr to " + node.Value)
			break
		}
	}

	var router *mux.Router
	if context.RootDomain == "" {
		fmt.Println("Using path muxer")
		router = api.GetPathMuxer(context)
	} else {
		fmt.Println("Using domain muxer")
		router = api.GetDomainMuxer(context)
	}
	http.Handle("/", router)
	fmt.Println("Listening on " + listenAddr)
	err = http.ListenAndServe(listenAddr, nil)
	if err != nil {
		panic(err)
	}
}


text:
#include "EventManager.h"
#include <RmlUi/Core/Context.h>
#include <RmlUi/Core/ElementDocument.h>
#include <RmlUi/Core/ElementUtilities.h>
#include "EventHandler.h"
#include "MickLogger.h"

// The game's element context (declared in MenuRenderer.h).
extern Rml::Context* context;

// The event handler for the current screen. This may be nullptr if the current screen has no specific functionality.
static EventHandler* event_handler = nullptr;

// The event handlers registered with the manager.
typedef Rml::SmallUnorderedMap< Rml::String, EventHandler* > EventHandlerMap;
EventHandlerMap event_handlers;

static EventManager* managerInstance = nullptr;

EventManager::EventManager(Rml::Context* rmlContext)
{
	m_context = rmlContext;
}

EventManager* EventManager::getInstance()
{
  if (!managerInstance)
  {
	  managerInstance = new EventManager(Rml::GetContext("default"));
  }
  return managerInstance;
}

EventManager::~EventManager()
{
}

// Releases all event handlers registered with the manager.
void EventManager::Shutdown()
{
	for (EventHandlerMap::iterator i = event_handlers.begin(); i != event_handlers.end(); ++i)
		delete (*i).second;

	event_handlers.clear();
	event_handler = nullptr;
}

// Registers a new event handler with the manager.
void EventManager::RegisterEventHandler(const Rml::String& handler_name, EventHandler* handler)
{
	// Release any handler bound under the same name.
	EventHandlerMap::iterator iterator = event_handlers.find(handler_name);
	if (iterator != event_handlers.end())
		delete (*iterator).second;

	event_handlers[handler_name] = handler;
}

// Processes an event coming through from RmlUi.
void EventManager::ProcessEvent(Rml::Event& event, const Rml::String& value)
{
	Rml::StringList commands;
	Rml::StringUtilities::ExpandString(commands, value, ';');
	for (size_t i = 0; i < commands.size(); ++i)
	{
		// Check for a generic 'load' or 'exit' command.
		Rml::StringList values;
		Rml::StringUtilities::ExpandString(values, commands[i], ' ');

		if (values.empty())
			return;
		if (values[0] == "start")
		{
			// Start the game with the current settings.
			std::GameSettings::getInstance()->setGameState(std::GameSettings::GAME_INIT);

			// Close the menu.
			event.GetTargetElement()->GetOwnerDocument()->Close();
		}
		else if (values[0] == "open" &&
 			values.size() > 1)
		{
			// Load the window, and if successful close the old window.
			if (LoadWindow(values[1]))
				event.GetTargetElement()->GetOwnerDocument()->Close();
		}
		else if (values[0] == "exit")
		{
		  std::GameSettings::getInstance()->setGameState(std::GameSettings::GAME_QUIT);
		  event.GetTargetElement()->GetOwnerDocument()->Close();
		}
		else
		{
			std::MickLogger::getInstance()->debug(this, std::string("Got other event with value: ").append(values[0]));
			if (event_handler != nullptr)
				event_handler->ProcessEvent(event, commands[i]);
		}
	}
}

// Loads a window and binds the event handler for it.
Rml::ElementDocument* EventManager::LoadWindow(const Rml::String& window_name, bool loadAndShow)
{
	// Set the event handler for the new screen, if one has been registered.
	EventHandler* old_event_handler = event_handler;
	EventHandlerMap::iterator iterator = event_handlers.find(window_name);
	if (iterator != event_handlers.end())
		event_handler = (*iterator).second;
	else
		event_handler = nullptr;

	// Attempt to load the referenced RML document.
	Rml::String document_path = window_name; //  Rml::String("invaders/data/") + window_name + Rml::String(".rml");
	Rml::ElementDocument* document = m_context->LoadDocument(document_path.c_str());
	if (document == nullptr)
	{
		event_handler = old_event_handler;
		return nullptr;
	}

	// Set the element's title on the title; IDd 'title' in the RML.
	Rml::Element* title = document->GetElementById("title");
	if (title != nullptr)
		title->SetInnerRML(document->GetTitle());

	// M2S
	if(loadAndShow)
	{
	  document->Focus();
	  document->Show();
	}

	// M2S return document;
	return document;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Arenaria maritima Pall.

### Remarks
null


text:
asynctest(
  'browser.tinymce.plugins.table.InsertCommandsTest',
  [
    'ephox.agar.api.Pipeline',
    'ephox.mcagar.api.LegacyUnit',
    'ephox.mcagar.api.TinyLoader',
    'tinymce.plugins.table.Plugin',
    'tinymce.themes.modern.Theme'
  ],
  function (Pipeline, LegacyUnit, TinyLoader, Plugin, Theme) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];
    var suite = LegacyUnit.createSuite();

    Plugin();
    Theme();

    var cleanTableHtml = function (html) {
      return html.replace(/
( |
]+>)<\/p>$/, '');
    };

    suite.test("mceTableInsertColAfter command", function (editor) {
      editor.focus();
      editor.setContent('

1

2

');
      LegacyUnit.setSelection(editor, 'td', 0);
      editor.execCommand('mceTableInsertColAfter');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1

2

'
      );
    });

    suite.test("mceTableInsertColAfter command with two selected columns", function (editor) {
      editor.getBody().innerHTML = (
        '

1	2	' +
        '3

4	5	6

'
      );
      LegacyUnit.setSelection(editor, 'td', 0);
      editor.execCommand('mceTableInsertColAfter');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1	2	 	 	3
' +
        '
4	5	 	 	6

'
      );
    });

    suite.test("mceTableInsertColBefore command", function (editor) {
      editor.setContent('

1

2

');
      LegacyUnit.setSelection(editor, 'td', 0);
      editor.execCommand('mceTableInsertColBefore');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

 	1

 	2

'
      );
    });

    suite.test("mceTableInsertColBefore command with two selected columns", function (editor) {
      editor.getBody().innerHTML = (
        '

1	2	3	' +
        '

4	5	6

'
      );
      LegacyUnit.setSelection(editor, 'td:nth-child(2)', 0);
      editor.execCommand('mceTableInsertColBefore');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1	 	 	2	3	' +
        '

4	 	 	5	6

'
      );
    });

    suite.test("mceTableInsertRowAfter command", function (editor) {
      editor.setContent('

1	2

');
      LegacyUnit.setSelection(editor, 'td', 0);
      editor.execCommand('mceTableInsertRowAfter');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1	2

'
      );
    });

    suite.test("mceTableInsertRowAfter command with two selected rows", function (editor) {
      editor.getBody().innerHTML = (
        '

1	2

3	4

'
      );
      LegacyUnit.setSelection(editor, 'tr', 0);
      editor.execCommand('mceTableInsertRowAfter');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1	2

3	4

' +
        '

'
      );
    });

    suite.test("mceTableInsertRowAfter command on merged cells", function (editor) {
      editor.setContent(
        '
' +
        '
1	2	3
' +
        '
4	5
' +
        '
6
' +
        '
'
      );

      LegacyUnit.setSelection(editor, 'tr:nth-child(2) td', 0);
      editor.execCommand('mceTableInsertRowAfter');

      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),

        '
' +
        '
' +
        '
1	2	3
' +
        '
4	5
' +
        '

' +
        '
6
' +
        '
' +
        '
'
      );
    });

    suite.test("mceTableInsertRowBefore command", function (editor) {
      editor.setContent('

1	2

');
      LegacyUnit.setSelection(editor, 'td', 0);
      editor.execCommand('mceTableInsertRowBefore');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

1	2

'
      );
    });

    suite.test("mceTableInsertRowBefore command with two selected rows", function (editor) {
      editor.getBody().innerHTML = (
        '

1	2

3	4

'
      );
      LegacyUnit.setSelection(editor, 'tr', 0);
      editor.execCommand('mceTableInsertRowBefore');
      LegacyUnit.equal(
        cleanTableHtml(editor.getContent()),
        '

' +
        '
1	2

3	4

'
      );
    });

    TinyLoader.setup(function (editor, onSuccess, onFailure) {
      Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
    }, {
      plugins: 'table',
      indent: false,
      valid_styles: {
        '*': 'width,height,vertical-align,text-align,float,border-color,background-color,border,padding,border-spacing,border-collapse'
      },
      skin_url: '/project/src/skins/lightgray/dist/lightgray'
    }, success, failure);
  }
);


text:
from rllab.misc import logger
from rllab.misc import ext
from rllab.misc.overrides import overrides
from sandbox.rocky.tf.algos.batch_polopt import BatchPolopt
from sandbox.rocky.tf.optimizers.first_order_optimizer import FirstOrderOptimizer
from sandbox.rocky.tf.misc import tensor_utils
from rllab.core.serializable import Serializable
import tensorflow as tf
import gc

class VPG(BatchPolopt, Serializable):
    """
    Vanilla Policy Gradient.
    """

    def __init__(
            self,
            env,
            policy,
            baseline,
            optimizer=None,
            optimizer_args=None,
            **kwargs):
        Serializable.quick_init(self, locals())
        if optimizer is None:
            default_args = dict(
                batch_size=None,
                max_epochs=1,
            )
            if optimizer_args is None:
                optimizer_args = default_args
            else:
                optimizer_args = dict(default_args, **optimizer_args)
            optimizer = FirstOrderOptimizer(**optimizer_args)
        self.optimizer = optimizer
        self.opt_info = None
        super(VPG, self).__init__(env=env, policy=policy, baseline=baseline, **kwargs)

    @overrides
    def init_opt(self):
        is_recurrent = int(self.policy.recurrent)

        obs_var = self.env.observation_space.new_tensor_variable(
            'obs',
            extra_dims=1 + is_recurrent,
        )
        action_var = self.env.action_space.new_tensor_variable(
            'action',
            extra_dims=1 + is_recurrent,
        )
        advantage_var = tensor_utils.new_tensor(
            name='advantage',
            ndim=1 + is_recurrent,
            dtype=tf.float32,
        )
        dist = self.policy.distribution

        old_dist_info_vars = {
            k: tf.placeholder(tf.float32, shape=[None] * (1 + is_recurrent) + list(shape), name='old_%s' % k)
            for k, shape in dist.dist_info_specs
            }
        old_dist_info_vars_list = [old_dist_info_vars[k] for k in dist.dist_info_keys]

        state_info_vars = {
            k: tf.placeholder(tf.float32, shape=[None] * (1 + is_recurrent) + list(shape), name=k)
            for k, shape in self.policy.state_info_specs
            }
        state_info_vars_list = [state_info_vars[k] for k in self.policy.state_info_keys]

        if is_recurrent:
            valid_var = tf.placeholder(tf.float32, shape=[None, None], name="valid")
        else:
            valid_var = None

        dist_info_vars = self.policy.dist_info_sym(obs_var, state_info_vars)
        logli = dist.log_likelihood_sym(action_var, dist_info_vars)
        kl = dist.kl_sym(old_dist_info_vars, dist_info_vars)

        # formulate as a minimization problem
        # The gradient of the surrogate objective is the policy gradient
        if is_recurrent:
            surr_obj = - tf.reduce_sum(logli * advantage_var * valid_var) / tf.reduce_sum(valid_var)
            mean_kl = tf.reduce_sum(kl * valid_var) / tf.reduce_sum(valid_var)
            max_kl = tf.reduce_max(kl * valid_var)
        else:
            surr_obj = - tf.reduce_mean(logli * advantage_var)
            mean_kl = tf.reduce_mean(kl)
            max_kl = tf.reduce_max(kl)

        input_list = [obs_var, action_var, advantage_var] + state_info_vars_list
        if is_recurrent:
            input_list.append(valid_var)

        vars_info = {
            "mean_kl": mean_kl,
            "input_list": input_list,
            "obs_var": obs_var,
            "action_var": action_var,
            "advantage_var": advantage_var,
            "surr_loss": surr_obj,
            "dist_info_vars": dist_info_vars,
            "lr": logli,
        }

        if self.qprop:
            eta_var = tensor_utils.new_tensor(
                'eta',
                ndim=1 + is_recurrent,
                dtype=tf.float32,
            )
            qvalue = self.qf.get_e_qval_sym(vars_info["obs_var"], self.policy, deterministic=True)
            qprop_surr_loss = - tf.reduce_mean(vars_info["lr"] *
                vars_info["advantage_var"]) - tf.reduce_mean(
                qvalue * eta_var)
            input_list += [eta_var]
            self.optimizer.update_opt(
                loss=qprop_surr_loss,
                target=self.policy,
                inputs=input_list,
            )
            control_variate = self.qf.get_cv_sym(obs_var,
                    action_var, self.policy)
            f_control_variate = tensor_utils.compile_function(
                inputs=[obs_var, action_var],
                outputs=control_variate,
            )
            self.opt_info_qprop = dict(
                f_control_variate=f_control_variate,
            )
        else:
            self.optimizer.update_opt(loss=surr_obj, target=self.policy, inputs=input_list)

        f_kl = tensor_utils.compile_function(
            inputs=input_list + old_dist_info_vars_list,
            outputs=[mean_kl, max_kl],
        )
        self.opt_info = dict(
            f_kl=f_kl,
            target_policy=self.policy,
        )
        self.init_opt_critic()

    @overrides
    def optimize_policy(self, itr, samples_data):
        logger.log("optimizing policy")
        inputs = ext.extract(
            samples_data,
            "observations", "actions", "advantages"
        )
        agent_infos = samples_data["agent_infos"]
        state_info_list = [agent_infos[k] for k in self.policy.state_info_keys]
        inputs += tuple(state_info_list)
        if self.policy.recurrent:
            inputs += (samples_data["valids"],)
        if self.qprop:
            inputs += (samples_data["etas"], )
            logger.log("Using Qprop optimizer")
        optimizer = self.optimizer
        dist_info_list = [agent_infos[k] for k in self.policy.distribution.dist_info_keys]
        loss_before = optimizer.loss(inputs)
        gc.collect()
        optimizer.optimize(inputs)
        gc.collect()
        loss_after = optimizer.loss(inputs)
        logger.record_tabular("LossBefore", loss_before)
        logger.record_tabular("LossAfter", loss_after)

        mean_kl, max_kl = self.opt_info['f_kl'](*(list(inputs) + dist_info_list))
        logger.record_tabular('MeanKL', mean_kl)
        logger.record_tabular('MaxKL', max_kl)

    @overrides
    def get_itr_snapshot(self, itr, samples_data):
        return dict(
            itr=itr,
            policy=self.policy,
            baseline=self.baseline,
            env=self.env,
        )


text:
namespace HallOfFame.Data.Contracts
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    using HallOfFame.Models;

    public interface IHallOfFameDbContext
    {
        IDbSet<User> Users { get; set; }

        IDbSet<Project> Projects { get; set; }

        IDbSet<Category> Categories { get; set; }

        IDbSet<Comment> Comments { get; set; }

        IDbSet<Course> Courses { get; set; }

        IDbSet<Like> Likes { get; set; }

        IDbSet<Message> Messages { get; set; }

        IDbSet<Conversation> Conversations { get; set; }

        DbContext DbContext { get; }

        void Dispose();

        int SaveChanges();

        IDbSet<TEntity> Set<TEntity>() where TEntity : class;

        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    }
}


text:
/**
 * \brief This file contains class specific functions imaging devices such as
 *        webcams and scanners
 *
 *        USB Device Class 0x06
 * ===========================================================================
 */

/*
 * Copyright (c) 2007-2013 ETH Zurich.
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */


text:
[![Build Status](https://travis-ci.org/Frojd/wagtail-systemtext.svg?branch=master)](https://travis-ci.org/Frojd/wagtail-systemtext) [![PyPI version](https://badge.fury.io/py/wagtailsystemtext.svg)](https://badge.fury.io/py/wagtailsystemtext)

# Wagtail System Text

This is a library that enables cms editors to update static test in Wagtail. By using identifiers developers mark the strings that can be updated by the editor/moderator from the cms.

A template identifier can look like this `{% systemtext "title" %}`. When this identifier are evaluated it will be added to the cms under the section **Settings / System Text** under the name `title`. The entry has a field called `string` that can be updated, this is the text that will be rendered to the website users.

Identifiers can also be grouped, by using the group argument `{% systemtext "title" group "headlines" %}` we can make management easier, identifiers without group will be assigned to the `general` group.

By default identifiers will added in lazy mode, so for instance when a site renders a idenifier it will be added to that sites set of identifiers. The are also management commands that both searches through your code base and finds suiteable identifiers (`find_and_add_systemtext`), syncs then betweeen sites (`sync_systemtext`) and manual add/delete commands (`add_systemtext` / `delete_systemtext`).

## Requirements

- Python 3
- Django 2+
- Wagtail 2+

## Installation

Install the library with pip:

```bash
$ pip install wagtailsystemtext
```

## Quick Setup

Make sure `wagtail.contrib.modeladmin` and `wagtailsystemtext` is added to your `INSTALLED_APPS`.

```python
INSTALLED_APPS = (
    # ...
    'wagtail.contrib.modeladmin',
    'wagtailsystemtext',
)
```

Then add SiteSystemTextMiddleware to your middlewares, make sure you add it after `wagtail.wagtail.core.middleware.SiteMiddleware`

```python
MIDDLEWARE_CLASSES = (
    # ...
    'wagtail.wagtail.core.middleware.SiteMiddleware',
    'wagtailsystemtext.middlewares.SiteSystemTextMiddleware',
)
```

Done!

## Usage

Overall the implementation follows the same convention of django translations.

### Strings

This is how you work with regular text, supply identifer and group and retrive the systemtext string.

```python
from wagtailsystemtext.utils import systemtext as _st

_st('my_text')
_st('main_label', group='buttons')
_st('main_label', group='buttons', default='My label')
```

### Lazy strings

Lazy strings are run when called upon, when for instance you want to initialize a systemtext retrival before the middleware has run. Like in a admin interface.

```python
from wagtailsystemtext.utils import systemtext_lazy as _st

_st('my_text')
_st('main_label', group='buttons')
_st('main_label', group='buttons', default='My label')
```

### Templates

Systemtext contains a templatetag called systemtext, that behaves in the same way as Djangos `{% trans... %}`

#### Templatetags

```python
{% load systemtext %}

{% systemtext "my_text" %}
{% systemtext "main_label" group "buttons" %}
{% systemtext "main_label" group "buttons" default "My label" %}
```

## Management commands

- `find_and_add_systemtext`: Finds the systemtext identifiers in your applications (by looking for `_st` and `{% systemtext ... %}`) and adds them to each wagtail site).
- `add_systemtext`: Add identifier to site(s)
- `delete_systemtext`: Remove identifiers from site(s)
- `sync_systemtext`: Sync identifiers between sites to make sure they contain the same
- `list_systemtext`: List all active systemtext

## Settings

- `SYSTEMTEXT_CACHE_PREFIX`: Cache prefix (`"wagtailsystemtext"` by default)
- `SYSTEMTEXT_CACHE_EXPIRY`: Cache expiry in seconds (10 min by default)
- `SYSTEMTEXT_REBUILD_ON_SAVE`: If cache should be rebuilt on save (`True` by default)
- `SYSTEMTEXT_USE_DEFAULT_ON_EMPTY`: If present, use default value when string is empty (`False` by default)

### Release start

These hooks will automatically bump the application version when using `git flow release ...`

```bash
chmod +x $PWD/git-hooks/bump-version.sh
ln -nfs $PWD/git-hooks/bump-version.sh .git/hooks/post-flow-release-start
ln -nfs $PWD/git-hooks/bump-version.sh .git/hooks/post-flow-hotfix-start
```

## Roadmap

- [x] `trans` template tag support
- [x] Wagtail admin view with site permissions
- [x] Cache-rebild on save through admin
- [x] Default text support (on declaration)
- [x] Lazy text transforms
- [x] Add setting for fallbacking to default if string is empty
- [x] Automatic tag discovery
- [x] Sync command between sites
- [ ] Group filter in Wagtail admin
- [ ] Last accessed timestamps
- [ ] `blocktrans` template tag support

## Contributing

Want to contribute? Awesome. Just send a pull request.

## License

Wagtail System Text is released under the [MIT License](http://www.opensource.org/licenses/MIT).


text:
package agent

import (
	"context"
	"sync"
	"time"

	"github.com/moby/swarmkit/v2/agent/exec"
	"github.com/moby/swarmkit/v2/api"
	"github.com/moby/swarmkit/v2/api/equality"
	"github.com/moby/swarmkit/v2/log"
)

// taskManager manages all aspects of task execution and reporting for an agent
// through state management.
type taskManager struct {
	task     *api.Task
	ctlr     exec.Controller
	reporter StatusReporter

	updateq chan *api.Task

	shutdown     chan struct{}
	shutdownOnce sync.Once
	closed       chan struct{}
	closeOnce    sync.Once
}

func newTaskManager(ctx context.Context, task *api.Task, ctlr exec.Controller, reporter StatusReporter) *taskManager {
	t := &taskManager{
		task:     task.Copy(),
		ctlr:     ctlr,
		reporter: reporter,
		updateq:  make(chan *api.Task),
		shutdown: make(chan struct{}),
		closed:   make(chan struct{}),
	}
	go t.run(ctx)
	return t
}

// Update the task data.
func (tm *taskManager) Update(ctx context.Context, task *api.Task) error {
	select {
	case tm.updateq <- task:
		return nil
	case <-tm.closed:
		return ErrClosed
	case <-ctx.Done():
		return ctx.Err()
	}
}

// Close shuts down the task manager, blocking until it is closed.
func (tm *taskManager) Close() error {
	tm.shutdownOnce.Do(func() {
		close(tm.shutdown)
	})

	<-tm.closed

	return nil
}

func (tm *taskManager) Logs(ctx context.Context, options api.LogSubscriptionOptions, publisher exec.LogPublisher) {
	ctx = log.WithModule(ctx, "taskmanager")

	logCtlr, ok := tm.ctlr.(exec.ControllerLogs)
	if !ok {
		return // no logs available
	}
	if err := logCtlr.Logs(ctx, publisher, options); err != nil {
		log.G(ctx).WithError(err).Errorf("logs call failed")
	}
}

func (tm *taskManager) run(ctx context.Context) {
	ctx, cancelAll := context.WithCancel(ctx)
	defer cancelAll() // cancel all child operations on exit.

	ctx = log.WithModule(ctx, "taskmanager")

	var (
		opctx    context.Context
		cancel   context.CancelFunc
		run      = make(chan struct{}, 1)
		statusq  = make(chan *api.TaskStatus)
		errs     = make(chan error)
		shutdown = tm.shutdown
		updated  bool // true if the task was updated.
	)

	defer func() {
		// closure  picks up current value of cancel.
		if cancel != nil {
			cancel()
		}
	}()

	run <- struct{}{} // prime the pump
	for {
		select {
		case <-run:
			// always check for shutdown before running.
			select {
			case <-tm.shutdown:
				shutdown = tm.shutdown // a little questionable
				continue               // ignore run request and handle shutdown
			case <-tm.closed:
				continue
			default:
			}

			opctx, cancel = context.WithCancel(ctx)

			// Several variables need to be snapshotted for the closure below.
			opcancel := cancel        // fork for the closure
			running := tm.task.Copy() // clone the task before dispatch
			statusqLocal := statusq
			updatedLocal := updated // capture state of update for goroutine
			updated = false
			go runctx(ctx, tm.closed, errs, func(ctx context.Context) error {
				defer opcancel()

				if updatedLocal {
					// before we do anything, update the task for the controller.
					// always update the controller before running.
					if err := tm.ctlr.Update(opctx, running); err != nil {
						log.G(ctx).WithError(err).Error("updating task controller failed")
						return err
					}
				}

				status, err := exec.Do(opctx, running, tm.ctlr)
				if status != nil {
					// always report the status if we get one back. This
					// returns to the manager loop, then reports the status
					// upstream.
					select {
					case statusqLocal <- status:
					case <-ctx.Done(): // not opctx, since that may have been cancelled.
					}

					if err := tm.reporter.UpdateTaskStatus(ctx, running.ID, status); err != nil {
						log.G(ctx).WithError(err).Error("task manager failed to report status to agent")
					}
				}

				return err
			})
		case err := <-errs:
			// This branch is always executed when an operations completes. The
			// goal is to decide whether or not we re-dispatch the operation.
			cancel = nil

			select {
			case <-tm.shutdown:
				shutdown = tm.shutdown // re-enable the shutdown branch
				continue               // no dispatch if we are in shutdown.
			default:
			}

			switch err {
			case exec.ErrTaskNoop:
				if !updated {
					continue // wait till getting pumped via update.
				}
			case exec.ErrTaskRetry:
				// TODO(stevvooe): Add exponential backoff with random jitter
				// here. For now, this backoff is enough to keep the task
				// manager from running away with the CPU.
				time.AfterFunc(time.Second, func() {
					errs <- nil // repump this branch, with no err
				})
				continue
			case nil, context.Canceled, context.DeadlineExceeded:
				// no log in this case
			default:
				log.G(ctx).WithError(err).Error("task operation failed")
			}

			select {
			case run <- struct{}{}:
			default:
			}
		case status := <-statusq:
			tm.task.Status = *status
		case task := <-tm.updateq:
			if equality.TasksEqualStable(task, tm.task) {
				continue // ignore the update
			}

			if task.ID != tm.task.ID {
				log.G(ctx).WithField("task.update.id", task.ID).Error("received update for incorrect task")
				continue
			}

			if task.DesiredState < tm.task.DesiredState {
				log.G(ctx).WithField("task.update.desiredstate", task.DesiredState).
					Error("ignoring task update with invalid desired state")
				continue
			}

			task = task.Copy()
			task.Status = tm.task.Status // overwrite our status, as it is canonical.
			tm.task = task
			updated = true

			// we have accepted the task update
			if cancel != nil {
				cancel() // cancel outstanding if necessary.
			} else {
				// If this channel op fails, it means there is already a
				// message on the run queue.
				select {
				case run <- struct{}{}:
				default:
				}
			}
		case <-shutdown:
			if cancel != nil {
				// cancel outstanding operation.
				cancel()

				// subtle: after a cancellation, we want to avoid busy wait
				// here. this gets renabled in the errs branch and we'll come
				// back around and try shutdown again.
				shutdown = nil // turn off this branch until op proceeds
				continue       // wait until operation actually exits.
			}

			// disable everything, and prepare for closing.
			statusq = nil
			errs = nil
			shutdown = nil
			tm.closeOnce.Do(func() {
				close(tm.closed)
			})
		case <-tm.closed:
			return
		case <-ctx.Done():
			tm.closeOnce.Do(func() {
				close(tm.closed)
			})
			return
		}
	}
}


text:
package org.apache.geode.internal.cache.xmlcache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionService;

/**
 * FunctionServiceCreation to be used in CacheXmlParser
 *
 */
public class FunctionServiceCreation {

  private final List<Function> functions = new ArrayList<>();

  public FunctionServiceCreation() {}

  public void registerFunction(Function f) {
    this.functions.add(f);
  }

  public void create() {
    for (Function function : this.functions) {
      FunctionService.registerFunction(function);
    }
  }

  List<Function> getFunctionList() {
    return this.functions;
  }

  public Map<String, Function> getFunctions() {
    Map<String, Function> result = new HashMap<>();
    for (Function function : this.functions) {
      result.put(function.getId(), function);
    }
    return result;
  }
}


text:
import os
import sys

import subprocess
import traceback

SCRIPT_DIR = os.path.dirname(__file__)

ENVIRON32_FILE = 'environment.x86'
ENVIRON64_FILE = 'environment.x64'

VC_VARS_SCRIPTS = [
  "vcvarsall.bat",
  os.path.join("VC", "vcvarsall.bat"),
  os.path.join("Community", "Common7", "Tools", "VsDevCmd.bat"),
]

def GetEnvDictFromSet(set_output):
  env_dict = {}
  for line in set_output.splitlines():
    line = line.strip()
    if line and "=" in line:
      key, value = line.split('=', 1)
      env_dict[key] = value

  return env_dict

def GetVCVarsEnv(vc_vars_path):
  """Returns both the 32 and 64 bit environment dictionary as a tuple."""
  env32 = subprocess.check_output([vc_vars_path, '&&', 'set'],
                                  shell=True)
  env32_dict = GetEnvDictFromSet(env32)

  env64 = subprocess.check_output([vc_vars_path, '&&', 'set'],
                                  shell=True)
  env64_dict = GetEnvDictFromSet(env64)

  return (env32_dict, env64_dict)

def WriteWindowEnvFile(env_dict, env_file):
  with open(env_file, 'wb') as f:
    for key, value in env_dict.iteritems():
      f.write(key + '=' + value + '\0')
    f.write('\0')
  with open(env_file + '.txt', 'wt') as f:
    for key, value in env_dict.iteritems():
      f.write(key + '=' + value + '\n')

def DoMain(argv):
  if len(argv) != 1 or '--h' in argv or '--help' in argv or '\?' in argv:
    print 'Usage: %s vs_path' % sys.argv[0]
    return 1

  vs_path, = argv
  for vc_vars_script in VC_VARS_SCRIPTS:
    script_file = os.path.join(vs_path, vc_vars_script)
    if os.path.isfile(script_file):
      vc_vars_path = script_file
      break
  else:
    assert False, "Could not determine VC Vars script path."
    vc_vars_path = os.path.join(vs_path, 'VC', 'vcvarsall.bat')

  env_dict32, env_dict64 = GetVCVarsEnv(vc_vars_path)

  WriteWindowEnvFile(env_dict32, ENVIRON32_FILE)
  WriteWindowEnvFile(env_dict64, ENVIRON64_FILE)
  return 0

if __name__ == "__main__":
  try:
    sys.exit(DoMain(sys.argv[1:]))
  except Exception as e:
    traceback.print_exc()
    sys.exit(1)


text:
<?php

namespace PHPixie\Template;

class Exception extends \Exception
{

}


text:
# GMDColors
[![Build Status](https://travis-ci.org/wa7eedem/GMDColors.svg?branch=master)](https://travis-ci.org/wa7eedem/GMDColors)
[![Code Climate](https://codeclimate.com/github/wa7eedem/GMDColors/badges/gpa.svg)](https://codeclimate.com/github/wa7eedem/GMDColors)
[![Latest Stable Version](https://poser.pugx.org/wa7eedem/gmdcolors/v/stable?format=flat)](https://packagist.org/packages/wa7eedem/gmdcolors)
[![Total Downloads](https://poser.pugx.org/wa7eedem/gmdcolors/downloads?format=flat)](https://packagist.org/packages/wa7eedem/gmdcolors)
[![License](https://poser.pugx.org/wa7eedem/gmdcolors/license?format=flat)](https://packagist.org/packages/wa7eedem/gmdcolors)

#### get Google Material Design hex colors for php
see the Color palette in [google material](https://material.io/guidelines/style/color.html#color-color-tool)
## Usage :
### get a single color :

```
$getC = new getcolors;
$hex   = $getC->hex('Blue','100');
// return : string '#BBDEFB'
```

### get a a random colors :

```
$getC = new getcolors;
$rand = $getC->rand(3);

/*return : array (size=3)
0 => string '#BA68C8' (length=7)
1 => string '#FFF176' (length=7)
2 => string '#64B5F6' (length=7)
*/
```