text:
require 'vagrant'

class Numeric
  Alphabet = ('a'..'z').to_a
  def vdev
    s, q = '', self
    (q, r = (q - 1).divmod(26)) && s.prepend(Alphabet[r]) until q.zero?
    'vd'+s
  end
end

module VagrantPlugins
  module ProviderLibvirt
    class Config < Vagrant.plugin('2', :config)
      # manually specify URI
      # will supercede most other options if provided
      attr_accessor :uri

      # A hypervisor name to access via Libvirt.
      attr_accessor :driver

      # The name of the server, where libvirtd is running.
      attr_accessor :host

      # If use ssh tunnel to connect to Libvirt.
      attr_accessor :connect_via_ssh
      # Path towards the libvirt socket
      attr_accessor :socket

      # The username to access Libvirt.
      attr_accessor :username

      # Password for Libvirt connection.
      attr_accessor :password

      # ID SSH key file
      attr_accessor :id_ssh_key_file

      # Libvirt storage pool name, where box image and instance snapshots will
      # be stored.
      attr_accessor :storage_pool_name

      # Turn on to prevent hostname conflicts
      attr_accessor :random_hostname

      # Libvirt default network
      attr_accessor :management_network_name
      attr_accessor :management_network_address
      attr_accessor :management_network_mode

      # Default host prefix (alternative to use project folder name)
      attr_accessor :default_prefix

      # Domain specific settings used while creating new domain.
      attr_accessor :memory
      attr_accessor :cpus
      attr_accessor :cpu_mode
      attr_accessor :machine_type
      attr_accessor :disk_bus
      attr_accessor :nic_model_type
      attr_accessor :nested
      attr_accessor :volume_cache
      attr_accessor :kernel
      attr_accessor :cmd_line
      attr_accessor :initrd
      attr_accessor :graphics_type
      attr_accessor :graphics_autoport
      attr_accessor :graphics_port
      attr_accessor :graphics_passwd
      attr_accessor :graphics_ip
      attr_accessor :video_type
      attr_accessor :video_vram
      attr_accessor :keymap

      # Storage
      attr_accessor :disks
  	  attr_accessor :cdroms

      def initialize
        @uri               = UNSET_VALUE
        @driver            = UNSET_VALUE
        @host              = UNSET_VALUE
        @connect_via_ssh   = UNSET_VALUE
        @username          = UNSET_VALUE
        @password          = UNSET_VALUE
        @id_ssh_key_file   = UNSET_VALUE
        @storage_pool_name = UNSET_VALUE
        @random_hostname   = UNSET_VALUE
        @management_network_name    = UNSET_VALUE
        @management_network_address = UNSET_VALUE
        @management_network_mode = UNSET_VALUE

        # Domain specific settings.
        @memory            = UNSET_VALUE
        @cpus              = UNSET_VALUE
        @cpu_mode          = UNSET_VALUE
        @machine_type      = UNSET_VALUE
        @disk_bus          = UNSET_VALUE
        @nic_model_type    = UNSET_VALUE
        @nested            = UNSET_VALUE
        @volume_cache      = UNSET_VALUE
        @kernel            = UNSET_VALUE
        @initrd            = UNSET_VALUE
        @cmd_line          = UNSET_VALUE
        @graphics_type     = UNSET_VALUE
        @graphics_autoport = UNSET_VALUE
        @graphics_port     = UNSET_VALUE
        @graphics_ip       = UNSET_VALUE
        @graphics_passwd   = UNSET_VALUE
        @video_type        = UNSET_VALUE
        @video_vram        = UNSET_VALUE
        @keymap            = UNSET_VALUE

        # Storage
        @disks             = []
        @cdroms			       = []
      end

      def _get_device(disks)
        # skip existing devices and also the first one (vda)
        exist = disks.collect {|x| x[:device]}+[1.vdev.to_s]
        skip = 1		# we're 1 based, not 0 based...
        while true do
          dev = skip.vdev	# get lettered device
          if !exist.include?(dev)
            return dev
          end
          skip+=1
        end
      end

      def _get_cdrom_dev(cdroms)
        exist = Hash[cdroms.collect{|x| [x[:dev],true]}]
        # hda - hdc
        curr = "a".ord
        while curr <= "d".ord
          dev = "hd" + curr.chr
          if exist[dev]
            curr += 1
            next
          else
            return dev
          end
        end

        # is it better to raise our own error, or let libvirt cause the exception?
        raise "Only four cdroms may be attached at a time"
      end

      # NOTE: this will run twice for each time it's needed- keep it idempotent
      def storage(storage_type, options={})
        if storage_type == :file
          if options[:device] == :cdrom
            _handle_cdrom_storage(options)
          else
            _handle_disk_storage(options)
          end
        end
      end

      def _handle_cdrom_storage(options={})
        # <disk type="file" device="cdrom">
        #   <source file="/home/user/virtio-win-0.1-100.iso"/>
        #   <target dev="hdc"/>
        #   <readonly/>
        #   <address type='drive' controller='0' bus='1' target='0' unit='0'/>
        # </disk>
        #
        # note the target dev will need to be changed with each cdrom drive (hdc, hdd, etc),
        # as will the address unit number (unit=0, unit=1, etc)

        options = {
          :dev => self._get_cdrom_dev(@cdroms),
          :bus => "ide",
          :path => nil,
        }.merge(options)

        cdrom = {
          :dev => options[:dev],
          :bus => options[:bus],
          :path => options[:path]
        }

        @cdroms << cdrom
      end

      def _handle_disk_storage(options={})
        options = {
          :device => _get_device(@disks),
          :type => 'qcow2',
          :size => '10G',	# matches the fog default
          :path => nil,
          :bus => 'virtio'
        }.merge(options)

        disk = {
          :device => options[:device],
          :type => options[:type],
          :size => options[:size],
          :path => options[:path],
          :bus => options[:bus],
          :cache => options[:cache] || 'default',
          :allow_existing => options[:allow_existing],
        }

        @disks << disk	# append
      end

      # code to generate URI from a config moved out of the connect action
      def _generate_uri
        # builds the libvirt connection URI from the given driver config
        # Setup connection uri.
        uri = @driver.dup
        virt_path = case uri
        when 'qemu', 'openvz', 'uml', 'phyp', 'parallels', 'kvm'
          '/system'
        when '@en', 'esx'
          '/'
        when 'vbox', 'vmwarews', 'hyperv'
          '/session'
        else
          raise "Require specify driver #{uri}"
        end
        if uri == 'kvm'
          uri = 'qemu'	# use qemu uri for kvm domain type
        end

        if @connect_via_ssh
          uri << '+ssh://'
          if @username
            uri << @username + '@'
          end

          if @host
            uri << @host
          else
            uri << 'localhost'
          end
        else
          uri << '://'
          uri << @host if @host
        end

        uri << virt_path
        uri << '?no_verify=1'

        if @id_ssh_key_file
          # set ssh key for access to libvirt host
          uri << "\&keyfile="
          # if no slash, prepend $HOME/.ssh/
          uri << "#{`echo ${HOME}`.chomp}/.ssh/" if @id_ssh_key_file !~ /\A\//
          uri << @id_ssh_key_file
        end
        # set path to libvirt socket
        uri << "\&socket="+@socket if @socket
        return uri
      end

      def finalize!
        @driver = 'kvm' if @driver == UNSET_VALUE
        @host = nil if @host == UNSET_VALUE
        @connect_via_ssh = false if @connect_via_ssh == UNSET_VALUE
        @username = nil if @username == UNSET_VALUE
        @password = nil if @password == UNSET_VALUE
        @id_ssh_key_file = 'id_rsa' if @id_ssh_key_file == UNSET_VALUE
        @storage_pool_name = 'default' if @storage_pool_name == UNSET_VALUE
        @random_hostname = false if @random_hostname == UNSET_VALUE
        @management_network_name = 'vagrant-libvirt' if @management_network_name == UNSET_VALUE
        @management_network_address = '192.168.121.0/24' if @management_network_address == UNSET_VALUE
        @management_network_mode = 'nat' if @management_network_mode == UNSET_VALUE

        # generate a URI if none is supplied
        @uri = _generate_uri() if @uri == UNSET_VALUE

        # Domain specific settings.
        @memory = 512 if @memory == UNSET_VALUE
        @cpus = 1 if @cpus == UNSET_VALUE
        @cpu_mode = 'host-model' if @cpu_mode == UNSET_VALUE
        @machine_type = nil if @machine_type == UNSET_VALUE
        @disk_bus = 'virtio' if @disk_bus == UNSET_VALUE
        @nic_model_type = 'virtio' if @nic_model_type == UNSET_VALUE
        @nested = false if @nested == UNSET_VALUE
        @volume_cache = 'default' if @volume_cache == UNSET_VALUE
        @kernel = nil if @kernel == UNSET_VALUE
        @cmd_line = '' if @cmd_line == UNSET_VALUE
        @initrd = '' if @initrd == UNSET_VALUE
        @graphics_type = 'vnc' if @graphics_type == UNSET_VALUE
        @graphics_autoport = 'yes' if @graphics_port == UNSET_VALUE
        @graphics_autoport = 'no' if @graphics_port != UNSET_VALUE
        if (@graphics_type != 'vnc' && @graphics_port != 'spice') ||
            @graphics_passwd == UNSET_VALUE
          @graphics_passwd = nil
        end
        @graphics_port = 5900 if @graphics_port == UNSET_VALUE
        @graphics_ip = '127.0.0.1' if @graphics_ip == UNSET_VALUE
        @video_type = 'cirrus' if @video_type == UNSET_VALUE
        @video_vram = 9216 if @video_vram == UNSET_VALUE
        @keymap = 'en-us' if @keymap == UNSET_VALUE

        # Storage
        @disks = [] if @disks == UNSET_VALUE
        @cdroms = [] if @cdroms == UNSET_VALUE
      end

      def validate(machine)
        errors = _detected_errors

        machine.provider_config.disks.each do |disk|
          if disk[:path] and disk[:path][0] == '/'
            errors << "absolute volume paths like '#{disk[:path]}' not yet supported"
          end
        end

         { "Libvirt Provider" => errors }
      end

      def merge(other)
        super.tap do |result|
          c = disks.dup
          c += other.disks
          result.disks = c
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import { ShaderLib } from '../shaders/ShaderLib.js';
import { Pass } from './pass.js';

/**
 * Supersample Anti-Aliasing Render Pass
 *
 * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
 */
var SSAARenderPass = function(scene, camera, clearColor, clearAlpha) {

  Pass.call(this);

  this.scene = scene;
  this.camera = camera;
  this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  this.unbiased = true;

  // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  this.clearColor = (clearColor !== undefined) ? clearColor : 0x000000;
  this.clearAlpha = (clearAlpha !== undefined) ? clearAlpha : 0;

  // if (THREE.CopyShader === undefined) {
  //   console.error("PIXY.SSAARenderPass rlies on THREEE.CopyShader");
  // }

  var copyShader = ShaderLib.copy;
  this.copyUniforms = THREE.UniformsUtils.clone(copyShader.uniforms);
  this.copyMaterial = new THREE.ShaderMaterial({
    uniforms: this.copyUniforms,
    vertexShader: copyShader.vertexShader,
    fragmentShader: copyShader.fragmentShader,
    premultipliedAlpha: true,
    transparent: true,
    blending: THREE.AdditiveBlending,
    depthTest: false,
    depthWrite: false
  });

  this.camera2 = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  this.scene2 = new THREE.Scene();
  this.quad2 = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.copyMaterial);
  this.quad2.frustumCulled = false; // Avoid getting clipped
  this.scene2.add(this.quad2);
};

SSAARenderPass.prototype = Object.assign(Object.create(Pass.prototype), {

  constructor: SSAARenderPass,

  dispose: function() {
    if (this.sampleRenderTarget) {
      this.sampleRenderTarget.dispose();
      this.sampleRenderTarget = null;
    }
  },

  render: function(renderer, writeBuffer, readBuffer, delta, maskActive) {
    if (!this.sampleRenderTarget) {
      this.sampleRenderTarget = new THREE.WebGLRenderTarget(readBuffer.width, readBuffer.height,
        { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat });
    }

    var jitterOffsets = SSAARenderPass.JitterVectors[ Math.max(0, Math.min(this.sampleLevel, 5)) ];
    var autoClear = renderer.autoClear;
    renderer.autoClear = false;

    var oldRenderTarget = renderer.getRenderTarget();
    var oldClearColor = renderer.getClearColor().getHex();
    var oldClearAlpha = renderer.getClearAlpha();

    var baseSampleWeight = 1.0 / jitterOffsets.length;
    var roundingRange = 1/32;
    this.copyUniforms["tDiffuse"].value = this.sampleRenderTarget.texture;

    var width = readBuffer.width, height = readBuffer.height;

    // render the scene multiple times, each slightly jitter offset from the last and accumulate the results
    for (var i=0; i<jitterOffsets.length; i++) {
      var jitterOffset = jitterOffsets[i];
      if (this.camera.setViewOffset) {
        this.camera.setViewOffset(width, height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625, // 0.0625 = 1/16
          width, height);
      }

      var sampleWeight = baseSampleWeight;
      if (this.unbiased) {
        // the theory is that equal weights for each sample lead to an accumulation of rounding errors.
        // The following equation varies the sampleWeight per sample so that it is uniformly distributed
        // across a range of values whose rounding errors cancel each other out.
        var uniformCenteredDistribution = (-0.5 + (i + 0.5) / jitterOffsets.length);
        sampleWeight += roundingRange * uniformCenteredDistribution;
      }

      this.copyUniforms["opacity"].value = sampleWeight;
      renderer.setClearColor(this.clearColor, this.clearAlpha);
      renderer.setRenderTargeT(this.sampleRenderTarget);
      renderer.clear();
      renderer.render(this.scene, this.camera);

      if (i === 0) {
        renderer.setClearColor(0x000000, 1.0);
      }
      renderer.setRenderTarget(writeBuffer);
      if (i === 0) renderer.clear();
      renderer.render(this.scene2, this.camera2);
    }

    if (this.camera.clearViewOffset) {
      this.camera.clearViewOffset();
    }

    renderer.autoClear = autoClear;
    renderer.setClearColor(oldClearColor, oldClearAlpha);
    renderer.setRenderTarget(oldRenderTarget);
  }
});

// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8, 8] integer grid, but it needs to be mapped onto [-0.5,0.5)
// before being used, thus these integers needs to be scaled by 1/16
//
//
// Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
SSAARenderPass.JitterVectors = [
  [
    [ 0, 0 ]
  ],
  [
    [ 4, 4 ], [ - 4, - 4 ]
  ],
  [
    [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  ],
  [
    [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
    [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  ],
  [
    [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
    [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
    [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
    [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  ],
  [
    [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
    [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
    [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
    [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
    [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
    [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
    [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
    [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  ]
];

export { SSAARenderPass };


text:
package com.github.jweixin.jwx.message.strategy;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.log4j.Logger;

import com.github.jweixin.jwx.context.InitialWeixinConfigureException;
import com.github.jweixin.jwx.context.MsgMatcher;
import com.github.jweixin.jwx.context.WeixinContext;
import com.github.jweixin.jwx.context.WeixinMethod;
import com.github.jweixin.jwx.message.annotation.ScanEvent;
import com.github.jweixin.jwx.message.annotation.ScanSubscribeEvent;
import com.github.jweixin.jwx.message.request.InMessage;
import com.github.jweixin.jwx.message.request.event.InScanEvent;
import com.github.jweixin.jwx.message.request.event.InScanSubscribeEvent;
import com.github.jweixin.jwx.util.CollectionUtil;
import com.github.jweixin.jwx.util.StringUtil;

/**
 * 扫描事件处理策略
 * @author Administrator
 *
 */
public class ScanEventStrategy implements MsgStrategy {

	public final static String SCAN_EVENT_TEXT_MATCHOR = "SCAN_EVENT_TEXT_MATCHOR";
	public final static String SCAN_EVENT_PATTERN_MATCHOR = "SCAN_EVENT_PATTERN_MATCHOR";
	public final static String SCAN_EVENT_DEFAULT_MATCHOR = "SCAN_EVENT_DEFAULT_MATCHOR";

	private static Logger logger = Logger.getLogger(ScanEventStrategy.class);

	/**
	 * 扫描事件与注解名称对应关系
	 */
	private static Map<String, String> nameMap = new HashMap<String, String>();

	static {
		nameMap.put(InScanEvent.class.getName(), ScanEvent.class.getName());
		nameMap.put(InScanSubscribeEvent.class.getName(), ScanSubscribeEvent.class.getName());
	}

	@Override
	public void buildMsgMethodMapper(WeixinContext context, WeixinMethod method, Annotation anno)
			throws ServletException {
		String prefix = anno.annotationType().getName();
		String value = null;
		String scenePattern = null;
		if(anno instanceof ScanEvent){
			value = ((ScanEvent) anno).value();
			scenePattern = ((ScanEvent) anno).scenePattern();
		} else if(anno instanceof ScanSubscribeEvent){
			value = ((ScanSubscribeEvent) anno).value();
			scenePattern = ((ScanSubscribeEvent) anno).scenePattern();
		}

		Map<String, List<MsgMatcher>> mapper = context.getMessageMethodMappper();
		if(!StringUtil.isNull(value)){
			MsgMatcher matcher = new MsgMatcher();
			matcher.setMethod(method);
			matcher.setWxAnnotation(anno);
			matcher.setMatchValue(prefix + "-" + value);
			List<MsgMatcher> matcherList = mapper.get(SCAN_EVENT_TEXT_MATCHOR);
			if(matcherList == null){
				matcherList = new ArrayList<MsgMatcher>();
				mapper.put(SCAN_EVENT_TEXT_MATCHOR, matcherList);
			} else {
				Iterator<MsgMatcher> iter = matcherList.iterator();
				while(iter.hasNext()){
					MsgMatcher m = iter.next();
					if(m.getMatchValue().equals(matcher.getMatchValue())){
						throw new InitialWeixinConfigureException("微信上下文(" + context.getUrl() + ")配置了多个扫描事件[" + prefix + "(" + value + ")]文本适配方法,按要求只能配置一个。");
					}
				}
			}
			matcherList.add(matcher);
			logger.debug("建立微信扫描事件" + anno.annotationType().getName() + "(" + value + ")与方法" + method.getWxObj().getClass().getName() + "." + method.getWxMethod().getName() + "的映射关系");
		}

		if(!StringUtil.isNull(scenePattern)){
			MsgMatcher matcher = new MsgMatcher();
			matcher.setMethod(method);
			matcher.setWxAnnotation(anno);
			matcher.setMatchValue(prefix + "-" + scenePattern);
			List<MsgMatcher> matcherList = mapper.get(SCAN_EVENT_PATTERN_MATCHOR);
			if(matcherList == null){
				matcherList = new ArrayList<MsgMatcher>();
				mapper.put(SCAN_EVENT_PATTERN_MATCHOR, matcherList);
			}
			matcherList.add(matcher);
			logger.debug("建立微信扫描事件场景模式" + anno.annotationType().getName() + "{" + scenePattern + "}与方法" + method.getWxObj().getClass().getName() + "." + method.getWxMethod().getName() + "的映射关系");
		}

		if(StringUtil.isNull(value) && StringUtil.isNull(scenePattern)){
			MsgMatcher matcher = new MsgMatcher();
			matcher.setMethod(method);
			matcher.setWxAnnotation(anno);
			matcher.setMatchValue(prefix);
			List<MsgMatcher> matcherList = mapper.get(SCAN_EVENT_DEFAULT_MATCHOR);
			if(matcherList == null){
				matcherList = new ArrayList<MsgMatcher>();
				mapper.put(SCAN_EVENT_DEFAULT_MATCHOR, matcherList);
			} else {
				Iterator<MsgMatcher> iter = matcherList.iterator();
				while(iter.hasNext()){
					MsgMatcher msgMatcher = iter.next();
					if(msgMatcher.getMatchValue().equals(prefix)){
						throw new InitialWeixinConfigureException("微信上下文(" + context.getUrl() + ")配置了多个扫描事件[" + prefix + "]的缺省方法,按要求只能配置一个。");
					}
				}
			}
			matcherList.add(matcher);
			logger.debug("建立微信缺省扫描事件" + anno.annotationType().getName() + "与方法" + method.getWxObj().getClass().getName() + "." + method.getWxMethod().getName() + "的映射关系");
		}
	}

	@Override
	public WeixinMethod getInMsgWeixinMethod(WeixinContext context, InMessage in) {
		String prefix = nameMap.get(in.getClass().getName());
		String scene = null;
		if(in instanceof InScanEvent){
			scene = ((InScanEvent) in).getEventKey();
		} else if(in instanceof InScanSubscribeEvent){
			scene = ((InScanSubscribeEvent) in).getEventKey().substring("qrscene_".length());
		}

		if(!StringUtil.isNull(scene)){
			//场景文本适配
			List<MsgMatcher> matchers = context.getMessageMethodMappper().get(SCAN_EVENT_TEXT_MATCHOR);
			if(!CollectionUtil.isNull(matchers)){
				Iterator<MsgMatcher> iter = matchers.iterator();
				while(iter.hasNext()){
					MsgMatcher matcher = iter.next();
					if(matcher.getMatchValue().equals(prefix + "-" + scene)){
						logger.debug("微信(" + context.getUrl() + ")扫描事件[" + in.getClass().getName() + "]场景{" + scene + "}找到微信处理方法:" + matcher.getMethod().getWxObj().getClass().getName() + "." + matcher.getMethod().getWxMethod().getName());
						return matcher.getMethod();
					}
				}
			}

			//场景正则表达式适配
			matchers = context.getMessageMethodMappper().get(SCAN_EVENT_PATTERN_MATCHOR);
			if(!CollectionUtil.isNull(matchers)){
				Iterator<MsgMatcher> iter = matchers.iterator();
				while(iter.hasNext()){
					MsgMatcher matcher = iter.next();
					String matchValue = matcher.getMatchValue();
					if(matchValue.startsWith(prefix + "-")){
						matchValue = matchValue.substring((prefix + "-").length());
						if(scene.matches(matchValue)){
							logger.debug("微信(" + context.getUrl() + ")扫描事件[" + in.getClass().getName() + "]场景{" + scene + "}通过正则表达式[" + matchValue +"]找到微信处理方法:" + matcher.getMethod().getWxObj().getClass().getName() + "." + matcher.getMethod().getWxMethod().getName());
							return matcher.getMethod();
						}
					}
				}
			}
		}

		//缺省适配
		List<MsgMatcher> matchers = context.getMessageMethodMappper().get(SCAN_EVENT_DEFAULT_MATCHOR);
		if(!CollectionUtil.isNull(matchers)){
			Iterator<MsgMatcher> iter = matchers.iterator();
			while(iter.hasNext()){
				MsgMatcher matcher = iter.next();
				String matchValue = matcher.getMatchValue();
				if(matchValue.equals(prefix)){
					logger.debug("微信(" + context.getUrl() + ")扫描事件[" + in.getClass().getName() + "]场景{" + scene + "}找到缺省的微信处理方法:" + matcher.getMethod().getWxObj().getClass().getName() + "." + matcher.getMethod().getWxMethod().getName());
					return matcher.getMethod();
				}
			}
		}

		return null;
	}

}


text:
namespace StudentSystem.Web.Models
{
    using System;
    using StudentSystem.Models;

    public class StudentDataModel
    {
        public static Func<Student, StudentDataModel> FromDataToModel
        {
            get
            {
                return s => new StudentDataModel
                {
                    Address = s.AdditionalInformation.Address,
                    Email = s.AdditionalInformation.Email,
                    FirstName = s.FirstName,
                    LastName = s.LastName,
                    Level = s.Level,
                    StudentIdentification = s.StudentIdentification
                };
            }
        }

        public int StudentIdentification { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Level { get; set; }

        public string Assistant { get; set; }

        public string Email { get; set; }

        public string Address { get; set; }

        public static Student FromModelToData(StudentDataModel studentModel)
        {
            return new Student
            {
                AdditionalInformation =
                {
                    Address = studentModel.Address,
                    Email = studentModel.Email,
                },
                FirstName = studentModel.FirstName,
                LastName = studentModel.LastName,
                Level = studentModel.Level,
                StudentIdentification = studentModel.StudentIdentification
            };
        }
    }
}


text:
Transport <?php echo $button ?>

        <form action="<?php echo $action; ?>" method="post">

            Transport Mode <?php echo form_error('transport_mode') ?>
            <input type="text" class="form-control" name="transport_mode" id="transport_mode" placeholder="Transport Mode" value="<?php echo $transport_mode; ?>" />

            Transport Desc <?php echo form_error('transport_desc') ?>
            <input type="text" class="form-control" name="transport_desc" id="transport_desc" placeholder="Transport Desc" value="<?php echo $transport_desc; ?>" />

            Transport Per Unit <?php echo form_error('transport_per_unit') ?>
            <input type="text" class="form-control" name="transport_per_unit" id="transport_per_unit" placeholder="Transport Per Unit" value="<?php echo $transport_per_unit; ?>" />

            Transport Price <?php echo form_error('transport_price') ?>
            <input type="text" class="form-control" name="transport_price" id="transport_price" placeholder="Transport Price" value="<?php echo $transport_price; ?>" />

            Ispublic <?php echo form_error('ispublic') ?>
            <input type="text" class="form-control" name="ispublic" id="ispublic" placeholder="Ispublic" value="<?php echo $ispublic; ?>" />

	    <input type="hidden" name="transport_id" value="<?php echo $transport_id; ?>" />
	    <button type="submit" class="btn btn-primary"><?php echo $button ?></button>
	    <a href="<?php echo site_url('transport') ?>" class="btn btn-default">Cancel
	</form>


text:
[![Build Status](https://circleci.com/gh/crushlovely/ansible-linux-base.svg?style=shield)](https://github.com/crushlovely/ansible-linux-base)
[![Current Version](http://img.shields.io/github/release/crushlovely/ansible-linux-base.svg?style=flat)](https://galaxy.ansible.com/list#/roles/1362)

This Ansible role that updates `apt` and upgrades all packages. It then installs the following packages:

* `git`
* `ntp`
* `unattended-upgrades`
* `build-essential`
* `libreadline6`
* `libreadline6-dev`
* `curl`
* `zlib1g`
* `zlib1g-dev`
* `libssl-dev`
* `libyaml-dev`
* `libsqlite3-dev`
* `sqlite3`
* `libxml2-dev`
* `libxslt1-dev`
* `autoconf`
* `libc6-dev`
* `libncurses5-dev`
* `automake`
* `libtool`
* `bison`
* `pkg-config`

Finally it sets the default timezone for the server.  We use this as the base image for all our Ruby and Node.js applications.

## Installation

``` bash
$ ansible-galaxy install crushlovely.linux-base,v1.0.0
```

## Variables

``` yaml
time_zone: UTC
```

## Usage

Once this role is installed on your system, include it in the roles list of your playbook.

``` yaml
---
- hosts: localhost
  roles:
    - crushlovely.linux-base
```

## Dependencies

None

## License

MIT


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

namespace Modelisation
{
	/// <summary>
	/// Scenario item that play a sound as long as it is active.
	/// </summary>
	public class AudioScenarioItem : ScenarioItem
	{
		private AudioSource audio;

		/// <summary>
		/// Allow creation of an audioscenario item; the sound is played until the next scenarioItem become current.
		/// </summary>
		/// <param name="name">The name of the object in the unity scene.</param>
		/// <param name="descrition">Desciption of what the action is supposed to achieve.</param>
		/// <param name="audioName">Name of the audio that should be played.</param>
		/// <param name="name">Allow the execution of other actions.</param>
		/// <param name="name">Allow this action to be executed in a different mode than the current one.</param>
		public AudioScenarioItem (string name, string description, string audioName, bool auth = true, Mode? mode = null)  :  base(name, description, auth, mode)
		{
			audio = GameObject.Find ("/GameManager/" + audioName).GetComponent<AudioSource>();
		}

		public virtual void startAction() {
			audio.Play ();
		}
		public virtual void stopAction() {
			audio.Stop ();
		}

	}
}


text:
@interface TGTopCommentCell ()
@property (weak, nonatomic) IBOutlet UIImageView *iconImageV;
@property (weak, nonatomic) IBOutlet UILabel *commentLbl;
@property (weak, nonatomic) IBOutlet UIButton *voiceBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *voiceBtnLeftConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentLblCenterYConstratint;

@property (strong, nonatomic) AVPlayerItem *playerItem;
@end

static AVPlayer * commentPlayer_;
static UIButton *lastBtn_;
static TGCommentNewM *lastCommentM_;

@implementation TGTopCommentCell

- (void)awakeFromNib {
    [super awakeFromNib];
    [self.voiceBtn setAdjustsImageWhenHighlighted:NO];
    UIImageView * imageView = self.voiceBtn.imageView;
    imageView.animationImages=[NSArray arrayWithObjects:
                               [UIImage imageNamed:@"play-voice-icon-0"],
                               [UIImage imageNamed:@"play-voice-icon-1"],
                               [UIImage imageNamed:@"play-voice-icon-2"],
                               nil ];
    imageView.animationDuration=1.0;
    imageView.animationRepeatCount = 0;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)setCommentM:(TGCommentNewM *)commentM{
    _commentM = commentM;
    [self.iconImageV tg_setHeader:commentM.u.header.length>0 ? commentM.u.header : commentM.user.profile_image.length>0 ? commentM.user.profile_image : commentM.u.profile_image];
    self.commentLbl.attributedText = commentM.attrStrM;
    self.voiceBtn.hidden = commentM.voiceuri.length<=0;
    self.voiceBtnLeftConstraint.constant = commentM.topCommentWidth;
    self.commentLblCenterYConstratint.constant = commentM.voiceuri.length>0 ? 0 : commentM.topCommentCellHeight > 25 ? (commentM.topCommentCellHeight - 25) * .5: 0;

    if (commentM.voiceuri.length) {
        [self.voiceBtn setTitle:[NSString stringWithFormat:@"%zd''", commentM.voicetime] forState:UIControlStateNormal];
    }

    [self.voiceBtn setImage:[UIImage imageNamed:@"play-voice-icon-2"] forState:UIControlStateNormal];
    [self setBtn:self.voiceBtn play:commentM.voicePlaying];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:commentM.voiceuri]];
        commentPlayer_ = [AVPlayer playerWithPlayerItem:self.playerItem];
        commentPlayer_.volume = 1.0f;
    });
}

- (IBAction)voicePlay:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    lastBtn_.selected = !lastBtn_.isSelected;
    if (lastCommentM_ != self.commentM) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];

        self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.commentM.voiceuri]];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(playerItemDidReachEnd:)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:self.playerItem];

        [commentPlayer_ replaceCurrentItemWithPlayerItem:self.playerItem];
        [commentPlayer_ play];
        lastCommentM_.voicePlaying = NO;
        self.commentM.voicePlaying = YES;
        [self setBtn:lastBtn_ play:lastCommentM_.voicePlaying];
        [self setBtn:sender play:self.commentM.voicePlaying];
    }else{
        if(lastCommentM_.voicePlaying){
            [commentPlayer_ pause];
            self.commentM.voicePlaying = NO;
            [self setBtn:sender play:self.commentM.voicePlaying];
        }else{
            [commentPlayer_ play];
            lastCommentM_.voicePlaying = NO;
            [self setBtn:lastBtn_ play:lastCommentM_.voicePlaying];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(playerItemDidReachEnd:)
                                                         name:AVPlayerItemDidPlayToEndTimeNotification
                                                       object:self.playerItem];
            self.commentM.voicePlaying = YES;
            [self setBtn:sender play:self.commentM.voicePlaying];
        }
    }
    lastCommentM_ = self.commentM;
    lastBtn_ = sender;
}

-(void) setBtn : (UIButton *) btn play:(BOOL) isPlay{
    !(!isPlay && [btn.imageView isAnimating]) ? : [btn.imageView stopAnimating];
    !(isPlay && (! btn.imageView.isAnimating)) ? : [btn.imageView startAnimating];
}

-(void) playerItemDidReachEnd:(AVPlayerItem *)playerItem{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    lastCommentM_.voicePlaying = NO;
    self.commentM.voicePlaying = NO;
    [self setBtn:self.voiceBtn play:self.commentM.voicePlaying];
    [self setBtn:lastBtn_ play:lastCommentM_.voicePlaying];
    [commentPlayer_ pause];
    [commentPlayer_ seekToTime:kCMTimeZero];
}

-(void)dealloc{
    [commentPlayer_ pause];
    lastCommentM_.voicePlaying = NO;
    [self setBtn:lastBtn_ play:lastCommentM_.voicePlaying];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    //[avTimer_ invalidate];
    //avTimer_= nil;
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    return NO;
}

@end


text:
// Template Source: BaseEntityRequest.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.SecureScoreControlProfile;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;

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

/**
 * The class for the Secure Score Control Profile Request.
 */
public class SecureScoreControlProfileRequest extends BaseRequest<SecureScoreControlProfile> {

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

    /**
     * Gets the SecureScoreControlProfile from the service
     *
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<SecureScoreControlProfile> getAsync() {
        return sendAsync(HttpMethod.GET, null);
    }

    /**
     * Gets the SecureScoreControlProfile from the service
     *
     * @return the SecureScoreControlProfile from the request
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public SecureScoreControlProfile get() throws ClientException {
       return send(HttpMethod.GET, null);
    }

    /**
     * Delete this item from the service
     *
     * @return a future with the deletion result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<SecureScoreControlProfile> deleteAsync() {
        return sendAsync(HttpMethod.DELETE, null);
    }

    /**
     * Delete this item from the service
     * @return the resulting response if the service returns anything on deletion
     *
     * @throws ClientException if there was an exception during the delete operation
     */
    @Nullable
    public SecureScoreControlProfile delete() throws ClientException {
        return send(HttpMethod.DELETE, null);
    }

    /**
     * Patches this SecureScoreControlProfile with a source
     *
     * @param sourceSecureScoreControlProfile the source object with updates
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<SecureScoreControlProfile> patchAsync(@Nonnull final SecureScoreControlProfile sourceSecureScoreControlProfile) {
        return sendAsync(HttpMethod.PATCH, sourceSecureScoreControlProfile);
    }

    /**
     * Patches this SecureScoreControlProfile with a source
     *
     * @param sourceSecureScoreControlProfile the source object with updates
     * @return the updated SecureScoreControlProfile
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public SecureScoreControlProfile patch(@Nonnull final SecureScoreControlProfile sourceSecureScoreControlProfile) throws ClientException {
        return send(HttpMethod.PATCH, sourceSecureScoreControlProfile);
    }

    /**
     * Creates a SecureScoreControlProfile with a new object
     *
     * @param newSecureScoreControlProfile the new object to create
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<SecureScoreControlProfile> postAsync(@Nonnull final SecureScoreControlProfile newSecureScoreControlProfile) {
        return sendAsync(HttpMethod.POST, newSecureScoreControlProfile);
    }

    /**
     * Creates a SecureScoreControlProfile with a new object
     *
     * @param newSecureScoreControlProfile the new object to create
     * @return the created SecureScoreControlProfile
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public SecureScoreControlProfile post(@Nonnull final SecureScoreControlProfile newSecureScoreControlProfile) throws ClientException {
        return send(HttpMethod.POST, newSecureScoreControlProfile);
    }

    /**
     * Creates a SecureScoreControlProfile with a new object
     *
     * @param newSecureScoreControlProfile the object to create/update
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<SecureScoreControlProfile> putAsync(@Nonnull final SecureScoreControlProfile newSecureScoreControlProfile) {
        return sendAsync(HttpMethod.PUT, newSecureScoreControlProfile);
    }

    /**
     * Creates a SecureScoreControlProfile with a new object
     *
     * @param newSecureScoreControlProfile the object to create/update
     * @return the created SecureScoreControlProfile
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public SecureScoreControlProfile put(@Nonnull final SecureScoreControlProfile newSecureScoreControlProfile) throws ClientException {
        return send(HttpMethod.PUT, newSecureScoreControlProfile);
    }

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

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

}


text:
package org.deeplearning4j.util;

import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.optimize.listeners.CollectScoresListener;
import org.nd4j.base.Preconditions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.reduce.longer.MatchCondition;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.ops.transforms.Transforms;

import java.lang.reflect.Field;
import java.util.*;

import static org.junit.Assert.*;

@Slf4j
public class CuDNNValidationUtil {

    public static final double MAX_REL_ERROR = 1e-4;
//    public static final double MAX_REL_ERROR = 1e-3;
//    public static final double MIN_ABS_ERROR = 1e-3;
    public static final double MIN_ABS_ERROR = 1e-5;

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @Builder
    public static class TestCase {
        private String testName;
        private List<Class<?>> allowCudnnHelpersForClasses;
        @Builder.Default private boolean testForward = true;
        @Builder.Default private boolean testScore = true;
        @Builder.Default private boolean testBackward = true;
        @Builder.Default private boolean testTraining = true;
        @Builder.Default private boolean trainFirst = false;
        @Builder.Default private double maxRE = MAX_REL_ERROR;
        @Builder.Default private double minAbsErr = MIN_ABS_ERROR;
        INDArray features;
        INDArray labels;
        private DataSetIterator data;
    }

    public static void validateMLN(MultiLayerNetwork netOrig, TestCase t){
        assertNotNull(t.getAllowCudnnHelpersForClasses());
        assertFalse(t.getAllowCudnnHelpersForClasses().isEmpty());

        //Don't allow fallback:
        for(Layer l : netOrig.getLayers()){
            org.deeplearning4j.nn.conf.layers.Layer lConf = l.conf().getLayer();
            if(lConf instanceof ConvolutionLayer){
                ((ConvolutionLayer) lConf).setCudnnAllowFallback(false);
            } else if(lConf instanceof SubsamplingLayer){
                ((SubsamplingLayer) lConf).setCudnnAllowFallback(false);
            }
        }

        MultiLayerNetwork net1NoCudnn = new MultiLayerNetwork(netOrig.getLayerWiseConfigurations().clone());
        net1NoCudnn.init();
        log.info("Removing all CuDNN helpers from network copy 1");
        removeHelpers(net1NoCudnn.getLayers(), null);

        MultiLayerNetwork net2With = new MultiLayerNetwork(netOrig.getLayerWiseConfigurations().clone());
        net2With.init();
        net2With.params().assign(netOrig.params());
        log.info("Removing all except for specified CuDNN helpers from network copy 2: " + t.getAllowCudnnHelpersForClasses());
        removeHelpers(net2With.getLayers(), t.getAllowCudnnHelpersForClasses());

        if(t.isTrainFirst()){
            Preconditions.checkState(t.getData() != null, "Test data iterator is ");
            log.info("Validation - training first...");
            log.info("*** NOT YET IMPLEMENTED***");

        }

        if(t.isTestForward()){
            Preconditions.checkNotNull(t.getFeatures(), "Features are not set (null)");

            for (boolean train : new boolean[]{false, true}) {
                assertEquals(net1NoCudnn.params(), net2With.params());
                String s = "Feed forward test - " + t.getTestName() + " - " + (train ? "Train: " : "Test: ");
                List<INDArray> ff1 = net1NoCudnn.feedForward(t.getFeatures(), train);
                List<INDArray> ff2 = net2With.feedForward(t.getFeatures(), train);
                List<String> paramKeys = new ArrayList<>(net1NoCudnn.paramTable().keySet());
                Collections.sort(paramKeys);
                for (String p : paramKeys) {
                    INDArray p1 = net1NoCudnn.getParam(p);
                    INDArray p2 = net2With.getParam(p);
                    INDArray re = relError(p1, p2, t.minAbsErr);
                    double maxRE = re.maxNumber().doubleValue();
                    if (maxRE >= t.maxRE) {
                        System.out.println("Failed param values: parameter " + p + " - No CuDNN vs. with CuDNN - train=" + train);
                        System.out.println(p1);
                        System.out.println(p2);
                    }
                    assertTrue(s + " - param changed during forward pass: " + p, maxRE < t.maxRE);
                }

                for( int i=0; i<ff1.size(); i++ ){
                    int layerIdx = i-1; //FF includes input
                    String layerName = "layer_" + layerIdx + " - " +
                            (i == 0 ? "input" : net1NoCudnn.getLayer(layerIdx).getClass().getSimpleName());
                    INDArray arr1 = ff1.get(i);
                    INDArray arr2 = ff2.get(i);

                    INDArray relError = relError(arr1, arr2, t.minAbsErr);
                    double maxRE = relError.maxNumber().doubleValue();
                    int idx = relError.argMax(Integer.MAX_VALUE).getInt(0);
                    if(maxRE >= t.maxRE){
                        double d1 = arr1.dup('c').getDouble(idx);
                        double d2 = arr2.dup('c').getDouble(idx);
                        System.out.println("Different values at index " + idx + ": " + d1 + ", " + d2 + " - RE = " + maxRE);
                    }
                    assertTrue(s + layerName + " - max RE: " + maxRE, maxRE < t.maxRE);
                    log.info("Forward pass, max relative error: " + layerName + " - " + maxRE);
                }

                INDArray out1 = net1NoCudnn.output(t.getFeatures(), train);
                INDArray out2 = net2With.output(t.getFeatures(), train);
                INDArray relError = relError(out1, out2, t.minAbsErr);
                double maxRE = relError.maxNumber().doubleValue();
                log.info(s + "Output, max relative error: " + maxRE);

                assertEquals(net1NoCudnn.params(), net2With.params());  //Check that forward pass does not modify params
                assertTrue(s + "Max RE: " + maxRE, maxRE < t.maxRE);
            }
        }

        if(t.isTestScore()) {
            Preconditions.checkNotNull(t.getFeatures(), "Features are not set (null)");
            Preconditions.checkNotNull(t.getLabels(), "Labels are not set (null)");

            log.info("Validation - checking scores");
            double s1 = net1NoCudnn.score(new DataSet(t.getFeatures(), t.getLabels()));
            double s2 = net2With.score(new DataSet(t.getFeatures(), t.getLabels()));

            double re = relError(s1, s2);
            String s = "Relative error: " + re;
            assertTrue(s, re < t.maxRE);
        }

        if(t.isTestBackward()) {
            Preconditions.checkNotNull(t.getFeatures(), "Features are not set (null)");
            Preconditions.checkNotNull(t.getLabels(), "Labels are not set (null)");
            log.info("Validation - checking backward pass");

            //Check gradients
            net1NoCudnn.setInput(t.getFeatures());
            net1NoCudnn.setLabels(t.getLabels());

            net2With.setInput(t.getFeatures());
            net2With.setLabels(t.getLabels());

            net1NoCudnn.computeGradientAndScore();
            net2With.computeGradientAndScore();

            List<String> paramKeys = new ArrayList<>(net1NoCudnn.paramTable().keySet());
            Collections.sort(paramKeys);
            for(String p : paramKeys){
                INDArray g1 = net1NoCudnn.gradient().gradientForVariable().get(p);
                INDArray g2 = net2With.gradient().gradientForVariable().get(p);

                if(g1 == null || g2 == null){
                    throw new RuntimeException("Null gradients");
                }

                INDArray re = relError(g1, g2, t.minAbsErr);
                double maxRE = re.maxNumber().doubleValue();
                if (maxRE >= t.maxRE) {
                    System.out.println("Failed param values: no CuDNN vs. with CuDNN - parameter: " + p);
                    System.out.println(Arrays.toString(g1.dup().data().asFloat()));
                    System.out.println(Arrays.toString(g2.dup().data().asFloat()));
                } else {
                    System.out.println("OK: " + p);
                }
                assertTrue("Gradients are not equal: " + p + ": maxRE=" + maxRE, maxRE < t.maxRE);
            }
        }

        if(t.isTestTraining()){
            Preconditions.checkNotNull(t.getData(), "DataSetIterator is not set (null)");
            log.info("Testing run-to-run consistency of training with CuDNN");

            net2With = new MultiLayerNetwork(netOrig.getLayerWiseConfigurations().clone());
            net2With.init();
            net2With.params().assign(netOrig.params());
            log.info("Removing all except for specified CuDNN helpers from network copy 2: " + t.getAllowCudnnHelpersForClasses());
            removeHelpers(net2With.getLayers(), t.getAllowCudnnHelpersForClasses());

            CollectScoresListener listener = new CollectScoresListener(1);
            net2With.setListeners(listener);
            net2With.fit(t.getData());

            for( int i=0; i<2; i++ ) {

                net2With = new MultiLayerNetwork(netOrig.getLayerWiseConfigurations().clone());
                net2With.init();
                net2With.params().assign(netOrig.params());
                log.info("Removing all except for specified CuDNN helpers from network copy 2: " + t.getAllowCudnnHelpersForClasses());
                removeHelpers(net2With.getLayers(), t.getAllowCudnnHelpersForClasses());

                CollectScoresListener listener2 = new CollectScoresListener(1);
                net2With.setListeners(listener2);
                net2With.fit(t.getData());

                DoubleArrayList listOrig = listener.getListScore();
                DoubleArrayList listNew = listener2.getListScore();

                assertEquals(listOrig.size(), listNew.size());
                for (int j = 0; j < listOrig.size(); j++) {
                    double d1 = listOrig.get(j);
                    double d2 = listNew.get(j);
                    double re = relError(d1, d2);
                    String msg = "Scores at iteration " + j + " - relError = " + re + ", score1 = " + d1 + ", score2 = " + d2;
                    assertTrue(msg, re < t.maxRE);
                    System.out.println("j=" + j + ", d1 = " + d1 + ", d2 = " + d2);
                }
            }
        }
    }

    private static void removeHelpers(Layer[] layers, List<Class<?>> keepHelpersFor){

        Map<Class<?>, Integer> map = new HashMap<>();
        for(Layer l : layers){
            Field f;
            try{
                f = l.getClass().getDeclaredField("helper");
            } catch (Exception e){
                //OK, may not be a CuDNN supported layer
                continue;
            }

            f.setAccessible(true);
            boolean keepAndAssertPresent = false;
            if(keepHelpersFor != null) {
                for (Class<?> c : keepHelpersFor) {
                    if(c.isAssignableFrom(l.getClass())){
                        keepAndAssertPresent = true;
                        break;
                    }
                }
            }
            try {
                if (keepAndAssertPresent) {
                    Object o = f.get(l);
                    assertNotNull(o);
                } else {
                    f.set(l, null);
                    Integer i = map.get(l.getClass());
                    if(i == null){
                        i = 0;
                    }
                    map.put(l.getClass(), i+1);
                }
            } catch (IllegalAccessException e){
                throw new RuntimeException(e);
            }
        }

        for(Map.Entry<Class<?>,Integer> c : map.entrySet()){
            System.out.println("Removed " + c.getValue() + " CuDNN helpers instances from layer " + c.getKey());
        }
    }

    private static double relError(double d1, double d2){
        Preconditions.checkState(!Double.isNaN(d1), "d1 is NaN");
        Preconditions.checkState(!Double.isNaN(d2), "d2 is NaN");
        if(d1 == 0.0 && d2 == 0.0){
            return 0.0;
        }

        return Math.abs(d1-d2) / (Math.abs(d1) + Math.abs(d2));
    }

    private static INDArray relError(@NonNull INDArray a1, @NonNull INDArray a2, double minAbsError){
        long numNaN1 = Nd4j.getExecutioner().exec(new MatchCondition(a1, Conditions.isNan(), Integer.MAX_VALUE)).getInt(0);
        long numNaN2 = Nd4j.getExecutioner().exec(new MatchCondition(a2, Conditions.isNan(), Integer.MAX_VALUE)).getInt(0);
        Preconditions.checkState(numNaN1 == 0, "Array 1 has NaNs");
        Preconditions.checkState(numNaN2 == 0, "Array 2 has NaNs");

//        INDArray isZero1 = a1.eq(0.0);
//        INDArray isZero2 = a2.eq(0.0);
//        INDArray bothZero = isZero1.muli(isZero2);

        INDArray abs1 = Transforms.abs(a1, true);
        INDArray abs2 = Transforms.abs(a2, true);
        INDArray absDiff = Transforms.abs(a1.sub(a2), false);

        //abs(a1-a2) < minAbsError ? 1 : 0
        INDArray greaterThanMinAbs = Transforms.abs(a1.sub(a2), false);
        BooleanIndexing.replaceWhere(greaterThanMinAbs, 0.0, Conditions.lessThan(minAbsError));
        BooleanIndexing.replaceWhere(greaterThanMinAbs, 1.0, Conditions.greaterThan(0.0));

        INDArray result = absDiff.divi(abs1.add(abs2));
        //Only way to have NaNs given there weren't any in original : both 0s
        BooleanIndexing.replaceWhere(result, 0.0, Conditions.isNan());
        //Finally, set to 0 if less than min abs error, or unchanged otherwise
        result.muli(greaterThanMinAbs);

//        double maxRE = result.maxNumber().doubleValue();
//        if(maxRE > t.maxRe){
//            System.out.println();
//        }
        return result;
    }

}


text:
namespace web {

class WebThreadTest : public PlatformTest {
 protected:
  static void BasicFunction(base::OnceClosure continuation,
                            WebThread::ID target) {
    auto other_thread = target == WebThread::UI ? WebThread::IO : WebThread::UI;

    EXPECT_TRUE(WebThread::CurrentlyOn(target));
    EXPECT_FALSE(WebThread::CurrentlyOn(other_thread));
    std::move(continuation).Run();
  }

  web::WebTaskEnvironment task_environment_{WebTaskEnvironment::REAL_IO_THREAD};
};

TEST_F(WebThreadTest, BasePostTask) {
  base::RunLoop run_loop;
  EXPECT_TRUE(GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::IO)));
  run_loop.Run();
}

TEST_F(WebThreadTest, GetUITaskRunnerPostTask) {
  base::RunLoop run_loop;
  EXPECT_TRUE(GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::UI)));
  run_loop.Run();
}

TEST_F(WebThreadTest, GetIOTaskRunnerPostTask) {
  base::RunLoop run_loop;
  EXPECT_TRUE(GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::IO)));
  run_loop.Run();
}

TEST_F(WebThreadTest, PostTaskViaTaskRunner) {
  scoped_refptr<base::TaskRunner> task_runner = GetIOThreadTaskRunner({});
  base::RunLoop run_loop;
  EXPECT_TRUE(task_runner->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::IO)));
  run_loop.Run();
}

TEST_F(WebThreadTest, PostTaskViaSequencedTaskRunner) {
  scoped_refptr<base::SequencedTaskRunner> task_runner =
      GetIOThreadTaskRunner({});
  base::RunLoop run_loop;
  EXPECT_TRUE(task_runner->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::IO)));
  run_loop.Run();
}

TEST_F(WebThreadTest, PostTaskViaSingleThreadTaskRunner) {
  scoped_refptr<base::SingleThreadTaskRunner> task_runner =
      GetIOThreadTaskRunner({});
  base::RunLoop run_loop;
  EXPECT_TRUE(task_runner->PostTask(
      FROM_HERE, base::BindOnce(&BasicFunction, run_loop.QuitWhenIdleClosure(),
                                WebThread::IO)));
  run_loop.Run();
}

}  // namespace web


text:
//Copyright (c) 2014 Andrew Savinykh
//
//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.
using Metaname.Api.Logging;
using Newtonsoft.Json;

namespace Metaname.Api.Models
{
    public class NameServerDetails : CanDumpPropertiesToString
    {
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("ip4_address")]
        public string Ip4Address { get; set; }
        [JsonProperty("ip6_address")]
        public string Ip6Address { get; set; }
    }
}


text:
# a Shoutcast radio media server for the Coherence UPnP Framework
# (heavily revamped from the existing IRadio plugin)

# Copyright 2007, Frank Scholz <coherence@beebits.net>
# Copyright 2009-2010, Jean-Michel Sizun <jmDOTsizunATfreeDOTfr>

from twisted.internet import defer, reactor
from twisted.python.failure import Failure
from twisted.web import server

from coherence.upnp.core import utils

from coherence.upnp.core import DIDLLite
from coherence.upnp.core.DIDLLite import classChooser, Resource, DIDLElement

import coherence.extern.louie as louie

from coherence.extern.simple_plugin import Plugin

from coherence import log
from coherence.backend import BackendItem, BackendStore, Container, LazyContainer, AbstractBackendStore

from urlparse import urlsplit

DEFAULT_NAME = 'iRadioStore'

SHOUTCAST_WS_URL = 'http://www.shoutcast.com/sbin/newxml.phtml'

genre_families = {
    # genre hierarchy created from http://forums.winamp.com/showthread.php?s=&threadid=303231
    "Alternative": ["Adult Alternative", "Britpop", "Classic Alternative", "College", "Dancepunk", "Dream Pop", "Emo", "Goth", "Grunge", "Indie Pop", "Indie Rock", "Industrial", "Lo-Fi", "Modern Rock", "New Wave", "Noise Pop", "Post-Punk", "Power Pop", "Punk", "Ska", "Xtreme"],
    "Blues": ["Acoustic Blues", "Chicago Blues", "Contemporary Blues", "Country Blues", "Delta Blues", "Electric Blues", "Cajun/Zydeco"],
    "Classical": ["Baroque", "Chamber", "Choral", "Classical Period", "Early Classical", "Impressionist", "Modern", "Opera", "Piano", "Romantic", "Symphony"],
    "Country": ["Alt-Country", "Americana", "Bluegrass", "Classic Country", "Contemporary Bluegrass", "Contemporary Country", "Honky Tonk", "Hot Country Hits", "Western"],
    "Easy Listening": ["Exotica", "Light Rock", "Lounge", "Orchestral Pop", "Polka", "Space Age Pop"],
    "Electronic": ["Acid House", "Ambient", "Big Beat", "Breakbeat", "Dance", "Demo", "Disco", "Downtempo", "Drum and Bass", "Electro", "Garage", "Hard House", "House", "IDM", "Remixes", "Jungle", "Progressive", "Techno", "Trance", "Tribal", "Trip Hop"],
    "Folk": ["Alternative Folk", "Contemporary Folk", "Folk Rock", "New Acoustic", "Traditional Folk", "World Folk"],
    "Themes": ["Adult", "Best Of", "Chill", "Experimental", "Female", "Heartache", "LGBT", "Love/Romance", "Party Mix", "Patriotic", "Rainy Day Mix", "Reality", "Sexy", "Shuffle", "Travel Mix", "Tribute", "Trippy", "Work Mix"],
    "Rap": ["Alternative Rap", "Dirty South", "East Coast Rap", "Freestyle", "Hip Hop", "Gangsta Rap", "Mixtapes", "Old School", "Turntablism", "Underground Hip-Hop", "West Coast Rap"],
    "Inspirational": ["Christian", "Christian Metal", "Christian Rap", "Christian Rock", "Classic Christian", "Contemporary Gospel", "Gospel", "Praise/Worship", "Sermons/Services", "Southern Gospel", "Traditional Gospel"],
    "International": ["African", "Afrikaans", "Arabic", "Asian", "Brazilian", "Caribbean", "Celtic", "European", "Filipino", "Greek", "Hawaiian/Pacific", "Hindi", "Indian", "Japanese", "Jewish", "Klezmer", "Mediterranean", "Middle Eastern", "North American", "Polskie", "Polska", "Soca", "South American", "Tamil", "Worldbeat", "Zouk"],
    "Jazz": ["Acid Jazz", "Avant Garde", "Big Band", "Bop", "Classic Jazz", "Cool Jazz", "Fusion", "Hard Bop", "Latin Jazz", "Smooth Jazz", "Swing", "Vocal Jazz", "World Fusion"],
    "Latin": ["Bachata", "Banda", "Bossa Nova", "Cumbia", "Latin Dance", "Latin Pop", "Latin Rap/Hip-Hop", "Latin Rock", "Mariachi", "Merengue", "Ranchera", "Reggaeton", "Regional Mexican", "Salsa", "Tango", "Tejano", "Tropicalia"],
    "Metal": ["Black Metal", "Classic Metal", "Extreme Metal", "Grindcore", "Hair Metal", "Heavy Metal", "Metalcore", "Power Metal", "Progressive Metal", "Rap Metal"],
    "New Age": ["Environmental", "Ethnic Fusion", "Healing", "Meditation", "Spiritual"],
    "Decades": ["30s", "40s", "50s", "60s", "70s", "80s", "90s"],
    "Pop": ["Adult Contemporary", "Barbershop", "Bubblegum Pop", "Dance Pop", "Idols", "Oldies", "JPOP", "Soft Rock", "Teen Pop", "Top 40", "World Pop"],
    "R&B/Urban": ["Classic R&B", "Contemporary R&B", "Doo Wop", "Funk", "Motown", "Neo-Soul", "Quiet Storm", "Soul", "Urban Contemporary", "Reggae", "Contemporary Reggae", "Dancehall", "Dub", "Pop-Reggae", "Ragga", "Rock Steady", "Reggae Roots"],
    "Rock": ["Adult Album Alternative", "British Invasion", "Classic Rock", "Garage Rock", "Glam", "Hard Rock", "Jam Bands", "Piano Rock", "Prog Rock", "Psychedelic", "Rock & Roll", "Rockabilly", "Singer/Songwriter", "Surf"],
    "Seasonal/Holiday": ["Anniversary", "Birthday", "Christmas", "Halloween", "Hanukkah", "Honeymoon", "Valentine", "Wedding", "Winter"],
    "Soundtracks": ["Anime", "Bollywood", "Kids", "Original Score", "Showtunes", "Video Game Music"],
    "Talk": ["Comedy", "Community", "Educational", "Government", "News", "Old Time Radio", "Other Talk", "Political", "Public Radio", "Scanner", "Spoken Word", "Sports", "Technology", "Hardcore", "Eclectic", "Instrumental"],
    "Misc": [],
}

synonym_genres = {
  # TODO: extend list with entries from "Misc" which are clearly the same
  "24h": ["24h", "24hs"],
  "80s": ["80s", "80er"],
  "Acid Jazz": ["Acid", "Acid Jazz"],
  "Adult": ["Adult", "Adulto"],
  "Alternative": ["Alt", "Alternativa", "Alternative", "Alternativo"],
  "Francais": ["Francais", "French"],
  "Heavy Metal": ["Heavy Metal", "Heavy", "Metal"],
  "Hip Hop": ["Hip", "Hop", "Hippop", "Hip Hop"],
  "Islam": ["Islam", "Islamic"],
  "Italy": ["Italia", "Italian", "Italiana", "Italo", "Italy"],
  "Latina": ["Latin", "Latina", "Latino"],
}
useless_title_content = [
    # TODO: extend list with title expressions which are clearly useless
    " - [SHOUTcast.com]"
]
useless_genres = [
    # TODO: extend list with entries from "Misc" which are clearly useless
    "genres", "go", "here",
    "Her", "Hbwa"
]

class PlaylistStreamProxy(utils.ReverseProxyUriResource, log.Loggable):
    """ proxies audio streams published as M3U playlists (typically the case for shoutcast streams) """
    logCategory = 'PlaylistStreamProxy'

    stream_url = None

    def __init__(self, uri):
        log.Loggable.__init__(self)
        self.stream_url = None
        utils.ReverseProxyUriResource.__init__(self, uri)

    def requestFinished(self, result):
        """ self.connection is set in utils.ReverseProxyResource.render """
        self.debug("ProxyStream requestFinished")
        if self.connection is not None:
            self.connection.transport.loseConnection()

    def render(self, request):

        if self.stream_url is None:
            def got_playlist(result):
                if result is None:
                    self.warning('Error to retrieve playlist - nothing retrieved')
                    return requestFinished(result)
                result = result[0].split('\n')
                for line in result:
                    if line.startswith('File1='):
                        self.stream_url = line[6:]
                        break
                if self.stream_url is None:
                    self.warning('Error to retrieve playlist - inconsistent playlist file')
                    return requestFinished(result)
                #self.resetUri(self.stream_url)
                request.uri = self.stream_url
                return self.render(request)

            def got_error(error):
                self.warning('Error to retrieve playlist - unable to retrieve data')
                self.warning(error)
                return None

            playlist_url = self.uri
            d = utils.getPage(playlist_url, timeout=20)
            d.addCallbacks(got_playlist, got_error)
            return server.NOT_DONE_YET

        self.info("this is our render method %s %s %s %s", request.method, request.uri, request.client, request.clientproto)
        self.info("render %s", request.getAllHeaders())
        if request.clientproto == 'HTTP/1.1':
            self.connection = request.getHeader('connection')
            if self.connection:
                tokens = map(str.lower, self.connection.split(' '))
                if 'close' in tokens:
                    d = request.notifyFinish()
                    d.addBoth(self.requestFinished)
        else:
            d = request.notifyFinish()
            d.addBoth(self.requestFinished)
        return utils.ReverseProxyUriResource.render(self, request)

class IRadioItem(BackendItem):
    logCategory = 'iradio'

    def __init__(self, station_id, title, stream_url, mimetype):
        BackendItem.__init__(self)
        self.station_id = station_id
        self.name = title
        self.mimetype = mimetype
        self.stream_url = stream_url

        self.location = PlaylistStreamProxy(self.stream_url)

        self.item = None

    def replace_by (self, item):
        # do nothing: we suppose the replacement item is the same
        return

    def get_item(self):
        if self.item == None:
            upnp_id = self.get_id()
            upnp_parent_id = self.parent.get_id()
            self.item = DIDLLite.AudioBroadcast(upnp_id, upnp_parent_id, self.name)
            res = Resource(self.url, 'http-get:*:%s:%s' % (self.mimetype,
                                                           ';'.join(('DLNA.ORG_PN=MP3',
                                                                     'DLNA.ORG_CI=0',
                                                                     'DLNA.ORG_OP=01',
                                                                     'DLNA.ORG_FLAGS=01700000000000000000000000000000'))))
            res.size = 0  # None
            self.item.res.append(res)
        return self.item

    def get_path(self):
        self.url = self.store.urlbase + str(self.storage_id)
        return self.url

    def get_id(self):
        return self.storage_id

class IRadioStore(AbstractBackendStore):

    logCategory = 'iradio'

    implements = ['MediaServer']

    genre_parent_items = {}  # will list the parent genre for every given genre

    def __init__(self, server, **kwargs):
        AbstractBackendStore.__init__(self, server, **kwargs)

        self.name = kwargs.get('name', DEFAULT_NAME)
        self.refresh = int(kwargs.get('refresh', 60)) * 60

        self.shoutcast_ws_url = self.config.get('genrelist', SHOUTCAST_WS_URL)

        # set root item
        root_item = Container(None, self.name)
        self.set_root_item(root_item)

        # set root-level genre family containers
        # and populate the genre_parent_items dict from the family hierarchy information
        for family, genres in genre_families.items():
            family_item = self.append_genre(root_item, family)
            if family_item is not None:
                self.genre_parent_items[family] = root_item
                for genre in genres:
                    self.genre_parent_items[genre] = family_item

        # retrieve asynchronously the list of genres from the souhtcast server
        # genres not already attached to a family will be attached to the "Misc" family
        self.retrieveGenreList_attemptCount = 0
        deferredRoot = self.retrieveGenreList()
        # self.init_completed() # will be fired when the genre list is retrieved

    def append_genre(self, parent, genre):
        if genre in useless_genres:
            return None
        if synonym_genres.has_key(genre):
            same_genres = synonym_genres[genre]
        else:
            same_genres = [genre]
        title = genre.encode('utf-8')
        family_item = LazyContainer(parent, title, genre, self.refresh, self.retrieveItemsForGenre, genres=same_genres, per_page=1)

        # we will use a specific child items sorter
        # in order to get the sub-genre containers first
        def childs_sort(x, y):
            if x.__class__ == y.__class__:
                return cmp(x.name, y.name)  # same class, we compare the names
            else:
                # the IRadioItem is deemed the lowest item class,
                # other classes are compared by name (as usual)
                if isinstance(x, IRadioItem):
                    return 1
                elif isinstance(y, IRadioItem):
                    return -1
                else:
                    return cmp(x.name, y.name)
        family_item.sorting_method = childs_sort

        parent.add_child(family_item, external_id=genre)
        return family_item

    def __repr__(self):
        return self.__class__.__name__

    def upnp_init(self):
        self.current_connection_id = None

        self.wmc_mapping = {'4': self.get_root_id()}

        if self.server:
            self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo',
                                                                    ['http-get:*:audio/mpeg:*',
                                                                     'http-get:*:audio/x-scpls:*'],
                                                                     default=True)

    # populate a genre container (parent) with the sub-genre containers
    # and corresponding IRadio (list retrieved from the shoutcast server)
    def retrieveItemsForGenre (self, parent, genres, per_page=1, offset=0, page=0):
        genre = genres[page]
        if page < len(genres) - 1:
            parent.childrenRetrievingNeeded = True
        url = '%s?genre=%s' % (self.shoutcast_ws_url, genre)

        if genre_families.has_key(genre):
            family_genres = genre_families[genre]
            for family_genre in family_genres:
                self.append_genre(parent, family_genre)

        def got_page(result):
            self.info('connection to ShoutCast service successful for genre %s', genre)
            result = utils.parse_xml(result, encoding='utf-8')
            tunein = result.find('tunein')
            if tunein != None:
                tunein = tunein.get('base', '/sbin/tunein-station.pls')
            prot, host_port, path, _, _ = urlsplit(self.shoutcast_ws_url)
            tunein = prot + '://' + host_port + tunein

            stations = {}
            for stationResult in result.findall('station'):
                mimetype = stationResult.get('mt')
                station_id = stationResult.get('id')
                bitrate = stationResult.get('br')
                name = stationResult.get('name').encode('utf-8')
                # remove useless substrings (eg. '[Shoutcast.com]' ) from title
                for substring in useless_title_content:
                    name = name.replace(substring, "")
                lower_name = name.lower()
                url = '%s?id=%s' % (tunein, stationResult.get('id'))

                sameStation = stations.get(lower_name)
                if sameStation == None or bitrate > sameStation['bitrate']:
                    station = {'name': name,
                               'station_id': station_id,
                               'mimetype': mimetype,
                               'id': station_id,
                               'url': url,
                               'bitrate': bitrate}
                    stations[lower_name] = station

            for station in stations.values():
                station_id = station.get('station_id')
                name = station.get('name')
                url = station.get('url')
                mimetype = station.get('mimetype')
                item = IRadioItem(station_id, name, url, mimetype)
                parent.add_child(item, external_id=station_id)

            return True

        def got_error(error):
            self.warning("connection to ShoutCast service failed: %s", url)
            self.debug("%r", error.getTraceback())
            parent.childrenRetrievingNeeded = True  # we retry
            return Failure("Unable to retrieve stations for genre" % genre)

        d = utils.getPage(url)
        d.addCallbacks(got_page, got_error)
        return d

    # retrieve the whole list of genres from the shoutcast server
    # to complete the population of the genre families classification
    # (genres not previously classified are put into the "Misc" family)
    # ...and fire mediaserver init completion
    def retrieveGenreList(self):

        def got_page(result):
            if self.retrieveGenreList_attemptCount == 0:
                self.info("Connection to ShoutCast service successful for genre listing")
            else:
                self.warning("Connection to ShoutCast service successful for genre listing after %d attempts.", self.retrieveGenreList_attemptCount)
            result = utils.parse_xml(result, encoding='utf-8')

            genres = {}
            main_synonym_genre = {}
            for main_genre, sub_genres in synonym_genres.items():
                genres[main_genre] = sub_genres
                for genre in sub_genres:
                    main_synonym_genre[genre] = main_genre

            for genre in result.findall('genre'):
                name = genre.get('name')
                if name not in main_synonym_genre:
                    genres[name] = [name]
                    main_synonym_genre[name] = name

            for main_genre, sub_genres in genres.items():
                if not self.genre_parent_items.has_key(main_genre):
                    genre_families["Misc"].append(main_genre)

            self.init_completed()

        def got_error(error):
            self.warning("connection to ShoutCast service for genre listing failed - Will retry! %r", error)
            self.debug("%r", error.getTraceback())
            self.retrieveGenreList_attemptCount += 1
            reactor.callLater(5, self.retrieveGenreList)

        d = utils.getPage(self.shoutcast_ws_url)
        d.addCallback(got_page)
        d.addErrback(got_error)
        return d


text:
<!doctype>

  <meta charset="utf-8">
  <title>Timestamp Microservice</title>
  <meta name="description" content="Timestamp Microservice">
  <meta name="author" content="doanthieu">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">

        timestamp

Get timestamp description

Feature

Pass a string as a parameter, and it will check to see whether that string contains either a unix timestamp or a
          natural language date (example: January 1, 2016)

If it does, it returns both the Unix timestamp and the natural language form of that date.

If it does not contain a date or Unix timestamp, it returns null for those properties.

Example usage:

            https://u-timestamp.herokuapp.com/December%2015,%202015

            https://u-timestamp.herokuapp.com/1450137600

Example respond:

{ "unix": 1450137600, "natural": "December 15, 2015" }

timestamp microservice

              Creator

              Source code

Other microservices

              Request Header Parser

              URL Shortener

              Image Search

              File Metadata


text:
require 'delegate'
require 'link_thumbnailer/models/title'
require 'link_thumbnailer/models/description'
require 'link_thumbnailer/models/image'
require 'link_thumbnailer/models/video'

module LinkThumbnailer
  module Scrapers
    class Base < ::SimpleDelegator

      attr_reader :config, :document, :website, :attribute_name

      def initialize(document, website = nil)
        @config   = ::LinkThumbnailer.page.config
        @document = document
        @website  = website

        super(config)
      end

      def call(attribute_name)
        return false unless website.present?
        return false unless applicable?

        @attribute_name = attribute_name

        website.send("#{attribute_name}=", value)
        website
      end

      def applicable?
        true
      end

      def value
        fail NotImplementedError
      end

      private

      def meta_xpath(options = {})
        meta_xpaths(options).first
      end

      def meta_xpaths(options = {})
        key       = options.fetch(:key, :property)
        value     = options.fetch(:value, :content)
        attribute = options.fetch(:attribute, attribute_name)

        document.xpath("//meta[translate(@#{key},'#{abc.upcase}','#{abc}') = '#{attribute}' and string-length(@#{value}) > 0]")
      end

      def abc
        'abcdefghijklmnopqrstuvwxyz'
      end

      def model_class
        "::LinkThumbnailer::Models::#{attribute_name.to_s.camelize}".constantize
      end

      def modelize(node, text = nil)
        model_class.new(node, text)
      end

    end
  end
end


text:
class VersionUI : public content::WebUIController {
 public:
  explicit VersionUI(content::WebUI* web_ui);
  ~VersionUI() override;

 private:
  DISALLOW_COPY_AND_ASSIGN(VersionUI);
};

#endif  // CHROME_BROWSER_UI_WEBUI_VERSION_UI_H_


text:
local encoding = require 'core.encoding'
local cipher = require 'security.crypto.cipher'
local digest = require 'security.crypto.digest'

local ticket = require 'security.crypto.ticket'

describe('ticket', function()
    local t = ticket.new {
        --digest = digest.new('md5'),
        digest = digest.hmac('ripemd160', 'key1'),
        cipher = cipher.new {
            cipher = 'aes128',
            key = string.rep('x', 16),
            iv = string.rep('x', 16)
        },
        encoder = encoding.new('base64')
    }

    assert.equals(900, t.max_age)

    it('decrypt encrypted', function()
        local r = t:encode('test')
        local value = t:decode(r)
        assert.equals('test', value)
    end)

    describe('new', function()
        it('supports string for digest', function()
            assert(ticket.new {
                digest = 'md5',
                cipher = cipher.new {
                    cipher = 'aes128',
                    key = ''
                },
                encoder = encoding.new('base64')
            })
        end)

        it('supports function for digest', function()
            local md5 = digest.new 'md5'
            assert(ticket.new {
                digest = md5,
                cipher = cipher.new {
                    cipher = 'aes128',
                    key = ''
                },
                encoder = encoding.new('base64')
            })
        end)

        it('raises an error if digest is not a string or function', function()
            local f = function()
                ticket.new {}
            end
            assert.error(f, 'digest: string or function expected')
        end)

        it('supports max_age', function()
            assert.equals(60, ticket.new {
                digest = 'md5',
                max_age = 60,
                cipher = cipher.new {
                    cipher = 'aes128',
                    key = ''
                },
                encoder = encoding.new('base64')
            }.max_age)
        end)
    end)

    describe('decode', function()
        it('unable to decode', function()
            local value, err = t:decode('$')
            assert.is_nil(value)
            assert.equals('unable to decode', err)
        end)

        it('signature mismatch', function()
            local value, err = t:decode('invalid')
            assert.is_nil(value)
            assert.equals('signature missmatch', err)
        end)

        it('unable to decrypt', function()
            local s = string.rep('x', 10)
            local r = t.encoder.encode(t.digest(s) .. s)
            local value, err = t:decode(r)
            assert.is_nil(value)
            assert.equals('unable to decrypt', err)
        end)

        it('expired', function()
            local value, err = t:decode(
                'f4dixtKVgSjFjXkKjskzafHB1sOXpDxlvxxY' ..
                'z8yJUeqaRBQuRrLAnEODr1kVE8SU9JkVZw==')
            assert.is_nil(value)
            assert.equals('expired', err)
        end)
    end)
end)