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

namespace Codaxy.Common
{
    public static class NullableMath
    {
        public static decimal? Abs(decimal? value)
        {
            return value.HasValue ? Math.Abs(value.Value) : value;
        }

        public static decimal? Round(decimal? value, int decimals, MidpointRounding rounding)
        {
            return value.HasValue ? Math.Round(value.Value, decimals, rounding) : value;
        }

        public static decimal? Round(decimal? value, int decimals)
        {
            return value.HasValue ? Math.Round(value.Value, decimals) : value;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Quick Equations Options</title>
    <link rel="stylesheet" href="popup.css">

Quick Equations

Options

      <form style="text-align: left">
        <input id="enableWebwork" type="checkbox">
        Show on pages with WeBWorK

        <input id="enableGoogleForms" type="checkbox">
        Show on Google Forms
      </form>


text:
namespace arangodb {
namespace application_features {
class ApplicationServer;
}

class GreetingsFeature final : public application_features::ApplicationFeature {
 public:
  explicit GreetingsFeature(application_features::ApplicationServer& server);

 public:
  void prepare() override final;
  void unprepare() override final;
};

}  // namespace arangodb


text:
<?php

require_once __DIR__ . '/../bootstrap.php';

$observable = new Rx\Observable\ArrayObservable(array(21, 42, 21, 42, 21, 42));
$observable
    ->groupBy(
        function($elem) {
            if ($elem === 42) {
                return 0;
            }

            return 1;
        },
        null,
        function($key){ return $key; }
    )
    ->subscribeCallback(function($groupedObserver) use ($createStdoutObserver) {
        $groupedObserver->subscribe($createStdoutObserver($groupedObserver->getKey() . ": "));
    });


text:
class PostHistory < ActiveRecord::Base
  belongs_to :post_history_type
  belongs_to :user
  belongs_to :post, :polymorphic => true

  def self.question_edited(question, user)
    self.new_question_event('Edit', question, user)
  end

  def self.question_deleted(question, user)
    self.new_question_event('Delete', question, user)
  end

  def self.question_undeleted(question, user)
    self.new_question_event('Undelete', question, user)
  end

  def self.question_closed(question, user)
    self.new_question_event('Close', question, user)
  end

  def self.question_reopened(question, user)
    self.new_question_event('Reopen', question, user)
  end

  def self.answer_edited(answer, user)
    self.new_answer_event('Edit', answer, user)
  end

  def self.answer_deleted(answer, user)
    self.new_answer_event('Delete', answer, user)
  end

  def self.answer_undeleted(answer, user)
    self.new_answer_event('Undelete', answer, user)
  end

  private
    def self.new_question_event(type_name, question, user)
      event = PostHistory.new
      event.post_history_type = PostHistoryType.find_by_name type_name
      event.user = user
      event.post = question
      event.save!
    end

    def self.new_answer_event(type_name, answer, user)
      event = PostHistory.new
      event.post_history_type = PostHistoryType.find_by_name type_name
      event.user = user
      event.post = answer
      event.save!
    end
end


text:
from django.contrib import admin
from models import Practice

class PracticeAdmin(admin.ModelAdmin):
    """Makes all fields of Practice visible on admin site.

    """
    list_display = Practice._meta.get_all_field_names()

admin.site.register(Practice, PracticeAdmin)


text:
'''
Copyright (c) 2014
@author: Marat Khayrullin <xmm.dev@gmail.com>
'''

from api import create_app

application = create_app()

if __name__ == '__main__':
    application.run()


text:
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */
import * as tslib_1 from "tslib";
import { OuterSubscriber } from '../OuterSubscriber';
import { InnerSubscriber } from '../InnerSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';
import { map } from './map';
import { from } from '../observable/from';
export function exhaustMap(project, resultSelector) {
    if (resultSelector) {
        return function (source) { return source.pipe(exhaustMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
    }
    return function (source) {
        return source.lift(new ExhauseMapOperator(project));
    };
}
var ExhauseMapOperator = /*@__PURE__*/ (function () {
    function ExhauseMapOperator(project) {
        this.project = project;
    }
    ExhauseMapOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
    };
    return ExhauseMapOperator;
}());
var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_1.__extends(ExhaustMapSubscriber, _super);
    function ExhaustMapSubscriber(destination, project) {
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.hasSubscription = false;
        _this.hasCompleted = false;
        _this.index = 0;
        return _this;
    }
    ExhaustMapSubscriber.prototype._next = function (value) {
        if (!this.hasSubscription) {
            this.tryNext(value);
        }
    };
    ExhaustMapSubscriber.prototype.tryNext = function (value) {
        var result;
        var index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.hasSubscription = true;
        this._innerSub(result, value, index);
    };
    ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) {
        var innerSubscriber = new InnerSubscriber(this, undefined, undefined);
        this.add(innerSubscriber);
        subscribeToResult(this, result, value, index, innerSubscriber);
    };
    ExhaustMapSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (!this.hasSubscription) {
            this.destination.complete();
        }
    };
    ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(innerValue);
    };
    ExhaustMapSubscriber.prototype.notifyError = function (err) {
        this.destination.error(err);
    };
    ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) {
        this.remove(innerSub);
        this.hasSubscription = false;
        if (this.hasCompleted) {
            this.destination.complete();
        }
    };
    return ExhaustMapSubscriber;
}(OuterSubscriber));
//# sourceMappingURL=exhaustMap.js.map


text:
<?php

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\RegexValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class RegexValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator()
    {
        return new RegexValidator();
    }

    public function testNullIsValid()
    {
        $this->validator->validate(null, new Regex(array('pattern' => '/^[0-9]+$/')));

        $this->assertNoViolation();
    }

    public function testEmptyStringIsValid()
    {
        $this->validator->validate('', new Regex(array('pattern' => '/^[0-9]+$/')));

        $this->assertNoViolation();
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedValueException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
    }

    /**
     * @dataProvider getValidValues
     */
    public function testValidValues($value)
    {
        $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
        $this->validator->validate($value, $constraint);

        $this->assertNoViolation();
    }

    public function getValidValues()
    {
        return array(
            array(0),
            array('0'),
            array('090909'),
            array(90909),
        );
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value)
    {
        $constraint = new Regex(array(
            'pattern' => '/^[0-9]+$/',
            'message' => 'myMessage',
        ));

        $this->validator->validate($value, $constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '"'.$value.'"')
            ->setCode(Regex::REGEX_FAILED_ERROR)
            ->assertRaised();
    }

    public function getInvalidValues()
    {
        return array(
            array('abcd'),
            array('090foo'),
        );
    }
}


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

namespace Jbi.Graph.Core.Data.Entities
{
    public class Edge
    {
        [Key]
        public int Id { get; set; }

        public int FromNodeId { get; set; }
        public int ToNodeId { get; set; }
        public decimal Weight { get; set; }

        [StringLength(1)]
        public string Dir { get; set; }

        [ForeignKey("FromNodeId")]
        public Node FromNode { get; set; }

        [ForeignKey("ToNodeId")]
        public Node ToNode { get; set; }
    }
}


text:
/*
https://github.com/atom/autocomplete-plus/wiki
*/
module.exports.run = function (objects) {
	var completions = [];

	function pushOjb(obj, name, type) {
		if (obj.ignore) return;
		var t = {};
		t.text = name;
		t.snippet = obj.snippet;
		t.displayText = obj.displayText;
		t.description = obj.description;
		t.prefix = obj.prefix;
		switch (type) {
		case 'attributes':
			t.type = "attribute";
			break;
		case 'datatypes':
			t.type = "datatype";
			break;
		case 'functions_with_parenthases':
			t.type = 'function';
			if (!obj.displayText) t.displayText = name + '()';
			if (!obj.snippet) t.snippet = name + '(${1:value...})';
			break;
		case 'functions_without_parenthases':
			t.type = 'function';
			break;
		case 'handles':
			t.type = "handle";
			break;
		case 'methods':
			t.type = "method";
			if (!obj.displayText) t.displayText = name + '()';
			if (!obj.snippet) t.snippet = name + '(${1:value...})';
			break;
		case 'preprocessor_directives':
			t.type = 'preprocessor';
			if (obj.parenthases) t.displayText = name + '()';
			else t.displayText = '&' + name;
			break;
		case 'statements':
			t.type = "statement";
			break;
		case 'system_references':
			t.type = 'keyword';
			break;
		case 'widgets':
			t.type = "widget";
			break;
		case 'unknowns':
			t.type = 'keyword';
			break;
		case 'webspeed':
			if (obj.preprocessor) {
				t.type = 'preprocessor';
				t.displayText = '&' + name;
			} else t.type = 'variable';
			break;
		case 'snippets':
			t = obj;
			break;

		}
		completions.push(t);
	}
	for (var o in objects) {
		var arr = objects[o];
		for (var i in arr) {
			var obj = arr[i];
			pushOjb(obj, obj.name, o);
			if (obj.abbreviation) {
				/*var temp = obj.name;
				while (temp.length > obj.abbreviation.length) {
					temp = temp.substring(0, temp.length - 1);
					pushOjb(obj, temp, o);
				}*/
				pushOjb(obj, obj.abbreviation, o);
			}
		}
	}
	completions.sort(function (a, b) {
		if (a.text < b.text) return -1;
		if (a.text > b.text) return 1;
		return 0;
	});
	return completions;
};


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Onfullscreen & onfullscreenExit - Editor.md examples</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="../css/editormd.css" />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />

Onfullscreen & onfullscreenExit event

Plaese press F12, open the develop tools.

                <textarea style="display:none;">#### Setting

```javascript
{
    onfullscreen : function() {
        // alert("onfullscreen");
        // console.log("onfullscreen =>", this, this.id, this.settings);
    },

    onfullscreenExit : function() {
        // alert("onfullscreenExit");
        // console.log("onfullscreenExit =>", this, this.id, this.settings);
    }
}
```
</textarea>


text:
#ifndef JOYNRMESSAGINGCONNECTORFACTORY_H
#define JOYNRMESSAGINGCONNECTORFACTORY_H

#include "joynr/JoynrExport.h"

#include <memory>
#include <string>

namespace joynr
{

class IMessageSender;
class ISubscriptionManager;
class MessagingQos;

namespace types
{
class DiscoveryEntryWithMetaInfo;
} // namespace types

// traits class which is specialized for every Interface
// this links Interface with the respective Connector
template <typename Interface>
struct JoynrMessagingTraits;

// Create a JoynrMessagingConnector for a generated interface
class JOYNR_EXPORT JoynrMessagingConnectorFactory
{
public:
    JoynrMessagingConnectorFactory(std::shared_ptr<IMessageSender> messageSender,
                                   std::shared_ptr<ISubscriptionManager> subscriptionManager);

    template <class T>
    std::shared_ptr<T> create(const std::string& domain,
                              const std::string proxyParticipantId,
                              const MessagingQos& qosSettings,
                              const types::DiscoveryEntryWithMetaInfo& providerDiscoveryEntry)
    {
        using Connector = typename JoynrMessagingTraits<T>::Connector;
        return std::make_shared<Connector>(_messageSender,
                                           _subscriptionManager,
                                           domain,
                                           proxyParticipantId,
                                           qosSettings,
                                           providerDiscoveryEntry);
    }

private:
    std::shared_ptr<IMessageSender> _messageSender;
    std::shared_ptr<ISubscriptionManager> _subscriptionManager;
};

} // namespace joynr
#endif // JOYNRMESSAGINGCONNECTORFACTORY_H


text:
#include <io/output.h>
#include <io/serial.h>
#include <io/text.h>

#include <stddef.h>

void kernel_putchar ( char c )
{
	// check whether the serial debug channel is active
	if ( __builtin_expect( kernel_active_debug_mode
		& DEBUG_CHANNEL_SERIAL, TRUE ) )
	{
		// write the character to the serial debug channel
		serial_putchar( c );
	}

	// check whether the text debug channel is active
	if ( __builtin_expect( kernel_active_debug_mode
		& DEBUG_CHANNEL_TEXT, TRUE ) )
	{
		// write the character to the vga text channel
		text_putchar( c );
	}
}


text:
package org.mule.tooling.lang.dw.parser.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface WeaveNullLiteral extends WeaveExpression {

}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>answering webrtc without signaling server demo</title>
<link rel="stylesheet" type="text/css" href="style.css">

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">

webrtc without signaling server demo.

<input id="chatinput" type="text"  placeholder="type here" disabled>
<button id="chatbutton" onclick="chatbuttonclick()" disabled>send</button>

answering to a connection offer from a peer

please wait for peer to give offer and paste it below

<textarea id="textoffer"
  placeholder="please paste offer from initiating side"></textarea>
<button id="buttonofferpasted" onclick="clickofferpasted()">offer pasted</button>

please send following answer to peer

<textarea id="textanswer" readonly
  placeholder="please wait a few seconds"></textarea>


text:
package org.saiku.service.olap;

import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SimpleCubeElement;
import org.saiku.olap.dto.resultset.CellDataSet;
import org.saiku.olap.query.IQuery;
import org.saiku.olap.query.IQuery.QueryType;
import org.saiku.olap.query.OlapQuery;
import org.saiku.olap.query.QueryDeserializer;
import org.saiku.olap.query2.ThinHierarchy;
import org.saiku.olap.query2.ThinQuery;
import org.saiku.olap.query2.ThinQueryModel.AxisLocation;
import org.saiku.olap.query2.util.Fat;
import org.saiku.olap.query2.util.Thin;
import org.saiku.olap.util.*;
import org.saiku.olap.util.formatter.CellSetFormatterFactory;
import org.saiku.olap.util.formatter.FlattenedCellSetFormatter;
import org.saiku.olap.util.formatter.ICellSetFormatter;
import org.saiku.query.Query;
import org.saiku.query.QueryDetails;
import org.saiku.query.QueryHierarchy;
import org.saiku.query.QueryLevel;
import org.saiku.query.util.QueryUtil;
import org.saiku.service.olap.totals.AxisInfo;
import org.saiku.service.olap.totals.TotalNode;
import org.saiku.service.olap.totals.TotalsListsBuilder;
import org.saiku.service.olap.totals.aggregators.TotalAggregator;
import org.saiku.service.util.KeyValue;
import org.saiku.service.util.QueryContext;
import org.saiku.service.util.QueryContext.ObjectKey;
import org.saiku.service.util.QueryContext.Type;
import org.saiku.service.util.exception.SaikuServiceException;
import org.saiku.service.util.export.CsvExporter;
import org.saiku.service.util.export.ExcelExporter;

import org.apache.commons.lang.StringUtils;
import org.olap4j.*;
import org.olap4j.mdx.ParseTreeNode;
import org.olap4j.mdx.ParseTreeWriter;
import org.olap4j.mdx.SelectNode;
import org.olap4j.mdx.parser.impl.DefaultMdxParserImpl;
import org.olap4j.metadata.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

import mondrian.olap4j.SaikuMondrianHelper;

public class ThinQueryService implements Serializable {

    /**
     * Unique serialization UID
     */
    private static final long serialVersionUID = -7615296596528274904L;

    private static final Logger log = LoggerFactory.getLogger(ThinQueryService.class);

    private static final AtomicLong ID_GENERATOR = new AtomicLong();

    private OlapDiscoverService olapDiscoverService;

    private CellSetFormatterFactory cff = new CellSetFormatterFactory();

    private Map<String, QueryContext> context = new HashMap<String, QueryContext>();

    public void setOlapDiscoverService(OlapDiscoverService os) {
        this.olapDiscoverService = os;
    }

    public void setCellSetFormatterFactory(CellSetFormatterFactory cff) {
        this.cff = cff;
    }

    public ThinQuery createQuery(ThinQuery tq) throws Exception {
        if (StringUtils.isBlank(tq.getName())) {
            tq.setName(UUID.randomUUID().toString());
        }
        Map<String, Object> cubeProperties = olapDiscoverService.getProperties(tq.getCube());
        tq.getProperties().putAll(cubeProperties);
        if (!context.containsKey(tq.getName())) {
            //			Cube cub = olapDiscoverService.getNativeCube(tq.getCube());
            //			Query query = new Query(tq.getName(), cub);
            //			tq = Thin.convert(query, tq.getCube());
            QueryContext qt = new QueryContext(Type.OLAP, tq);
            qt.store(ObjectKey.QUERY, tq);
            this.context.put(tq.getName(), qt);
        }
        return tq;
    }

    public QueryContext getContext(String name) {
        return this.context.get(name);
    }

    @Deprecated
    public ThinQuery createEmpty(String name, SaikuCube cube) {
        try {
            Cube cub = olapDiscoverService.getNativeCube(cube);
            Query query = new Query(name, cub);
            ThinQuery tq = Thin.convert(query, cube);
            return tq;

        } catch (Exception e) {
            log.error("Cannot create new query for cube :" + cube, e);
        }
        return null;

    }

    protected CellSet executeInternalQuery(ThinQuery query) throws Exception {
        String runId = "RUN#:" + ID_GENERATOR.getAndIncrement();
        QueryContext queryContext = context.get(query.getName());

        if (queryContext == null) {
            queryContext = new QueryContext(Type.OLAP, query);
            this.context.put(query.getName(), queryContext);
        }

        OlapConnection con = olapDiscoverService.getNativeConnection(query.getCube().getConnection());
        if (StringUtils.isNotBlank(query.getCube().getCatalog())) {
            con.setCatalog(query.getCube().getCatalog());
        }

        if (queryContext.contains(ObjectKey.STATEMENT)) {
            Statement s = queryContext.getStatement();
            s.cancel();
            s.close();
            s = null;
            queryContext.remove(ObjectKey.STATEMENT);
        }

        OlapStatement stmt = con.createStatement();
        queryContext.store(ObjectKey.STATEMENT, stmt);

        query = updateQuery(query);

        try {
            String mdx = query.getParameterResolvedMdx();
            log.info(runId + "\tType:" + query.getType() + ":\n" + mdx);

            CellSet cs = stmt.executeOlapQuery(mdx);
            queryContext.store(ObjectKey.RESULT, cs);
            if (query != null) {
                queryContext.store(ObjectKey.QUERY, query);
            }
            return cs;
        } finally {
            stmt.close();
            queryContext.remove(ObjectKey.STATEMENT);
        }
    }

    public CellDataSet execute(ThinQuery tq) {
        if (tq.getProperties().containsKey("saiku.olap.result.formatter")) {
            return execute(tq, tq.getProperties().get("saiku.olap.result.formatter").toString());
        }
        return execute(tq, "");
    }

    public CellDataSet execute(ThinQuery tq, String formatter) {
        String formatterName = formatter == null ? "" : formatter.toLowerCase();
        ICellSetFormatter cf = cff.forName(formatterName);
        return execute(tq, cf);
    }

    public CellDataSet getFormattedResult(String query, String format) throws Exception {
        QueryContext qc = getContext(query);
        ThinQuery tq = qc.getOlapQuery();
        CellSet cs = qc.getOlapResult();
        String formatterName = (StringUtils.isBlank(format) ? "" : format.toLowerCase());
        ICellSetFormatter cf = cff.forName(formatterName);
        CellDataSet result = OlapResultSetUtil.cellSet2Matrix(cs,cf);

        if (ThinQuery.Type.QUERYMODEL.equals(tq.getType()) && cf instanceof FlattenedCellSetFormatter && tq.hasAggregators()) {
            calculateTotals(tq, result, cs, cf);
        }
        return result;
    }

    public CellDataSet execute(ThinQuery tq, ICellSetFormatter formatter) {
        try {

            Long start = (new Date()).getTime();
            CellSet cellSet =  executeInternalQuery(tq);
            String runId = "RUN#:" + ID_GENERATOR.get();
            Long exec = (new Date()).getTime();

            CellDataSet result = OlapResultSetUtil.cellSet2Matrix(cellSet,formatter);
            Long format = (new Date()).getTime();

            if (ThinQuery.Type.QUERYMODEL.equals(tq.getType()) && formatter instanceof FlattenedCellSetFormatter && tq.hasAggregators()) {
                calculateTotals(tq, result, cellSet, formatter);
            }
            Long totals = (new Date()).getTime();
            log.info(runId + "\tSize: " + result.getWidth() + "/" + result.getHeight() + "\tExecute:\t" + (exec - start)
                    + "ms\tFormat:\t" + (format - exec) + "ms\tTotals:\t" + (totals - format) + "ms\t Total: " + (totals - start) + "ms");

            result.setRuntime(new Double(format - start).intValue());
            return result;
        } catch (Exception e) {
            throw new SaikuServiceException("Can't execute query: " + tq.getName(),e);
        } catch (Error e) {
            throw new SaikuServiceException("Can't execute query: " + tq.getName(),e);
        }
    }

    public void cancel(String name) throws SQLException {
        if (context.containsKey(name)) {
            QueryContext queryContext = context.get(name);
            if (queryContext.contains(ObjectKey.STATEMENT)) {
                Statement stmt = queryContext.getStatement();
                if (stmt != null && !stmt.isClosed()) {
                    stmt.cancel();
                    stmt.close();
                }
                stmt = null;
                queryContext.remove(ObjectKey.STATEMENT);
            }
        }
    }

    public ThinQuery updateQuery(ThinQuery old) throws Exception {
        if (ThinQuery.Type.QUERYMODEL.equals(old.getType())) {
            Cube cub = olapDiscoverService.getNativeCube(old.getCube());
            Query q = Fat.convert(old, cub);
            ThinQuery tqAfter = Thin.convert(q, old.getCube());
            old.setQueryModel(tqAfter.getQueryModel());
            old.setMdx(tqAfter.getMdx());
        }
        if (context.containsKey(old.getName())) {
            QueryContext qc = context.get(old.getName());
            qc.store(ObjectKey.QUERY, old);
        }
        String mdx = old.getMdx();
        List<String> params = QueryUtil.parseParameters(mdx);
        old.addParameters(params);

        Map<String, Object> cubeProperties = olapDiscoverService.getProperties(old.getCube());
        old.getProperties().putAll(cubeProperties);

        return old;
    }

    public void deleteQuery(String queryName) {
        try {
            if (context.containsKey(queryName)) {
                QueryContext qc = context.remove(queryName);
                qc.destroy();
            }
        } catch (Exception e) {
            throw new SaikuServiceException(e);
        }
    }

    public byte[] getExport(String queryName, String type) {
        return getExport(queryName,type,new FlattenedCellSetFormatter());
    }

    public byte[] getExport(String queryName, String type, String formatter) {
        String formatterName = formatter == null ? "" : formatter.toLowerCase();
        ICellSetFormatter cf = cff.forName(formatterName);
        return getExport(queryName, type, cf);
    }

    public byte[] getExport(String queryName, String type, ICellSetFormatter formatter) {
        if (StringUtils.isNotBlank(type) && context.containsKey(queryName)) {
            CellSet rs = context.get(queryName).getOlapResult();
            ThinQuery tq = context.get(queryName).getOlapQuery();
            List<ThinHierarchy> filterHierarchies = null;
            if (ThinQuery.Type.QUERYMODEL.equals(tq.getType())) {
                filterHierarchies = tq.getQueryModel().getAxes().get(AxisLocation.FILTER).getHierarchies();
            }
            if (type.toLowerCase().equals("xls")) {
                return ExcelExporter.exportExcel(rs, formatter, filterHierarchies);
            }
            if (type.toLowerCase().equals("csv")) {
                return CsvExporter.exportCsv(rs, SaikuProperties.webExportCsvDelimiter, SaikuProperties.webExportCsvTextEscape, formatter);
            }
        }
        return new byte[0];
    }

    public ResultSet drillthrough(String queryName, int maxrows, String returns) {
        OlapStatement stmt = null;
        try {

            ThinQuery query = context.get(queryName).getOlapQuery();
            final OlapConnection con = olapDiscoverService.getNativeConnection(query.getCube().getConnection());
            stmt = con.createStatement();
            String mdx = query.getMdx();
            if (maxrows > 0) {
                mdx = "DRILLTHROUGH MAXROWS " + maxrows + " " + mdx;
            }
            else {
                mdx = "DRILLTHROUGH " + mdx;
            }
            if (StringUtils.isNotBlank(returns)) {
                mdx += "\r\n RETURN " + returns;
            }
            ResultSet rs = stmt.executeQuery(mdx);
            return rs;
        } catch (SQLException e) {
            throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
        } finally {
            try {
                if (stmt != null)  stmt.close();
            } catch (Exception e) {}
        }
    }

    public boolean isMdxDrillthrough(ThinQuery query) {
        try {
            if (ThinQuery.Type.MDX.equals(query.getType())) {
                SaikuCube cube = query.getCube();
                final OlapConnection con = olapDiscoverService.getNativeConnection(cube.getConnection());
                return SaikuMondrianHelper.isMondrianDrillthrough(con, query.getMdx());
            }
        } catch (Exception e) {
            log.warn("Error checking for DRILLTHROUGH: " + query.getName() + " DRILLTHROUGH MDX:" + query.getMdx(),e);
        } catch (Error e) {
            log.warn("Error checking for DRILLTHROUGH: " + query.getName() + " DRILLTHROUGH MDX:" + query.getMdx(),e);
        }
        return false;

    }

    public ResultSet drillthrough(ThinQuery query) {
        OlapStatement stmt = null;
        try {
            SaikuCube cube = query.getCube();
            final OlapConnection con = olapDiscoverService.getNativeConnection(cube.getConnection());
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query.getMdx());
            return rs;
        } catch (SQLException e) {
            throw new SaikuServiceException("Error DRILLTHROUGH: " + query.getMdx() + " DRILLTHROUGH MDX:" + query.getMdx(),e);
        } finally {
            try {
                if (stmt != null)  stmt.close();
            } catch (Exception e) {}
        }

    }

    public ResultSet drillthrough(String queryName, List<Integer> cellPosition, Integer maxrows, String returns) {
        OlapStatement stmt = null;
        try {
            QueryContext queryContext = context.get(queryName);
            ThinQuery query = queryContext.getOlapQuery();
            CellSet cs = queryContext.getOlapResult();
            SaikuCube cube = query.getCube();
            final OlapConnection con = olapDiscoverService.getNativeConnection(cube.getConnection());
            stmt = con.createStatement();
            SelectNode sn = (new DefaultMdxParserImpl().parseSelect(query.getMdx()));
            String select = null;
            StringBuffer buf = new StringBuffer();
            if (sn.getWithList() != null && sn.getWithList().size() > 0) {
                buf.append("WITH \n");
                StringWriter sw = new StringWriter();
                ParseTreeWriter ptw = new ParseTreeWriter(sw);
                final PrintWriter pw = ptw.getPrintWriter();
                for (ParseTreeNode with : sn.getWithList()) {
                    with.unparse(ptw);
                    pw.println();
                }
                buf.append(sw.toString());
            }
            buf.append("SELECT (");
            for (int i = 0; i < cellPosition.size(); i++) {
                List<Member> members = cs.getAxes().get(i).getPositions().get(cellPosition.get(i)).getMembers();
                for (int k = 0; k < members.size(); k++) {
                    Member m = members.get(k);
                    if (k > 0 || i > 0) {
                        buf.append(", ");
                    }
                    buf.append(m.getUniqueName());
                }
            }
            buf.append(") ON COLUMNS \r\n");
            buf.append("FROM [" + cube.getName() + "]\r\n");
            final Writer writer = new StringWriter();
            sn.getFilterAxis().unparse(new ParseTreeWriter(new PrintWriter(writer)));
            if (StringUtils.isNotBlank(writer.toString())) {
                buf.append("WHERE " + writer.toString());
            }
            select = buf.toString();
            if (maxrows > 0) {
                select = "DRILLTHROUGH MAXROWS " + maxrows + " " + select + "\r\n";
            }
            else {
                select = "DRILLTHROUGH " + select + "\r\n";
            }
            if (StringUtils.isNotBlank(returns)) {
                select += "\r\n RETURN " + returns;
            }
            log.debug("Drill Through for query (" + queryName + ") : \r\n" + select);
            ResultSet rs = stmt.executeQuery(select);
            return rs;
        } catch (Exception e) {
            throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (Exception e) {}
        }
    }

    public byte[] exportDrillthroughCsv(String queryName, int maxrows) {
        OlapStatement stmt = null;
        try {
            QueryContext queryContext = context.get(queryName);
            ThinQuery query = queryContext.getOlapQuery();
            final OlapConnection con = olapDiscoverService.getNativeConnection(query.getCube().getConnection());
            stmt = con.createStatement();
            String mdx = query.getMdx();
            if (maxrows > 0) {
                mdx = "DRILLTHROUGH MAXROWS " + maxrows + " " + mdx;
            }
            else {
                mdx = "DRILLTHROUGH " + mdx;
            }

            ResultSet rs = stmt.executeQuery(mdx);
            return CsvExporter.exportCsv(rs);
        } catch (SQLException e) {
            throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
        } finally {
            try {
                if (stmt != null)  stmt.close();
            } catch (Exception e) {}
        }

    }

    public byte[] exportResultSetCsv(ResultSet rs) {
        return CsvExporter.exportCsv(rs);
    }

    public byte[] exportResultSetCsv(ResultSet rs, String delimiter, String enclosing, boolean printHeader, List<KeyValue<String,String>> additionalColumns) {
        return CsvExporter.exportCsv(rs, delimiter, enclosing, printHeader, additionalColumns);
    }

    public List<SimpleCubeElement> getResultMetadataMembers(
            String queryName,
            boolean preferResult,
            String hierarchyName,
            String levelName,
            String searchString,
            int searchLimit) {

        if (context.containsKey(queryName)) {
            CellSet cs = context.get(queryName).getOlapResult();
            List<SimpleCubeElement> members = new ArrayList<SimpleCubeElement>();
            Set<Level> levels = new HashSet<Level>();
            boolean search = StringUtils.isNotBlank(searchString);
            preferResult = (preferResult && !search);
            searchString = search ? searchString.toLowerCase() : null;

            if (cs != null && preferResult) {
                for (CellSetAxis axis : cs.getAxes()) {
                    int posIndex = 0;
                    for (Hierarchy h : axis.getAxisMetaData().getHierarchies()) {
                        if (h!=null && (h.getUniqueName().equals(hierarchyName) || h.getName().equals(hierarchyName))) {
                            log.debug("Found hierarchy in the result: " + hierarchyName);
                            if (h.getLevels().size() == 1) {
                                break;
                            }
                            Set<Member> mset = new HashSet<Member>();
                            for (Position pos : axis.getPositions()) {
                                Member m = pos.getMembers().get(posIndex);
                                if (!m.getLevel().getLevelType().equals(org.olap4j.metadata.Level.Type.ALL)) {
                                    levels.add(m.getLevel());
                                }
                                if (m.getLevel().getUniqueName().equals(levelName) || m.getLevel().getName().equals(levelName)) {
                                    mset.add(m);
                                }
                            }

                            members = ObjectUtil.convert2Simple(mset);
                            Collections.sort(members, new SaikuUniqueNameComparator());

                            break;
                        }
                        posIndex++;
                    }
                }
                log.debug("Found members in the result: " + members.size());

            }
            if (cs == null || !preferResult || members.size() == 0 || levels.size() == 1) {
                members = olapDiscoverService.getLevelMembers(context.get(queryName).getOlapQuery().getCube(), hierarchyName, levelName, searchString, searchLimit);
            }
            return members;
        }
        return null;
    }

    private void calculateTotals(ThinQuery tq, CellDataSet result, CellSet cellSet, ICellSetFormatter formatter) throws Exception {
        if (ThinQuery.Type.QUERYMODEL.equals(tq.getType()) && formatter instanceof FlattenedCellSetFormatter) {
            Cube cub = olapDiscoverService.getNativeCube(tq.getCube());
            Query query = Fat.convert(tq, cub);

            QueryDetails details = query.getDetails();
            Measure[] selectedMeasures = new Measure[details.getMeasures().size()];
            for (int i = 0; i < selectedMeasures.length; i++)
                selectedMeasures[i] = details.getMeasures().get(i);
            result.setSelectedMeasures(selectedMeasures);

            int rowsIndex = 0;
            if (!cellSet.getAxes().get(0).getAxisOrdinal().equals(Axis.ROWS)) {
                rowsIndex = (rowsIndex + 1) & 1;
            }
            // TODO - refactor this using axis ordinals etc.
            final AxisInfo[] axisInfos = new AxisInfo[]{new AxisInfo(cellSet.getAxes().get(rowsIndex)), new AxisInfo(cellSet.getAxes().get((rowsIndex + 1) & 1))};
            List<TotalNode>[][] totals = new List[2][];
            TotalsListsBuilder builder = null;
            for (int index = 0; index < 2; index++) {
                final int second = (index + 1) & 1;
                TotalAggregator[] aggregators = new TotalAggregator[axisInfos[second].maxDepth + 1];
                for (int i = 1; i < aggregators.length - 1; i++) {
                    List<String> aggs = query.getAggregators(axisInfos[second].uniqueLevelNames.get(i - 1));;
                    String totalFunctionName = aggs != null && aggs.size() > 0 ? aggs.get(0) : null;
                    aggregators[i] = StringUtils.isNotBlank(totalFunctionName) ? TotalAggregator.newInstanceByFunctionName(totalFunctionName) : null;
                }
                List<String> aggs = query.getAggregators(axisInfos[second].axis.getAxisOrdinal().name());
                String totalFunctionName = aggs != null && aggs.size() > 0 ? aggs.get(0) : null;
                aggregators[0] = StringUtils.isNotBlank(totalFunctionName) ? TotalAggregator.newInstanceByFunctionName(totalFunctionName) : null;
                builder = new TotalsListsBuilder(selectedMeasures, aggregators, cellSet, axisInfos[index], axisInfos[second]);
                totals[index] = builder.buildTotalsLists();
            }
            result.setLeftOffset(axisInfos[0].maxDepth);
            result.setRowTotalsLists(totals[1]);
            result.setColTotalsLists(totals[0]);
        }
    }

    public ThinQuery zoomIn(String queryName, List<List<Integer>> realPositions) {

        try {
            if (context.containsKey(queryName)) {
                CellSet cs = context.get(queryName).getOlapResult();
                ThinQuery old = context.get(queryName).getOlapQuery();
                Cube cub = olapDiscoverService.getNativeCube(old.getCube());
                Query q = Fat.convert(old, cub);

                if (cs == null) {
                    throw new SaikuServiceException("Cannot zoom in if last cellset is null");
                }
                if (realPositions == null || realPositions.size() == 0) {
                    throw new SaikuServiceException("Cannot zoom in if zoom in position is empty");
                }

                Map<Hierarchy, Set<Member>> memberSelection = new HashMap<Hierarchy, Set<Member>>();
                for (List<Integer> position : realPositions) {
                    for (int k = 0; k < position.size(); k++) {
                        Position p = cs.getAxes().get(k).getPositions().get(position.get(k));
                        List<Member> members = p.getMembers();
                        for (Member m : members) {
                            Hierarchy h = m.getHierarchy();
                            if (!memberSelection.containsKey(h)) {
                                Set<Member> mset = new HashSet<Member>();
                                memberSelection.put(h, mset);
                            }
                            memberSelection.get(h).add(m);
                        }
                    }
                }

                for(Hierarchy h : memberSelection.keySet()) {
                    QueryHierarchy qh = q.getHierarchy(h);
                    for (QueryLevel ql : qh.getActiveQueryLevels()) {
                        ql.getInclusions().clear();
                        ql.getExclusions().clear();
                        ql.setMdxSetExpression(null);
                    }
                    for (Member m : memberSelection.get(h)) {
                        qh.includeMember(m);
                    }
                }
                ThinQuery tqAfter = Thin.convert(q, old.getCube());
                q = null;
                return tqAfter;
            } else {
                throw new SaikuServiceException("Cannot get query result from context: " + queryName);
            }

        } catch (Exception e) {
            throw new SaikuServiceException("Error zoom in on query: " + queryName,e);
        }

    }

    public ThinQuery drillacross(String queryName, List<Integer> cellPosition,Map<String, List<String>> levels) {
        try {
            ThinQuery old = context.get(queryName).getOlapQuery();
            Cube cub = olapDiscoverService.getNativeCube(old.getCube());
            Query query = Fat.convert(old, cub);
            CellSet cs = context.get(queryName).getOlapResult();

            Set<Level> levelSet = new HashSet<Level>();
            if (cs == null) {
                throw new SaikuServiceException("Cannot drill across. Last CellSet empty");
            }
            for (int i = 0; i < cellPosition.size(); i++) {
                List<Member> members = cs.getAxes().get(i).getPositions().get(cellPosition.get(i)).getMembers();
                for (int k = 0; k < members.size(); k++) {
                    Member m = members.get(k);
                    QueryHierarchy qh = query.getHierarchy(m.getHierarchy());
                    if (qh.getHierarchy().getDimension().getName().equals("Measures")) {
                        Measure measure = query.getMeasure(m.getName());
                        if (!query.getDetails().getMeasures().contains(measure)) {
                            query.getDetails().add(measure);
                        }

                    } else {
                        qh.clearSelection();
                        qh.clearFilters();
                        qh.clearSort();
                        query.moveHierarchy(qh, Axis.FILTER);
                        qh.includeMember(m);
                        levelSet.add(m.getLevel());
                    }

                }
            }
            boolean clearedMeasures = false;

            if (levels != null) {
                for (String key : levels.keySet()) {
                    String dimensionName = key.split("###")[0];

                    if ("Measures".equals(dimensionName)) {
                        if (!clearedMeasures) {
                            query.getDetails().getMeasures().clear();
                            clearedMeasures = true;
                        }
                        for (String measureName : levels.get(key)) {
                            Measure measure = query.getMeasure(measureName);
                            if (measure != null) {
                                query.getDetails().add(measure);
                            } else {
                                for (Measure m : cub.getMeasures()) {
                                    if (m.getUniqueName().equals(measureName)) {
                                        query.getDetails().add(m);
                                    }
                                }
                            }
                        }
                        continue;
                    }
                    String hierarchyName = key.split("###")[1];
                    Dimension d = cub.getDimensions().get(dimensionName);
                    Hierarchy h = d.getHierarchies().get(hierarchyName);
                    QueryHierarchy qh = query.getHierarchy(h);
                    for (Level l : h.getLevels()) {
                        for (String levelU : levels.get(key)) {
                            if (l.getUniqueName().equals(levelU) || l.getName().equals(levelU)) {
                                qh.includeLevel(l);
                            }
                        }
                    }
                    if (qh.getActiveQueryLevels().size() > 0) {
                        query.moveHierarchy(qh, Axis.ROWS);
                    }
                }
            }
            if (query.getDetails().getMeasures().size() == 0) {
                QueryHierarchy qh = query.getHierarchy("Measures");
                Member defaultMeasure = qh.getHierarchy().getDefaultMember();
                query.getDetails().add(query.getMeasure(defaultMeasure.getName()));
            }
            return Thin.convert(query, old.getCube());
        } catch (Exception e) {
            throw new SaikuServiceException("Error drilling across: " + queryName, e);
        }
    }

    public boolean isOldQuery(String xml) {
        return StringUtils.isNotBlank(xml) && xml.trim().startsWith("<?xml");
    }

    public ThinQuery convertQuery(String xml) throws Exception {
        if (StringUtils.isNotBlank(xml) && xml.trim().startsWith("<?xml")) {
            QueryDeserializer qd = new QueryDeserializer();
            SaikuCube scube = qd.getFakeCube(xml);
            OlapConnection con = olapDiscoverService.getNativeConnection(scube.getConnection());
            IQuery query = qd.unparse(xml, con);

            if (QueryType.QM.equals(query.getType())) {
                OlapQuery qr = (OlapQuery) query;
                Query sQ = QueryConverter.convertQuery(qr.getQuery());
                SaikuCube converted = ObjectUtil.convert(scube.getConnection(), sQ.getCube());
                return Thin.convert(sQ, converted);
            } else {
                SaikuCube converted = ObjectUtil.convert(scube.getConnection(), olapDiscoverService.getNativeCube(scube));
                return new ThinQuery(query.getName(), converted, query.getMdx());
            }
        }
        return null;

    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>LogTs Demo</title>
	<link rel="stylesheet" href="style.css">

LogTs Demos


text:
/**
 * Created on 2008-8-11 12:54:32
 */
package cn.net.openid.jos.service.exception;

/**
 * Unchecked exception thrown when an attempt is made to parse a domain
 * operation upon an unresolved domain.
 *
 * @author Sutra Zhou
 */
public class UnresolvedDomainException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 8159796608529077134L;

	/**
	 * Constructs a new unresolved domain exception with the specified detail
	 * message. The cause is not initialized, and may subsequently be
	 * initialized by a call to {@link #initCause}.
	 *
	 * @param message
	 *            the detail message. The detail message is saved for later
	 *            retrieval by the {@link #getMessage()} method.
	 */
	public UnresolvedDomainException(final String message) {
		super(message);
	}

}


text:
<?php

namespace Chippyash\Matrix\Traits;

use Chippyash\Matrix\Exceptions\MatrixException;

/**
 * Assert parameter is an array
 */
Trait AssertParameterIsArray
{
    /**
     * Run test to ensure parameter is an array
     *
     * @param $param
     * @param string $msg Optional message
     * @return $this
     *
     * @throws MatrixException
     * @internal param mixed $value
     */
    protected function assertParameterIsArray($param, $msg = 'Parameter is not an array')
    {
        if (!is_array($param)) {
            throw new MatrixException($msg);
        }

        return $this;
    }
}


text:
import System.Environment
import Data.List

cell :: [Char] -> [Char]
cell seed =  intercalate seed ["
", "
"]

build :: Int -> ([Char] -> [Char]) -> [Char]
build order generator = apply order (cell "") generator
    where
      apply order seed generator
          | order <= 0 =  seed
          | otherwise  =  apply (order - 1) (generator seed) generator

-- | base structure
--
--

--

--

--

--
generator :: [Char] -> [Char]
generator seed = cell (intercalate "" (replicate 2 seed))

main :: IO()
main = do
    args <- getArgs
    putStrLn (build (getLevel args) generator)
        where
          getLevel []   = 0
          getLevel args = read (head args) :: Int


text:
function ver = CFF_get_current_fData_version()
%CFF_GET_CURRENT_FDATA_VERSION  Current version of fData.
%
%   The fData format sometimes requires updating to implement novel
%   features. Such changes imply that data that have been previously
%   converted may not be compatible with newer versions of processing code.
%   As a result, it is necessary to version the fData format. This function
%   returns the current version of the fData format in order for code to
%   test whether a converted data is up-to-date or if re-converting is
%   advised.
%
%   IMPORTANT NOTE FOR DEVELOPERS: Whenever you change the fData format,
%   please update this function appropriately. Keep the existing version
%   number as a comment and add the new one as a new line above. Add the
%   date, and ideally a quick summary of changes.
%
%   See also CFF_GET_FDATA_VERSION, CFF_coffee_version.

%   Authors: Alex Schimel (NGU, alexandre.schimel@ngu.no) and Yoann
%   Ladroit (NIWA, yoann.ladroit@niwa.co.nz)
%   2017-2022; Last revision: 11-08-2022

ver = '0.3'; % DD-MM-YYYY. Changes?
% ver = '0.2'; % DD-MM-YYYY. Changes?
% ver = '0.1'; % DD-MM-YYYY. Changes?
% ver = '0.0'; % DD-MM-YYYY. Changes?

end


text:
<?php

require_once dirname(__FILE__) . '/../../AbstractTest.php';

require_once 'PHP/PMD/Rule/Naming/BooleanGetMethodName.php';

/**
 * Test case for the {@link PHP_PMD_Rule_Naming_BooleanGetMethodName} rule class.
 *
 * @category   PHP
 * @package    PHP_PMD
 * @subpackage Rule_Naming
 * @author     Manuel Pichler <mapi@phpmd.org>
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://phpmd.org
 *
 * @covers PHP_PMD_Rule_Naming_BooleanGetMethodName
 * @group phpmd
 * @group phpmd::rule
 * @group phpmd::rule::naming
 * @group unittest
 */
class PHP_PMD_Rule_Naming_BooleanGetMethodNameTest extends PHP_PMD_AbstractTest
{
    /**
     * testRuleAppliesToMethodStartingWithGetAndReturningBoolean
     *
     * @return void
     */
    public function testRuleAppliesToMethodStartingWithGetAndReturningBoolean()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getMethod());
    }

    /**
     * testRuleAppliesToMethodStartingWithGetAndReturningBool
     *
     * @return void
     */
    public function testRuleAppliesToMethodStartingWithGetAndReturningBool()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getMethod());
    }

    /**
     * testRuleAppliesToPearPrivateMethodStartingWithGetAndReturningBoolean
     *
     * @return void
     */
    public function testRuleAppliesToPearPrivateMethodStartingWithGetAndReturningBoolean()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getMethod());
    }

    /**
     * testRuleIgnoresParametersWhenNotExpliciteConfigured
     *
     * @return void
     */
    public function testRuleIgnoresParametersWhenNotExpliciteConfigured()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getMethod());
    }

    /**
     * testRuleNotAppliesWhenParametersAreExpliciteEnabled
     *
     * @return void
     */
    public function testRuleNotAppliesWhenParametersAreExpliciteEnabled()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'true');
        $rule->setReport($this->getReportMock(0));

        $rule->apply($this->getMethod());
    }

    /**
     * testRuleNotAppliesToMethodStartingWithIs
     *
     * @return void
     */
    public function testRuleNotAppliesToMethodStartingWithIs()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(0));

        $rule->apply($this->getMethod());
    }

    /**
     * testRuleNotAppliesToMethodStartingWithHas
     *
     * @return void
     */
    public function testRuleNotAppliesToMethodStartingWithHas()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(0));

        $rule->apply($this->getMethod());
    }

    /**
     * testRuleNotAppliesToMethodWithReturnTypeNotBoolean
     *
     * @return void
     */
    public function testRuleNotAppliesToMethodWithReturnTypeNotBoolean()
    {
        $rule = new PHP_PMD_Rule_Naming_BooleanGetMethodName();
        $rule->addProperty('checkParameterizedMethods', 'false');
        $rule->setReport($this->getReportMock(0));

        $rule->apply($this->getMethod());
    }

    /**
     * Returns the first method found in a source file related to the calling
     * test method.
     *
     * @return PHP_PMD_Node_Method
     */
    protected function getMethod()
    {
        $methods = $this->getClass()->getMethods();
        return reset($methods);
    }
}


text:
var _       = require('lodash'),
    Promise = require('bluebird'),
    config  = require('../../config'),
    i18n    = require('../../i18n'),
    schema  = require('./schema'),
    clients = require('./clients'),

    dbConfig;

function addTableColumn(tablename, table, columnname) {
    var column,
        columnSpec = schema[tablename][columnname];

    // creation distinguishes between text with fieldtype, string with maxlength and all others
    if (columnSpec.type === 'text' && columnSpec.hasOwnProperty('fieldtype')) {
        column = table[columnSpec.type](columnname, columnSpec.fieldtype);
    } else if (columnSpec.type === 'string' && columnSpec.hasOwnProperty('maxlength')) {
        column = table[columnSpec.type](columnname, columnSpec.maxlength);
    } else {
        column = table[columnSpec.type](columnname);
    }

    if (columnSpec.hasOwnProperty('nullable') && columnSpec.nullable === true) {
        column.nullable();
    } else {
        column.notNullable();
    }
    if (columnSpec.hasOwnProperty('primary') && columnSpec.primary === true) {
        column.primary();
    }
    if (columnSpec.hasOwnProperty('unique') && columnSpec.unique) {
        column.unique();
    }
    if (columnSpec.hasOwnProperty('unsigned') && columnSpec.unsigned) {
        column.unsigned();
    }
    if (columnSpec.hasOwnProperty('references')) {
        // check if table exists?
        column.references(columnSpec.references);
    }
    if (columnSpec.hasOwnProperty('defaultTo')) {
        column.defaultTo(columnSpec.defaultTo);
    }
}

function addColumn(table, column) {
    dbConfig = dbConfig || config.database;
    return dbConfig.knex.schema.table(table, function (t) {
        addTableColumn(table, t, column);
    });
}

function addUnique(table, column) {
    dbConfig = dbConfig || config.database;
    return dbConfig.knex.schema.table(table, function (table) {
        table.unique(column);
    });
}

function dropUnique(table, column) {
    dbConfig = dbConfig || config.database;
    return dbConfig.knex.schema.table(table, function (table) {
        table.dropUnique(column);
    });
}

function createTable(table) {
    dbConfig = dbConfig || config.database;
    return dbConfig.knex.schema.createTable(table, function (t) {
        var columnKeys = _.keys(schema[table]);
        _.each(columnKeys, function (column) {
            return addTableColumn(table, t, column);
        });
    });
}

function deleteTable(table) {
    dbConfig = dbConfig || config.database;
    return dbConfig.knex.schema.dropTableIfExists(table);
}

function getTables() {
    dbConfig = dbConfig || config.database;
    var client = dbConfig.client;

    if (_.contains(_.keys(clients), client)) {
        return clients[client].getTables();
    }

    return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
}

function getIndexes(table) {
    dbConfig = dbConfig || config.database;
    var client = dbConfig.client;

    if (_.contains(_.keys(clients), client)) {
        return clients[client].getIndexes(table);
    }

    return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
}

function getColumns(table) {
    dbConfig = dbConfig || config.database;
    var client = dbConfig.client;

    if (_.contains(_.keys(clients), client)) {
        return clients[client].getColumns(table);
    }

    return Promise.reject(i18n.t('notices.data.utils.index.noSupportForDatabase', {client: client}));
}

function checkTables() {
    dbConfig = dbConfig || config.database;
    var client = dbConfig.client;

    if (client === 'mysql') {
        return clients[client].checkPostTable();
    }
}

module.exports = {
    checkTables: checkTables,
    createTable: createTable,
    deleteTable: deleteTable,
    getTables: getTables,
    getIndexes: getIndexes,
    addUnique: addUnique,
    dropUnique: dropUnique,
    addColumn: addColumn,
    getColumns: getColumns
};


text:
/*
 * $Id: Quantity.java,v 1.16 2008/01/19 01:05:40 jimcdiver Exp $
 * Created on Oct 7, 2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

package ca.strangebrew.recipe;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * @author aavis
 *
 * This is the class for amounts + units.
 * It's pretty smart, and knows how to convert itself to other units.
 *
 */

public class Quantity {

    public static final String WEIGHT = "weight";
    public static final String VOLUME = "volume";
    public static final String PRESSURE = "pressure";
    public static final String OTHER = "other";

    private String type; // can be vol, weight, or temp
	private String unit = ""; // must match one of the known units
	private String abrv; // ditto
	private double value;

    public Quantity(String stringValue) {
        int i = stringValue.indexOf(" ");
        String d = stringValue.substring(0,i);
        String u = stringValue.substring(i);
        Double dAmount = 0.0;
        try {
            NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
            Number number = format.parse(d.trim());
            dAmount = number.doubleValue();

        } catch (NumberFormatException m) {
            return;
        } catch (ParseException e) {
            return;
        }
        this.setAmount(dAmount);
        this.setUnits(u.trim());
    }

    public static String getUnitType(String units) {
        return null;
    }

    // why can't we have structs?????
	// because a static class is better for what we are trying to acomplish here!
	public static class Converter {
		public String abrv;
		public String unit;
		public double toBase;

		public Converter(String n, String a, double t) {
			unit = n;
			abrv = a;
			toBase = t;
		}
	}

	// TODO public static string all of this stuff!
	final static public String FL_OUNCES = "fl. ounces";
	final static public String OZ = "oz";
	final static public String GALLONS_US = "gallons US";
	final static public String GAL = "gal";
	final static public String LITRES = "litres";
	final static public String L = "l";
	final static public String MILLILITERS = "milliliters";
	final static public String ML = "ml";
	final static public String QUART_US = "quart US";
	final static public String QT = "qt";
	final static public String OUNCES = "ounces";
//	final static public String OZ = "oz";
	final static public String POUNDS = "pounds";
	final static public String LB = "lb";
	final static public String MILLIGRAMS = "milligrams";
	final static public String MG = "mg";
	final static public String GRAMS = "grams";
	final static public String G = "g";
	final static public String KILOGRAMS = "kilgrams";
	final static public String KG = "kg";

	final static public Converter volUnits[] =
	{
		new Converter("barrel IMP", "bbl Imp", 0.023129837),
		new Converter("barrel US", "bbl", 0.032258065),
		new Converter(FL_OUNCES, OZ, 128),
		new Converter("gallons IMP", "gal Imp", 0.8327),
		new Converter(GALLONS_US, GAL, 1),
		new Converter(LITRES, L, 3.7854),
		new Converter(MILLILITERS, ML, 3785.4118),
		new Converter("pint US", "pt", 8),
		new Converter(QUART_US, QT, 4)
	};

	final static public Converter weightUnits[] =
	{
		new Converter(MILLIGRAMS, MG, 4535.9237),
		new Converter(GRAMS, G, 453.59237),
		new Converter(KILOGRAMS, KG, 0.45359237),
		new Converter(OUNCES, OZ, 16),
		new Converter(POUNDS, LB, 1),
		new Converter("ton S", "T", 0.0005),
		new Converter("tonne SI", "T SI", 0.000453592)
	};

	final static public Converter pressureUnits[] =
	{
		new Converter("pounds per square inch", "psi", 1),
		new Converter("kilopascals", "KPa", 6.8947624),
		new Converter("bar", "bar", 0.068947635),
		new Converter("atmospheres", "atm", 0.0680460253)
	};

    final static public Converter otherUnits[] =
    {
        new Converter("packages", "pkgs", 1)
    };
	// Get/Set:

	public Quantity() {
		unit = "";
		type = "";
		abrv = "";
	}

	public Quantity(String u, double am){
		setUnits(u);
		setAmount(am);
	}

	public Quantity(Quantity q) {
		this.type = q.type;
		this.unit = q.getUnits();
		this.abrv = q.getAbrv();
		this.value = q.getValue();
	}

	// This sets a quantity's unit, abrv, and type:
	public void setUnits(String s){
		String t = getTypeFromUnit(s);
		type = t;

		if (isAbrv(s)){
			unit = getUnitFromAbrv(t, s);;
			abrv = s;
		}
		// it's a unit
		else {
			unit = s;
			abrv = getAbrvFromUnit(t, s);
		}
	}

	// set the amount only:
	public void setAmount(double am){
		value = am;
	}

	public double getValue(){ return value;	}
	public String getUnits(){ return unit; }
	public String getAbrv(){ return abrv; }

	public double getValueAs(String to){
		double fromBase ;
		double toBase;
		Converter[] u;

		// don't do any work if we're converting to ourselves
		if (to.equals(unit) || type.equals(abrv))
			return value;

		switch (type) {
			case Quantity.VOLUME:
				u = volUnits;
				break;
			case Quantity.PRESSURE:
				u = pressureUnits;
				break;
			default:
				u = weightUnits;
				break;
		}
		fromBase = getBaseValue(u, unit);
		toBase = getBaseValue(u, to);

		return value * (toBase / fromBase);
	}

	public void add(double v, String u){
		// convert v from u to current units
		// then add it
		Quantity q = new Quantity(u,v);
		double v2 = q.getValueAs(getUnits());
		value += v2;
	}

	public void convertTo(String to){
		if(!Objects.equals(to, this.unit)) {
			value = Quantity.convertUnit(unit, to, value);
			setUnits(to);
		}
	}

	//	 implement to support comboboxes in Swing:
	public String getName(){
		return unit;
	}

	// private functions:
	static private double getBaseValue(Converter[] u, String n){
		int i=0;
		while (i < u.length
				&& !u[i].abrv.equalsIgnoreCase(n)
				&& !u[i].unit.equalsIgnoreCase(n)) {
			i++;
		}
		if (i >= u.length)
			return 1;
		else
			return u[i].toBase;
	}

	static private String getUnitFromAbrv(String t, String a){
		int i=0;
		Converter[] u;

		if (Objects.equals(t, "vol"))
			u = volUnits;
		else if (Objects.equals(t, "pressure"))
			u = pressureUnits;
		else // assume weight
			u = weightUnits;

		while (i < u.length
				&& !u[i].abrv.equalsIgnoreCase(a)) {
			i++;
		}
		if (i >= u.length)
			return null;
		else
			return u[i].unit;
	}

	static private boolean isAbrv(String a){

		Converter[] u;
		String t = getTypeFromUnit(a);
		if (Objects.equals(t, "vol"))
			u = volUnits;
		else if (Objects.equals(t, "pressure"))
			u = pressureUnits;
		else // assume weight
			u = weightUnits;

		for (Converter unit  : u){
			if (unit.abrv.equalsIgnoreCase(a))
				return true;
		}
		return false;

	}

	static private String getAbrvFromUnit(String t, String s){
		int i=0;
		Converter[] u;

		if (Objects.equals(t, "vol"))
			u = volUnits;
		else if (Objects.equals(t, "pressure"))
			u = pressureUnits;
		else // assume weight
			u = weightUnits;

		while (i < u.length
				&& !u[i].unit.equalsIgnoreCase(s)) {
			i++;
		}
		if (i >= u.length)
			return null;
		else
			return u[i].abrv;
	}

	public static String getTypeFromUnit(String s){

		for (Converter weight : weightUnits) {
			if (weight.unit.equalsIgnoreCase(s) ||
					weight.abrv.equalsIgnoreCase(s)) {
				return Quantity.WEIGHT;
			}
		}

		for (Converter volume : volUnits) {
			if (volume.unit.equalsIgnoreCase(s) ||
					volume.abrv.equalsIgnoreCase(s)) {
				return Quantity.VOLUME;
			}
		}

		for (Converter pressure : pressureUnits) {
			if (pressure.unit.equalsIgnoreCase(s) ||
					pressure.abrv.equalsIgnoreCase(s)) {
				return Quantity.PRESSURE;
			}
		}

        for (Converter other : otherUnits) {
            if (other.unit.equalsIgnoreCase(s) ||
                    other.abrv.equalsIgnoreCase(s)) {
                return Quantity.OTHER;
            }
        }

		return "undefined";
	}

	/*
	 * These are "generic" functions you can call on any quantity object (or just
	 * create a new one).  No!.. we have static functions for a reason. Creating and garbage
	 * collecting objects bad.
	 */

	static public List<String> getListofUnits(String type, boolean abrv) {
		List<String> list = new ArrayList<>();
		switch (type){

            case "weight":
			for (Converter w : weightUnits) {
                if (abrv)
                    list.add(w.abrv);
                else
                    list.add(w.unit);

            }
                break;
            case "pressure":
			for (Converter p: pressureUnits) {
                if (abrv)
                    list.add(p.abrv);
                else
                    list.add(p.unit);
            }
                break;
            default:
			for (Converter v: volUnits) {
                if (abrv)
                    list.add(v.abrv);
                else
                    list.add(v.unit);
            }
		}

		return list;
	}

	static public List<String> getListofUnits(String type) {
		return (getListofUnits(type, false));
	}

	static public String getVolAbrv(String unit) {
		Quantity q = new Quantity();
		q.setUnits(unit);
		return q.abrv;
	}

	// let's just convert a unit from something to something else
	public static double convertUnit(String from, String to, double value){
		Quantity q = new Quantity(from,value);
		return q.getValueAs(to);
	}

    /**
     * Return the current Quantity as a string of "<volume> <units>"
     * @return the current quantity
     */
    @Override
    public String toString() {
        return this.getValue() + " " + this.getUnits();
    }
}


text:
package com.trevorgowing.projectlog.project;

import static com.trevorgowing.projectlog.project.IdentifiedProjectDTOBuilder.anIdentifiedProjectDTO;
import static com.trevorgowing.projectlog.project.ProjectBuilder.aProject;
import static com.trevorgowing.projectlog.user.IdentifiedUserDTOBuilder.anIdentifiedUserDTO;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

import com.trevorgowing.projectlog.common.types.AbstractTests;
import com.trevorgowing.projectlog.user.IdentifiedUserDTO;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

public class ProjectRetrieverTests extends AbstractTests {

  private static final long IRRELEVANT_PROJECT_ID = 1L;
  private static final String IRRELEVANT_PROJECT_CODE = "irrelevant.project.code";
  private static final String IRRELEVANT_PROJECT_NAME = "irrelevant.project.name";
  private static final IdentifiedUserDTO IRRELEVANT_OWNER =
      anIdentifiedUserDTO()
          .id(IRRELEVANT_USER_ID)
          .email(IRRELEVANT_USER_EMAIL)
          .firstName(IRRELEVANT_USER_FIRST_NAME)
          .lastName(IRRELEVANT_USER_LAST_NAME)
          .build();

  @Mock private ProjectRepository projectRepository;

  @InjectMocks private ProjectRetriever projectRetriever;

  @Test(expected = ProjectNotFoundException.class)
  public void testFindProjectWithNoMatchingProject_shouldThrowProjectNotFoundException() {
    // Set up expectations
    when(projectRepository.findById(IRRELEVANT_PROJECT_ID)).thenReturn(Optional.empty());

    // Exercise SUT
    projectRetriever.findProject(IRRELEVANT_PROJECT_ID);
  }

  @Test
  public void testFindProjectWithMatchingProject_shouldReturnProject() {
    // Set up fixture
    Project expectedProject = aProject().id(IRRELEVANT_PROJECT_ID).build();

    // Set up expectations
    when(projectRepository.findById(IRRELEVANT_PROJECT_ID))
        .thenReturn(Optional.of(expectedProject));

    // Exercise SUT
    Project actualProject = projectRetriever.findProject(IRRELEVANT_PROJECT_ID);

    // Verify behaviour
    assertThat(actualProject, is(expectedProject));
  }

  @Test
  public void
      testGetIdentifiedProjectDTOs_shouldDelegateToProjectRepositoryAndReturnIdentifiedProjectDTOs() {
    // Set up fixture
    IdentifiedProjectDTO identifiedProjectOneDTO =
        anIdentifiedProjectDTO()
            .id(IRRELEVANT_PROJECT_ID)
            .code(IRRELEVANT_PROJECT_CODE)
            .name(IRRELEVANT_PROJECT_NAME)
            .owner(IRRELEVANT_OWNER)
            .startDate(IRRELEVANT_DATE)
            .endDate(IRRELEVANT_DATE)
            .build();

    IdentifiedProjectDTO identifiedProjectTwoDTO =
        anIdentifiedProjectDTO()
            .id(2L)
            .code("project.two.code")
            .name("project.two.name")
            .owner(
                anIdentifiedUserDTO()
                    .id(2L)
                    .email("owner.two@trevorgowing.com")
                    .firstName("owner.two.first.name")
                    .lastName("owner.two.last.name")
                    .build())
            .startDate(IRRELEVANT_DATE)
            .endDate(IRRELEVANT_DATE)
            .build();

    List<IdentifiedProjectDTO> expectedIdentifiedProjectDTOs =
        asList(identifiedProjectOneDTO, identifiedProjectTwoDTO);

    // Set up expectations
    when(projectRepository.findIdentifiedProjectDTOs()).thenReturn(expectedIdentifiedProjectDTOs);

    // Exercise SUT
    List<IdentifiedProjectDTO> actualIdentifiedProjectDTOs =
        projectRetriever.getIdentifiedProjectDTOs();

    // Verify behaviour
    assertThat(actualIdentifiedProjectDTOs, is(expectedIdentifiedProjectDTOs));
  }

  @Test(expected = ProjectNotFoundException.class)
  public void
      testGetIdentifiedProjectDTOByIdWithNoMatchingProject_shouldThrowProjectNotFoundException() {
    // Set up expectations
    when(projectRepository.findIdentifiedProjectDTOById(IRRELEVANT_PROJECT_ID)).thenReturn(null);

    // Exercise SUT
    projectRetriever.getIdentifiedProjectDTOById(IRRELEVANT_PROJECT_ID);
  }

  @Test
  public void testGetIdentifiedProjectDTOByIdWithMatchingProject_shouldReturnProject() {
    // Set up fixture
    IdentifiedProjectDTO expectedIdentifiedProjectDTO =
        anIdentifiedProjectDTO()
            .id(IRRELEVANT_PROJECT_ID)
            .code(IRRELEVANT_PROJECT_CODE)
            .name(IRRELEVANT_PROJECT_NAME)
            .owner(IRRELEVANT_OWNER)
            .startDate(IRRELEVANT_DATE)
            .endDate(IRRELEVANT_DATE)
            .build();

    // Set up expectations
    when(projectRepository.findIdentifiedProjectDTOById(IRRELEVANT_PROJECT_ID))
        .thenReturn(expectedIdentifiedProjectDTO);

    // Exercise SUT
    IdentifiedProjectDTO actualIdentifiedProjectDTO =
        projectRetriever.getIdentifiedProjectDTOById(IRRELEVANT_PROJECT_ID);

    // Verify behaviour
    assertThat(actualIdentifiedProjectDTO, is(expectedIdentifiedProjectDTO));
  }
}


text:
package org.hibernate.engine.jdbc.internal;

/**
 * Models type info extracted from {@link java.sql.DatabaseMetaData#getTypeInfo()}
 *
 * @author Steve Ebersole
 */
public class TypeInfo {
	private final String typeName;
	private final int jdbcTypeCode;
	private final String[] createParams;
	private final boolean unsigned;
	private final int precision;
	private final short minimumScale;
	private final short maximumScale;
	private final boolean fixedPrecisionScale;
	private final String literalPrefix;
	private final String literalSuffix;
	private final boolean caseSensitive;
	private final TypeSearchability searchability;
	private final TypeNullability nullability;

	public TypeInfo(
			String typeName,
			int jdbcTypeCode,
			String[] createParams,
			boolean unsigned,
			int precision,
			short minimumScale,
			short maximumScale,
			boolean fixedPrecisionScale,
			String literalPrefix,
			String literalSuffix,
			boolean caseSensitive,
			TypeSearchability searchability,
			TypeNullability nullability) {
		this.typeName = typeName;
		this.jdbcTypeCode = jdbcTypeCode;
		this.createParams = createParams;
		this.unsigned = unsigned;
		this.precision = precision;
		this.minimumScale = minimumScale;
		this.maximumScale = maximumScale;
		this.fixedPrecisionScale = fixedPrecisionScale;
		this.literalPrefix = literalPrefix;
		this.literalSuffix = literalSuffix;
		this.caseSensitive = caseSensitive;
		this.searchability = searchability;
		this.nullability = nullability;
	}

	public String getTypeName() {
		return typeName;
	}

	public int getJdbcTypeCode() {
		return jdbcTypeCode;
	}

	public String[] getCreateParams() {
		return createParams;
	}

	public boolean isUnsigned() {
		return unsigned;
	}

	public int getPrecision() {
		return precision;
	}

	public short getMinimumScale() {
		return minimumScale;
	}

	public short getMaximumScale() {
		return maximumScale;
	}

	public boolean isFixedPrecisionScale() {
		return fixedPrecisionScale;
	}

	public String getLiteralPrefix() {
		return literalPrefix;
	}

	public String getLiteralSuffix() {
		return literalSuffix;
	}

	public boolean isCaseSensitive() {
		return caseSensitive;
	}

	public TypeSearchability getSearchability() {
		return searchability;
	}

	public TypeNullability getNullability() {
		return nullability;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Dos.ORM.NoSql;

namespace Dos.ORM.NoSql
{
    /// <summary>
    ///
    /// </summary>
    public class NoSqlSession
    {
        /// <summary>
        /// NoSql数据库类型
        /// </summary>
        public NoSqlType NoSqlType;
        /// <summary>
        /// 缓存对象
        /// </summary>
        private ICache Cache;
        /// <summary>
        /// 构造函数
        /// </summary>
        public NoSqlSession()
        {
            var type = System.Configuration.ConfigurationManager.AppSettings["NoSqlType"];
            if (string.IsNullOrWhiteSpace(type))
            {
                throw new Exception("请在AppSetting中配置<add key=\"NoSqlType\" value=\"IIS/Redis/MongoDB/Memcache\" />");
            }

            switch (type.ToLower())
            {
                case "redis":
                    NoSqlType = NoSqlType.Redis;
                    Cache = new Redis();
                    break;
                case "iis":
                    NoSqlType = NoSqlType.IIS;
                    Cache = new IIS();
                    break;
                default:
                    throw new Exception("暂时不支持的NoSql数据库!");
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        public NoSqlSession(NoSqlType noSqlType,string host = "",string port = "",string pwd = "")
        {
            switch (noSqlType)
            {
                case NoSqlType.Redis:
                    NoSqlType = NoSqlType.Redis;
                    Cache = new Redis(host, port, pwd);
                    break;
                case NoSqlType.IIS:
                    NoSqlType = NoSqlType.IIS;
                    Cache = new IIS();
                    break;
                default:
                    throw new Exception("暂时不支持的NoSql数据库!");
            }
        }
        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            return Cache.Remove(key);
        }
        /// <summary>
        /// 新增/覆盖 缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Set<T>(string key, T value)
        {
            return Cache.Set(key, value);
        }
        /// <summary>
        /// 新增/覆盖 缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiresIn"></param>
        /// <returns></returns>
        public bool Set<T>(string key, T value, TimeSpan expiresIn)
        {
            return Cache.Set(key, value, expiresIn);
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return Cache.Get<T>(key);
        }
    }
}


text:
package org.apache.zookeeper.server.jersey;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.server.jersey.jaxb.ZChildren;
import org.apache.zookeeper.server.jersey.jaxb.ZChildrenJSON;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.sun.jersey.api.client.ClientResponse;

/**
 * Test stand-alone server.
 *
 */
@RunWith(Parameterized.class)
public class GetChildrenTest extends Base {
    protected static final Logger LOG = Logger.getLogger(GetChildrenTest.class);

    private String accept;
    private String path;
    private ClientResponse.Status expectedStatus;
    private String expectedPath;
    private List<String> expectedChildren;

    @Parameters
    public static Collection<Object[]> data() throws Exception {
        String baseZnode = Base.createBaseZNode();
        String baseZnode2 = Base.createBaseZNode();
        String baseZnode3 = Base.createBaseZNode();
        String baseZnode4 = Base.createBaseZNode();
        String baseZnode5 = Base.createBaseZNode();
        String baseZnode6 = Base.createBaseZNode();

        return Arrays.asList(new Object[][] {
          {MediaType.APPLICATION_JSON, baseZnode + "abddkdkd",
              ClientResponse.Status.NOT_FOUND, null, null },
          {MediaType.APPLICATION_XML, baseZnode + "abddkdkd",
              ClientResponse.Status.NOT_FOUND, null, null },
          {MediaType.APPLICATION_JSON, baseZnode, ClientResponse.Status.OK,
              baseZnode, Arrays.asList(new String[] {}) },
          {MediaType.APPLICATION_XML, baseZnode, ClientResponse.Status.OK,
              baseZnode, Arrays.asList(new String[] {}) },
          {MediaType.APPLICATION_JSON, baseZnode, ClientResponse.Status.OK,
              baseZnode, Arrays.asList(new String[] {"c1"}) },
          {MediaType.APPLICATION_XML, baseZnode4, ClientResponse.Status.OK,
              baseZnode4, Arrays.asList(new String[] {"c1"}) },
          {MediaType.APPLICATION_JSON, baseZnode2, ClientResponse.Status.OK,
              baseZnode2, Arrays.asList(new String[] {"c1", "c2"}) },
          {MediaType.APPLICATION_XML, baseZnode5, ClientResponse.Status.OK,
              baseZnode5, Arrays.asList(new String[] {"c1", "c2"}) },
          {MediaType.APPLICATION_JSON, baseZnode3, ClientResponse.Status.OK,
              baseZnode3, Arrays.asList(new String[] {"c1", "c2", "c3", "c4"}) },
          {MediaType.APPLICATION_XML, baseZnode6, ClientResponse.Status.OK,
              baseZnode6, Arrays.asList(new String[] {"c1", "c2", "c3", "c4"}) }

          });
    }

    public GetChildrenTest(String accept, String path, ClientResponse.Status status,
            String expectedPath, List<String> expectedChildren)
    {
        this.accept = accept;
        this.path = path;
        this.expectedStatus = status;
        this.expectedPath = expectedPath;
        this.expectedChildren = expectedChildren;
    }

    @Test
    public void testGetChildren() throws Exception {
        LOG.info("STARTING " + getName());

        if (expectedChildren != null) {
            for(String child : expectedChildren) {
                zk.create(expectedPath + "/" + child, null,
                        Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }

        ClientResponse cr = r.path(path).queryParam("view", "children")
            .accept(accept).get(ClientResponse.class);
        assertEquals(expectedStatus, cr.getClientResponseStatus());

        if (expectedChildren == null) {
            return;
        }

        if (accept.equals(MediaType.APPLICATION_JSON)) {
            ZChildrenJSON zchildren = cr.getEntity(ZChildrenJSON.class);
            Collections.sort(expectedChildren);
            Collections.sort(zchildren.children);
            assertEquals(expectedChildren, zchildren.children);
            assertEquals(r.path(path).toString(), zchildren.uri);
            assertEquals(r.path(path).toString() + "/{child}",
                    zchildren.child_uri_template);
        } else if (accept.equals(MediaType.APPLICATION_XML)) {
            ZChildren zchildren = cr.getEntity(ZChildren.class);
            Collections.sort(expectedChildren);
            Collections.sort(zchildren.children);
            assertEquals(expectedChildren, zchildren.children);
            assertEquals(r.path(path).toString(), zchildren.uri);
            assertEquals(r.path(path).toString() + "/{child}",
                    zchildren.child_uri_template);
        } else {
            fail("unknown accept type");
        }
    }
}


text:
namespace blink {

class Document;

namespace {

class CSSStyleSheetResourceTest : public ::testing::Test {
 protected:
  CSSStyleSheetResourceTest() {
    m_originalMemoryCache = replaceMemoryCacheForTesting(MemoryCache::create());
    m_page = DummyPageHolder::create();
    document().setURL(KURL(KURL(), "https://localhost/"));
  }

  ~CSSStyleSheetResourceTest() override {
    replaceMemoryCacheForTesting(m_originalMemoryCache.release());
  }

  Document& document() { return m_page->document(); }

  Persistent<MemoryCache> m_originalMemoryCache;
  std::unique_ptr<DummyPageHolder> m_page;
};

TEST_F(CSSStyleSheetResourceTest, DuplicateResourceNotCached) {
  const char url[] = "https://localhost/style.css";
  KURL imageURL(KURL(), url);
  KURL cssURL(KURL(), url);

  // Emulate using <img> to do async stylesheet preloads.

  Resource* imageResource = ImageResource::create(ResourceRequest(imageURL));
  ASSERT_TRUE(imageResource);
  memoryCache()->add(imageResource);
  ASSERT_TRUE(memoryCache()->contains(imageResource));

  CSSStyleSheetResource* cssResource =
      CSSStyleSheetResource::createForTest(ResourceRequest(cssURL), "utf-8");
  cssResource->responseReceived(
      ResourceResponse(cssURL, "style/css", 0, nullAtom, String()), nullptr);
  cssResource->finish();

  CSSParserContext* parserContext = CSSParserContext::create(HTMLStandardMode);
  StyleSheetContents* contents = StyleSheetContents::create(parserContext);
  CSSStyleSheet* sheet = CSSStyleSheet::create(contents, document());
  EXPECT_TRUE(sheet);

  contents->checkLoaded();
  cssResource->saveParsedStyleSheet(contents);

  // Verify that the cache will have a mapping for |imageResource| at |url|.
  // The underlying |contents| for the stylesheet resource must have a
  // matching reference status.
  EXPECT_TRUE(memoryCache()->contains(imageResource));
  EXPECT_FALSE(memoryCache()->contains(cssResource));
  EXPECT_FALSE(contents->isReferencedFromResource());
  EXPECT_FALSE(cssResource->restoreParsedStyleSheet(parserContext));
}

}  // namespace
}  // namespace blink


text:
importScripts('/poc/weather/javascripts/geometry/sphere.js');

(function () {

    var root = this,
        Cur = (root.Cur = {});

    Cur.evolve = function (delta, input) {
    };

    Cur.map = function (delta, input) {
    };

})();


text:
![Wind JS](https://f.cloud.github.com/assets/351164/2349895/36ba1c9a-a569-11e3-859d-5d753ea0898c.jpeg)

This project is an experiment in client-side data processing and visualization. Most of the code in this project is taken from https://github.com/cambecc/earth and has been re-purposed to support easier application to a variety of mapping APIs and Frameworks.

## How it works

The code for this project uses nothing but an HTML5 Canvas element and pure Javascript. The data come from the Global Forecast System which produces a large variety of datasets as continuous global gridded datasets (more info below). The data is passed into a JS class called `Windy` which takes the bounds of the map, the data, and the canvas element and then applies a [Bilinear Interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation) to generate a smooth surface. Once the surface has been generated a function randomly places "particles" onto canvas at random x/y points. Each particle is then "evolved", moving in a direction and at a velocity that is dictated by the interpolated surface.

## The Demo

[http://esri.github.io/wind-js/](http://esri.github.io/wind-js/)

## The Data

For more information about GFS data visit: [GFS Data](http://nomads.ncdc.noaa.gov/data.php?name=access#hires_weather_datasets).

Before GFS data can be used with this code it has to be converted into JSON. To do this we used another awesome project by @cambecc here [https://github.com/cambecc/grib2json](https://github.com/cambecc/grib2json). That tool converts data in the GRIB2 file format into a JSON structure with the grid represented as an array. An example result of that tool can be seen in the `gfs.json` file.

## Resources

* [https://github.com/cambecc/earth](https://github.com/cambecc/earth)
* [http://earth.nullschool.net/](http://earth.nullschool.net/)
* [GFS Data](http://nomads.ncdc.noaa.gov/data.php?name=access#hires_weather_datasets)
* [ArcGIS Developers](http://developers.arcgis.com)
* [twitter@esri](http://twitter.com/esri)

## Issues

Find a bug or want to request a new feature?  Please let us know by submitting an issue.

## Contributing

Esri welcomes contributions from anyone and everyone. Please see our [guidelines for contributing](https://github.com/esri/contributing).

## Credit

All the credit for this work goes to: https://github.com/cambecc for creating the repo: https://github.com/cambecc/earth. The majority of this code is directly taken from there, since it's utterly awesome.

## Licensing

This project inherits the MIT license from it's [original code base](https://github.com/cambecc/earth) from which 95% of this code was "cp'd"

A copy of the license is available in the repository's [license.txt]( https://raw.github.com/Esri/wind-js/master/license.txt) file.

[](Esri Tags: ArcGIS Web Mapping Visualization Wind Canvas Animation)
[](Esri Language: JavaScript)


text:
package io.pratik.dynamodbspring;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DynamodbspringApplicationTests {

	@Test
	void contextLoads() {
	}

}


text:
<?php
/**
 * @license https://raw.github.com/mediaslave/phrails/master/LICENSE The MIT License
 * @package exceptions
 */

/**
* @package exceptions
* @author Justin Palmer
*/
class RecordNotFoundException extends Exception
{

	function __construct($query, $params)
	{
		$query = preg_replace('/\?/', '%s', $query);
		$query = vsprintf($query, $params);
		parent::__construct("The record could not be found. Query prepared: $query");
	}
}


text:
  Les Pieux est
      une commune localisée dans le département de Manche en Basse-Normandie. Elle comptait 3 387 habitants en 2008.

La localité dispose en ce qui concerne l'éducation des jeunes de un collège.
S'agissant les moins de 6 ans, la localité est pourvue pour le bien être de sa population de une maternelle et une école primaire.
Les Pieux propose les équipements éducatifs facilitant une éducation de qualité.
Si vous avez un projet d'achat immobilier à Les Pieux, vous devrez impérativement évaluer la qualité des écoles de la communes

À Les Pieux, la valorisation moyenne à la vente d'un appartement se situe à 1 937 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 426 € du m². À la location le prix moyen se situe à 7,37 € du m² mensuel.

À proximité de Les Pieux sont positionnées géographiquement les communes de
Le Rozel à 3 km, 268 habitants,
Helleville à 4 km, 418 habitants,
Grosville localisée à 4 km, 689 habitants,
Tréauville localisée à 1 km, 675 habitants,
Flamanville localisée à 4 km, 1 686 habitants,
Benoîtville située à 2 km, 541 habitants,
 entre autres. De plus, Les Pieux est située à seulement 19 km de Cherbourg-Octeville.

Le parc de logements, à Les Pieux, était réparti en 2011 en 92 appartements et 1 464 maisons soit
 un marché relativement équilibré.

La commune compte de multiples  équipements, elle propose entre autres un bassin de natation, un terrain de tennis, un centre d'équitation et une base nautique.

À Les Pieux le salaire moyen par mois par personne se situe à approximativement 2 366 €  net. Ceci est supérieur à la moyenne du pays.