text:
var path = require( "path" );
var util = require( "util" );
var crypto = require( "crypto" );
var wordpress = require( "wordpress" );
var async = require( "async" );
var glob = require( "glob" );
var version = require( "./package" ).version;

exports.createClient = createClient;
exports.Client = Client;

function createClient( options ) {
	return new Client( options );
}

function Client( options ) {
	this.options = options;
	this.verbose = options.verbose || false;
	this.client = wordpress.createClient( options );
	this.bindClientMethods();
}

Client.prototype.log = console.log;
Client.prototype.logError = console.error;

Client.prototype.bindClientMethods = function() {
	var context = this;
	var client = this.client;

	function bindContext( property ) {
		if ( typeof client[ property ] !== "function" ) {
			return;
		}

		var original = client[ property ];
		client[ property ] = function() {
			if ( !arguments.length ) {
				return;
			}

			var args = [].slice.apply( arguments );
			var last = args.pop();
			if ( typeof last === "function" ) {
				last = last.bind( context );
			}
			args.push( last );

			original.apply( client, args );
		};
	}

	for ( var property in client ) {
		bindContext( property );
	}
};

Client.prototype.waterfall = function( steps, callback ) {
	var context = this;

	async.waterfall(
		steps.map(function( step ) {
			return step.bind( context );
		}),
		callback.bind( context )
	);
};

Client.prototype.forEach = function( items, eachFn, complete ) {
	async.forEachSeries( items, eachFn.bind( this ), complete.bind( this ) );
};

Client.prototype.path = function( partial ) {
	return path.join( this.options.dir, partial );
};

// Async directory recursion, always walks all files before recursing
Client.prototype.recurse = function( rootdir, walkFn, complete ) {
	complete = complete.bind( this );

	glob( rootdir + "/*", { mark: true }, function( error, entries ) {
		if ( error ) {
			return complete( error );
		}

		var directories = [];
		var files = entries.filter(function( entry ) {
			if ( /\/$/.test( entry ) ) {
				directories.push( entry );
				return false;
			}

			return true;
		});

		this.forEach( files, walkFn, function( error ) {
			if ( error ) {
				return complete( error );
			}

			this.forEach( directories, function( directory, directoryComplete ) {
				this.recurse( directory, walkFn, directoryComplete );
			}, complete );
		});
	}.bind( this ));
};

Client.prototype.createChecksum = (function() {
	function flatten( obj ) {
		if ( obj == null ) {
			return "";
		}

		if ( typeof obj === "string" ) {
			return obj;
		}

		if ( typeof obj === "number" ) {
			return String( obj );
		}

		if ( util.isDate( obj ) ) {
			return obj.toGMTString();
		}

		if ( util.isArray( obj ) ) {
			return obj.map(function( item ) {
				return flatten( item );
			}).join( "," );
		}

		return Object.keys( obj ).sort().map(function( prop ) {
			return prop + ":" + flatten( obj[ prop ] );
		}).join( ";" );
	}

	return function( obj ) {
		var md5 = crypto.createHash( "md5" );
		md5.update( flatten( obj ), "utf8" );
		return md5.digest( "hex" );
	};
})();

Client.prototype.validateXmlrpcVersion = function( callback ) {
	callback = callback.bind( this );

	if ( this.verbose ) {
		this.log( "Verifying XML-RPC version..." );
	}

	this.client.authenticatedCall( "gw.getVersion", function( error, xmlrpcVersion ) {
		if ( error ) {
			if ( error.code === "ECONNREFUSED" ) {
				return callback( new Error( "Could not connect to WordPress." ) );
			}
			if ( error.code === -32601 ) {
				return callback( new Error(
					"XML-RPC extensions for Gilded WordPress are not installed." ) );
			}
			if ( !error.code ) {
				error.message += "\nPlease ensure that your database server is running " +
					"and WordPress is functioning properly.";
			}

			// XML-RPC is disabled or bad credentials
			// WordPress provides good error messages, so we don't do any special handling
			return callback( error );
		}

		if ( xmlrpcVersion !== version ) {
			return callback( new Error( "Mismatching versions for Gilded WordPress. " +
				"Version " + version + " is installed as a Node.js module, " +
				"but the WordPress server is running version " + xmlrpcVersion + "." ) );
		}

		if ( this.verbose ) {
			this.log( "XML-RPC version matches Node.js version." );
		}

		callback( null );
	});
};

Client.prototype.validate = function( callback ) {
	this.waterfall([
		this.validateXmlrpcVersion,
		this.validateTerms,
		this.validatePosts
	], function( error ) {
		if ( error ) {
			return callback( error );
		}

		callback( null );
	});
};

Client.prototype.sync = function( callback ) {
	this.waterfall([
		this.syncTerms,
		this.syncPosts,
		this.syncResources
	], function( error ) {
		if ( error ) {
			if ( error.code === "ECONNREFUSED" ) {
				this.logError( "Could not connect to WordPress XML-RPC server." );
			}

			return callback( error );
		}

		callback( null );
	});
};

[ "posts", "taxonomies", "resources" ].forEach(function( module ) {
	require( "./lib/" + module )( Client );
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=============================================================================
**
**
**
** Purpose: For methods that are passed arrays with the wrong number of
**          dimensions.
**
**
=============================================================================*/

using System.Runtime.Serialization;

namespace System
{
    [Serializable]
    [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public class RankException : SystemException
    {
        public RankException()
            : base(SR.Arg_RankException)
        {
            HResult = HResults.COR_E_RANK;
        }

        public RankException(string? message)
            : base(message)
        {
            HResult = HResults.COR_E_RANK;
        }

        public RankException(string? message, Exception? innerException)
            : base(message, innerException)
        {
            HResult = HResults.COR_E_RANK;
        }

        protected RankException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>thread_pool::has_service</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../thread_pool.html" title="thread_pool">
<link rel="prev" href="get_executor.html" title="thread_pool::get_executor">
<link rel="next" href="join.html" title="thread_pool::join">

thread_pool::has_service

          Inherited from execution_context.

Determine if an execution_context contains a specified
          service type.

template<
    typename Service>
friend bool has_service(
    execution_context & e);

          This function is used to determine whether the execution_context contains a service
          object corresponding to the given service type.

          Parameters

e

                The execution_context object
                that owns the service.

          Return Value

          A boolean indicating whether the execution_context contains the
          service.

          Requirements

          Header: asio/thread_pool.hpp

          Convenience header: asio.hpp

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
class AddPdfDestinationToItem < ActiveRecord::Migration[5.2]
  def change
    add_column :items, :pdf_destination, :text
  end
end


text:
package tests.javax_servlet.ServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 	A Test for getInputStream method
 */

public class GetInputStreamTestServlet extends GenericServlet {

    public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        ServletInputStream sin = request.getInputStream();

        if ( sin != null ) {
            out.println( "GetInputStreamTest test PASSED" );
        } else {
            out.println( "GetInputStreamTest test FAILED
" );
            out.println( "    ServletRequest.request.getInputStream() returned a null
" );
        }
    }
}


text:
require 'active_record'

class Carto::ExternalSource < ActiveRecord::Base

  # Seconds
  REFRESH_INTERVAL = 30*24*60*60

end


text:
package org.funytest.common.internal;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.funytest.common.exception.CheckFailException;
import org.funytest.common.internal.method.IFunnyTestMethod;
import org.funytest.common.internal.method.IFunnyTestMethodFactory;
import org.funytest.common.model.FunnyConfig;
import org.funytest.common.model.TestContext;
import org.funytest.common.utils.ExceptionUtil;
import org.funytest.common.utils.LogUtils;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.TestInstance;

/**
 * FunnyTest 测试核心引擎类, 基于spring 上下文进行
 * @author xiuzhu.hp
 */
public class FunyTestEngine extends AbstractTestNGSpringContextTests implements IFunyTestCase {

	public String configfile = "/config/funny-test.config";

	/* 配置信息类 */
	protected IConfiguration config;

	/* funnyTestMethod 工厂类 */
	protected IFunnyTestMethodFactory funyTestMethodFactory;

	/* funnyTestMethod map */
	protected Map<Class<? extends Annotation>, IFunnyTestMethod> funnyTestMethodMap;

	/* 存储类 */
	protected List<Class<? extends Annotation>> annotationClassList;

	/**
	 * 执行方法
	 * @throws Exception
	 */
	public void run(TestContext context){
		try {
			this.config.getTestRunner().run(context);
		} catch (Exception e) {

			if (e instanceof CheckFailException){
				Assert.fail(((CheckFailException)e).getFailMessage());
			}

			Assert.fail(ExceptionUtil.getStackTrace(e));
		}

	}

	protected void initConfig(){
		//首先初始化配置信息
		if (config!=null){
			return;
		}

		this.config = this.getConfig();
		config.init(this);
	}

	/**
	 * 初始化
	 */
	@BeforeClass
	public void init(){
		LogUtils.info("funny-test is starting ......");

		initConfig();
		/* 初始化变量 */
		annotationClassList = new LinkedList<Class<? extends Annotation>>();

		funyTestMethodFactory = this.config.getFunnyMethodFactory();

		//扫描注解方法,并放置到配置中
		initAnnotationMethods();

		LogUtils.info("funny-test start success !!!");
	}

	private void initAnnotationMethods(){

		IAnnotationMethodFinder finder = this.config.getAnnotationFinder();
		/* 初始化特定方法 */
		this.funnyTestMethodMap = finder.findFunnyTestMethodMap(this.getClass(), getAnnotationClassList(),funyTestMethodFactory);
	}

	/**
	 *
	 * @return
	 */
	protected void register(Class<? extends Annotation> cls){
		this.annotationClassList.add(cls);
	}

	/**
	 * 数据驱动
	 * @param m 测试方法
	 * @param instance 测试类的当前实例
	 * @return
	 */
	@DataProvider(name = "FunyTestDataProvider")
	public Iterator<?> getData(Method m, @TestInstance Object instance){
		try {
			initConfig();
			return this.config.getDataProvider().getData(m, this.getClass(), instance);
		} catch (DocumentException e) {
			// TODO 说明解析失败了
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 从spring上下文中获取指定的bean
	 * @param name
	 * @return
	 */
	public Object getBean(String name){
		try {
			return applicationContext.getBean(name);
		} catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/*==========================[待实现区域]=============================*/
	public IConfiguration getConfig(){
		return new FunnyConfig(configfile);
	}

	/*==========================[配置相关区域]=============================*/
	public IConfiguration getIConfiguration(){
		return this.config;
	}

	public IFunnyTestMethodFactory getFunyTestMethodFactory() {
		return funyTestMethodFactory;
	}

	public void setFunyTestMethodFactory(IFunnyTestMethodFactory funyTestMethodFactory) {
		this.funyTestMethodFactory = funyTestMethodFactory;
	}

	public Map<Class<? extends Annotation>, IFunnyTestMethod> getFunnyTestMethodMap() {
		return funnyTestMethodMap;
	}

	public void setFunnyTestMethodMap(Map<Class<? extends Annotation>, IFunnyTestMethod> funnyTestMethodMap) {
		this.funnyTestMethodMap = funnyTestMethodMap;
	}

	public List<Class<? extends Annotation>> getAnnotationClassList() {
		return annotationClassList;
	}

	public void setAnnotationClassList(List<Class<? extends Annotation>> annotationClassList) {
		this.annotationClassList = annotationClassList;
	}

	public void setConfiguration(IConfiguration config) {

		this.config = config;
	}

}


text:
package gov.faa.ang.swac.datalayer;

import gov.faa.ang.swac.common.datatypes.Timestamp;
import gov.faa.ang.swac.datalayer.identity.*;
import gov.faa.ang.swac.datalayer.storage.DataMarshaller;
import gov.faa.ang.swac.datalayer.storage.db.DataAccessObject;
import gov.faa.ang.swac.datalayer.storage.fileio.FileMarshaller;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * MappedDataAccess is a client-facing facade for the data layer, acting as a
 * simple key-value store. DataDescriptor keys provide metadata that
 * MappedDataAccess interprets to differentiate between named files,
 * parameterized queries, and transient or persistent intermediate data. A
 * DataMarshaller for loading/saving the data is created and cached for future
 * queries. Data may or may not continue to reside in memory after it is
 * marshalled to/from a data store: that is the marshaller's responsibility.
 * Manual clean-up of references is made possible with purge and purge-all.
 *
 * @author csmith
 *
 */
public class MappedDataAccess extends ResourceManager {

    private static final Logger logger = LogManager.getLogger(MappedDataAccess.class);
    private final Map<DataDescriptor, DataMarshaller> storageMap;
    private final Map<DataDescriptor, List<String>> resourceNameMap;

    public MappedDataAccess() {
        storageMap = new LinkedHashMap<DataDescriptor, DataMarshaller>();
        resourceNameMap = new ConcurrentSkipListMap<DataDescriptor, List<String>>(new DataDescriptorComparator());
    }

    public MappedDataAccess(MappedDataAccess val) {
        super(val);
        this.storageMap = val.storageMap;
        this.resourceNameMap = val.resourceNameMap;
    }

    public void loadScenarioFileDataDescriptor(FileDataDescriptor fdd) {
        if (fdd.getResourceName() == null || fdd.getResourceName().isEmpty()) {
            logger.error("Error loading scenario import for class: " + fdd.getDataType());
        } else {
            List<String> files = new ArrayList<String>();
            StringBuilder parameters = new StringBuilder("");

            parameters.append("," + (fdd.getBaseDate() == null ? " " : Long.toString(fdd.getBaseDate().getTime())));
            parameters.append("," + (fdd.getForecastFiscalYear() == null ? " " : fdd.getForecastFiscalYear()));
            parameters.append("," + (fdd.getClassifier() == null ? " " : fdd.getClassifier()));

            if (fdd instanceof FileSetDescriptor) {
                for (String file : ((FileSetDescriptor)fdd).getResourceNames()) {
                    files.add(file + parameters);
                }
            } else {
                files.add(fdd.getResourceName() + parameters);
            }
            this.resourceNameMap.put(fdd, files);
            this.storageMap.put(fdd, fdd.createMarshaller(this));
        }
    }

    // TODO: temporary workaround for fuzzy-matching filter criteria on parameterized queries.
    public <T> void load(DataDescriptor descriptor, List<T> output) throws DataAccessException {
        logger.info("Loading data: " + descriptor.toString());
        DataMarshaller marshaller = this.getMarshaller(descriptor);
        if (marshaller == null) {
            marshaller = this.getMarshaller(descriptor);
        }

        marshaller.load(output);
        logger.debug(output.size() + " records of type " + descriptor.getDataType().getSimpleName() + " loaded");
        if (output.isEmpty()) {
            logger.warn("No records loaded for type " + descriptor.getDataType().getSimpleName() + ": data source may be missing or corrupted.");
        }
    }

    public <T> void save(DataDescriptor descriptor, List<T> data) throws DataAccessException {
        DataMarshaller marshaller = this.getMarshaller(descriptor);

        marshaller.save(data);
        logger.debug(data.size() + " records of type " + descriptor.getDataType().getSimpleName() + " saved");
    }

    /**
     * In order to avoid changing object state in a predicate, exists will
     * return false if the descriptor is not already registered in the map XXX:
     * No longer true...getMarshaller will create the marshaller if it does not
     * exist. Existence check should work ok but it potentially changes the
     * object which is bad juju
     *
     * @param descriptor
     * @return
     */
    public boolean exists(DataDescriptor descriptor) throws DataAccessException {
        DataMarshaller marshaller = this.getMarshaller(descriptor);
        return (marshaller != null && marshaller.exists());
    }

    /**
     * This is for free-form text output that circumvents the normal formalism
     * of the key-value store, which is useful for dumping unstructured output
     * data and reports. Use TextSerializable and load/save instead for
     * structured data.
     *
     * @param descriptor
     * @return
     * @throws DataAccessException
     */
    public PrintWriter getWriter(FileDataDescriptor descriptor) throws DataAccessException {
        if (descriptor.isReadOnly()) {
            throw new DataAccessException("Read-only");
        }
        return new PrintWriter(this.openOutput(descriptor.getLocation(), descriptor.getResourceName()));
    }

    /**
     * Resolves a DataDescriptor directly to a file system path. Only
     * FileDataDescriptors are permitted. WARNING: This should be used only as a
     * last resort for pathological cases, since it violates the abstraction
     * provided by the data layer.
     *
     * TODO: Any calling code should be refactored to use data layer abstraction
     * at the earliest convenience.
     *
     * @param descriptor
     * @return
     */
    public File getAbsoluteFile(DataDescriptor descriptor) {
        if (descriptor instanceof FileDataDescriptor) {
            FileDataDescriptor f = (FileDataDescriptor) descriptor;

            if (f.getResourceName() == null || f.getResourceName().isEmpty()) {
                String[] params = this.resourceNameMap.get(f).get(0).split(",");
                f.setResourceName(params[0]);
            }

            return this.getFile(f.getLocation(), f.getResourceName());
        } else {
            throw new IllegalArgumentException();
        }
    }

    public DataMarshaller getMarshaller(DataDescriptor descriptor) throws DataAccessException {
        DataMarshaller marshaller;
        DataDescriptor d = descriptor;

        if (d instanceof FileDataDescriptor) {
            FileDataDescriptor f = (FileDataDescriptor) d;

            FileDataDescriptor key = null;
            boolean requireSuccessfulLookup = false;
            if (f.getResourceName() == null || f.getResourceName().isEmpty()) {
            	key = f;
            	requireSuccessfulLookup = true;
            } else {
            	key = new FileDataDescriptor(f);
            	key.setLocation(f.getLocation());
            	key.setResourceName(null);
            }

            List<String> paramList = this.resourceNameMap.get(key);
            if(!requireSuccessfulLookup)
            	paramList = null;
            if (paramList == null || paramList.isEmpty()) {
            	if (requireSuccessfulLookup) {
            		throw new DataAccessException("Invalid baseDate|forecastFiscalYear entry in scenarioImports for resource type " + f.getDataType().getSimpleName());
            	}
            } else {
                List<String> files = new ArrayList<String>();
                f = new FileSetDescriptor(f);

                for (String param : paramList) {
                    files.add(param.split(",")[0]);
                }

                ((FileSetDescriptor)f).setResourceNames(files);

                String[] params = paramList.get(0).split(",");

                f.setResourceName(params[0]);
                if (params.length > 1) {
                    if (params[1].trim().length() > 0) {
                        ((FileDataDescriptor)d).setBaseDate(new Timestamp(Long.parseLong(params[1]))); // changes to f are not propogated back to the caller
                        f.setBaseDate(new Timestamp(Long.parseLong(params[1])));
                    }
                    if (params.length > 2 ) {
                        if (params[2].trim().length() > 0) {
                            ((FileDataDescriptor)d).setForecastFiscalYear(Integer.parseInt(params[2])); // changes to f are not propogated back to the caller
                            f.setForecastFiscalYear(Integer.parseInt(params[2]));
                        }
                        if (params.length > 3) {
                            if (params[3].trim().length() > 0) {
                                ((FileDataDescriptor)d).setClassifier(params[3]); // changes to f are not propogated back to the caller
                                f.setClassifier(params[3]);
                            }
                        }
                    }
                }
                String schema = f.getSchemaName();

                if (schema != null && !schema.isEmpty()) {
                    storageMap.put(f, f.createMarshaller(this));
                }

                d = f;
            }
        }

        marshaller = this.storageMap.get(d);

        if (marshaller == null) {
            marshaller = d.createMarshaller(this);
            this.storageMap.put(d, marshaller);
            logger.debug("Registered metadata for: " + d.toString());
        }

        return marshaller;
    }

    /**
     * Strong typing
     *
     * @param descriptor
     * @return
     * @throws DataAccessException
     */
    public DataAccessObject getDataAccessObject(DataAccessObjectDescriptor descriptor) throws DataAccessException {
        return (DataAccessObject) this.getMarshaller(descriptor);
    }

    // XXX: It's probably cleaner to re-implement the equals method in ParameterizedDataDescriptor to fuzzy-match instead of checking the map for all permutations of parameters
    // NOTE: An important distinction between this and getMarshaller is that this should not insert anything into the storage maps since it is searching in potentially multiple locations
    // getMarshaller works in a get-or-create fashion.
    private DataMarshaller getParameterizedMarshaller(ParameterizedDataDescriptor originalDescriptor) {
        Integer forecastFiscalYearParam = originalDescriptor.getForecastFiscalYear();
        String classifierParam = originalDescriptor.getClassifier();

        ParameterizedDataDescriptor descriptor = originalDescriptor.clone();

        if (!this.storageMap.containsKey(descriptor)) // 111
        {
            descriptor.setClassifier(null); // 110
            if (!this.storageMap.containsKey(descriptor)) {
                descriptor.setForecastFiscalYear(null); // 100
                if (!this.storageMap.containsKey(descriptor)) {
                    descriptor.setClassifier(classifierParam); // 101
                    if (!this.storageMap.containsKey(descriptor)) {
                        descriptor.setBaseDate(null); // 001
                        if (!this.storageMap.containsKey(descriptor)) {
                            descriptor.setForecastFiscalYear(forecastFiscalYearParam); // 011
                            if (!this.storageMap.containsKey(descriptor)) {
                                descriptor.setClassifier(null); // 010
                            }
                        }
                    }
                }
            }
        }
        return this.storageMap.get(descriptor);
    }

    /**
     * The map must be cleared for GC
     */
    public void clearMap() {
        this.storageMap.clear();
        //HK: have to keep resourceNameMap around forever because DB is now initialized in Job so it must
        //look up the location of scripts at it's Thread execution time.
        //this.resourceNameMap.clear();
    }

    @Override
    public String toString() {
        Comparator<Entry<DataDescriptor, DataMarshaller>> comp = new Comparator<Entry<DataDescriptor, DataMarshaller>>() {
            @Override
            public int compare(Entry<DataDescriptor, DataMarshaller> o1,
                    Entry<DataDescriptor, DataMarshaller> o2) {
                if (o1.getClass().equals(o2.getClass())) {
                    if (o1 instanceof IntermediateDataDescriptor) {
                        IntermediateDataDescriptor _o1 = (IntermediateDataDescriptor) o1;
                        IntermediateDataDescriptor _o2 = (IntermediateDataDescriptor) o2;
                        Integer instance1 = _o1.getInstanceId();
                        Integer instance2 = _o2.getInstanceId();
                        if (instance1.equals(instance2)) {
                            String source1 = _o1.getDataSource().toString();
                            String source2 = _o2.getDataSource().toString();
                            if (source1.equals(source2)) {
                                return _o1.getDataType().getSimpleName().compareTo(_o2.getDataType().getSimpleName());
                            } else {
                                return source1.compareTo(source2);
                            }
                        } else {
                            return instance1.compareTo(instance2);
                        }
                    } else {
                        return o1.toString().compareTo(o2.toString());
                    }
                } else {
                    return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
                }
            }
        };

        List<Entry<DataDescriptor, DataMarshaller>> entries = new ArrayList<Entry<DataDescriptor, DataMarshaller>>(this.storageMap.entrySet());
        Collections.sort(entries, comp);

        StringBuilder str = new StringBuilder();
        for (Entry<DataDescriptor, DataMarshaller> entry : entries) {
            str.append(entry.toString() + "\n");
        }
        return str.toString();
    }

    private class DataDescriptorComparator implements Comparator<DataDescriptor> {

        @Override
        public int compare(DataDescriptor o1, DataDescriptor o2) {
            if (o1 instanceof ParameterizedDataDescriptor && o2 instanceof ParameterizedDataDescriptor) {
                if (o1 instanceof FileDataDescriptor && o2 instanceof FileDataDescriptor) {
                    FileDataDescriptor fdd1 = (FileDataDescriptor) o1;
                    FileDataDescriptor fdd2 = (FileDataDescriptor) o2;

                    if (fdd1.equals(fdd2)) {
                        return 0;
                    }
                }
                ParameterizedDataDescriptor pdd1 = (ParameterizedDataDescriptor) o1;
                ParameterizedDataDescriptor pdd2 = (ParameterizedDataDescriptor) o2;

                if (pdd1.getDataType() != pdd2.getDataType()) {
                    return pdd1.getDataType().getCanonicalName().compareTo(pdd2.getDataType().getCanonicalName());
                } else {
                    String c1 = pdd1.getClassifier();
                    String c2 = pdd2.getClassifier();

                    if (c1 == null || c1.isEmpty() || c2 == null || c2.isEmpty() || c1.contentEquals(c2)) {
                        Timestamp ts1 = pdd1.getBaseDate();
                        Timestamp ts2 = pdd2.getBaseDate();

                        if (ts1 == null || ts2 == null || ts1.equalValue(ts2)) {
                            Integer ffy1 = pdd1.getForecastFiscalYear();
                            Integer ffy2 = pdd2.getForecastFiscalYear();

                            if (ffy1 == null || ffy2 == null) {
                                return 0;
                            } else {
                                return ffy1.compareTo(ffy2);
                            }
                        } else {
                            return pdd1.getBaseDate().compareTo(pdd2.getBaseDate());
                        }
                    } else {
                        return pdd1.getClassifier().compareTo(pdd2.getClassifier());
                    }
                }
            }
            return -1;
        }
    }
}


text:
using Boxing.Contracts.Dto;
using Boxing.Core.Handlers.Interfaces;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using Boxing.Contracts.Requests.Matches;
using System.Net.Http;
using System.Net;

namespace Boxing.Api.Handlers.Controllers
{
    public class MatchesController : ApiController
    {
        private readonly IMediator _mediator;

        public MatchesController(IMediator mediator)
        {
            _mediator = mediator;
        }

        [HttpGet]
        public async Task<IEnumerable<MatchDto>> Get([FromUri] GetAllMatchesRequest request)
        {
            return await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }

        [HttpGet]
        public async Task<MatchDto> Get([FromUri] int id)
        {
            var request = new GetMatchRequest
            {
                Id = id
            };
            return await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }

        [HttpPost]
        public async Task<HttpResponseMessage> Create([FromBody] MatchDto userAccount)
        {
            var request = new CreateMatchRequest
            {
                Match = userAccount
            };
            await _mediator.ExecuteAsync(request).ConfigureAwait(false);
            return Request.CreateResponse(HttpStatusCode.Created);
        }

        [HttpPut]
        public async Task Update(int id, [FromBody] MatchDto match)
        {
            match.Id = id;
            var request = new UpdateMatchRequest
            {
                Match = match
            };
            await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }

        [HttpPut]
        [Route("api/matches/{id}/finish/")]
        public async Task Finish(int id, [FromBody] int winnerId)
        {
            var request = new FinishMatchRequest
            {
                Id = id,
                WinnerId = winnerId
            };
            await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }

        [HttpPut]
        [Route("api/matches/{id}/cancel/")]
        public async Task Cancel(int id)
        {
            var request = new CancelMatchRequest
            {
                Id = id
            };
            await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }

        [HttpDelete]
        public async Task Delete([FromUri] DeleteMatchRequest request)
        {
            await _mediator.ExecuteAsync(request).ConfigureAwait(false);
        }
    }
}


text:
from clothstream.lib.rest import SharedAPIRootRouter
from .views import ItemViewSet

router = SharedAPIRootRouter()
router.register(r'items', ItemViewSet)


text:
<?php

namespace DevGroup\DataStructure\search\implementation\db\QueryModifiers;

use DevGroup\DataStructure\search\base\SearchEvent;
use yii;

class MainEntityAttributes
{
    public static function modify(SearchEvent $e)
    {
        $searchQuery = $e->searchQuery();
        if (count($searchQuery->mainEntityAttributes) === 0) {
            return;
        }

        /** @var yii\db\ActiveQuery $activeQuery */
        $activeQuery = &$e->params['activeQuery'];
        $activeQuery->andFilterWhere($searchQuery->mainEntityAttributes);

    }
}


text:
package org.hoteia.qalingo.core.domain;

import java.sql.Blob;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name="TBO_SERVER_STATUS")
public class ServerStatus extends AbstractEntity<ServerStatus> {

    /**
     * Generated UID
     */
    private static final long serialVersionUID = 5455152426025490243L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID", nullable=false)
    private Long id;

    @Column(name="SERVER_NAME")
    private String serverName;

    @Column(name="SERVER_IP")
    private String serverIp;

    @Column(name="LAST_CHECK_RECEIVED")
    private Date lastCheckReceived;

    @Column(name="MESSAGE_CONTENT")
    @Lob
    private Blob messageContent;

    public ServerStatus() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getServerIp() {
        return serverIp;
    }

    public void setServerIp(String serverIp) {
        this.serverIp = serverIp;
    }

    public Date getLastCheckReceived() {
        return lastCheckReceived;
    }

    public void setLastCheckReceived(Date lastCheckReceived) {
        this.lastCheckReceived = lastCheckReceived;
    }

    public Blob getMessageContent() {
        return messageContent;
    }

    public void setMessageContent(Blob messageContent) {
        this.messageContent = messageContent;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((lastCheckReceived == null) ? 0 : lastCheckReceived.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object sourceObj) {
        Object obj = deproxy(sourceObj);
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ServerStatus other = (ServerStatus) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (lastCheckReceived == null) {
            if (other.lastCheckReceived != null)
                return false;
        } else if (!lastCheckReceived.equals(other.lastCheckReceived))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "ServerStatus [id=" + id + ", serverName=" + serverName + ", serverIp=" + serverIp + ", lastCheckReceived=" + lastCheckReceived + "]";
    }

}


text:
// Draw four triangles on a red background
#include <GL/glew.h>
#include <GL/glfw.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
//#include <ctime>
#include <FreeImage.h>

// Read a shader source from a file
// store the shader source in a std::vector<char>
void read_shader_src(const char *fname, std::vector<char> &buffer);

// Compile a shader
GLuint load_and_compile_shader(const char *fname, GLenum shaderType);

// Create a program from two shaders
GLuint create_program(const char *path_vert_shader, const char *path_frag_shader);

// Called when the window is resized
void GLFWCALL window_resized(int width, int height);

// Called for keyboard events
void keyboard(int key, int action);

// Render scene
void display(GLuint &vao);

// Initialize the data to be rendered
void initialize(GLuint &vao);

// Load an image from the disk with FreeImage
void load_image(const char *fname);

int main () {
	// Initialize GLFW
	if ( !glfwInit()) {
		std::cerr << "Failed to initialize GLFW! I'm out!" << std::endl;
		exit(-1);
	}

	// Use OpenGL 3.2 core profile
    /*
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    */

	// Open a window and attach an OpenGL rendering context to the window surface
	if( !glfwOpenWindow(800, 600, 8, 8, 8, 0, 0, 0, GLFW_WINDOW)) {
		std::cerr << "Failed to open a window! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Register a callback function for window resize events
	glfwSetWindowSizeCallback( window_resized );

	// Register a callback function for keyboard pressed events
	glfwSetKeyCallback(keyboard);

	// Print the OpenGL version
	int major, minor, rev;
	glfwGetGLVersion(&major, &minor, &rev);
	std::cout << "OpenGL - " << major << "." << minor << "." << rev << std::endl;

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK) {
		std::cerr << "Failed to initialize GLEW! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Create a vertex array object
	GLuint vao;

	// Initialize the data to be rendered
	initialize(vao);

	// Create a rendering loop
	int running = GL_TRUE;

	while(running) {
		// Display scene
		display(vao);

		// Pool for events
		glfwPollEvents();
		// Check if the window was closed
		running = glfwGetWindowParam(GLFW_OPENED);
	}

	// Terminate GLFW
	glfwTerminate();

	return 0;
}

// Render scene
void display(GLuint &vao) {
	glClear(GL_COLOR_BUFFER_BIT);

	glBindVertexArray(vao);
	glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

	// Swap front and back buffers
	glfwSwapBuffers();
}

void initialize(GLuint &vao) {
	// Use a Vertex Array Object
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// 1 square (made by 2 triangles) to be rendered
	GLfloat vertices_position[8] = {
		-0.5, -0.5,
		0.5, -0.5,
		0.5, 0.5,
		-0.5, 0.5,
	};

	GLfloat texture_coord[8] = {
		0.0, 0.0,
		1.0, 0.0,
		1.0, 1.0,
		0.0, 1.0,
	};

	GLuint indices[6] = {
		0, 1, 2,
		2, 3, 0
	};

	// Create a Vector Buffer Object that will store the vertices on video memory
	GLuint vbo;
	glGenBuffers(1, &vbo);

	// Allocate space for vertex positions and texture coordinates
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices_position) + sizeof(texture_coord), NULL, GL_STATIC_DRAW);

	// Transfer the vertex positions:
	glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices_position), vertices_position);

	// Transfer the texture coordinates:
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices_position), sizeof(texture_coord), texture_coord);

	// Create an Element Array Buffer that will store the indices array:
	GLuint eab;
	glGenBuffers(1, &eab);

	// Transfer the data from indices to eab
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eab);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	// Create a texture
	GLuint texture;
	glGenTextures(1, &texture);

	// Specify that we work with a 2D texture
	glBindTexture(GL_TEXTURE_2D, texture);

	load_image("squirrel.jpg");

	GLuint shaderProgram = create_program("shaders/vert.shader", "shaders/frag.shader");

	// Get the location of the attributes that enters in the vertex shader
	GLint position_attribute = glGetAttribLocation(shaderProgram, "position");

	// Specify how the data for position can be accessed
	glVertexAttribPointer(position_attribute, 2, GL_FLOAT, GL_FALSE, 0, 0);

	// Enable the attribute
	glEnableVertexAttribArray(position_attribute);

	// Texture coord attribute
	GLint texture_coord_attribute = glGetAttribLocation(shaderProgram, "texture_coord");
	glVertexAttribPointer(texture_coord_attribute, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid *)sizeof(vertices_position));
	glEnableVertexAttribArray(texture_coord_attribute);

}

void load_image(const char *fname) {

	// active only for static linking
	#ifdef FREEIMAGE_LIB
		FreeImage_Initialise();
	#endif

	FIBITMAP *bitmap;
	// Get the format of the image file
	FREE_IMAGE_FORMAT fif =FreeImage_GetFileType(fname, 0);

	// If the format can't be determined, try to guess the format from the file name
	if(fif == FIF_UNKNOWN) {
		fif = FreeImage_GetFIFFromFilename(fname);
	}

	// Load the data in bitmap if possible
	if(fif != FIF_UNKNOWN && FreeImage_FIFSupportsReading(fif)) {
		bitmap = FreeImage_Load(fif, fname);
	}
	else {
		bitmap = NULL;
	}

	// PROCESS IMAGE if bitmap was successfully initialized
	if(bitmap) {
		unsigned int w = FreeImage_GetWidth(bitmap);
		unsigned int h = FreeImage_GetHeight(bitmap);
		unsigned pixel_size = FreeImage_GetBPP(bitmap);

		// Get a pointer to the pixel data
		BYTE *data = (BYTE*)FreeImage_GetBits(bitmap);

		// Process only RGB and RGBA images
		if(pixel_size == 24) {
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_BGR, GL_UNSIGNED_BYTE, (GLvoid*)data);
		}
		else if (pixel_size == 32) {
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)data);
		}
		else {
			std::cerr << "pixel size = " << pixel_size << " don't know how to process this case. I'm out!" << std::endl;
			exit(-1);
		}

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}
	else {
		std::cerr << "Unable to load the image file " << fname  << " I'm out!" << std::endl;
		exit(-1);
	}

	// Clean bitmap;
	FreeImage_Unload(bitmap);

	// active only for static linking
	#ifdef FREEIMAGE_LIB
		FreeImage_DeInitialise();
	#endif
}

// Called when the window is resized
void GLFWCALL window_resized(int width, int height) {
	// Use red to clear the screen
	//glClearColor(1, 0, 0, 1);

	// Set the viewport
	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT);
	glfwSwapBuffers();
}

// Called for keyboard events
void keyboard(int key, int action) {
	if(key == 'Q' && action == GLFW_PRESS) {
		glfwTerminate();
		exit(0);
	}
}

// Read a shader source from a file
// store the shader source in a std::vector<char>
void read_shader_src(const char *fname, std::vector<char> &buffer) {
	std::ifstream in;
	in.open(fname, std::ios::binary);

	if(in.is_open()) {
		// Get the number of bytes stored in this file
		in.seekg(0, std::ios::end);
		size_t length = (size_t)in.tellg();

		// Go to start of the file
		in.seekg(0, std::ios::beg);

		// Read the content of the file in a buffer
		buffer.resize(length + 1);
		in.read(&buffer[0], length);
		in.close();
		// Add a valid C - string end
		buffer[length] = '\0';
	}
	else {
		std::cerr << "Unable to open " << fname << " I'm out!" << std::endl;
		exit(-1);
	}
}

// Compile a shader
GLuint load_and_compile_shader(const char *fname, GLenum shaderType) {
	// Load a shader from an external file
	std::vector<char> buffer;
	read_shader_src(fname, buffer);
	const char *src = &buffer[0];

	// Compile the shader
	GLuint shader = glCreateShader(shaderType);
	glShaderSource(shader, 1, &src, NULL);
	glCompileShader(shader);
	// Check the result of the compilation
	GLint test;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &test);
	if(!test) {
		std::cerr << "Shader compilation failed with this message:" << std::endl;
		std::vector<char> compilation_log(512);
		glGetShaderInfoLog(shader, compilation_log.size(), NULL, &compilation_log[0]);
		std::cerr << &compilation_log[0] << std::endl;
		glfwTerminate();
		exit(-1);
	}
	return shader;
}

// Create a program from two shaders
GLuint create_program(const char *path_vert_shader, const char *path_frag_shader) {
	// Load and compile the vertex and fragment shaders
	GLuint vertexShader = load_and_compile_shader(path_vert_shader, GL_VERTEX_SHADER);
	GLuint fragmentShader = load_and_compile_shader(path_frag_shader, GL_FRAGMENT_SHADER);

	// Attach the above shader to a program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);

	// Flag the shaders for deletion
	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	// Link and use the program
	glLinkProgram(shaderProgram);
	glUseProgram(shaderProgram);

	return shaderProgram;
}


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

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

	<groupId>com.jat</groupId>
	<artifactId>springbootyml</artifactId>
	<version>1.0</version>

	<name>${project.artifactId}</name>
	<url>http://www.jat168.com</url>

	<properties>
		<!-- 声明项目配置依赖编码格式为 utf-8 -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<!-- 编译UTF-8 -->
		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>

		<!-- java jdk 版本声明 可变更 根据自己配置去匹配 -->
		<java.version>1.8</java.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<maven.deploy.skip>true</maven.deploy.skip>
		<maven.install.skip>true</maven.install.skip>
		<!-- 解决pom头部unkonow错误 -->
		<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
	    <mavenCompilerPlugin.version>3.8.1</mavenCompilerPlugin.version>
		<mavenSurefirePlugin.version>2.22.2</mavenSurefirePlugin.version>

		<testng.version>7.5</testng.version>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.7</version>
		<relativePath />
		<!-- lookup parent from repository -->
	</parent>
	<dependencies>
		<!-- spring boot devtools 第一步添加依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>runtime</scope>
		</dependency>
		<!-- spring boot核心,包括自动配置支持,日志和YAML -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

		<!-- 对web开发的支持,包含了spring webmvc和tomcat等web开发的特性 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- 排除Tomcat依赖 -->
			<exclusions>
				<exclusion>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-undertow</artifactId>
		</dependency>
		<!-- TestNG start -->
		<!-- https://mvnrepository.com/artifact/org.testng/testng -->
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>${testng.version}</version>
		</dependency>
		<!-- TestNG end -->
		<!-- log4j start -->
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
		<!-- log4j end -->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${mavenCompilerPlugin.version}</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<!-- true:跳过测试 -->
					<skip>true</skip>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${mavenSurefirePlugin.version}</version>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>
			<!-- spring boot devtools 第二步添加maven插件 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>2.6.7</version>
				<configuration>
					<mainClass>com.jat.Application</mainClass>
					<!--fork如果没有该项配置,这个devtools不会起作用,即应用不会restart这个要手动加进去 -->
					<fork>true</fork>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
import {RestServiceBase, ViewModelBase, ApiModelBase} from "../../js/shared/restService";

export class ValuesService extends RestServiceBase {
    constructor($http, $q) {
        super($http, $q, "Values");
    }

    toViewModel(apiModel) {
        return ValueViewModel.fromApiModel(apiModel);
    };

    toApiModel(viewModel) {
        return viewModel
    };
}

class ValueViewModel extends ViewModelBase {
    constructor(id, name){
        super(id);
        this.name = name;
    }

    static fromApiModel(apiModel) {
        return new ValueViewModel(apiModel.Id, apiModel.Name);
    }
}


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

    <parent>
        <groupId>net.distilledcode.aem.samples</groupId>
        <artifactId>aem-sample-project-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../../aem-parent/pom.xml</relativePath>
    </parent>

    <artifactId>aem-sample-project-commons</artifactId>
    <packaging>bundle</packaging>

    <name>AEM Sample Project :: Commons Bundle</name>

    <build>
        <plugins>
            <!-- activate the maven-bundle-plugin, including its configurations from the parent -->
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
            </plugin>

            <!--
                activate the maven-scr-plugin, including its configurations from the parent
                the plugin can be omitted if no scr annotations are used, this may speed up the build
            -->
            <!-- <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin> -->

            <!-- activate the maven-sling-plugin to allow using the installBundle profile -->
            <plugin>
                <groupId>org.apache.sling</groupId>
                <artifactId>maven-sling-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

namespace Kunstmaan\NodeBundle\Tests\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Kunstmaan\NodeBundle\Entity\Node;
use Kunstmaan\NodeBundle\Entity\NodeIterator;
use PHPUnit\Framework\TestCase;

class NodeIteratorTest extends TestCase
{
    public function testNodeIterator()
    {
        $node1 = new Node();
        $node1->setId(1);
        $node2 = new Node();
        $node2->setId(2);
        $node3 = new Node();
        $node3->setId(3);
        $node4 = new Node();
        $node4->setId(4);

        $node1->setChildren(new ArrayCollection([$node4]));

        $collection = new ArrayCollection([
            $node1, $node2, $node3,
        ]);

        $iterator = new NodeIterator($collection);

        $this->assertTrue($iterator->valid());
        $this->assertTrue($iterator->hasChildren());
        $this->assertInstanceOf(NodeIterator::class, $iterator->getChildren());
        $this->assertInstanceOf(Node::class, $iterator->current());
        $iterator->next();

        $this->assertTrue($iterator->valid());
        $this->assertFalse($iterator->hasChildren());
        $this->assertEquals(1, $iterator->key());
        $iterator->next();

        $this->assertTrue($iterator->valid());
        $this->assertFalse($iterator->hasChildren());
        $iterator->next();

        $this->assertFalse($iterator->valid());
        $iterator->rewind();
    }
}


text:
<?php

namespace frontend\controllers;

use Yii;
use frontend\models\AntiCode;
use frontend\models\AntiReply;
use frontend\models\AntiCodeSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\models\AntiCodenew;
use yii\helpers\ArrayHelper;
use frontend\models\Product;
use yii\helpers\Url;
//use yii\db\Schema;
use frontend\models\TraceabilityInfonew;

/**
 * AnticodeController implements the CRUD actions for AntiCode model.
 */
class AnticodeController extends Controller
{
    public $layout='user';
 /*   public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
*/

    public function init(){
    //    $uid=Yii::$app->user->id;
      //  $tableCode='{{%anti_code_'.$uid.'}}';
        //$column='query_area';
   //     $type=Schema::TYPE_DOUBLE.'(10,6) NOT NULL';
     ///   $this->addColumn($tableCode,$column,$type);
    }

    protected function addColumn($table, $column, $type){

        $sql="Describe $table $column";
        $con=Yii::$app->db->createCommand($sql)->queryOne();
        if($con['Field']==null){
            Yii::$app->db->createCommand()->addColumn($table, $column, $type)->execute();
        }

    }

    /**
     * Lists all AntiCode models.
     * @return mixed
     */
    public function actionIndex()
    {
        $uid=Yii::$app->user->id;
        $dirPath = 'Uploads/' . $uid . '/GenQRcode/';
        if (!file_exists($dirPath)) {
            mkdir($dirPath, 0777, true);
        }

        $table='tbhome_anti_code_'.$uid;
        $ta=Yii::$app->db->createCommand("SHOW TABLES LIKE '".$table."'")->queryAll();
        if($ta==null){
            Yii::$app->getSession()->setFlash('danger', '请先生成防伪码!');
            return $this->redirect(['anti/gencode']);
        }else{
            $product=Product::find()->where(['uid'=>$uid])->all();

            $listProduct1=ArrayHelper::map($product, 'id', 'name');
            $listProduct2=ArrayHelper::map($product, 'id', 'specification');
            $listProduct=array();
            foreach($listProduct1 as $key1=>$value1){

                $listProduct[$key1]=$value1.' '.$listProduct2[$key1];
            }
            $listProduct['']='全部';

            $searchModel = new AntiCodeSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
                'listProduct' => $listProduct,
            ]);
        }
    }

    /**
     * Displays a single AntiCode model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    protected function listTraceability(){
        $uid=Yii::$app->user->id;
        $role=Yii::$app->user->identity->role;

        if ($role>=60){
            $traceaInfo='tbhome_traceability_info_'.$uid;
            $mobanInfo = 'tbhome_traceability_info';
            $sqlInfo = 'CREATE TABLE IF NOT EXISTS '.$traceaInfo.' LIKE '.$mobanInfo;
            $commandInfo=Yii::$app->db->createCommand($sqlInfo);
            $commandInfo->execute();

            $traceabiliy=TraceabilityInfonew::find()->all();
            $listTraceability=ArrayHelper::map($traceabiliy, 'id', 'label');
            if (!$listTraceability){
                Yii::$app->getSession()->setFlash('danger', '请先添加追溯信息!');
                return $this->redirect(['traceabilityinfo/create']);
            }else{
                return $listTraceability;
            }

        }else{
           return array();
        }

    }

    /**
     * Creates a new AntiCode model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {

        $model = new AntiCodenew();
        $uid=Yii::$app->user->id;
        $model->uid=$uid;
        $model->create_time=time();
        //     $model->clicks=3;
        //    $model->query_time=time()-(3600*24);

        $reply=AntiReply::find()->where(['uid'=>$uid])->all();
        $listReply=ArrayHelper::map($reply, 'id', 'tag');
//        $list2=ArrayHelper::map($reply, 'id', 'specification');
        //      $listReply=array();
//        foreach($list1 as $key1=>$value1){
        //          $listReply[$key1]=$value1.' '.$list2[$key1];
        //       }

        //>=60质量追溯
     $listTraceability=$this->listTraceability();

        $product=Product::find()->where(['uid'=>$uid])->all();
        $listData1=ArrayHelper::map($product, 'id', 'name');
        $listData2=ArrayHelper::map($product, 'id', 'specification');
        $listProduct=array();
        foreach($listData1 as $key1=>$value1){
            $listProduct[$key1]=$value1.' '.$listData2[$key1];
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'listReply'=>$listReply,
                'listProduct'=>$listProduct,
                'listTraceability'=>$listTraceability,
            ]);
        }
    }

    /**
     * Updates an existing AntiCode model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $uid=Yii::$app->user->id;
        $model->uid=$uid;

        $reply=AntiReply::find()->where(['uid'=>$uid])->all();
        $listReply=ArrayHelper::map($reply, 'id', 'tag');
//        $list2=ArrayHelper::map($reply, 'id', 'specification');
  //      $listReply=array();
//        foreach($list1 as $key1=>$value1){
  //          $listReply[$key1]=$value1.' '.$list2[$key1];
//        }

        $product=Product::find()->where(['uid'=>$uid])->all();
        $listData1=ArrayHelper::map($product, 'id', 'name');
        $listData2=ArrayHelper::map($product, 'id', 'specification');
        $listProduct=array();
        foreach($listData1 as $key1=>$value1){

            $listProduct[$key1]=$value1.' '.$listData2[$key1];
        }

        //>=60质量追溯
        $listTraceability=$this->listTraceability();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'listReply'=>$listReply,
                'listProduct'=>$listProduct,
                'listTraceability'=>$listTraceability,
            ]);
        }
    }

    /**
     * Deletes an existing AntiCode model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the AntiCode model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AntiCode the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AntiCodenew::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionExcelall(){

        $objPHPExcel=new \PHPExcel();
        $objPHPExcel->getProperties()  //获得文件属性对象,给下文提供设置资源
        ->setCreator( "798904845")                 //设置文件的创建者
        ->setLastModifiedBy( "Maarten Balliauw")          //设置最后修改者
        ->setTitle( "Office 2007 XLSX Test Document" )    //设置标题
        ->setSubject( "Office 2007 XLSX Test Document" )  //设置主题
        ->setDescription( "Test document for Office 2007 XLSX, generated using PHP classes.") //设置备注
        ->setKeywords( "office 2007 openxml php")        //设置标记
        ->setCategory( "Test result file");

        $objPHPExcel->setActiveSheetIndex(0);
        $objActivSheet=$objPHPExcel->getActiveSheet();
        $objActivSheet->setCellValue('A1', '防伪码')
            ->setCellValue('B1', '创建时间')
            ->setCellValue('C1', '查询时间')
            ->setCellValue('D1', '点击量')
            ->setCellValue('E1', '奖品')
            ->setCellValue('F1', '备注')
            ->setCellValue('G1', '网址')
            ->setCellValue('H1', '序号');

        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
            $start=$_POST['start'];
            $end=$_POST['end'];
            $data=AntiCodenew::find()->where('id>='.$start.' AND id<='.$end);
            $num=$data->count();
            $data= $data->all();
        }else{

            $data=AntiCodenew::find();//->asArray();
            $num=$data->count();
            $data= $data->all();
        }
        for($i=2; $i<($num+2); $i++){
            $arrid=$i-2;
            $createTime=date('Y-m-d H:m:s', $data[$arrid]->create_time);
            $queryTime =$data[$arrid]->query_time==0 ? 0 : date('Y-m-d H:m:s', $data[$arrid]->query_time);

            $url=Url::to([
                '/anti/antipage',
                'replyid'=>$data[$arrid]->replyid,
              //  'productid'=>$data[$arrid]->productid,
                'code'=>$data[$arrid]->code
            ], true);

            $objActivSheet->setCellValue('A'.$i, $data[$arrid]->code)
                ->setCellValue('B'.$i, $createTime)
                ->setCellValue('C'.$i, $queryTime)
                ->setCellValue('D'.$i, $data[$arrid]->clicks)
                ->setCellValue('E'.$i, $data[$arrid]->prize)
                ->setCellValue('F'.$i, $data[$arrid]->remark)
                ->setCellValue('G'.$i, $url)//->setCellValue('G'.$i, $data[$arrid]->url)
                ->setCellValue('H'.$i, $data[$arrid]->id);
        }

        $objActivSheet->setTitle('AntiCode');
        $name='Anticode';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }

    public function actionGenimage(){

    //    require(__DIR__ . '/../assets/phpqrcode/qrlib.php');
        $uid = Yii::$app->user->id;

        if (is_numeric($_POST['start']) && is_numeric($_POST['end']) && ($_POST['end'] > $_POST['start'])) {

            $date = date('Y_m_d_Hms_', time());
            $rand = rand();
            $dirPath = 'Uploads/' . $uid . '/GenQRcode/' . $date . $rand . '/';
            if (!file_exists($dirPath)) {
                mkdir($dirPath, 0777, true);
            }

            $start = $_POST['start'];
            $end = $_POST['end'];
            $data = AntiCodenew::find()->where('id>=' . $start . ' AND id<=' . $end);
            $num = $data->count();
            $data = $data->all();

            for ($i = 0; $i < $num; $i++) {
                //   $url = $data[$i]->url;
                $url=Url::to([
                    '/anti/antipage',
                    'replyid'=>$data[$i]->replyid,
                 //   'productid'=>$data[$i]->productid,
                    'code'=>$data[$i]->code
                ], true);

                $id = $data[$i]->id;
                \QRcode::png($url, $dirPath . $id . '.png', 'M', 6, 1);
            }

            //         $dirPath = 'Uploads/' . $uid . '/GenQRcode/' . $date . $rand. '/';

            $dir = opendir($dirPath);
            $filename = 'Uploads/' . $uid . '/GenQRcode/' . 'image' . time() . '_' . $rand . '.zip';
            $zip = new \ZipArchive;
           // $file = readdir($dir);
            if ($zip->open($filename, \ZipArchive::CREATE) === TRUE) {
                while (($file = readdir($dir)) !== false) {
              //  while ($file) {
                    if ($file !== "." && $file !== "..") {//文件夹文件名字为'.'和'..',不要对他们进行操作
                        $zip->addFile($dirPath.$file);//假设加入的文件名是image.txt,在当前路径下
                    }
                }

            }

            $zip->close();
     //    while(($file = readdir($dir)) !== false){unlink($dirPath.$file);}
          //  rmdir($dirPath);
            closedir($dir);

            //循环删除目录和文件函数
            function delDirAndFile( $dirName )
            {
                if ( $handle = opendir( "$dirName" ) ) {
                    while ( false !== ( $item = readdir( $handle ) ) ) {
                        if ( $item != "." && $item != ".." ) {
                            if ( is_dir( "$dirName/$item" ) ) {
                                delDirAndFile( "$dirName/$item" );
                            } else {
                                if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item
\n";
                            }
                        }
                    }
                    closedir( $handle );
                    if( rmdir( $dirName ) )echo "成功删除目录: $dirName
\n";
                }
            }

       //     $uid = Yii::$app->user->id;
       //     $dirPath = 'Uploads/' . $uid . '/GenQRcode';

//文件的类型
            header('Content-type: application/zip');
//下载显示的名字
            header('Content-Disposition: attachment; filename="QRcodeImage.zip"');
            readfile($filename);
  delDirAndFile($dirPath);
            //  $this->redirect(['index']);
            //    Yii::$app->getSession()->setFlash('success', '已生产二维码图片' . $num . '张, 目录' . $dirPath);
            exit();

        }else{
            Yii::$app->getSession()->setFlash('danger', '防伪码序号输入错误');

        }

    }

}


text:
namespace remoting {

// A class for getting an OAuth authorization code.
class AuthCodeGetter : public base::NonThreadSafe {
 public:
  AuthCodeGetter();
  ~AuthCodeGetter();

  // Starts a browser and navigates it to a URL that starts an Installed
  // Application OAuth flow. |on_auth_code| will be called with an
  // authorization code, or an empty string on error.
  void GetAuthCode(base::Callback<void(const std::string&)> on_auth_code);

 private:
  // Starts a timer used to poll the browser's URL.
  void StartTimer();
  // Called when that timer fires.
  void OnTimer();
  // Returns whether to stop polling the browser's URL. If true, then
  // |auth_code| is an authorization code, or the empty string on an error.
  bool TestBrowserUrl(std::string* auth_code);
  // Kills the browser.
  void KillBrowser();

  // The authorization code callback.
  base::Callback<void(const std::string&)> on_auth_code_;
  // The browser through which the user requests an authorization code.
  base::win::ScopedComPtr<IWebBrowser2, &IID_IWebBrowser2> browser_;
  // A timer used to poll the browser's URL.
  base::OneShotTimer<AuthCodeGetter> timer_;
  // The interval at which the timer fires.
  base::TimeDelta timer_interval_;

  DISALLOW_COPY_AND_ASSIGN(AuthCodeGetter);
};

}  // namespace remoting

#endif  // REMOTING_HOST_SETUP_WIN_AUTH_CODE_GETTER_H


text:
Turbulenz SDK 0.23.1
--------------------

.. highlight:: javascript

Summary
=======

Turbulenz SDK 0.23.1 is an update for both the Turbulenz Engine
Installer and SDK components.

Change List
===========

New Features
------------

**0.23.0**

* Support for Internet Explorer 10 has now been added.

* Support has been added in Turbulenz Services for play before sign-in.
  Games that are built with this version of the SDK will automatically support play before sign-in, when available on turbulenz.com

Fixed
-----

**0.23.1**

* Fix for cases where game could make calls to `InputDevice` which
  should fail, but resulted in mouse cursor being hidden outside of
  the plugin window.

* Issue where listeners were being called multiple times on Firefox canvas after going fullscreen (T1234).

* InputApp canvas configuration now runs in WebGL. Allows fullscreen mode to be set.

**0.23.0**

* In previous versions, calls to Turbulenz.setInterval() in plugin
  mode could generate callbacks at 60Hz independent of the interval
  value passed in.  This has been fixed.

* The previous version of the Turbulenz Engine installer (0.22.0) for
  Mac OS X unconditionally replaces parts of existing plugins, even if
  a newer plugin is already installed.  This has been fixed, but users
  installing 0.22.0 *after* later versions of the engine should be
  aware of this behavior and should ensure that they (re)install the
  newest Turbulenz Engine *after* 0.22.0 if they wish to continue
  using the 0.22.0 engine alongside newer versions.

* Callbacks from the `NetworkDevice` are now called asynchronously,
  fixing an inconsistency between the canvas and plugin versions.

* Sending of websocket data >8kb was being incorrectly buffered in the plugin (T1221)

Known Issues
============

New
---

* An implementation difference between canvas and plugin GraphicsDevice implementations has been observed:

    * WebGL clears the back buffer after a present.
    * WebGL clears all created buffers.

    Not all platforms will demonstrate the same behaviour in the plugin.
    To ensure consistent behaviour you should clear all relevant buffers and not rely on the WebGL behaviour.

    For more information see :ref:`Graphics Device <graphicsdevice>`

* SVG sample fails to run in Internet Explorer 10

Unchanged
---------

For a list of current known issues see the :ref:`known issues section <known_issues>`.


text:
using SudokuSolver.Workers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SudokuSolver.Strategies
{
    class SimpleMarkUpStrategy : ISudokuStrategy
    {
        private readonly SudokuMapper _sudokuMapper;

        public SimpleMarkUpStrategy(SudokuMapper sudokuMapper)
        {
            _sudokuMapper = sudokuMapper;
        }

        public int[,] Solve(int[,] sudokuBoard)
        {
            for (int row = 0; row < sudokuBoard.GetLength(0); row++)
            {
                for (int col = 0; col < sudokuBoard.GetLength(1); col++)
                {
                    if (sudokuBoard[row, col] == 0 || sudokuBoard[row, col].ToString().Length > 1)
                    {
                        var possibilitiesInRowAndCol = GetPossibilitiesInRowAndCol(sudokuBoard, row, col);
                        var possibilitiesInBlock = GetPossibilitiesInBlock(sudokuBoard, row, col);
                        sudokuBoard[row, col] = GetPossibilityIntersection(possibilitiesInRowAndCol, possibilitiesInBlock);
                    }
                }
            }

            return sudokuBoard;
        }

        private int GetPossibilitiesInRowAndCol(int[,] sudokuBoard, int givenRow, int givenCol)
        {
            int[] possibilities = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            for (int col = 0; col < 9; col++) if (IsValidSingle(sudokuBoard[givenRow, col])) possibilities[sudokuBoard[givenRow, col] - 1] = 0;
            for (int row = 0; row < 9; row++) if (IsValidSingle(sudokuBoard[row, givenCol])) possibilities[sudokuBoard[row, givenCol] - 1] = 0;

            return Convert.ToInt32(String.Join(string.Empty, possibilities.Select(p => p).Where(p => p != 0)));
        }

        private int GetPossibilitiesInBlock(int[,] sudokuBoard, int givenRow, int givenCol)
        {
            int[] possibilities = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            var sudokuMap = _sudokuMapper.Find(givenRow, givenCol);

            for (int row = sudokuMap.StartRow; row <= sudokuMap.StartRow + 2; row++)
            {
                for (int col = sudokuMap.StartCol; col <= sudokuMap.StartCol + 2; col++)
                {
                    if (IsValidSingle(sudokuBoard[row, col])) possibilities[sudokuBoard[row, col] - 1] = 0;
                }
            }

            return Convert.ToInt32(String.Join(string.Empty, possibilities.Select(p => p).Where(p => p != 0)));
        }

        private bool IsValidSingle(int cellDigit)
        {
            return cellDigit != 0 && cellDigit.ToString().Length == 1;
        }

        private int GetPossibilityIntersection(int possibilitiesInRowAndCol, int possibilitiesInBlock)
        {
            var possibilitiesInRowAndColCharArray = possibilitiesInRowAndCol.ToString().ToCharArray();
            var possibilitiesInBlockCharArray = possibilitiesInBlock.ToString().ToCharArray();
            var possibilitiesSubset = possibilitiesInRowAndColCharArray.Intersect(possibilitiesInBlockCharArray);
            return Convert.ToInt32(string.Join(string.Empty, possibilitiesSubset));
        }
    }
}


text:
from telemetry import decorators
from telemetry.internal.actions import loop
from telemetry.testing import tab_test_case

import py_utils

AUDIO_1_LOOP_CHECK = 'window.__hasEventCompleted("#audio_1", "loop");'
VIDEO_1_LOOP_CHECK = 'window.__hasEventCompleted("#video_1", "loop");'

class LoopActionTest(tab_test_case.TabTestCase):

  def setUp(self):
    tab_test_case.TabTestCase.setUp(self)
    self.Navigate('video_test.html')

  # crbug.com/749890
  @decorators.Disabled('android', 'linux', 'chromeos')
  def testLoopWithNoSelector(self):
    """Tests that with no selector Loop action loops first media element."""
    action = loop.LoopAction(loop_count=2, selector='#video_1',
                             timeout_in_seconds=10)
    action.WillRunAction(self._tab)
    action.RunAction(self._tab)
    # Assert only first video has played.
    self.assertTrue(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
    self.assertFalse(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK))

  # crbug.com/749890
  @decorators.Disabled('android', 'linux', 'chromeos')
  def testLoopWithAllSelector(self):
    """Tests that Loop action loops all video elements with selector='all'."""
    action = loop.LoopAction(loop_count=2, selector='all',
                             timeout_in_seconds=10)
    action.WillRunAction(self._tab)
    # Both videos not playing before running action.
    self.assertFalse(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
    self.assertFalse(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK))
    action.RunAction(self._tab)
    # Assert all media elements played.
    self.assertTrue(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
    self.assertTrue(self._tab.EvaluateJavaScript(AUDIO_1_LOOP_CHECK))

  # crbug.com/749890
  @decorators.Disabled('android', 'linux', 'chromeos')
  def testLoopWaitForLoopTimeout(self):
    """Tests that wait_for_loop timeout_in_secondss if video does not loop."""
    action = loop.LoopAction(loop_count=2, selector='#video_1',
                             timeout_in_seconds=1)
    action.WillRunAction(self._tab)
    self.assertFalse(self._tab.EvaluateJavaScript(VIDEO_1_LOOP_CHECK))
    self.assertRaises(py_utils.TimeoutException, action.RunAction, self._tab)


text:
using Assets.Gamelogic.Core;
using Assets.Gamelogic.Utils;
using Improbable;
using Improbable.Abilities;
using Improbable.Collections;
using Improbable.Core;
using Improbable.Fire;
using Improbable.Unity;
using Improbable.Unity.Core;
using Improbable.Unity.Visualizer;
using UnityEngine;

namespace Assets.Gamelogic.Abilities
{
    [EngineType(EnginePlatform.FSim)]
    public class SpellsBehaviour : MonoBehaviour
    {
        [Require] private Spells.Writer spells;

        private Collider[] spellTargets;
        private Coroutine reduceCooldownsCoroutine;

        private void OnEnable()
        {
            spellTargets = new Collider[SimulationSettings.MaxSpellTargets];
            spells.CommandReceiver.OnSpellCastRequest += OnSpellCastRequest;
            reduceCooldownsCoroutine = StartCoroutine(TimerUtils.CallRepeatedly(1f, ReduceCooldowns));
        }

        private void OnDisable()
        {
            spells.CommandReceiver.OnSpellCastRequest -= OnSpellCastRequest;
            CancelExistingReduceCooldownsCoroutine();
        }

        private void CancelExistingReduceCooldownsCoroutine()
        {
            if (reduceCooldownsCoroutine != null)
            {
                StopCoroutine(reduceCooldownsCoroutine);
                reduceCooldownsCoroutine = null;
            }
        }

        private void OnSpellCastRequest(Improbable.Entity.Component.ResponseHandle<Spells.Commands.SpellCastRequest, SpellCastRequest, Nothing> request)
        {
            CastSpell(request.Request.spellType, request.Request.position.ToVector3());
            request.Respond(new Nothing());
        }

        public void CastSpell(SpellType spellType, Vector3 position)
        {
            if (!spells.Data.canCastSpells || spells.Data.cooldowns[spellType] > 0f)
            {
                return;
            }
            var targetCount = FindSpellTargetEntities(position);
            ApplySpellEffectOnTargets(spellType, targetCount);
            spells.Send(new Spells.Update().AddSpellAnimationEvent(new SpellAnimationEvent(spellType, position.ToCoordinates())));
            SetSpellCooldown(spellType, SimulationSettings.SpellCooldown);
        }

        private int FindSpellTargetEntities(Vector3 position)
        {
            return Physics.OverlapCapsuleNonAlloc(position, position + Vector3.up * 10f, SimulationSettings.PlayerSpellAOEDiameter * 0.5f, spellTargets);
        }

        private void ApplySpellEffectOnTargets(SpellType spellType, int targetCount)
        {
            for (var spellTargetIndex = 0; spellTargetIndex < targetCount; spellTargetIndex++)
            {
                var targetEntityId = spellTargets[spellTargetIndex].gameObject.EntityId();
                if (targetEntityId != EntityId.InvalidEntityId)
                {
                    switch (spellType)
                    {
                        case SpellType.LIGHTNING:
                            SpatialOS.Commands.SendCommand(spells, Flammable.Commands.Ignite.Descriptor, new Nothing(), targetEntityId, _ => { });
                            break;
                        case SpellType.RAIN:
                            SpatialOS.Commands.SendCommand(spells, Flammable.Commands.Extinguish.Descriptor, new ExtinguishRequest(true), targetEntityId, _ => { });
                            break;
                    }
                }
            }
        }

        private void SetSpellCooldown(SpellType spellType, float value)
        {
            var cooldowns = new Map<SpellType, float>(spells.Data.cooldowns);
            cooldowns[spellType] = value;
            spells.Send(new Spells.Update().SetCooldowns(cooldowns));
        }

        private void ReduceCooldowns()
        {
            var cooldowns = new Map<SpellType, float>(spells.Data.cooldowns);
            var enumerator = cooldowns.Keys.GetEnumerator();
            var componentNeedsUpdate = false;
            while (enumerator.MoveNext())
            {
                if (cooldowns[enumerator.Current] > 0f)
                {
                    cooldowns[enumerator.Current] = Mathf.Max(cooldowns[enumerator.Current] - 1f, 0f);
                    componentNeedsUpdate = true;
                }
            }
            if (componentNeedsUpdate)
            {
                spells.Send(new Spells.Update().SetCooldowns(cooldowns));
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LogicaDeNegocios
{
    public partial class LogicaDeNegocios_SignalDB : files.IFilesLogicaDeNegocios
    {
        Dominio.Querys.files.IFilesQuery filesQuerys = new Dominio.Querys.Querys();

        public int InsertarFiles(Dominio.Dtos.filesDTO dto)
        {
            try
            {
                return filesQuerys.InsertarFiles(dto);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }

        public bool ActualizarFiles(Dominio.Dtos.filesDTO dto)
        {
            try
            {
                return filesQuerys.ActualizarFiles(dto);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }

        public bool EliminarFiles(int id)
        {
            try
            {
                return filesQuerys.EliminarFiles(id);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }

        public Dominio.Dtos.filesDTO BuscarFiles(int id)
        {
            try
            {
                return filesQuerys.BuscarFiles(id);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }

        public List<Dominio.Dtos.filesDTO> ListarFiles(string param)
        {
            try
            {
                return filesQuerys.ListarFiles(param);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>cnf: Cnf Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Namespace List

Classes |
Typedefs

Cnf Namespace Reference

Classes

struct  	feature_t

struct  	fbnode

class  	Cnflearn

struct  	viterbinode

class  	Cnftagger

Typedefs

typedef struct Cnf::viterbinode 	vnode

Detailed Description

Conditional Neural Fields with FOLOS Copyright (C) 2010 - Kei Uchiumi

Implementation of Conditional Neural Fields with FOLOS. Jian Peng, Liefeng Bo and Jinbo Xu. "Conditional Neural Fields". The 23rd Annual Conference on Neural Information Processing Systems (NIPS 2009) John Duchi and Yoram Singer. "Online and Batch Learning using Forward Backward Splitting". Journal of Machine Learning Research (JMLR 2009) and Neural Information Processing Systems (NIPS 2009).

 All Classes Namespaces Functions Variables

<address class="footer">Generated on Sat Jul 24 2010 21:38:18 for cnf by

 1.7.1 </address>


text:
package com.acme;

import static org.junit.Assert.*;
import static org.springframework.xd.dirt.test.process.SingleNodeProcessingChainSupport.*;

import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

import org.springframework.xd.dirt.plugins.ModuleConfigurationException;
import org.springframework.xd.dirt.server.singlenode.SingleNodeApplication;
import org.springframework.xd.dirt.test.SingleNodeIntegrationTestSupport;
import org.springframework.xd.dirt.test.SingletonModuleRegistry;
import org.springframework.xd.dirt.test.process.SingleNodeProcessingChain;
import org.springframework.xd.module.ModuleType;
import org.springframework.xd.test.RandomConfigurationSupport;

/**
 * Unit tests a module deployed to an XD single node container.
 */
public class ExampleModuleIntegrationTest {

	private static SingleNodeApplication application;

	private static int RECEIVE_TIMEOUT = 5000;

	private static String moduleName = "siDslModule";

	SingleNodeProcessingChain chain;

	/**
	 * Start the single node container, binding random unused ports, etc. to not conflict with any other instances
	 * running on this host. Configure the ModuleRegistry to include the project module.
	 */
	@BeforeClass
	public static void setUp() {
		RandomConfigurationSupport randomConfigSupport = new RandomConfigurationSupport();
		application = new SingleNodeApplication().run();
		SingleNodeIntegrationTestSupport singleNodeIntegrationTestSupport = new SingleNodeIntegrationTestSupport
				(application);
		singleNodeIntegrationTestSupport.addModuleRegistry(new SingletonModuleRegistry(ModuleType.processor,
				moduleName));

	}

	/**
	 * Each test creates a stream with the module under test, or in general a "chain" of processors. The
	 * SingleNodeProcessingChain is a test fixture that allows the test to send and receive messages to verify each
	 * message is processed as expected.
	 */
	@Test
	public void testDefault() {
		String prefix = "foo";
		String suffix = "bar";
		String streamName = "testDefault";

		String processingChainUnderTest = String.format("%s --prefix=%s --suffix=%s", moduleName, prefix, suffix);

		chain = chain(application, streamName, processingChainUnderTest);

		chain.sendPayload("hello");
		String result = (String) chain.receivePayload(RECEIVE_TIMEOUT);
		assertEquals(prefix + "hello" + suffix, result);
	}

	@Test
	public void testPrefixOnly() {
		String prefix = "foo";
		String suffix = "bar";
		String streamName = "testPrefixOnly";

		String processingChainUnderTest = String.format("%s --prefix=%s --prefixOnly=true", moduleName, prefix);

		chain = chain(application, streamName, processingChainUnderTest);

		chain.sendPayload("hello");
		String result = (String) chain.receivePayload(RECEIVE_TIMEOUT);
		assertEquals(prefix + "hello", result);
	}

	@Test(expected = ModuleConfigurationException.class)
	public void testPrefixAndSuffixCannotBeTheSame() throws Exception {
		String prefix = "foo";
		String suffix = "foo";
		String streamName = "testPrefixNotSameAsSuffix";

		String processingChainUnderTest = String.format("%s --prefix=%s --suffix=%s", moduleName, prefix, suffix);
		chain = chain(application, streamName, processingChainUnderTest);
	}

	/**
	 * Destroy the chain to reset message bus bindings and destroy the stream.
	 */
	@After
	public void tearDown() {
		if (chain != null) {
			chain.destroy();
		}
	}
}


text:
import {ResourceLoader} from '@angular/compiler/src/resource_loader';

import {SpyObject} from '@angular/core/testing/src/testing_internal';

export class SpyResourceLoader extends SpyObject {
  constructor() { super(ResourceLoader); }
}


text:
@implementation FMMoveTableViewCell

- (void)prepareForMoveSnapshot
{
    // Should be implemented by subclasses if needed
}

- (void)prepareForMove
{
    self.textLabel.text = @"";
    self.detailTextLabel.text = @"";
    self.imageView.image = nil;
}

@end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package w2p1_Menu;

import java.util.Scanner;
/**
 *
 * @author Georgi Spasov
 */
public class ComputeByMenu {

    Scanner input = new Scanner (System.in);
    private double x;

    public ComputeByMenu(double num) {
        if (num == 0) {
            x = 0;
        } else {
            x = num;
        }
    }

    public void displayMenu() {
        for (int i = 0; i <= 60; i++) {
            System.out.println("");
        }
        System.out.println("Menu\nEnter the number of your choice\n"
                + "1. Enter number x with floating point\n"
                + "2. Calculate and print exp(x)\n"
                + "3. Calculate and print sin(x)\n"
                + "4. Calculate and print floor(x)\n"
                + "5. End");
    }

    public void doSelection(int choice) {
        while (choice != 5) {
            choice = input.nextInt();

            switch (choice) {
                case 1:
                    System.out.print("Enter number x with floating point: ");
                    x = input.nextDouble();
                    break;
                case 2:
                    System.out.printf("exp(x) = %f", Math.exp(x));
                    break;
                case 3:
                    System.out.printf("sin(x) = %f", Math.sin(x));
                    break;
                case 4:
                    System.out.printf("floor(x) = %f", Math.floor(x));
                    break;
                case 5:
                    System.out.println("End");
                    break;
                default:
                    System.out.println("Enter a valid choice.");
            }

            if (choice != 5) {
                System.out.println("\nEnter your next choice:");
            }
        }
    }

    public void getUserChoice() {
        displayMenu();
        doSelection(0);
    }
}


text:
@annotate: folktale.core.object.mapValues
category: Transforming
---
Transforms values of an object with an unary function.

The transformation works on the values of each own, enumerable
property of the given object. Inherited and non-enumerable
properties are ignored by this function.

## Example::

    const mapValues = require('folktale/core/object/map-values');

    const pair = { x: 10, y: 20 };
    mapValues(pair, x => x * 2);
    // ==> { x: 20, y: 40 }

## Caveats

`mapValues` will not preserve the shape of the original object.
It treats objects as plain maps from String to some value, and
ignores things like prototypical delegation, symbols, and non-enumerable
properties.

@annotate: folktale.core.object.mapValues.infix
category: Convenience
---
Conveniently transforms values in an object using the This-Binding syntax.

This is a free-method version of `mapValues` that applies the `this`
argument first, then the function it takes as argument. It's meant to
be used with the [This-Binding Syntax][es-bind] proposal::

    const map = require('folktale/core/object/map-values').infix;

    const pair = { x: 10, y: 20 };
    pair::map(x => x * 2);
    // ==> { x: 20, y: 40 }

[es-bind]: https://github.com/zenparsing/es-function-bind


text:
- `:default` is a pseudo-class selector used to select and style one or more UI elements that are the default among a set of similar elements.
- This selector typically applies to context menu items, buttons, and select lists/menus.

#### Case 1: default submit buttons

- Button inputs and buttons of type="submit" are considered one group, and therefore the first of them is the default.

```html
<input type="submit" value="Submit (<input>)">
<button type="submit">Submit (<Button>)</button>
```

```css
input[type="submit"] {
    color: #fff;
    border-radius: 4px;
    background-color: #f0f0f0;
}

input[type="submit"]:default {
    background-color: #a10000;
}

button[type="submit"] {
    color: #fff;
    border-radius: 4px;
    background-color: #f0f0f0;
}

button[type="submit"]:default {
    background-color: #a10000;
}
```

See the Pen xZXOxQ by aleen42 (@aleen42) on CodePen.

#### Case 2: default checkboxes and radio buttons

- Elements selected by `:default` also include checked checkboxes and radio buttons that have the **checked** attribute set, and options in a select menu that have the **selected** attribute set.

```html
<input type="radio" id="box-1"><label for="box-1">default radio buttons</label>
<input type="checkbox" id="box-2"><label for="box-2">default checkboxes</label>
```

```css
input[type="checkbox"]:default + label {
    text-decoration: underline;
}

input[type="checkbox"]:default + label {
    text-decoration: underline;
}
```

See the Pen MKEejV by aleen42 (@aleen42) on CodePen.


text:
package com.cloud.network.vpc;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.cloudstack.api.InternalIdentity;

@Entity
@Table(name = "private_ip_address")
public class PrivateIpVO implements InternalIdentity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    long id;

    @Column(name = "ip_address", updatable = false, nullable = false)
    String ipAddress;

    @Column(name = "mac_address")
    private long macAddress;

    @Column(name = "taken")
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date takenAt;

    @Column(name = "network_id", updatable = false, nullable = false)
    private long networkId;

    @Column(name = "vpc_id")
    private Long vpcId;

    @Column(name = "source_nat")
    private boolean sourceNat;

    public PrivateIpVO() {
    }

    public PrivateIpVO(String ipAddress, long networkId, long macAddress, long vpcId, boolean sourceNat) {
        this.ipAddress = ipAddress;
        this.networkId = networkId;
        this.macAddress = macAddress;
        this.vpcId = vpcId;
        this.sourceNat = sourceNat;
    }

    public void setTakenAt(Date takenDate) {
        this.takenAt = takenDate;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public long getNetworkId() {
        return networkId;
    }

    public Date getTakenAt() {
        return takenAt;
    }

    @Override
    public long getId() {
        return id;
    }

    public long getMacAddress() {
        return macAddress;
    }

    public Long getVpcId() {
        return vpcId;
    }

    public boolean getSourceNat() {
        return sourceNat;
    }

}


text:
author: slowe
categories: News
comments: true
date: 2009-12-04T13:33:36Z
slug: multiport-uplink-driver
tags:
- Networking
- Virtualization
- VMware
- vSphere
title: Multiport Uplink Driver
url: /2009/12/04/multiport-uplink-driver/
wordpress_id: 1762
---

Virtual I/O is getting more attention. [This press release](http://www.chelsio.com/pr_120409.html) from Chelsio crossed my desk this morning:

>Virtual Multi-port Software allows for consolidation of switch ports and cabling by using 10Gb infrastructure while maintaining the existing Gigabit-based ESX setup.  The software enables the consolidation by keeping the infrastructure update completely transparent to the ESX hypervisor, enabling a 10Gb adapter to appear to the hypervisor as eight virtual Gigabit adapters.  By offloading the tasks performed by the hypervisor, the Chelsio adapters can deliver the best I/O performance for virtualized applications.

There's no mention of SR-IOV (more information on SR-IOV is available in [this post][1]), so I'm guessing that this is a proprietary technology similar to what HP is using in Virtual Connect Flex-10. The key difference with HP Virtual Connect Flex-10 and the Chelsio solution is that Flex-10 doesn't require _any_ software support in the OS or hypervisor, whereas Chelsio's solution does require software support (as does SR-IOV). Nevertheless, it's clear that I/O virtualization---even relatively simple forms of I/O virtualization such as this---is gaining more and more attention.

[1]: {{< relref "2009-12-02-what-is-sr-iov.md" >}}


text:
% controls for creating the adaptive importance sampling density
iters = 8;
initialparticles = nworkers*round(300/nworkers); % number to take from sample from prior
nparticles = nworkers*round(300/nworkers); % number per round
particlequantile = 20; % keep the top % of particles
verbose = false;
% controls for drawing the final sample from mixture of AIS and prior
mixture = 0.2; % proportion sampled from original prior
AISdraws = nworkers*round(5000/nworkers); # number of draws from final AIS density


text:
BSLS_IDENT_RCSID(bdlma_multipoolallocator_cpp,"$Id$ $CSID$")

#include <bdlma_bufferedsequentialallocator.h>  // for testing only

#include <bsls_performancehint.h>

namespace BloombergLP {
namespace bdlma {

                     // ------------------------
                     // class MultipoolAllocator
                     // ------------------------

// CREATORS
MultipoolAllocator::~MultipoolAllocator()
{
}

// MANIPULATORS
void MultipoolAllocator::reserveCapacity(size_type size, size_type numObjects)
{
    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == size)) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;
        return;                                                       // RETURN
    }

    d_multipool.reserveCapacity(size, numObjects);
}

}  // close package namespace
}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2012 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------