text:
package scaleio

import (
	"encoding/gob"
	"errors"
	"fmt"
	"os"
	"path"
	"strconv"

	"github.com/golang/glog"

	api "k8s.io/api/core/v1"
	"k8s.io/kubernetes/pkg/volume"
	volutil "k8s.io/kubernetes/pkg/volume/util"
)

var (
	confKey = struct {
		gateway,
		sslEnabled,
		secretRef,
		system,
		protectionDomain,
		storagePool,
		storageMode,
		sdcRootPath,
		volumeName,
		volSpecName,
		fsType,
		readOnly,
		username,
		password,
		namespace,
		sdcGuid string
	}{
		gateway:          "gateway",
		sslEnabled:       "sslEnabled",
		secretRef:        "secretRef",
		system:           "system",
		protectionDomain: "protectionDomain",
		storagePool:      "storagePool",
		storageMode:      "storageMode",
		sdcRootPath:      "sdcRootPath",
		volumeName:       "volumeName",
		volSpecName:      "volSpecName",
		fsType:           "fsType",
		readOnly:         "readOnly",
		username:         "username",
		password:         "password",
		namespace:        "namespace",
		sdcGuid:          "sdcGuid",
	}
	sdcGuidLabelName = "scaleio.sdcGuid"
	sdcRootPath      = "/opt/emc/scaleio/sdc/bin"

	secretNotFoundErr              = errors.New("secret not found")
	configMapNotFoundErr           = errors.New("configMap not found")
	gatewayNotProvidedErr          = errors.New("ScaleIO gateway not provided")
	secretRefNotProvidedErr        = errors.New("secret ref not provided")
	systemNotProvidedErr           = errors.New("ScaleIO system not provided")
	storagePoolNotProvidedErr      = errors.New("ScaleIO storage pool not provided")
	protectionDomainNotProvidedErr = errors.New("ScaleIO protection domain not provided")
)

// mapScaleIOVolumeSource maps attributes from a ScaleIOVolumeSource to config
func mapVolumeSource(config map[string]string, source *api.ScaleIOVolumeSource) {
	config[confKey.gateway] = source.Gateway
	config[confKey.secretRef] = func() string {
		if source.SecretRef != nil {
			return string(source.SecretRef.Name)
		}
		return ""
	}()
	config[confKey.system] = source.System
	config[confKey.volumeName] = source.VolumeName
	config[confKey.sslEnabled] = strconv.FormatBool(source.SSLEnabled)
	config[confKey.protectionDomain] = source.ProtectionDomain
	config[confKey.storagePool] = source.StoragePool
	config[confKey.storageMode] = source.StorageMode
	config[confKey.fsType] = source.FSType
	config[confKey.readOnly] = strconv.FormatBool(source.ReadOnly)

	//optionals
	applyConfigDefaults(config)
}

func validateConfigs(config map[string]string) error {
	if config[confKey.gateway] == "" {
		return gatewayNotProvidedErr
	}
	if config[confKey.secretRef] == "" {
		return secretRefNotProvidedErr
	}
	if config[confKey.system] == "" {
		return systemNotProvidedErr
	}
	if config[confKey.storagePool] == "" {
		return storagePoolNotProvidedErr
	}
	if config[confKey.protectionDomain] == "" {
		return protectionDomainNotProvidedErr
	}

	return nil
}

// applyConfigDefaults apply known defaults to incoming spec for dynamic PVCs.
func applyConfigDefaults(config map[string]string) {
	b, err := strconv.ParseBool(config[confKey.sslEnabled])
	if err != nil {
		glog.Warning(log("failed to parse param sslEnabled, setting it to false"))
		b = false
	}
	config[confKey.sslEnabled] = strconv.FormatBool(b)
	config[confKey.storageMode] = defaultString(config[confKey.storageMode], "ThinProvisioned")
	config[confKey.fsType] = defaultString(config[confKey.fsType], "xfs")
	b, err = strconv.ParseBool(config[confKey.readOnly])
	if err != nil {
		glog.Warning(log("failed to parse param readOnly, setting it to false"))
		b = false
	}
	config[confKey.readOnly] = strconv.FormatBool(b)
}

func defaultString(val, defVal string) string {
	if val == "" {
		return defVal
	}
	return val
}

// loadConfig loads configuration data from a file on disk
func loadConfig(configName string) (map[string]string, error) {
	glog.V(4).Info(log("loading config file %s", configName))
	file, err := os.Open(configName)
	if err != nil {
		glog.Error(log("failed to open config file %s: %v", configName, err))
		return nil, err
	}
	defer file.Close()
	data := map[string]string{}
	if err := gob.NewDecoder(file).Decode(&data); err != nil {
		glog.Error(log("failed to parse config data %s: %v", configName, err))
		return nil, err
	}
	applyConfigDefaults(data)
	if err := validateConfigs(data); err != nil {
		glog.Error(log("failed to load ConfigMap %s: %v", err))
		return nil, err
	}

	return data, nil
}

// saveConfig saves the configuration data to local disk
func saveConfig(configName string, data map[string]string) error {
	glog.V(4).Info(log("saving config file %s", configName))

	dir := path.Dir(configName)
	if _, err := os.Stat(dir); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		glog.V(4).Info(log("creating config dir for config data: %s", dir))
		if err := os.MkdirAll(dir, 0750); err != nil {
			glog.Error(log("failed to create config data dir %v", err))
			return err
		}
	}

	file, err := os.Create(configName)
	if err != nil {
		glog.V(4).Info(log("failed to save config data file %s: %v", configName, err))
		return err
	}
	defer file.Close()
	if err := gob.NewEncoder(file).Encode(data); err != nil {
		glog.Error(log("failed to save config %s: %v", configName, err))
		return err
	}
	glog.V(4).Info(log("config data file saved successfully as %s", configName))
	return nil
}

// attachSecret loads secret object and attaches to configData
func attachSecret(plug *sioPlugin, namespace string, configData map[string]string) error {
	// load secret
	secretRefName := configData[confKey.secretRef]
	kubeClient := plug.host.GetKubeClient()
	secretMap, err := volutil.GetSecretForPV(namespace, secretRefName, sioPluginName, kubeClient)
	if err != nil {
		glog.Error(log("failed to get secret: %v", err))
		return secretNotFoundErr
	}
	// merge secret data
	for key, val := range secretMap {
		configData[key] = val
	}

	return nil
}

// attachSdcGuid injects the sdc guid node label value into config
func attachSdcGuid(plug *sioPlugin, conf map[string]string) error {
	guid, err := getSdcGuidLabel(plug)
	if err != nil {
		return err
	}
	conf[confKey.sdcGuid] = guid
	return nil
}

// getSdcGuidLabel fetches the scaleio.sdcGuid node label
// associated with the node executing this code.
func getSdcGuidLabel(plug *sioPlugin) (string, error) {
	nodeLabels, err := plug.host.GetNodeLabels()
	if err != nil {
		return "", err
	}
	label, ok := nodeLabels[sdcGuidLabelName]
	if !ok {
		glog.V(4).Info(log("node label %s not found", sdcGuidLabelName))
		return "", nil
	}

	glog.V(4).Info(log("found node label %s=%s", sdcGuidLabelName, label))
	return label, nil
}

// getVolumeSourceFromSpec safely extracts ScaleIOVolumeSource from spec
func getVolumeSourceFromSpec(spec *volume.Spec) (*api.ScaleIOVolumeSource, error) {
	if spec.Volume != nil && spec.Volume.ScaleIO != nil {
		return spec.Volume.ScaleIO, nil
	}
	if spec.PersistentVolume != nil &&
		spec.PersistentVolume.Spec.ScaleIO != nil {
		return spec.PersistentVolume.Spec.ScaleIO, nil
	}

	return nil, fmt.Errorf("ScaleIO not defined in spec")
}

func log(msg string, parts ...interface{}) string {
	return fmt.Sprintf(fmt.Sprintf("scaleio: %s", msg), parts...)
}


text:
MOCK_COUCHBASE_VERSION=1.5.18

mkdir -p mock-couchbase
if [ -d mock-couchbase/.git ];
  then
    git -C mock-couchbase pull
    git -C mock-couchbase checkout tags/${MOCK_COUCHBASE_VERSION}
  else
    git clone https://github.com/couchbase/CouchbaseMock.git mock-couchbase
    git -C mock-couchbase checkout tags/${MOCK_COUCHBASE_VERSION}
  fi
pushd mock-couchbase
if ! mvn package -Dmaven.test.skip=true; then
  echo "Error building mock-couchbase"
  exit 1
fi
popd

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 34: 454 (1951)

#### Original name
Mycena longicystis R. Heim

### Remarks
null


text:
//
//  AKAControlViewBindingDelegate.h
//  AKABeacon
//
//  Created by Michael Utech on 13.10.15.
//  Copyright © 2015 AKA Sarl. All rights reserved.
//

#import "AKANullability.h"

#import "AKABeaconNullability.h"

@protocol AKAControlViewBindingDelegate<AKABindingDelegate>

/**
 * Informs the delegate, that the target (f.e. view-) value changed to the specified
 * invalid value. The source value will not be updated by the binding and the target
 * value remains "dirty". This is a common situation occuring when the user enters
 * invalid data. The delegate or the controls framework should present a validation
 * message (depending on the configuration and setup of the framework and the app).
 */
@optional
- (void)                                            binding:(req_AKAControlViewBinding)binding
                           targetValueDidChangeFromOldValue:(opt_id)oldTargetValue
                                             toInvalidValue:(opt_id)newTargetValue
                                                  withError:(opt_NSError)error;

@optional
/**
 * Informs the delegate, that an attempt to update the
 * source (model) value for a target (view) value change to the specified
 * value failed, because the target value could not be converted
 * to a valid source value.
 *
 * @param binding the binding observing target value changes.
 * @param targetValue the target value that could not be converted.
 * @param error an error object providing additional information.
 */
- (void)                                            binding:(req_AKAControlViewBinding)binding
                     sourceUpdateFailedToConvertTargetValue:(opt_id)targetValue
                                     toSourceValueWithError:(opt_NSError)error;

@optional
/**
 * Informs the delegate, that an attempt to update the
 * source value for a target value change to the specified
 * value failed because the target value is not valid.
 *
 * @param binding the binding observing the source value change
 * @param targetValue the invalid target value
 * @param error an error object providing additional information.
 */
- (void)                                            binding:(req_AKAControlViewBinding)binding
                    sourceUpdateFailedToValidateSourceValue:(opt_id)sourceValue
                                   convertedFromTargetValue:(opt_id)targetValue
                                                  withError:(opt_NSError)error;

@optional
/**
 * Determines whether the binding should update the source value from the specified
 * oldSourceValue to the specified newSourceValue as a result of a source value change
 * from oldTargetValue to newTargetValue.
 *
 * If the delegate returns NO, the source value is not updated. The target value will
 * never be updated. It is the responsability of the delegate to synchronize the
 * source and target values participating in the binding if it vetoes the update.
 *
 * @param binding the binding
 * @param oldSourceValue the old source (f.e. model-) value
 * @param newSourceValue the new source value
 * @param oldTargetValue the old target (f.e. view-) value
 * @param newTargetValue the new target value
 *
 * @return YES if the binding should update the source value, NO otherwise.
 */
- (BOOL)                                      shouldBinding:(req_AKAControlViewBinding)binding
                                          updateSourceValue:(opt_id)oldSourceValue
                                                         to:(opt_id)newSourceValue
                                             forTargetValue:(opt_id)oldTargetValue
                                                   changeTo:(opt_id)newTargetValue;

@optional
- (void)                                            binding:(req_AKAControlViewBinding)binding
                                      willUpdateSourceValue:(opt_id)oldSourceValue
                                                         to:(opt_id)newSourceValue;

@optional
- (void)                                            binding:(req_AKAControlViewBinding)binding
                                       didUpdateSourceValue:(opt_id)oldSourceValue
                                                         to:(opt_id)newSourceValue;
@end


text:
using De.Osthus.Ambeth.Annotation;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.Ioc.Config;
using De.Osthus.Ambeth.Ioc.Factory;
using De.Osthus.Ambeth.Typeinfo;
using De.Osthus.Ambeth.Util;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace De.Osthus.Ambeth.Ioc.Proxy
{
    public class SelfAnnotationCache : AnnotationCache<Self>
    {
        protected override bool AnnotationEquals(Self left, Self right)
        {
            return Object.ReferenceEquals(left, right);
        }
    }

    public class CallingProxyPostProcessor : IInitializingBean
    {
        protected static readonly MemberInfo[] EMPTY_MEMBERS = new MemberInfo[0];

        protected readonly HashMap<Type, MemberInfo[]> typeToMembersMap = new HashMap<Type, MemberInfo[]>(0.5f);

        protected readonly AnnotationCache<Self> logInstanceCache = new SelfAnnotationCache();

        protected readonly Object readLock, writeLock;

        public IPropertyInfoProvider PropertyInfoProvider { protected get; set; }

        public CallingProxyPostProcessor()
        {
            readLock = new Object();
            writeLock = readLock;
        }

        public virtual void AfterPropertiesSet()
        {
            ParamChecker.AssertNotNull(PropertyInfoProvider, "PropertyInfoProvider");
        }

        public void BeanPostProcessed(IBeanContextFactory beanContextFactory, IServiceContext beanContext, IBeanConfiguration beanConfiguration, Type beanType,
                Object proxyBean, Object targetBean)
        {
            MemberInfo[] members = GetMembers(targetBean.GetType());
            Type proxyBeanType = proxyBean.GetType();
            foreach (MemberInfo member in members)
            {
                if (member is FieldInfo)
                {
                    FieldInfo field = (FieldInfo)member;
                    if (field.FieldType.IsAssignableFrom(proxyBeanType))
                    {
                        // Only if the proxy can be cast to the needed type we use it
                        field.SetValue(targetBean, proxyBean);
                    }
                    else
                    {
                        // Otherwise we choose the target bean itself for injection
                        field.SetValue(targetBean, targetBean);
                    }
                    continue;
                }
                MethodInfo method = (MethodInfo)member;
                ParameterInfo[] parameterTypes = method.GetParameters();
                Object[] parms = new Object[parameterTypes.Length];
                for (int a = parameterTypes.Length; a-- > 0; )
                {
                    if (parameterTypes[a].ParameterType.IsAssignableFrom(proxyBeanType))
                    {
                        // Only if the proxy can be cast to the needed type we use it
                        parms[a] = proxyBean;
                    }
                    else
                    {
                        // Otherwise we choose the target bean itself for injection
                        parms[a] = targetBean;
                    }
                }
                method.Invoke(targetBean, parms);
            }
        }

        protected MemberInfo[] GetMembersIntern(Type type)
	    {
            Object writeLock = this.writeLock;
            lock (writeLock)
            {
                return typeToMembersMap.Get(type);
            }
	    }

        protected MemberInfo[] GetMembers(Type type)
        {
            MemberInfo[] members = GetMembersIntern(type);
            if (members != null)
            {
                return members;
            }
            List<MemberInfo> ownMembers = new List<MemberInfo>();
            ScanForCallingProxyField(type, type, ownMembers);

            members = GetMembersIntern(type);
            if (members != null)
            {
                // discard own members
                return members;
            }
            Object writeLock = this.writeLock;
            lock (writeLock)
            {
                members = GetMembersIntern(type);
                if (members != null)
                {
                    // discard own members
                    return members;
                }
                members = ownMembers.ToArray();
                typeToMembersMap.Put(type, members.Length > 0 ? members : EMPTY_MEMBERS);
                return members.Length > 0 ? members : EMPTY_MEMBERS;
            }
        }

        protected void ScanForCallingProxyField(Type beanType, Type type, List<MemberInfo> targetMembers)
        {
            if (type == null || typeof(Object).Equals(type))
            {
                return;
            }
            ScanForCallingProxyField(beanType, type.BaseType, targetMembers);
            FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            for (int a = fields.Length; a-- > 0; )
            {
                FieldInfo field = fields[a];
                if (!field.FieldType.IsAssignableFrom(beanType))
                {
                    continue;
                }
                Self callingProxy = logInstanceCache.GetAnnotation(field);
                if (callingProxy == null)
                {
                    continue;
                }
                targetMembers.Add(field);
            }
            MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            for (int a = methods.Length; a-- > 0; )
            {
                MethodInfo method = methods[a];
                Self callingProxy = logInstanceCache.GetAnnotation(method);
                if (callingProxy == null)
                {
                    continue;
                }
                if (method.GetParameters().Length == 0)
                {
                    // Methods without parameter can not be invoked here
                    continue;
                }
                targetMembers.Add(method);
            }
        }
    }
}


text:
template<typename T>
struct ThingHelper
{
    constexpr T value() const;
};
template<>
constexpr void ThingHelper<void>::value() const {}
template<typename T>
constexpr T ThingHelper<T>::value() const { return {}; }

template<char C, typename TAIL = void>
struct Thing
{
    constexpr char head() const { return C; }
    template<typename Y = TAIL>
        constexpr Y tail() const
        {
            return ThingHelper<Y>().value();
        }
    typedef TAIL tail_t;
    constexpr bool more() const { return std::is_void<TAIL>::value; }
};

// PRINTY ===================================================

#include <cstdio>
template<typename T>
struct printyHelper2
{
    constexpr void continuee() const;
};
template<bool more> void printyHelper(char);
template<typename T, bool more = true>
void printy(T t)
{
    printyHelper<t.more()>(t.head());
    printyHelper2<typename T::tail_t>().continuee();
}

template<>
constexpr void printyHelper2<void>::continuee() const {}
template<typename T>
constexpr void printyHelper2<T>::continuee() const
{
    T t;
    printy<T, t.more()>(t);
}

template<>
void printyHelper<true>(char c)
{
    printf("%c", c);
}
template<>
void printyHelper<false>(char c)
{
    printf("%c\n", c);
}

int main()
{
    Thing<'a', Thing<'b', Thing<'c'>>> thing;
    printy(thing);
}


text:
@interface UIImage (Emboss)

+ (UIImage *)imageWithInteriorShadowAndString:(NSString *)string font:(UIFont *)font textColor:(UIColor *)textColor size:(CGSize)size;
+ (UIImage *)imageWithUpwardShadowAndImage:(UIImage *)image;

@end


text:
'use strict';

//Setting up route
angular.module('trustees').config(['$stateProvider',
	function($stateProvider) {
		// Trustees state routing
		$stateProvider.
		state('listTrustees', {
			url: '/trustees',
			templateUrl: 'modules/trustees/views/list-trustees.client.view.html'
		}).
		state('createTrustee', {
			url: '/trustees/create',
			templateUrl: 'modules/trustees/views/create-trustee.client.view.html'
		}).
		state('viewTrustee', {
			url: '/trustees/:trusteeId',
			templateUrl: 'modules/trustees/views/view-trustee.client.view.html'
		}).
		state('editTrustee', {
			url: '/trustees/:trusteeId/edit',
			templateUrl: 'modules/trustees/views/edit-trustee.client.view.html'
		});
	}
]);


text:
<?php

	if(!defined('BASEPATH'))
		exit("Access forbidden.");

	class Site extends MX_Controller {

		function __construct() {
			parent::__construct();
				$this->load->library('session');
				$this->load->model("User_model");
		}

		public function index() {
			 // TODO Fix this guy's security problem
			$username = $this->session->userdata('username');
			$model = new User_model();
			if($model->fill_model($username))
				$user = [
					'username' => $model->get_username(),
					'fullname' => $model->get_fullname(),
					'activated' => $model->is_activated(),
				];
			else
				$user = NULL;
			$this->load->helper('form');
			$view = $this->load->view("web/site/index", [
					'user' => $user,
				], TRUE);
			$this->load->view('web/layout/container_main', [
				'content' => $view,
			]);
			$this->session->set_flashdata('prev_dest', $this->router->fetch_module().'/'.
				$this->router->fetch_class().'/'.$this->router->fetch_method());
		}
	}


text:
module PyBind
  module PySequence
    include Enumerable

    def include?(value)
      value = value.to_python
      value = LibPython.PySequence_Contains(@pystruct, value)
      raise PyError.fetch if value == -1
      value == 1
    end

    def each
      return enum_for unless block_given?
      size.times do |i|
        yield self[i]
      end
      self
    end

    def to_a
      each.to_a
    end

    alias_method :to_ary, :to_a
  end
end


text:
#ifndef _h_hmm_types
#define _h_hmm_types

#ifdef SET_RCSID
static const char hmm_type_h[] = "$Id: hmm_type.h,v 1.1.10.5 2007/08/31 17:44:53 dahan Exp $";
#endif

#include <math.h>
#include "all_defs.h"

typedef ESR_BOOL  booldata; /* general boolean data */
typedef int  scodata;        /* for path scores */
typedef int  prdata;         /* for observation probabilities */
typedef signed char     wtdata;
typedef unsigned char   unidata;        /* for unimodal model storage */
typedef unidata  moddata;        /* for segmental model storage */
typedef double          covdata;        /* covariance data */
typedef unsigned char   featdata;       /* for preprocessor data */
typedef int             imeldata;       /* for preprocessor data */
#define IMELDATA_TO_FEATDATA(X)   ((featdata)(X))
typedef long  accdata;        /* for accumulate storage */
typedef unsigned char   phonedata;      /* for model contexts */
typedef phonedata conxdata;
typedef int             latdata;        /* for lattice identifiers */

#endif


text:
BuoyTask::BuoyTask(CameraModel* camModel)
{
    this->camModel = camModel;
}

void move(int d){

}

void rise(int d){

}

void rotate(int t){

}

void BuoyTask::execute(){
    std::string s = "raw";
    ImgData* data = dynamic_cast<ImgData*>(camModel->getStateData(s));
    HSVFilter green (0, 155, 0, 255, 0,255);
    HSVFilter red (0 ,155,0,255,0,255);
    //only look for 1 circle
    ShapeFilter sf (2, 1);
    float imgWidth = data->getImg().size().width;
    float imgHeight = data->getImg().size().height;

    //assuming the sub is in the correct position
    //first look for green, and then hit it
    //then look and hit red

    bool hitGreen = false;
    bool hitRed = false;

    int retreat = 0;

    bool done = false;

    while (!done){
        //filter for a color depending if the other color is hit or not
        if (!hitGreen)
            green.filter(data);
        else if (!hitRed)
            red.filter(data);
        else if (hitGreen && hitRed){
            done = true;
            continue;
        }

        //after hitting a color, move the sub back to look for the other one
        //TODO: CALIBRATE THIS STEP
        if (retreat > 0){
            move(-40);
            retreat -= 1;
            continue;
        }

        if (sf.filter(data)){
            cv::Point2f cent = sf.getCenter()[0];
            if (std::abs(cent.x - imgWidth/2) < imgWidth/5){
                //in the middle 20% of the screen horzontally
                if (std::abs(cent.y - imgHeight/2) < imgHeight/5){
                    //in the middle 20% vertically

                    //move straight and hit it
                    move(40);

                    //if the radius of the circle is huge, so the sub will hit it
                    if (sf.getRad()[0] > imgWidth*imgHeight/3){
                        if (!hitGreen)
                            hitGreen = true;
                        else
                            hitRed = true;

                        //return the sub back to its orginal position
                        move(0);
                        retreat = 30;
                    }
                }
                else{
                    rise (cent.y - imgHeight/2);
                }
            }else{
                rotate(atan2(0, cent.x-imgWidth/2) * 180 / M_PI);
            }
        }else{
            //CIRCLES NOT FOUND
            //ROTATE/MOVE SUB
            rotate(45);
        }
    }
}


text:
.left { float: left; }
.right { float: right; }


text:
<!DOCTYPE HTML>

<title>Tikslus Zoom examples</title>

<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/tiksluszoom.css" />
<link rel="stylesheet" href="css/github.css" />

Tikslus Zoom

Example 1: with default Parameters

HTML

Javascript

		$(document).ready(function(){
		$("#example1").tiksluszoom();
		});

Example 2: with hotspot/annotations

HTML

Javascript

		$(document).ready(function(){
		var annotations=new Array();
		annotations[0]={x:400,y:65,annotation:"Halogen mask. Range upto 500 meters"};
		annotations[1]={x:420,y:200,annotation:"High quality oil based Disk brakes" };
		$("#example2").tiksluszoom();
		});

Example 3: Custom Lens size

HTML

Javascript

		$(document).ready(function(){
		$("#example3").tiksluszoom({lensWidth:150,lensHeight:70});
		});

Example 4: Lens customization (opacity,background Color,Border Color)

HTML

Javascript

		$(document).ready(function(){
		$("#example4").tiksluszoom({lensWidth:150,lensHeight:70,lensOpacity:0.8,lensBorderColor:'#ff0000',lensBackgroundColor:'#ffaacc',lensBorder:3});
		});

Example 5: animation

HTML

Javascript

		$(document).ready(function(){
		$("#example5").tiksluszoom({zoomAnimation:true,zoomAnimationInterval:25});
		});

Example 6: Load Big image dynamically

HTML

<button id="button" >Change Big image Dynamically</button>

Javascript

		$(document).ready(function(){
		$("#example6").tiksluszoom();

		$("#button").click(function(e){
		e.preventDefault();
		var new_img="images/bike_blue_dynamic.jpg";
		  var tiksluszoom=$("#example6").data('tiksluszoom');
		tiksluszoom.loadBigImage(new_img);
		});

		});

<button id="button1" >Change Big image Dynamically</button>


text:
<?php

namespace Google\Service\GoogleAnalyticsAdmin;

class GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilter extends \Google\Model
{
  /**
   * @var bool
   */
  public $atAnyPointInTime;
  protected $betweenFilterType = GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterBetweenFilter::class;
  protected $betweenFilterDataType = '';
  /**
   * @var string
   */
  public $fieldName;
  /**
   * @var int
   */
  public $inAnyNDayPeriod;
  protected $inListFilterType = GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterInListFilter::class;
  protected $inListFilterDataType = '';
  protected $numericFilterType = GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterNumericFilter::class;
  protected $numericFilterDataType = '';
  protected $stringFilterType = GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterStringFilter::class;
  protected $stringFilterDataType = '';

  /**
   * @param bool
   */
  public function setAtAnyPointInTime($atAnyPointInTime)
  {
    $this->atAnyPointInTime = $atAnyPointInTime;
  }
  /**
   * @return bool
   */
  public function getAtAnyPointInTime()
  {
    return $this->atAnyPointInTime;
  }
  /**
   * @param GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterBetweenFilter
   */
  public function setBetweenFilter(GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterBetweenFilter $betweenFilter)
  {
    $this->betweenFilter = $betweenFilter;
  }
  /**
   * @return GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterBetweenFilter
   */
  public function getBetweenFilter()
  {
    return $this->betweenFilter;
  }
  /**
   * @param string
   */
  public function setFieldName($fieldName)
  {
    $this->fieldName = $fieldName;
  }
  /**
   * @return string
   */
  public function getFieldName()
  {
    return $this->fieldName;
  }
  /**
   * @param int
   */
  public function setInAnyNDayPeriod($inAnyNDayPeriod)
  {
    $this->inAnyNDayPeriod = $inAnyNDayPeriod;
  }
  /**
   * @return int
   */
  public function getInAnyNDayPeriod()
  {
    return $this->inAnyNDayPeriod;
  }
  /**
   * @param GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterInListFilter
   */
  public function setInListFilter(GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterInListFilter $inListFilter)
  {
    $this->inListFilter = $inListFilter;
  }
  /**
   * @return GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterInListFilter
   */
  public function getInListFilter()
  {
    return $this->inListFilter;
  }
  /**
   * @param GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterNumericFilter
   */
  public function setNumericFilter(GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterNumericFilter $numericFilter)
  {
    $this->numericFilter = $numericFilter;
  }
  /**
   * @return GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterNumericFilter
   */
  public function getNumericFilter()
  {
    return $this->numericFilter;
  }
  /**
   * @param GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterStringFilter
   */
  public function setStringFilter(GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterStringFilter $stringFilter)
  {
    $this->stringFilter = $stringFilter;
  }
  /**
   * @return GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilterStringFilter
   */
  public function getStringFilter()
  {
    return $this->stringFilter;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilter::class, 'Google_Service_GoogleAnalyticsAdmin_GoogleAnalyticsAdminV1alphaAudienceDimensionOrMetricFilter');


text:
package org.xlcloud.service.heat.parsers.resources.metadata.cfninit;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import org.xlcloud.service.heat.parsers.JSONParser;
import org.xlcloud.service.heat.template.resources.metadata.cfninit.ServiceConfiguration;
import org.xlcloud.service.heat.template.resources.metadata.cfninit.ServicesConfigurationBlock;

/**
 * Implementation of {@link JSONParser} for {@link ServicesConfigurationBlock}
 * @author Konrad Król, AMG.net
 */
public class ServicesConfigurationBlockParser implements JSONParser<ServicesConfigurationBlock> {

    /** {@inheritDoc} */
    @Override
    public ServicesConfigurationBlock fromJSON(JSONObject json) throws JSONException {
        ServicesConfigurationBlock servicesBlock = new ServicesConfigurationBlock();
        ServiceConfigurationParser serviceParser = new ServiceConfigurationParser();

        @SuppressWarnings( "unchecked" )
        Iterator<String> keysIterator = (Iterator<String>) json.keys();
        while (keysIterator.hasNext()) {
            String serviceKey = keysIterator.next();
            ServiceConfiguration serviceConfig = serviceParser.fromJSON(json.getJSONObject(serviceKey));
            serviceConfig.setName(serviceKey);

            servicesBlock.getServices().add(serviceConfig);
        }

        return servicesBlock;
    }

    /** {@inheritDoc} */
    @Override
    public JSONObject fromPojo(ServicesConfigurationBlock pojo) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        ServiceConfigurationParser serviceParser = new ServiceConfigurationParser();

        for(ServiceConfiguration serviceConfig : pojo.getServices()) {
            jsonObject.put(serviceConfig.getName(), serviceParser.fromPojo(serviceConfig));
        }

        return jsonObject;
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Interface ArrayAccess | AloFramework Config 1.1 API</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?973e37a8502921d56bc02bb55321f45b072b6f71">
	<link rel="stylesheet" href="resources/style.css?49f43d3208c5d7e33fa16d36107a345bf11cc00d">

				AloFramework Config 1.1 API

                <form id="search" class="navbar-form navbar-left" role="search">
                    <input type="hidden" name="cx" value="">
                    <input type="hidden" name="ie" value="UTF-8">

                        <input type="text" name="q" class="search-query form-control" placeholder="Search">

				</form>

						Namespace

Class

						Tree

								Deprecated

								Todo

Namespaces

							AloFramework

							Config

							PHP

Interfaces

ArrayAccess

JsonSerializable

Serializable

Interface ArrayAccess

Direct known implementers

			AloFramework\Config\AbstractConfig

		PHP Extension: Core

			Documented at php.net

Methods summary

				 public

			#
			offsetExists(  <var>$offset</var> )

				 public

			#
			offsetGet(  <var>$offset</var> )

				 public

			#
			offsetSet(  <var>$offset</var>,  <var>$value</var> )

				 public

			#
			offsetUnset(  <var>$offset</var> )

		AloFramework Config 1.1 API API documentation generated by ApiGen


text:
<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "bills".
 *
 * @property integer $id
 * @property integer $bill_type
 * @property string $country_code
 * @property integer $denomination
 * @property integer $enabled
 * @property integer $security
 */
class Bill extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'bills';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['bill_type', 'country_code', 'denomination', 'enabled', 'security'], 'required'],
            [['bill_type', 'denomination', 'enabled', 'security'], 'integer'],
            [['country_code'], 'string', 'max' => 3]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'bill_type' => 'Bill Type',
            'country_code' => 'Country Code',
            'denomination' => 'Denomination',
            'enabled' => 'Enabled',
            'security' => 'Security',
        ];
    }

    public static function create($billType, $data)
    {
        $countryCode = $data[0];
        $denomination = $data[1];
        $enabled = $data[2];
        $security = $data[3];

        if ($countryCode !== '' && $countryCode !== 'BAR') {
            $bill = new Bill();
            $bill->bill_type = $billType;
            $bill->country_code = $countryCode;
            $bill->denomination = $denomination;
            $bill->enabled = $enabled;
            $bill->security = $security;
            $bill->save();
            return $bill;
        }

        return null;
    }

    public static function truncate()
    {
        Yii::$app->db->createCommand()
            ->truncateTable(self::tableName())
            ->execute();
    }
}


text:
<?php
// REQUIRES: Composer, libyaml, PEAR/PECL
// Install Composer
exec('./install.sh');
?>


text:
namespace gcm {

// static
std::string FakeGCMClient::GenerateGCMRegistrationID(
    const std::vector<std::string>& sender_ids) {
  // GCMService normalizes the sender IDs by making them sorted.
  std::vector<std::string> normalized_sender_ids = sender_ids;
  std::sort(normalized_sender_ids.begin(), normalized_sender_ids.end());

  // Simulate the registration_id by concaternating all sender IDs.
  // Set registration_id to empty to denote an error if sender_ids contains a
  // hint.
  std::string registration_id;
  if (sender_ids.size() != 1 ||
      sender_ids[0].find("error") == std::string::npos) {
    for (size_t i = 0; i < normalized_sender_ids.size(); ++i) {
      if (i > 0)
        registration_id += ",";
      registration_id += normalized_sender_ids[i];
    }
  }
  return registration_id;
}

// static
std::string FakeGCMClient::GenerateInstanceIDToken(
    const std::string& authorized_entity, const std::string& scope) {
  if (authorized_entity.find("error") != std::string::npos)
    return "";
  std::string token(authorized_entity);
  token += ",";
  token += scope;
  return token;
}

FakeGCMClient::FakeGCMClient(
    const scoped_refptr<base::SequencedTaskRunner>& ui_thread,
    const scoped_refptr<base::SequencedTaskRunner>& io_thread)
    : delegate_(nullptr),
      started_(false),
      start_mode_(DELAYED_START),
      start_mode_overridding_(RESPECT_START_MODE),
      ui_thread_(ui_thread),
      io_thread_(io_thread) {}

FakeGCMClient::~FakeGCMClient() {
}

void FakeGCMClient::Initialize(
    const ChromeBuildInfo& chrome_build_info,
    const base::FilePath& store_path,
    bool remove_account_mappings_with_email_key,
    const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner,
    scoped_refptr<base::SequencedTaskRunner> io_task_runner,
    base::RepeatingCallback<void(
        mojo::PendingReceiver<network::mojom::ProxyResolvingSocketFactory>)>
        get_socket_factory_callback,
    const scoped_refptr<network::SharedURLLoaderFactory>& url_loader_factory,
    network::NetworkConnectionTracker* network_connection_tracker,
    std::unique_ptr<Encryptor> encryptor,
    Delegate* delegate) {
  product_category_for_subtypes_ =
      chrome_build_info.product_category_for_subtypes;
  delegate_ = delegate;
}

void FakeGCMClient::Start(StartMode start_mode) {
  DCHECK(io_thread_->RunsTasksInCurrentSequence());

  if (started_)
    return;

  if (start_mode == IMMEDIATE_START)
    start_mode_ = IMMEDIATE_START;
  if (start_mode_ == DELAYED_START ||
      start_mode_overridding_ == FORCE_TO_ALWAYS_DELAY_START_GCM) {
    return;
  }

  DoStart();
}

void FakeGCMClient::DoStart() {
  started_ = true;
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(&FakeGCMClient::Started, weak_ptr_factory_.GetWeakPtr()));
}

void FakeGCMClient::Stop() {
  DCHECK(io_thread_->RunsTasksInCurrentSequence());
  started_ = false;
  delegate_->OnDisconnected();
}

void FakeGCMClient::Register(
    scoped_refptr<RegistrationInfo> registration_info) {
  DCHECK(io_thread_->RunsTasksInCurrentSequence());

  std::string registration_id;

  GCMRegistrationInfo* gcm_registration_info =
      GCMRegistrationInfo::FromRegistrationInfo(registration_info.get());
  if (gcm_registration_info) {
    registration_id = GenerateGCMRegistrationID(
        gcm_registration_info->sender_ids);
  }

  InstanceIDTokenInfo* instance_id_token_info =
      InstanceIDTokenInfo::FromRegistrationInfo(registration_info.get());
  if (instance_id_token_info) {
    registration_id = GenerateInstanceIDToken(
        instance_id_token_info->authorized_entity,
        instance_id_token_info->scope);
  }

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::BindOnce(&FakeGCMClient::RegisterFinished,
                                weak_ptr_factory_.GetWeakPtr(),
                                std::move(registration_info), registration_id));
}

bool FakeGCMClient::ValidateRegistration(
    scoped_refptr<RegistrationInfo> registration_info,
    const std::string& registration_id) {
  return true;
}

void FakeGCMClient::Unregister(
    scoped_refptr<RegistrationInfo> registration_info) {
  DCHECK(io_thread_->RunsTasksInCurrentSequence());

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(&FakeGCMClient::UnregisterFinished,
                     weak_ptr_factory_.GetWeakPtr(), registration_info));
}

void FakeGCMClient::Send(const std::string& app_id,
                         const std::string& receiver_id,
                         const OutgoingMessage& message) {
  DCHECK(io_thread_->RunsTasksInCurrentSequence());

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(&FakeGCMClient::SendFinished,
                     weak_ptr_factory_.GetWeakPtr(), app_id, message));
}

void FakeGCMClient::RecordDecryptionFailure(const std::string& app_id,
                                            GCMDecryptionResult result) {
  recorder_.RecordDecryptionFailure(app_id, result);
}

void FakeGCMClient::SetRecording(bool recording) {
  recorder_.set_is_recording(recording);
}

void FakeGCMClient::ClearActivityLogs() {
  recorder_.Clear();
}

GCMClient::GCMStatistics FakeGCMClient::GetStatistics() const {
  GCMClient::GCMStatistics statistics;
  statistics.is_recording = recorder_.is_recording();

  recorder_.CollectActivities(&statistics.recorded_activities);
  return statistics;
}

void FakeGCMClient::SetAccountTokens(
    const std::vector<AccountTokenInfo>& account_tokens) {
}

void FakeGCMClient::UpdateAccountMapping(
    const AccountMapping& account_mapping) {
}

void FakeGCMClient::RemoveAccountMapping(const CoreAccountId& account_id) {}

void FakeGCMClient::SetLastTokenFetchTime(const base::Time& time) {
}

void FakeGCMClient::UpdateHeartbeatTimer(
    std::unique_ptr<base::RetainingOneShotTimer> timer) {}

void FakeGCMClient::AddInstanceIDData(const std::string& app_id,
                                      const std::string& instance_id,
                                      const std::string& extra_data) {
  instance_id_data_[app_id] = make_pair(instance_id, extra_data);
}

void FakeGCMClient::RemoveInstanceIDData(const std::string& app_id) {
  instance_id_data_.erase(app_id);
}

void FakeGCMClient::GetInstanceIDData(const std::string& app_id,
                                      std::string* instance_id,
                                      std::string* extra_data) {
  auto iter = instance_id_data_.find(app_id);
  if (iter == instance_id_data_.end()) {
    instance_id->clear();
    extra_data->clear();
    return;
  }

  *instance_id = iter->second.first;
  *extra_data = iter->second.second;
}

void FakeGCMClient::AddHeartbeatInterval(const std::string& scope,
                                         int interval_ms) {
}

void FakeGCMClient::RemoveHeartbeatInterval(const std::string& scope) {
}

void FakeGCMClient::PerformDelayedStart() {
  DCHECK(ui_thread_->RunsTasksInCurrentSequence());

  io_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FakeGCMClient::DoStart, weak_ptr_factory_.GetWeakPtr()));
}

void FakeGCMClient::ReceiveMessage(const std::string& app_id,
                                   const IncomingMessage& message) {
  DCHECK(ui_thread_->RunsTasksInCurrentSequence());

  io_thread_->PostTask(
      FROM_HERE,
      base::BindOnce(&FakeGCMClient::MessageReceived,
                     weak_ptr_factory_.GetWeakPtr(), app_id, message));
}

void FakeGCMClient::DeleteMessages(const std::string& app_id) {
  DCHECK(ui_thread_->RunsTasksInCurrentSequence());

  io_thread_->PostTask(FROM_HERE,
                       base::BindOnce(&FakeGCMClient::MessagesDeleted,
                                      weak_ptr_factory_.GetWeakPtr(), app_id));
}

void FakeGCMClient::Started() {
  delegate_->OnGCMReady(std::vector<AccountMapping>(), base::Time());
  delegate_->OnConnected(net::IPEndPoint());
}

void FakeGCMClient::RegisterFinished(
    scoped_refptr<RegistrationInfo> registration_info,
    const std::string& registrion_id) {
  delegate_->OnRegisterFinished(std::move(registration_info), registrion_id,
                                registrion_id.empty() ? SERVER_ERROR : SUCCESS);
}

void FakeGCMClient::UnregisterFinished(
    scoped_refptr<RegistrationInfo> registration_info) {
  delegate_->OnUnregisterFinished(std::move(registration_info),
                                  GCMClient::SUCCESS);
}

void FakeGCMClient::SendFinished(const std::string& app_id,
                                 const OutgoingMessage& message) {
  delegate_->OnSendFinished(app_id, message.id, SUCCESS);

  // Simulate send error if message id contains a hint.
  if (message.id.find("error") != std::string::npos) {
    SendErrorDetails send_error_details;
    send_error_details.message_id = message.id;
    send_error_details.result = NETWORK_ERROR;
    send_error_details.additional_data = message.data;
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&FakeGCMClient::MessageSendError,
                       weak_ptr_factory_.GetWeakPtr(), app_id,
                       send_error_details),
        base::Milliseconds(200));
  } else if(message.id.find("ack") != std::string::npos) {
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&FakeGCMClient::SendAcknowledgement,
                       weak_ptr_factory_.GetWeakPtr(), app_id, message.id),
        base::Milliseconds(200));
  }
}

void FakeGCMClient::MessageReceived(const std::string& app_id,
                                    const IncomingMessage& message) {
  if (delegate_)
    delegate_->OnMessageReceived(app_id, message);
}

void FakeGCMClient::MessagesDeleted(const std::string& app_id) {
  if (delegate_)
    delegate_->OnMessagesDeleted(app_id);
}

void FakeGCMClient::MessageSendError(
    const std::string& app_id,
    const GCMClient::SendErrorDetails& send_error_details) {
  if (delegate_)
    delegate_->OnMessageSendError(app_id, send_error_details);
}

void FakeGCMClient::SendAcknowledgement(const std::string& app_id,
                                        const std::string& message_id) {
  if (delegate_)
    delegate_->OnSendAcknowledged(app_id, message_id);
}

}  // namespace gcm


text:
states_array = ["Alaska", "Alabama", "Arkansas", "Arizona", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Iowa", "Idaho", "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", "North Carolina", "North Dakota", "Nebraska", "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", "Vermont", "Washington", "Wisconsin", "West Virginia", "Wyoming"]

states_array.each do |state|
  State.create(name: state)
end

100.times do
  user = User.new
  user.name = Faker::Name.name
  user.email = Faker::Internet.email
  user.save
end

100.times do
  concern = Concern.new
  concern.title = Faker::Name.title
  concern.description = Faker::Company.catch_phrase
  concern.state_id = rand(50)
  concern.creator_id = rand(100) + 1
  concern.save
end

1000.times do |i|
  uid = rand(100) + 1
  cid = rand(100) + 1
  Vote.create(voter_id: uid, concern_id: cid, upvote: true)
end

1000.times do |i|
  uid = rand(100) + 1
  cid = rand(100) + 1
  Vote.create(voter_id: uid, concern_id: cid, upvote: false)
end


text:
/**
 * https://github.com/gruntjs/grunt-contrib-csslint
 *
 * Linting of CSS files. Adjust .csslintrc to specify tests.
 */

'use strict';
module.exports = {

  options: {
    csslintrc: '.csslintrc'
  },
  strict: {
    options: {
      import: 2
    },
    //all css-files, including subfolders
    src: ['<%= package.basedir %>/assets/dist/css/**/*.css']
  },
  lax: {
    options: {
      import: false
    },
    //all css-files, including subfolders
    src: ['<%= package.basedir %>/assets/dist/css/**/*.css']
  }
};


text:
from nanpy import DHT

# http://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor
# DHT sensor connected to digital pin 10
dhts = [
    DHT(6, DHT.DHT11),
    DHT(7, DHT.DHT11),
    DHT(8, DHT.DHT11)
]

for i, dht in enumerate(dhts):
    print("DHT %d" % i)
    print("Temperature is %.2f degrees Celcius" % dht.readTemperature(False))
    print("Temperature is %.2f degrees Fahrenheit" % dht.readTemperature(True))
    print("Humidity is %.2f %%" % dht.readHumidity())


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit5a00a0fb8e62e89cd15326a8339dbbfb::getLoader();


text:
var expect = require('chai').expect;
const polyglot = require('../lib').default;
describe('Translate multiple MESH terms (PubMed -> *)', ()=> {

	it('translate `"term1 term2"[Mesh]` -> PM `"term1 term2"[Mesh]`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'PubMed abbreviation')).to.equal('"term1 term2"[Mesh]');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'PubMed abbreviation')).to.equal('"term1 and term2"[Mesh]');
	});

	it('translate `"term1 term2"[Mesh]` -> OV `exp term1 term2/`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'Ovid MEDLINE')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'Ovid MEDLINE')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[Mesh]` -> CO `[mh "term1 term2"]`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'Cochrane Library')).to.equal('[mh "term1 term2"]');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'Cochrane Library')).to.equal('[mh "term1 and term2"]');
	});

	it('translate `"term1 term2"[Mesh]` -> EM `"term1 term2"/exp`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'Embase (Elsevier)')).to.equal('"term1 term2"/exp');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'Embase (Elsevier)')).to.equal('"term1 and term2"/exp');
	});

	it('translate `"term1 term2"[Mesh]` -> CI `(MH "term1 term2+")`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 term2+")');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 and term2+")');
	});

	it('translate `"term1 term2"[Mesh]` -> PY `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'PsycInfo (Ovid)')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'PsycInfo (Ovid)')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[Mesh]` -> SC `INDEXTERMS(term1 term2)`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 term2")');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 and term2")');
	});

	it('translate `"term1 term2"[Mesh]` -> WS `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[Mesh]', 'Web of Science')).to.equal('"term1 term2"');
		expect(polyglot.translate('"term1 and term2"[Mesh]', 'Web of Science')).to.equal('"term1 and term2"');
	});

});

describe('Translate multiple MESH terms (PubMed (short) -> *)', ()=> {

	it('translate `"term1 term2"[mh]` -> PM `"term1 term2"[Mesh]`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'PubMed abbreviation')).to.equal('"term1 term2"[Mesh]');
		expect(polyglot.translate('"term1 and term2"[mh]', 'PubMed abbreviation')).to.equal('"term1 and term2"[Mesh]');
	});

	it('translate `"term1 term2"[mh]` -> OV `exp term1 term2/`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'Ovid MEDLINE')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[mh]', 'Ovid MEDLINE')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[mh]` -> CO `[mh "term1 term2"]`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'Cochrane Library')).to.equal('[mh "term1 term2"]');
		expect(polyglot.translate('"term1 and term2"[mh]', 'Cochrane Library')).to.equal('[mh "term1 and term2"]');
	});

	it('translate `"term1 term2"[mh]` -> EM `"term1 term2"/exp`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'Embase (Elsevier)')).to.equal('"term1 term2"/exp');
		expect(polyglot.translate('"term1 and term2"[mh]', 'Embase (Elsevier)')).to.equal('"term1 and term2"/exp');
	});

	it('translate `"term1 term2"[mh]` -> CI `(MH "term1 term2+")`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 term2+")');
		expect(polyglot.translate('"term1 and term2"[mh]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 and term2+")');
	});

	it('translate `"term1 term2"[mh]` -> PY `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'PsycInfo (Ovid)')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[mh]', 'PsycInfo (Ovid)')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[mh]` -> SC `INDEXTERMS(term1 term2)`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 term2")');
		expect(polyglot.translate('"term1 and term2"[mh]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 and term2")');
	});

	it('translate `"term1 term2"[mh]` -> WS `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[mh]', 'Web of Science')).to.equal('"term1 term2"');
		expect(polyglot.translate('"term1 and term2"[mh]', 'Web of Science')).to.equal('"term1 and term2"');
	});

});

describe('Translate multiple MESH terms (PubMed (long) -> *)', ()=> {

	it('translate `"term1 term2"[MeSH Terms]` -> PM `"term1 term2"[Mesh]`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'PubMed abbreviation')).to.equal('"term1 term2"[Mesh]');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'PubMed abbreviation')).to.equal('"term1 and term2"[Mesh]');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> OV `exp term1 term2/`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'Ovid MEDLINE')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'Ovid MEDLINE')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> CO `[mh "term1 term2"]`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'Cochrane Library')).to.equal('[mh "term1 term2"]');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'Cochrane Library')).to.equal('[mh "term1 and term2"]');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> EM `"term1 term2"/exp`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'Embase (Elsevier)')).to.equal('"term1 term2"/exp');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'Embase (Elsevier)')).to.equal('"term1 and term2"/exp');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> CI `(MH "term1 term2+")`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 term2+")');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'CINAHL (Ebsco)')).to.equal('(MH "term1 and term2+")');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> PY `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'PsycInfo (Ovid)')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'PsycInfo (Ovid)')).to.equal('exp "term1 and term2"/');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> SC `INDEXTERMS(term1 term2)`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 term2")');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 and term2")');
	});

	it('translate `"term1 term2"[MeSH Terms]` -> WS `"term1 term2"`', ()=> {
		expect(polyglot.translate('"term1 term2"[MeSH Terms]', 'Web of Science')).to.equal('"term1 term2"');
		expect(polyglot.translate('"term1 and term2"[MeSH Terms]', 'Web of Science')).to.equal('"term1 and term2"');
	});

});

describe('Translate multiple MESH terms (Ovid MEDLINE -> *)', ()=> {

	it('translate `exp term1 term2/` -> PM `"term1 term2"[Mesh]`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'PubMed abbreviation')).to.equal('"term1 term2"[Mesh]');
		expect(polyglot.translate('exp term1 and term2/', 'PubMed abbreviation')).to.equal('"term1 and term2"[Mesh]');
		expect(polyglot.translate('exp "term1 and term2"/', 'PubMed abbreviation')).to.equal('"term1 and term2"[Mesh]');
	});

	it('translate `exp term1 term2/` -> OV `exp term1 term2/`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'Ovid MEDLINE')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('exp term1 and term2/', 'Ovid MEDLINE')).to.equal('exp "term1 and term2"/');
		expect(polyglot.translate('exp "term1 and term2"/', 'Ovid MEDLINE')).to.equal('exp "term1 and term2"/');
	});

	it('translate `exp term1 term2/` -> CO `[mh "term1 term2"]`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'Cochrane Library')).to.equal('[mh "term1 term2"]');
		expect(polyglot.translate('exp term1 and term2/', 'Cochrane Library')).to.equal('[mh "term1 and term2"]');
		expect(polyglot.translate('exp "term1 and term2"/', 'Cochrane Library')).to.equal('[mh "term1 and term2"]');
	});

	it('translate `exp term1 term2/` -> EM `"term1 term2"/exp`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'Embase (Elsevier)')).to.equal('"term1 term2"/exp');
		expect(polyglot.translate('exp term1 and term2/', 'Embase (Elsevier)')).to.equal('"term1 and term2"/exp');
		expect(polyglot.translate('exp "term1 and term2"/', 'Embase (Elsevier)')).to.equal('"term1 and term2"/exp');
	});

	it('translate `exp term1 term2/` -> CI `(MH "term1 term2+")`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'CINAHL (Ebsco)')).to.equal('(MH "term1 term2+")');
		expect(polyglot.translate('exp term1 and term2/', 'CINAHL (Ebsco)')).to.equal('(MH "term1 and term2+")');
		expect(polyglot.translate('exp "term1 and term2"/', 'CINAHL (Ebsco)')).to.equal('(MH "term1 and term2+")');
	});

	it('translate `exp term1 term2/` -> PY `"term1 term2"`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'PsycInfo (Ovid)')).to.equal('exp "term1 term2"/');
		expect(polyglot.translate('exp term1 and term2/', 'PsycInfo (Ovid)')).to.equal('exp "term1 and term2"/');
		expect(polyglot.translate('exp "term1 and term2"/', 'PsycInfo (Ovid)')).to.equal('exp "term1 and term2"/');
	});

	it('translate `exp term1 term2/` -> SC `INDEXTERMS(term1 term2)`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 term2")');
		expect(polyglot.translate('exp term1 and term2/', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 and term2")');
		expect(polyglot.translate('exp "term1 and term2"/', 'Scopus (advanced search)')).to.equal('INDEXTERMS("term1 and term2")');
	});

	it('translate `exp term1 term2/` -> WS `"term1 term2"`', ()=> {
		expect(polyglot.translate('exp term1 term2/', 'Web of Science')).to.equal('"term1 term2"');
		expect(polyglot.translate('exp term1 and term2/', 'Web of Science')).to.equal('"term1 and term2"');
		expect(polyglot.translate('exp "term1 and term2"/', 'Web of Science')).to.equal('"term1 and term2"');
	});

});


text:
import java.util.*;

import com.jalgoarena.type.ListNode;

public class Solution {
    /**
     * @param linkedList Linked List where we need to remove duplicates
     * @return  Linked List with removed duplicates
     */
    public ListNode removeDuplicates(ListNode node) {
        ListNode root = node;
        HashSet<Integer> set = new HashSet<>();
        ListNode previous = null;

        while (node != null) {
            if (set.contains(node.value)) {
                previous.next = node.next;
            } else {
                set.add(node.value);
                previous = node;
            }
            node = node.next;
        }

        return root;
    }
}


text:
	{{#tags}}
	<form method="POST" class="tagForm" action="/" name="{{tag}}Form">
		<input type="hidden" name="nTag" value="{{tag}}">
		<input type="hidden" name="_csrf" value="{{token}}" />
		<input type="hidden" name="type" value="addTag" />
		{{tag}}
	</form>
	{{/tags}}


text:
"""This file is part of the Scribee project.
"""

__author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>'
__copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi'
__version__ = '0.0.1'

import os

import settings

class Entity(object):
    """An Entity is a generic language-agnostic object.
    """
    class Types:
        Generic     = ""
        Namespace   = "namespace"
        Constant    = "const"
        Variable    = "var"
        Function    = "func"
        Class       = "class"

    class DuplicateEntityException(Exception):
        pass

    entities = []

    def __init__(self, name="", type="", brief="", details="", sources=[], parent=None, **kwargs):
        self.name = name
        self.type = type
        self.brief = brief
        self.details = details
        self.sources = sources
        self.parent = parent
        self.__dict__.update(kwargs)

        uid = self.uid()

        for e in Entity.entities:
            if e.uid() == uid:
                raise DuplicateEntityException

        Entity.entities.append(self)

    def __repr__(self):
        string = "Entity: <%s>" % self.uid()
        if self.brief != "":
            string += "\n-- brief: %s" % self.brief
        if self.details != "":
            string += "\n-- details: %s" % self.details
        return string

    def __str__(self):
        return self.__repr__()

    def uid(self):
        """Returns the entity's UID.
        """
        return Entity.get_uid(self.name, self.type, self.parent)

    def is_valid(self):
        return self.type.lower() != ""

    def ancestors(self):
        if isinstance(self.parent, Entity):
            return self.parent.ancestors() + [self.parent]
        return []

    def children(self, types=None):
        if not isinstance(types, (list, tuple)):
            types = (types)

        return [e for e in Entity.entities if e.parent == self and (not types or e.type in types)]

    @classmethod
    def get_uid(cls, name, type, parent):
        uid = "%s" % name
        if type:
            uid = "%s_%s" % (type, name)
            if parent:
                uid = "%s__%s" % (parent.uid(), uid)
        return uid

    @classmethod
    def nearest(cls, name, type=None, parent=None):
        # TODO: allow to search only with name and parent (without type).
        ref_uid = cls.get_uid(name, type, parent)
        ref_length = len(ref_uid)
        remaining_chars = -1
        nearest_entity = None

        for entity in Entity.entities:
            uid = entity.uid()
            if uid.endswith(ref_uid):
                rc = len(uid) - ref_length
                if remaining_chars < 0 or rc < remaining_chars:
                    remaining_chars = rc
                    nearest_entity = entity
                if rc == 0:
                    break

        return nearest_entity

    @classmethod
    def get_or_create(cls, name, type, sources=[], parent=None):
        if not name and not type:
            return None

        nearest = cls.nearest(name, type, parent)

        if not nearest:
            nearest = Entity(name, type, sources=sources, parent=parent)

        else:
            for s in sources:
                if s not in nearest.sources:
                    nearest.sources.append(s)

        return nearest

class DocBlock(object):
    """A DocBlock is a generic piece of documentation for one or more entities.
    """
    blocks = []

    def __init__(self, content="", source="", parent=None):
        all_filters = getattr(settings, "FILTERS", {})
        root, ext = os.path.splitext(source)

        self.source = source
        self.parent = parent
        self._original = content
        self.filtered = content.strip()

        if all_filters.has_key(ext):
            for filter_list in all_filters[ext]:
                if isinstance(filter_list, dict):
                    filter_list = filters_list.values()
                elif not isinstance(filter_list, (list, tuple)):
                    filter_list = (filter_list,)
                for f in filter_list:
                    f.filter(self)

        if isinstance(parent, Entity):
            self.parent.details = self.filtered
            try:
                self.parent.brief = [l for l in self.filtered.splitlines() if l][0]
            except IndexError:
                pass

        # FIXME: does it work?
        if self not in self.__class__.blocks:
            self.__class__.blocks.append(self)

    def __repr__(self):
        string = "DocBlock:"
        string += "\n-- content: %s" % self.filtered
        if self.parent:
            string += "\n-- parent: %s" % self.parent.uid()
        return string

    def __str__(self):
        return self.__repr__()

    def is_valid(self):
        return (self._original or self.filtered)

    @classmethod
    def get_or_create(cls, content, source=None, parent=None):
        for block in cls.blocks:
            if block._original == content:
                if source and block.source != source:
                    continue
                if parent and block.parent != parent:
                    continue
                return block

        return DocBlock(content, source=source, parent=parent)


text:
__sal_begin

namespace logger {

std::unique_ptr<worker_t> worker_t::default_{};

namespace {

thread_local event_t this_thread_event_{},
  *this_thread_event_ptr_ = &this_thread_event_;

inline event_t *this_thread_event_alloc ()
{
  auto result = this_thread_event_ptr_;
  this_thread_event_ptr_ = nullptr;
  return result;
}

inline void this_thread_event_release (event_t *event)
{
  // note: this function is called from unique_ptr custom deleter that's not
  // supposed to throw exception but we have no choice, let's rather fail
  // quickly than allow to mess with contract
  sal_assert(&this_thread_event_ == event);
  this_thread_event_ptr_ = event;
}

void write_and_release (event_t *event)
{
  // here it's ok to release event and still keep using it
  this_thread_event_release(event);

  try
  {
    event->sink->sink_event_write(*event);
  }
  catch (...)
  {
  }
}

} // namespace

event_ptr worker_t::make_event (const channel_type &channel)
{
  event_ptr event(sal_check_ptr(this_thread_event_alloc()), &write_and_release);

  try
  {
    event->message.reset();
    event->sink = channel.impl_.sink.get();
    event->sink->sink_event_init(*event, channel.name());
  }
  catch (...)
  {
    this_thread_event_release(event.release());
  }

  return event;
}

} // namespace logger

__sal_end


text:
package p2p

import (
	"errors"
	"fmt"
	"net"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"github.com/astaxie/beego/logs"
	"github.com/btcboost/copernicus/blockchain"
	"github.com/btcboost/copernicus/conf"
	"github.com/btcboost/copernicus/database"
	"github.com/btcboost/copernicus/net/conn"
	"github.com/btcboost/copernicus/net/msg"
	"github.com/btcboost/copernicus/net/network"
	"github.com/btcboost/copernicus/net/protocol"
)

const (
	DefaultServices         = protocol.SFNodeNetworkAsFullNode | protocol.SFNodeBloomFilter
	DefaultRequiredServices = protocol.SFNodeNetworkAsFullNode
)

type PeerManager struct {
	bytesReceived uint64
	bytesSend     uint64
	started       int32
	shutdown      int32
	shutdownSched int32

	chainParams          *msg.BitcoinParams
	netAddressManager    *network.NetAddressManager
	connectManager       *conn.ConnectManager
	BlockManager         *BlockManager
	modifyRebroadcastInv chan interface{}
	newPeers             chan *ServerPeer
	banPeers             chan *ServerPeer
	donePeers            chan *ServerPeer
	query                chan interface{}
	relayInventory       chan RelayMessage
	broadcast            chan BroadcastMessage
	peerHeightsUpdate    chan UpdatePeerHeightsMessage
	waitGroup            sync.WaitGroup
	quit                 chan struct{}

	// txMemPool    *mempool.TxPool
	nat network.NATInterface
	//  storage      boltdb.DBBase
	timeSource   *blockchain.MedianTime
	servicesFlag protocol.ServiceFlag

	// txIndex   *indexers.TxIndex
	// addrIndex *indexers.AddrIndex
}

type getOutboundGroup struct {
	key   string
	reply chan int
}

func NewPeerManager(listenAddrs []string, db database.DBWrapper, bitcoinParam *msg.BitcoinParams) (*PeerManager, error) {
	services := DefaultServices
	if conf.AppConf.NoPeerBloomFilters {
		services &^= protocol.SFNodeBloomFilter
	}
	netAddressManager := network.NewNetAddressManager(conf.AppConf.DataDir, conf.AppLookup)
	var listeners []net.Listener
	var natListener network.NATInterface
	peerManager := PeerManager{
		chainParams:          bitcoinParam,
		netAddressManager:    netAddressManager,
		newPeers:             make(chan *ServerPeer, conf.AppConf.MaxPeers),
		donePeers:            make(chan *ServerPeer, conf.AppConf.MaxPeers),
		banPeers:             make(chan *ServerPeer, conf.AppConf.MaxPeers),
		query:                make(chan interface{}),
		relayInventory:       make(chan RelayMessage, conf.AppConf.MaxPeers),
		broadcast:            make(chan BroadcastMessage, conf.AppConf.MaxPeers),
		quit:                 make(chan struct{}),
		modifyRebroadcastInv: make(chan interface{}),
		peerHeightsUpdate:    make(chan UpdatePeerHeightsMessage),
		nat:                  natListener,
		// storage:              db, todo:
		timeSource:   blockchain.NewMedianTime(),
		servicesFlag: protocol.ServiceFlag(services),
	}

	connectListener := conn.ConnectListener{
		Listeners:     listeners,
		Dial:          conf.AppDial,
		GetNewAddress: peerManager.newAddressFunc,
	}

	connectManager, err := conn.NewConnectManager(&connectListener)
	if err != nil {
		return nil, err
	}
	peerManager.connectManager = connectManager
	return &peerManager, nil

}
func (peerManager *PeerManager) OutboundGroupCount(key string) int {
	replyChan := make(chan int)
	peerManager.query <- getOutboundGroup{key: key, reply: replyChan}
	return <-replyChan
}

func (peerManager *PeerManager) newAddressFunc() (net.Addr, error) {
	for tries := 0; tries < 100; tries++ {
		address := peerManager.netAddressManager.GetAddress()

		logs.Debug(" newAddressFunc ")
		if address == nil {
			logs.Debug(" newAddressFunc address is nil")
			break
		}
		key := peerManager.netAddressManager.GetAddress().NetAddress.NetAddressKey()
		if peerManager.OutboundGroupCount(key) != 0 {
			logs.Debug("peerManager OutboundGroupCount :%s", key)
			continue
		}

		// if tries < 30 && time.Since(address.LastAttempt) < 10*time.Minute {
		// 	continue
		// }
		// port := fmt.Sprintf("%d", address.NetAddress.Port)
		// if tries < 50 && port != msg.ActiveNetParams.DefaultPort {
		// 	continue
		// }
		addressString := peerManager.netAddressManager.GetAddress().NetAddress.NetAddressKey()
		logs.Debug("get address :%s", addressString)
		return addrStringToNetAddr(addressString)

	}
	return nil, errors.New("no valid conn address")
}

func addrStringToNetAddr(addr string) (net.Addr, error) {
	host, strPort, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}

	port, err := strconv.Atoi(strPort)
	if err != nil {
		return nil, err
	}

	// Skip if host is already an IP address.
	if ip := net.ParseIP(host); ip != nil {
		return &net.TCPAddr{
			IP:   ip,
			Port: port,
		}, nil
	}

	// Tor addresses cannot be resolved to an IP, so just return an onion
	// address instead.
	// if strings.HasSuffix(host, ".onion") {
	// 	if cfg.NoOnion {
	// 		return nil, errors.New("tor has been disabled")
	// 	}
	//
	// 	return &onionAddr{addr: addr}, nil
	// }
	//
	// Attempt to look up an IP address associated with the parsed host.
	ips, err := conf.AppLookup(host)
	if err != nil {
		return nil, err
	}
	if len(ips) == 0 {
		return nil, fmt.Errorf("no addresses found for %s", host)
	}

	return &net.TCPAddr{
		IP:   ips[0],
		Port: port,
	}, nil
}

func (peerManager *PeerManager) BanPeer(serverPeer *ServerPeer) {
	peerManager.banPeers <- serverPeer
}

func (peerManager *PeerManager) AddPeer(serverPeer *ServerPeer) {
	peerManager.newPeers <- serverPeer
}

func (peerManager *PeerManager) Stop() error {
	if atomic.AddInt32(&peerManager.shutdown, 1) != 1 {
		logs.Info("PeerManager is already in the process of shutting down")
		return nil
	}
	logs.Info("PeerManager shutting down")
	close(peerManager.quit)
	return nil
}
func (peerManager *PeerManager) WaitForShutdown() {
	peerManager.waitGroup.Wait()
}

func (peerManager *PeerManager) Start() {
	if atomic.AddInt32(&peerManager.started, 1) != 1 {
		return
	}
	logs.Trace("starting server")
	peerManager.waitGroup.Add(1)
	go peerManager.peerHandler()
	if peerManager.nat != nil {
		peerManager.waitGroup.Add(1)
		go peerManager.upnpUpdateThread()
	}
	fmt.Println("PeerManager Start")

}

func (peerManager *PeerManager) peerHandler() {
	peerManager.netAddressManager.Start()
	peerManager.BlockManager.Start()
	logs.Trace("Starting p2p handler")
	peerState := &PeerState{
		inboundPeers:    make(map[int32]*ServerPeer),
		persistentPeers: make(map[int32]*ServerPeer),
		outboundPeers:   make(map[int32]*ServerPeer),
		banned:          make(map[string]time.Time),
		outboundGroups:  make(map[string]int),
	}
	if !conf.AppConf.DisableDNSSeed {
		conn.SeedFromDNS(msg.ActiveNetParams, DefaultRequiredServices, conf.AppLookup, func(addresses []*network.PeerAddress) {
			logs.Warn(addresses[0].IP.String())
			peerManager.netAddressManager.AddPeerAddresses(addresses, addresses[0])
		})

	}
	go peerManager.connectManager.Start()

out:
	for {
		select {
		case peer := <-peerManager.newPeers:
			peerManager.handleAddPeerMsg(peerState, peer)
		case <-peerManager.quit:
			peerState.forAllPeers(func(serverPeer *ServerPeer) {
				logs.Trace("Shutdown p2p %s", serverPeer)
				serverPeer.Disconnect()
			})
			break out
		}

	}
	peerManager.connectManager.Stop()
	peerManager.BlockManager.Stop()
	peerManager.netAddressManager.Stop()

}

func (peerManager *PeerManager) handleAddPeerMsg(peerState *PeerState, serverPeer *ServerPeer) bool {
	if serverPeer == nil {
		return false
	}

	// Ignore new peers if we're shutting down.
	if atomic.LoadInt32(&peerManager.shutdown) != 0 {
		logs.Info("New p2p %s ignored - server is shutting down", serverPeer)
		serverPeer.Disconnect()
		return false
	}

	// Disconnect banned peers.
	host, _, err := net.SplitHostPort(serverPeer.AddressString)
	if err != nil {
		logs.Debug("can't split hostport %v", err)
		serverPeer.Disconnect()
		return false
	}
	if banEnd, ok := peerState.banned[host]; ok {
		if time.Now().Before(banEnd) {
			logs.Debug("Peer %s is banned for another %s - disconnecting",
				host, banEnd.String())
			serverPeer.Disconnect()
			return false
		}

		logs.Info("Peer %s is no longer banned", host)
		delete(peerState.banned, host)
	}

	// TODO: Check for max peers from a single IP.

	// Limit max number of total peers.
	if peerState.Count() >= conf.AppConf.MaxPeers {
		logs.Info("Max peers reached [%d] - disconnecting p2p %s",
			conf.AppConf.MaxPeers, serverPeer)
		serverPeer.Disconnect()
		// TODO: how to handle permanent peers here?
		// they should be rescheduled.
		return false
	}

	// Add the new p2p and start it.
	logs.Debug("New p2p %s", serverPeer)
	if serverPeer.Inbound {
		peerState.inboundPeers[serverPeer.ID] = serverPeer
	} else {
		peerState.outboundGroups[serverPeer.PeerAddress.GroupKey()]++
		if serverPeer.persistent {
			peerState.persistentPeers[serverPeer.ID] = serverPeer
		} else {
			peerState.outboundPeers[serverPeer.ID] = serverPeer
		}
	}

	return true
}
func (peerManager *PeerManager) upnpUpdateThread() {

}

// func (s *PeerManager) inboundPeerConnected(conn net.Conn) {
// 	sp := NewServerPeer(s, false)
// 	sp.Peer = p2p.NewInboundPeer(InitPe(sp))
// 	sp.AssociateConnection(conn)
// 	go s.peerDoneHandler(sp)
// }


text:
package org.optaplanner.core.impl.heuristic.selector.move.generic.chained;

import java.util.Objects;

import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.heuristic.selector.move.generic.ChangeMove;
import org.optaplanner.core.impl.score.director.ScoreDirector;

/**
 * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
 */
public class ChainedChangeMove<Solution_> extends ChangeMove<Solution_> {

    protected final SingletonInverseVariableSupply inverseVariableSupply;

    public ChainedChangeMove(Object entity, GenuineVariableDescriptor<Solution_> variableDescriptor,
            SingletonInverseVariableSupply inverseVariableSupply, Object toPlanningValue) {
        super(entity, variableDescriptor, toPlanningValue);
        this.inverseVariableSupply = inverseVariableSupply;
    }

    // ************************************************************************
    // Worker methods
    // ************************************************************************

    @Override
    public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
        return super.isMoveDoable(scoreDirector)
                && !Objects.equals(entity, toPlanningValue);
    }

    @Override
    public ChainedChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
        Object oldValue = variableDescriptor.getValue(entity);
        return new ChainedChangeMove<>(entity, variableDescriptor, inverseVariableSupply, oldValue);
    }

    @Override
    protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
        Object oldValue = variableDescriptor.getValue(entity);
        Object oldTrailingEntity = inverseVariableSupply.getInverseSingleton(entity);
        Object newTrailingEntity = toPlanningValue == null ? null
                : inverseVariableSupply.getInverseSingleton(toPlanningValue);
        // Close the old chain
        if (oldTrailingEntity != null) {
            scoreDirector.changeVariableFacade(variableDescriptor, oldTrailingEntity, oldValue);
        }
        // Change the entity
        scoreDirector.changeVariableFacade(variableDescriptor, entity, toPlanningValue);
        // Reroute the new chain
        if (newTrailingEntity != null) {
            scoreDirector.changeVariableFacade(variableDescriptor, newTrailingEntity, entity);
        }
    }

}


text:
(function () {
  'use strict';

  describe('Seeds Route Tests', function () {
    // Initialize global variables
    var $scope,
      SeedsService;

    //We can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($rootScope, _SeedsService_) {
      // Set a new global scope
      $scope = $rootScope.$new();
      SeedsService = _SeedsService_;
    }));

    describe('Route Config', function () {
      describe('Main Route', function () {
        var mainstate;
        beforeEach(inject(function ($state) {
          mainstate = $state.get('seeds');
        }));

        it('Should have the correct URL', function () {
          expect(mainstate.url).toEqual('/seeds');
        });

        it('Should be abstract', function () {
          expect(mainstate.abstract).toBe(true);
        });

        it('Should have template', function () {
          expect(mainstate.template).toBe('<ui-view/>');
        });
      });

      describe('View Route', function () {
        var viewstate,
          SeedsController,
          mockSeed;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          viewstate = $state.get('seeds.view');
          $templateCache.put('modules/seeds/client/views/view-seed.client.view.html', '');

          // create mock Seed
          mockSeed = new SeedsService({
            _id: '525a8422f6d0f87f0e407a33',
            name: 'Seed Name'
          });

          //Initialize Controller
          SeedsController = $controller('SeedsController as vm', {
            $scope: $scope,
            seedResolve: mockSeed
          });
        }));

        it('Should have the correct URL', function () {
          expect(viewstate.url).toEqual('/:seedId');
        });

        it('Should have a resolve function', function () {
          expect(typeof viewstate.resolve).toEqual('object');
          expect(typeof viewstate.resolve.seedResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(viewstate, {
            seedId: 1
          })).toEqual('/seeds/1');
        }));

        it('should attach an Seed to the controller scope', function () {
          expect($scope.vm.seed._id).toBe(mockSeed._id);
        });

        it('Should not be abstract', function () {
          expect(viewstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(viewstate.templateUrl).toBe('modules/seeds/client/views/view-seed.client.view.html');
        });
      });

      describe('Create Route', function () {
        var createstate,
          SeedsController,
          mockSeed;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          createstate = $state.get('seeds.create');
          $templateCache.put('modules/seeds/client/views/form-seed.client.view.html', '');

          // create mock Seed
          mockSeed = new SeedsService();

          //Initialize Controller
          SeedsController = $controller('SeedsController as vm', {
            $scope: $scope,
            seedResolve: mockSeed
          });
        }));

        it('Should have the correct URL', function () {
          expect(createstate.url).toEqual('/create');
        });

        it('Should have a resolve function', function () {
          expect(typeof createstate.resolve).toEqual('object');
          expect(typeof createstate.resolve.seedResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(createstate)).toEqual('/seeds/create');
        }));

        it('should attach an Seed to the controller scope', function () {
          expect($scope.vm.seed._id).toBe(mockSeed._id);
          expect($scope.vm.seed._id).toBe(undefined);
        });

        it('Should not be abstract', function () {
          expect(createstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(createstate.templateUrl).toBe('modules/seeds/client/views/form-seed.client.view.html');
        });
      });

      describe('Edit Route', function () {
        var editstate,
          SeedsController,
          mockSeed;

        beforeEach(inject(function ($controller, $state, $templateCache) {
          editstate = $state.get('seeds.edit');
          $templateCache.put('modules/seeds/client/views/form-seed.client.view.html', '');

          // create mock Seed
          mockSeed = new SeedsService({
            _id: '525a8422f6d0f87f0e407a33',
            name: 'Seed Name'
          });

          //Initialize Controller
          SeedsController = $controller('SeedsController as vm', {
            $scope: $scope,
            seedResolve: mockSeed
          });
        }));

        it('Should have the correct URL', function () {
          expect(editstate.url).toEqual('/:seedId/edit');
        });

        it('Should have a resolve function', function () {
          expect(typeof editstate.resolve).toEqual('object');
          expect(typeof editstate.resolve.seedResolve).toEqual('function');
        });

        it('should respond to URL', inject(function ($state) {
          expect($state.href(editstate, {
            seedId: 1
          })).toEqual('/seeds/1/edit');
        }));

        it('should attach an Seed to the controller scope', function () {
          expect($scope.vm.seed._id).toBe(mockSeed._id);
        });

        it('Should not be abstract', function () {
          expect(editstate.abstract).toBe(undefined);
        });

        it('Should have templateUrl', function () {
          expect(editstate.templateUrl).toBe('modules/seeds/client/views/form-seed.client.view.html');
        });

        xit('Should go to unauthorized route', function () {

        });
      });

    });
  });
})();


text:
//
//  ZeroMQUtilityTests.hpp
//  MWorksCore
//
//  Created by Christopher Stawarz on 8/3/16.
//
//

#ifndef ZeroMQUtilityTests_hpp
#define ZeroMQUtilityTests_hpp

#include "MessageTestFixture.hpp"

BEGIN_NAMESPACE_MW

class ZeroMQUtilityTests : public MessageTestFixture {

    CPPUNIT_TEST_SUITE( ZeroMQUtilityTests );

    CPPUNIT_TEST( testFormatTCPEndpoint );
    CPPUNIT_TEST( testGetHostname );
    CPPUNIT_TEST( testResolveHostname );

    CPPUNIT_TEST_SUITE_END();

public:
    void testFormatTCPEndpoint();
    void testGetHostname();
    void testResolveHostname();

};

END_NAMESPACE_MW

#endif /* ZeroMQUtilityTests_hpp */


text:
package se.l4.dust.core.internal.conversion;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;

import se.l4.dust.api.conversion.Conversion;
import se.l4.dust.api.conversion.ConversionException;
import se.l4.dust.api.conversion.NonGenericConversion;

/**
 * Wrapper for {@link Conversion}s that turn them into non-generic dependent
 * variants for internal use.
 *
 * @author Andreas Holstenson
 *
 * @param <I>
 * @param <O>
 */
public class ConversionWrapper<I, O>
	implements NonGenericConversion<I, O>
{
	private final Conversion<I, O> conversion;
	private final Class<I> input;
	private final Class<O> output;

	public ConversionWrapper(Conversion<I, O> conversion)
	{
		this.conversion = conversion;

		Type input = null;
		Type output = null;

		Class<? extends Conversion> c = conversion.getClass();
		Type[] genericInterfaces = c.getGenericInterfaces();
		for(Type t : genericInterfaces)
		{
			if(t instanceof ParameterizedType)
			{
				ParameterizedType pt = (ParameterizedType) t;
				if(pt.getRawType() == Conversion.class)
				{
					// This is the conversion
					Type[] arguments = pt.getActualTypeArguments();
					input = arguments[0];
					output = arguments[1];
				}
			}
		}

		if(input == null)
		{
			throw new ConversionException("Unable to determine types for "
				+ conversion + " consider using "
				+ NonGenericConversion.class.getSimpleName()
			);
		}

		this.input = (Class<I>) findClass(conversion, input);
		this.output = (Class<O>) findClass(conversion, output);
	}

	private Class<?> findClass(Conversion<I, O> conversion, Type type)
	{
		if(type instanceof Class)
		{
			return (Class) type;
		}
		else if(type instanceof ParameterizedType)
		{
			return (Class) ((ParameterizedType) type).getRawType();
		}
		else if(type instanceof WildcardType)
		{
			WildcardType wc = (WildcardType) type;
			Type[] lowerBounds = wc.getLowerBounds();
			if(lowerBounds.length == 0)
			{
				throw new ConversionException("Could not determine type for " + conversion + " (on " + type + ")");
			}

			return findClass(conversion, lowerBounds[0]);
		}

		throw new ConversionException("Could not determine type for " + conversion + " (on " + type + ")");
	}

	@Override
	public O convert(I in)
	{
		return conversion.convert(in);
	}

	@Override
	public Class<I> getInput()
	{
		return input;
	}

	@Override
	public Class<O> getOutput()
	{
		return output;
	}
}


text:
namespace Umbraco.Core.Persistence.Migrations.Syntax.Alter.Expressions
{
    public class AlterTableExpression : MigrationExpressionBase
    {
        public AlterTableExpression()
        {
        }

        public AlterTableExpression(DatabaseProviders current, DatabaseProviders[] databaseProviders) : base(current, databaseProviders)
        {
        }

        public virtual string SchemaName { get; set; }
        public virtual string TableName { get; set; }

        public override string ToString()
        {
            return string.Format("ALTER TABLE {0}", TableName);
        }
    }
}


text:
import { combineReducers } from 'redux';
import { createAction /*,
         handleActions */ } from 'redux-actions';
import fetch from 'isomorphic-fetch';
import sources from './sources';
import sourcesMetadata from './sources-metadata';
import sourcesThumbs from './sources-thumbs';
import debugLib from 'debug';
const debug = debugLib('app:module:catalog');

const REQUEST_CATALOG = 'REQUEST_CATALOG';
export const RECEIVE_CATALOG = 'RECEIVE_CATALOG';
const REQUEST_CATALOG_FAILED = 'REQUEST_CATALOG_FAILED';

// actions
export const requestCatalog = createAction(REQUEST_CATALOG);
export const receiveCatalog = createAction(RECEIVE_CATALOG);
export const requestCatalogFailed = createAction(REQUEST_CATALOG_FAILED);
export const fetchCatalog = () => {
  return (dispatch /*, getState */) => {
    dispatch(requestCatalog());

    return fetch('/api/catalog')
      .then(response => response.json())
      .then(json => {
        debug('fetch response', json);
        dispatch(receiveCatalog(json));
      })
      .catch(reason => {
        debug('fetch error', reason);
        dispatch(requestCatalogFailed(reason));
      });
  };
};

export const actions = {
  requestCatalog,
  receiveCatalog,
  requestCatalogFailed,
  fetchCatalog
};

const loading = (state = false, action) => {
  switch (action.type) {
    case REQUEST_CATALOG:
      return true;
    case RECEIVE_CATALOG:
    case REQUEST_CATALOG_FAILED:
      return false;
    default:
      return state;
  }
};

const name = (state = '', action) => {
  switch (action.type) {
    case RECEIVE_CATALOG:
      return action.payload.name;
    default:
      return state;
  }
};

export default combineReducers({
  loading,
  name,
  sources,
  sourcesMetadata,
  sourcesThumbs
});