text:
using namespace std;

namespace g2o {

  OptimizationAlgorithmLevenberg::OptimizationAlgorithmLevenberg(Solver* solver) :
    OptimizationAlgorithmWithHessian(solver)
  {
    _currentLambda = -1.;
    _tau = 1e-5;
    _goodStepUpperScale = 2./3.;
    _goodStepLowerScale = 1./3.;
    _userLambdaInit = _properties.makeProperty<Property<double> >("initialLambda", 0.);
    _maxTrialsAfterFailure = _properties.makeProperty<Property<int> >("maxTrialsAfterFailure", 10);
    _ni=2.;
    _levenbergIterations = 0;
    _nBad = 0;
  }

  OptimizationAlgorithmLevenberg::~OptimizationAlgorithmLevenberg()
  {
  }

  OptimizationAlgorithm::SolverResult OptimizationAlgorithmLevenberg::solve(int iteration, bool online)
  {
    assert(_optimizer && "_optimizer not set");
    assert(_solver->optimizer() == _optimizer && "underlying linear solver operates on different graph");

    if (iteration == 0 && !online) { // built up the CCS structure, here due to easy time measure
      bool ok = _solver->buildStructure();
      if (! ok) {
        cerr << __PRETTY_FUNCTION__ << ": Failure while building CCS structure" << endl;
        return OptimizationAlgorithm::Fail;
      }
    }

    double t=get_monotonic_time();
    _optimizer->computeActiveErrors();
    G2OBatchStatistics* globalStats = G2OBatchStatistics::globalStats();
    if (globalStats) {
      globalStats->timeResiduals = get_monotonic_time()-t;
      t=get_monotonic_time();
    }

    double currentChi = _optimizer->activeRobustChi2();
    double tempChi=currentChi;

    double iniChi = currentChi;

    _solver->buildSystem();
    if (globalStats) {
      globalStats->timeQuadraticForm = get_monotonic_time()-t;
    }

    // core part of the Levenbarg algorithm
    if (iteration == 0) {
      _currentLambda = computeLambdaInit();
      _ni = 2;
      _nBad = 0;
    }

    double rho=0;
    int& qmax = _levenbergIterations;
    qmax = 0;
    do {
      _optimizer->push();
      if (globalStats) {
        globalStats->levenbergIterations++;
        t=get_monotonic_time();
      }
      // update the diagonal of the system matrix
      _solver->setLambda(_currentLambda, true);
      bool ok2 = _solver->solve();
      if (globalStats) {
        globalStats->timeLinearSolution+=get_monotonic_time()-t;
        t=get_monotonic_time();
      }
      _optimizer->update(_solver->x());
      if (globalStats) {
        globalStats->timeUpdate = get_monotonic_time()-t;
      }

      // restore the diagonal
      _solver->restoreDiagonal();

      _optimizer->computeActiveErrors();
      tempChi = _optimizer->activeRobustChi2();

      if (! ok2)
        tempChi=std::numeric_limits<double>::max();

      rho = (currentChi-tempChi);
      double scale = computeScale();
      scale += 1e-3; // make sure it's non-zero :)
      rho /=  scale;

      if (rho>0 && g2o_isfinite(tempChi)){ // last step was good
        double alpha = 1.-pow((2*rho-1),3);
        // crop lambda between minimum and maximum factors
        alpha = (std::min)(alpha, _goodStepUpperScale);
        double scaleFactor = (std::max)(_goodStepLowerScale, alpha);
        _currentLambda *= scaleFactor;
        _ni = 2;
        currentChi=tempChi;
        _optimizer->discardTop();
      } else {
        _currentLambda*=_ni;
        _ni*=2;
        _optimizer->pop(); // restore the last state before trying to optimize
      }
      qmax++;
    } while (rho<0 && qmax < _maxTrialsAfterFailure->value() && ! _optimizer->terminate());

    if (qmax == _maxTrialsAfterFailure->value() || rho==0)
      return Terminate;

    //Stop criterium (Raul)
    if((iniChi-currentChi)*1e3<iniChi)
        _nBad++;
    else
        _nBad=0;

    if(_nBad>=3)
        return Terminate;

    return OK;
  }

  double OptimizationAlgorithmLevenberg::computeLambdaInit() const
  {
    if (_userLambdaInit->value() > 0)
      return _userLambdaInit->value();
    double maxDiagonal=0.;
    for (size_t k = 0; k < _optimizer->indexMapping().size(); k++) {
      OptimizableGraph::Vertex* v = _optimizer->indexMapping()[k];
      assert(v);
      int dim = v->dimension();
      for (int j = 0; j < dim; ++j){
        maxDiagonal = std::max(fabs(v->hessian(j,j)),maxDiagonal);
      }
    }
    return _tau*maxDiagonal;
  }

  double OptimizationAlgorithmLevenberg::computeScale() const
  {
    double scale = 0.;
    for (size_t j=0; j < _solver->vectorSize(); j++){
      scale += _solver->x()[j] * (_currentLambda * _solver->x()[j] + _solver->b()[j]);
    }
    return scale;
  }

  void OptimizationAlgorithmLevenberg::setMaxTrialsAfterFailure(int max_trials)
  {
    _maxTrialsAfterFailure->setValue(max_trials);
  }

  void OptimizationAlgorithmLevenberg::setUserLambdaInit(double lambda)
  {
    _userLambdaInit->setValue(lambda);
  }

  void OptimizationAlgorithmLevenberg::printVerbose(std::ostream& os) const
  {
    os
      << "\t schur= " << _solver->schur()
      << "\t lambda= " << FIXED(_currentLambda)
      << "\t levenbergIter= " << _levenbergIterations;
  }

} // end namespace


text:
Ext.define('Flamingo.view.hdfsbrowser.viewer.FileViewerController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.fileViewerViewController',

    /**
     * File Viewer 창을 화면에 표시한 후 서버로부터 전달된 파일 내용을 화면에 표시한다.
     *
     * @param window File Viewer 창
     */
    onAfterRender: function (window) {
        var me = this;
        var refs = me.getReferences();
        var totalPage = window.propertyData.totalPage;

        refs.fileViewerContentsForm.getForm().setValues(window.propertyData);

        /**
         * 전체 페이지 범위가 1일 때 Next Button과 Last Button을 비활성화 한다.
         */
        if (window.propertyData.totalPage == window.propertyData.currentPage) {
            refs.nextButton.setDisabled(true);
            refs.lastButton.setDisabled(true);
        }

        // Total Page 크기에 따라 input number field width 조정.
        if (totalPage > 0 && totalPage < 100) {
            refs.currentPage.width = 30;
        } else if (totalPage > 100 && totalPage < 1000) {
            refs.currentPage.width = 35;
        } else if (totalPage > 1000 && totalPage < 10000) {
            refs.currentPage.width = 40;
        } else if (totalPage > 10000 && totalPage < 100000) {
            refs.currentPage.width = 45;
        } else if (totalPage > 100000 && totalPage < 1000000) {
            refs.currentPage.width = 55;
        } else {
            refs.currentPage.width = 60;
        }
    },

    /**
     * 첫 시작 페이지로 이동한다.
     */
    onFirstPageButtonClick: function () {
        var me = this;
        var refs = me.getReferences();
        var contentsFormValues = refs.fileViewerContentsForm.getForm().getValues();
        var url = CONSTANTS.FS.HDFS_GET_FILE_CONTENTS;
        var params = {
            filePath: contentsFormValues.filePath,
            fileSize: contentsFormValues.fileSize,
            dfsBlockSize: contentsFormValues.dfsBlockSize,
            chunkSizeToView: config['hdfs.viewFile.default.chunkSize'],
            startOffset: 0,
            dfsBlockStartOffset: 0,
            currentContentsBlockSize: 0,
            lastDfsBlockSize: 0,
            currentPage: 0,
            totalPage: contentsFormValues.totalPage,
            buttonType: 'firstButton',
            bestNode: contentsFormValues.bestNode
        };

        invokePostByMap(url, params,
            function (response) {
                var obj = Ext.decode(response.responseText);

                if (obj.success) {
                    refs.fileViewerContentsForm.getForm().setValues(obj.map);
                    refs.queryEditor.setValue(obj.map.contents);
                    refs.currentPage.setValue(obj.map['currentPage']);

                    /**
                     * Case 1. 현재 페이지가 1일 때 Fist & Previous Button 비활성화
                     * Case 2. 현재 페이지와 전체 페이지 범위가 같을 때 Next Button 비활성화
                     * Case 3. 현재 페이지가 1보다 클 때 Previous Button 활성화
                     */
                    if (refs.currentPage.getValue() == 1) {
                        refs.firstButton.setDisabled(true);
                        refs.prevButton.setDisabled(true);
                        refs.nextButton.setDisabled(false);
                        refs.lastButton.setDisabled(false);
                    }
                }
            },
            function () {
                error('Error', 'Please contact system admin');
            }
        );
    },

    /**
     * 이전 페이지로 이동한다.
     */
    onPreviousPageButtonClick: function () {
        var me = this;
        var refs = me.getReferences();
        var viewItems = me.getView();
        var contentsFormValues = refs.fileViewerContentsForm.getForm().getValues();
        var url = CONSTANTS.FS.HDFS_GET_FILE_CONTENTS;
        var params = {
            filePath: contentsFormValues.filePath,
            fileSize: contentsFormValues.fileSize,
            dfsBlockSize: contentsFormValues.dfsBlockSize,
            chunkSizeToView: config['hdfs.viewFile.default.chunkSize'],
            startOffset: contentsFormValues.startOffset,
            dfsBlockStartOffset: contentsFormValues.dfsBlockStartOffset,
            currentContentsBlockSize: contentsFormValues.currentContentsBlockSize,
            lastDfsBlockSize: contentsFormValues.lastDfsBlockSize,
            currentPage: refs.currentPage.getValue(),
            totalPage: contentsFormValues.totalPage,
            buttonType: 'prevButton',
            bestNode: contentsFormValues.bestNode
        };

        me.pageButtonStatus(true);

        invokePostByMap(url, params,
            function (response) {
                var obj = Ext.decode(response.responseText);

                if (obj.success) {
                    me.pageButtonStatus(false);
                    refs.fileViewerContentsForm.getForm().setValues(obj.map);
                    refs.queryEditor.setValue(obj.map.contents);
                    refs.currentPage.setValue(obj.map['currentPage']);

                    /**
                     * Case 1. 현재 페이지가 1일 때 Fist & Previous Button 비활성화
                     * Case 2. 현재 페이지와 전체 페이지 범위보다 적을 때 Next & Last Button 비활성화
                     * Case 3. 현재 페이지가 1보다 클 때 Previous Button 활성화
                     * Case 4. 현재 페이지와 전체 페이지 범위가 같을 때 Previous Button 비활성화
                     */
                    if (refs.currentPage.getValue() == 1) {
                        refs.firstButton.setDisabled(true);
                        refs.prevButton.setDisabled(true);
                    } else if (refs.currentPage.getValue() < viewItems.emptyPageData.total) {
                        refs.nextButton.setDisabled(false);
                        refs.lastButton.setDisabled(false);
                    } else {
                        refs.prevButton.setDisabled(false);
                    }
                }
            },
            function () {
                error('Error', 'Please contact system admin');
            }
        );
    },

    /**
     * 다음 페이지로 이동한다.
     */
    onNextPageButtonClick: function () {
        var me = this;
        var refs = me.getReferences();
        var contentsFormValues = refs.fileViewerContentsForm.getForm().getValues();
        var totalPage = contentsFormValues.totalPage;
        var url = CONSTANTS.FS.HDFS_GET_FILE_CONTENTS;

        var params = {
            filePath: contentsFormValues.filePath,
            fileSize: contentsFormValues.fileSize,
            dfsBlockSize: contentsFormValues.dfsBlockSize,
            chunkSizeToView: config['hdfs.viewFile.default.chunkSize'],
            startOffset: contentsFormValues.startOffset,
            dfsBlockStartOffset: contentsFormValues.dfsBlockStartOffset,
            currentContentsBlockSize: contentsFormValues.currentContentsBlockSize,
            startOffsetPerDfsBlocks: contentsFormValues.startOffsetPerDfsBlocks,
            lastDfsBlockSize: contentsFormValues.lastDfsBlockSize,
            currentPage: refs.currentPage.getValue(),
            totalPage: contentsFormValues.totalPage,
            buttonType: 'nextButton',
            bestNode: contentsFormValues.bestNode
        };

        me.pageButtonStatus(true);

        invokePostByMap(url, params,
            function (response) {
                var obj = Ext.decode(response.responseText);

                if (obj.success) {
                    me.pageButtonStatus(false);
                    refs.fileViewerContentsForm.getForm().setValues(obj.map);
                    refs.queryEditor.setValue(obj.map.contents);
                    refs.currentPage.setValue(obj.map['currentPage']);

                    // Case 1. 현재 페이지가 1보다 클 때 First & Previous Button 활성화
                    if (refs.currentPage.getValue() > 1) {
                        refs.firstButton.setDisabled(false);
                        refs.prevButton.setDisabled(false);
                    }

                    // Case 2. 현재 페이지와 전체 페이지 범위가 같을 때 Next & Last Button 비활성화
                    if (refs.currentPage.getValue() == totalPage) {
                        refs.nextButton.setDisabled(true);
                        refs.lastButton.setDisabled(true);
                    }
                }
            },
            function () {
                error('Error', 'Please contact system admin');
            }
        );
    },

    /**
     * 마지막 페이지로 이동한다.
     */
    onLastPageButtonClick: function () {
        var me = this;
        var refs = me.getReferences();
        var contentsFormValues = refs.fileViewerContentsForm.getForm().getValues();
        var url = CONSTANTS.FS.HDFS_GET_FILE_CONTENTS;
        var totalPage = contentsFormValues.totalPage;
        var params = {
            filePath: contentsFormValues.filePath,
            fileSize: contentsFormValues.fileSize,
            dfsBlockSize: contentsFormValues.dfsBlockSize,
            chunkSizeToView: config['hdfs.viewFile.default.chunkSize'],
            startOffset: 0,
            dfsBlockStartOffset: contentsFormValues.dfsBlockStartOffset,
            currentContentsBlockSize: contentsFormValues.currentContentsBlockSize,
            lastDfsBlockSize: contentsFormValues.lastDfsBlockSize,
            currentPage: refs.currentPage.getValue(),
            totalPage: totalPage,
            buttonType: 'lastButton',
            bestNode: contentsFormValues.bestNode
        };

        invokePostByMap(url, params,
            function (response) {
                var obj = Ext.decode(response.responseText);

                if (obj.success) {
                    refs.fileViewerContentsForm.getForm().setValues(obj.map);
                    refs.queryEditor.setValue(obj.map.contents);
                    refs.currentPage.setValue(obj.map['currentPage']);

                    // Case 1. 마지막 페이지 일 때 Next & Last Button 비활성화, First & Previous Button 활성화
                    if (refs.currentPage.getValue() == totalPage) {
                        refs.firstButton.setDisabled(false);
                        refs.prevButton.setDisabled(false);
                        refs.nextButton.setDisabled(true);
                        refs.lastButton.setDisabled(true);
                    }
                }
            },
            function () {
                error('Error', 'Please contact system admin');
            }
        );
    },

    /**
     * 입력한 페이지로 이동한다. //NIA
     */
    onEnterCustomPage: function (field, e, eOpts) {
        if (e.keyCode == 13) {
            var me = this;
            var refs = me.getReferences();
            var contentsFormValues = refs.fileViewerContentsForm.getForm().getValues();
            var totalPage = contentsFormValues.totalPage;
            var currentPage = refs.currentPage.getValue();

            if (currentPage < 1 || currentPage > totalPage) {
                return false;
            }

            if (totalPage == 1) {
                return false;
            }

            var url = CONSTANTS.FS.HDFS_GET_FILE_CONTENTS;
            var params = {
                filePath: contentsFormValues.filePath,
                fileSize: contentsFormValues.fileSize,
                dfsBlockSize: contentsFormValues.dfsBlockSize,
                chunkSizeToView: config['hdfs.viewFile.default.chunkSize'],
                startOffset: 0, // Service Side에서 Page 정보로 startOffset 결정
                dfsBlockStartOffset: contentsFormValues.dfsBlockStartOffset,
                currentContentsBlockSize: contentsFormValues.currentContentsBlockSize,
                startOffsetPerDfsBlocks: contentsFormValues.startOffsetPerDfsBlocks,
                lastDfsBlockSize: contentsFormValues.lastDfsBlockSize,
                currentPage: currentPage,
                totalPage: contentsFormValues.totalPage,
                buttonType: 'customPage',
                bestNode: contentsFormValues.bestNode
            };

            invokePostByMap(url, params,
                function (response) {
                    var obj = Ext.decode(response.responseText);

                    if (obj.success) {
                        refs.fileViewerContentsForm.getForm().setValues(obj.map);
                        refs.queryEditor.setValue(obj.map.contents);
                        refs.currentPage.setValue(obj.map['currentPage']);
                        var updatedCurrentPage = refs.currentPage.getValue();

                        // Case 1. 현재 페이지가 1보다 클 때 First & Previous Button 활성화
                        if (updatedCurrentPage == 1) {
                            refs.firstButton.setDisabled(true);
                            refs.prevButton.setDisabled(true);
                            refs.nextButton.setDisabled(false);
                            refs.lastButton.setDisabled(false)
                        } else if (updatedCurrentPage > 1 && updatedCurrentPage != totalPage) {
                            refs.firstButton.setDisabled(false);
                            refs.prevButton.setDisabled(false);
                            refs.nextButton.setDisabled(false);
                            refs.lastButton.setDisabled(false)
                        } else if (updatedCurrentPage == totalPage) {
                            refs.firstButton.setDisabled(false);
                            refs.prevButton.setDisabled(false);
                            refs.nextButton.setDisabled(true);
                            refs.lastButton.setDisabled(true)
                        } else {
                            refs.nextButton.setDisabled(true);
                            refs.lastButton.setDisabled(true)
                        }
                    }
                },
                function () {
                    error('Error', 'Please contact system admin');
                }
            );
        }
    },

    /**
     * 비활성된 페이지 버튼을 활성화 시킨다.
     *
     * @param value
     */
    pageButtonStatus: function (value) {
        var me = this;
        var refs = me.getReferences();

        refs.firstButton.setDisabled(value);
        refs.prevButton.setDisabled(value);
        refs.nextButton.setDisabled(value);
        refs.lastButton.setDisabled(value);
    }
});

redpajama_set_name: RedPajamaGithub


text:
#include "stdafx.h"
#include "GeographicLib/Georef.hpp"
#include "Georef.h"
#include "NETGeographicLib.h"

using namespace NETGeographicLib;

//*****************************************************************************
void Georef::Forward(double lat, double lon, int prec, System::String^% georef)
{
    try
    {
        std::string l;
        GeographicLib::Georef::Forward( lat, lon, prec, l );
        georef = gcnew System::String( l.c_str() );
    }
    catch ( const std::exception& xcpt )
    {
        throw gcnew GeographicErr( xcpt.what() );
    }
}

//*****************************************************************************
void Georef::Reverse( System::String^ georef,  double% lat,  double% lon,
        int% prec, bool centerp)
{
    try
    {
        double llat, llon;
        int lprec;
        GeographicLib::Georef::Reverse( StringConvert::ManagedToUnmanaged( georef ),
            llat, llon, lprec, centerp );
        lat = llat;
        lon = llon;
        prec = lprec;
    }
    catch ( const std::exception& err )
    {
        throw gcnew GeographicErr( err.what() );
    }
}

//*****************************************************************************
double Georef::Resolution(int prec) { return GeographicLib::Georef::Resolution(prec); }

//*****************************************************************************
int Georef::Precision(double res) { return GeographicLib::Georef::Precision(res); }


text:
package com.ibm.janusgraph.utils.importer.edge;

import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;

import org.apache.log4j.Logger;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
import org.janusgraph.core.SchemaViolationException;

import com.ibm.janusgraph.utils.importer.util.BatchHelper;
import com.ibm.janusgraph.utils.importer.util.Config;
import com.ibm.janusgraph.utils.importer.util.Constants;
import com.ibm.janusgraph.utils.importer.util.Worker;

public class EdgeLoaderWorker extends Worker {
	private final UUID myID = UUID.randomUUID();
	private final int COMMIT_COUNT;
	private JanusGraphTransaction graphTransaction;
	private long currentRecord;
	private final String defaultEdgeLabel;
	private String edgeLabelFieldName;

	private Logger log = Logger.getLogger(EdgeLoaderWorker.class);
    private GraphTraversalSource traversal;

	public EdgeLoaderWorker(final Iterator<Map<String, String>> records, final Map<String, Object> propertiesMap,
			final JanusGraph graph) {
		super(records, propertiesMap, graph);

		this.currentRecord = 0;
		this.defaultEdgeLabel = (String) propertiesMap.get(Constants.EDGE_LABEL_MAPPING);
		this.edgeLabelFieldName = null;
		COMMIT_COUNT = Config.getConfig().getEdgeRecordCommitCount();
		if (propertiesMap.values().contains(Constants.EDGE_LABEL_MAPPING)) {
			for (String propName : propertiesMap.keySet()) {
				if (Constants.EDGE_LABEL_MAPPING.equals(propertiesMap.get(propName))) {
					this.edgeLabelFieldName = propName;
					break;
				}
			}
		}
	}

	private void acceptRecord(Map<String, String> record) throws Exception {
		String edgeLabel = defaultEdgeLabel;
		if (edgeLabelFieldName != null) {
			edgeLabel = record.get(edgeLabelFieldName);
		}

		// Get the left and right edge labels

		Map<String, String> leftEdge = (Map<String, String>) getPropertiesMap().get(Constants.EDGE_LEFT_MAPPING);
		String leftEdgeFieldName = leftEdge.keySet().iterator().next();
		String leftVertex = leftEdge.get(leftEdgeFieldName);
		String leftVertexLabel = leftVertex.substring(0, leftVertex.indexOf('.'));
		String leftVertexFieldName = leftVertex.substring(leftVertex.indexOf('.') + 1);

		Map<String, String> rightEdge = (Map<String, String>) getPropertiesMap().get(Constants.EDGE_RIGHT_MAPPING);
		String rightEdgeFieldName = rightEdge.keySet().iterator().next();
		String rightVertex = rightEdge.get(rightEdgeFieldName);
		String rightVertexLabel = rightVertex.substring(0, rightVertex.indexOf('.'));
		String rightVertexFieldName = rightVertex.substring(rightVertex.indexOf('.') + 1);

		Iterator<Vertex> node_1 = traversal.V().has(leftVertexLabel, leftVertexFieldName,
				record.get(leftEdgeFieldName));
		Iterator<Vertex> node_2 = traversal.V().has(rightVertexLabel, rightVertexFieldName,
				record.get(rightEdgeFieldName));

		try {
			if (node_1.hasNext() && node_2.hasNext()) {
				Vertex v1 = node_1.next();
				Vertex v2 = node_2.next();
				Edge edge = v1.addEdge(edgeLabel, v2);

				// set the properties of the edge
				for (String column : record.keySet()) {
					String value = record.get(column);
					// If value="" or it is edge label then skip it
					if (value == null || value.length() == 0 || column.equals(edgeLabelFieldName)
							|| column.equals(leftEdgeFieldName) || column.equals(rightEdgeFieldName))
						continue;

					String propName = (String) getPropertiesMap().get(column);
					if (propName == null) {
						// log.info("Thread " + myID + ".Cannot find
						// property name
						// for column " + column
						// + " in the properties map. Using the column name
						// as
						// default.");
						// propName = column;
						continue;
					}

					// Update property only if it does not exist already
					if (!edge.properties(propName).hasNext()) {
						Object convertedValue = BatchHelper.convertPropertyValue(value,
								graphTransaction.getPropertyKey(propName).dataType());
						edge.property(propName, convertedValue);
					}
				}
			} else {
                log.error("Vertex1 or Vertex2 not found.");
			}
		} catch (SchemaViolationException e) {
            log.warn(e.getMessage());
        } catch (Exception e) {
			throw e;
		}
		if (currentRecord % COMMIT_COUNT == 0) {
			graphTransaction.commit();
			graphTransaction.close();
			graphTransaction = getGraph().newTransaction();
			traversal = graphTransaction.traversal();
		}
		currentRecord++;
	}

	public UUID getMyID() {
		return myID;
	}

	@Override
	public void run() {
		log.info("Starting new thread " + myID);

		// Start new graph transaction
		graphTransaction = getGraph().newTransaction();
		this.traversal = graphTransaction.traversal();
		getRecords().forEachRemaining(new Consumer<Map<String, String>>() {
			@Override
			public void accept(Map<String, String> record) {
				try {
					acceptRecord(record);
				} catch (Exception e) {
					log.error("Thread " + myID + ". Exception during record import.", e);
				}
			}

		});
		graphTransaction.commit();
		graphTransaction.close();

		graphTransaction = null;
		log.info("Finished thread " + myID);
	}
}


text:
"use strict";
let React = require("react/addons");
let Loader = require("./common/loader");
let ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
let Bluebird = require("bluebird");
let ListDisplay = require("./common/list_display");
let DrugListItem = require("./drugs/drug_list_item");
let EmptyState = require("./common/empty_state");

let SubscriptionStore = require("../stores/subscription_store");
let DrugStore = require("../stores/drug_store");

let subscriptionStore = new SubscriptionStore();
let drugStore = new DrugStore();

let MyDrugs = React.createClass({
    getInitialState: function () {
        return {
            loading: true,
            subscriptions: []
        };
    },

    componentDidMount: function () {
        this.getStateFromStore();
    },

    getStateFromStore: function () {
        this.setState({loading: true});
        subscriptionStore.list({
            fields: "openfda.brand_name"
        })
            .then((result) => result.items)
            .then((subscriptions) => subscriptions ? Bluebird.all(subscriptions.map((sub) => drugStore.get(sub.splSetId))) : [])
            .then((subscribedDrugs) => this.setState({subscriptions: subscribedDrugs, loading: false}))
            .catch((err) => {
                console.error("Error loading subscriptions", err, err.stack);
                this.setState({loading: false});
            });
    },

    _getEmptyState: function () {
        return (
            <EmptyState>

No saved drugs yet.

Search for drugs, then save them for later.

            </EmptyState>
        );
    },

    render: function () {
        let subs = [];
        this.state.subscriptions.forEach((sub) => {
            let brand = sub.openfda.brand_name[0];
            subs.push(
{brand}
);
        });
        return (

                <ReactCSSTransitionGroup component="div" transitionName="transition" transitionAppear={true}>
                    { !this.state.loading ?

My saved drugs

                            { this.state.subscriptions.length ?
                                <ListDisplay
                                    itemName={"drug"}
                                    itemHeight={65}
                                    itemComponent={DrugListItem}
                                    key={this.state.value}
                                    data={this.state.subscriptions}/>
                                : this._getEmptyState() }

                        : null
                    }
                    { this.state.loading ? <Loader/> : null }
                </ReactCSSTransitionGroup>

        );
    }
});

module.exports = MyDrugs;


text:
<form class="" (ngSubmit)="onSubmit()" [ngFormModel]="psForm">

		{{program.cRPId?'修改展示型奖励':'新建展示型奖励'}}
		<button class="rd-save" [disabled]="loading" type="submit"></button>

奖励正在运行中,修改内容并保存后将立即生效,请谨慎操作!

				<input type="hidden" name="cRPRewardType" [ngFormControl]="psForm.controls['cRPRewardType']" [(ngModel)]="program.cRPRewardType" >

基础信息

*奖励方案名称:

							<input class="inputtxt input-287" type="text" maxlength="8" name="cRPName" [(ngModel)]="program.cRPName" [ngFormControl]="psForm.controls['cRPName']" required placeholder="最多显示8个字">
							<input class="re-ckb re-pr" type="checkbox" name="cRPNameShow" [ngFormControl]="psForm.controls['cRPNameShow']" [(ngModel)]="program.cRPNameShow" value="1" id="ckb-name"> 显示

								奖励方案名称不能为空

奖励副标题:

							<input class="inputtxt input-287" type="text" name="cRPSubtitle" [ngFormControl]="psForm.controls['cRPSubtitle']" [(ngModel)]="program.cRPSubtitle"  maxlength="12"  placeholder="最多显示12个字">
							<input class="re-ckb re-pr" type="checkbox" name="cRPSubtitleShow"  [ngFormControl]="psForm.controls['cRPSubtitleShow']" [(ngModel)]="program.cRPSubtitleShow" value="1" id="ckb-subname"> 显示

自定义背景图:<input class="re-ckb" type="checkbox" [ngFormControl]="psForm.controls['cRPBackgroundShow']" [(ngModel)]="program.cRPBackgroundShow"  name="cRPBackgroundShow" id="ckb-bg"> 启用

请使用240*74比例的的PNG,JPG透明图片,小于2M

									<input type="file" name="fileName" accept="image/gif,image/jpeg,image/png" [ng-file-select]="options" (onUpload)="handleUpload($event)" >

选择文件

											{{basicProgress + '%'}}

									已上传图片  {{basicResp?.originalName||uploadFile?.data}}

										<input type="file" accept="image/gif,image/jpeg,image/png" name="fileName" [ng-file-select]="options" (onUpload)="handleUpload($event)" >

重新上传

删除

												{{basicProgress + '%'}}

									{{uploadFile.error.msg}}

										<input type="file" accept="image/gif,image/jpeg,image/png" name="fileName" [ng-file-select]="options" (onUpload)="handleUpload($event)" >

重新上传

删除

												{{basicProgress + '%'}}

活动说明:<input class="re-ckb" type="checkbox" name="cRPDescShow" [ngFormControl]="psForm.controls['cRPDescShow']" [(ngModel)]="program.cRPDescShow" value="1"  id="ckb-des"> 显示

							<textarea name="cRPDesc" id="" cols="30" rows="10" [ngFormControl]="psForm.controls['cRPDesc']" [(ngModel)]="program.cRPDesc" ></textarea>

奖励规则

有效日期:

自定义

发放后当日

发放后24小时

发放后7日

发放后30日

							<input name="cRPValidType" type="hidden" [ngFormControl]="psForm.controls['cRPValidType']" [(ngModel)]="program.cRPValidType" >

								<input type="text" readonly (click)="onShowDate($event)" name="name" class="inputtxt" [value]="program.cRPValidStartDate+'~'+program.cRPValidEndDate" style="width:100%" value="">

										<datepicker [ngModel]="program.cRPValidStartDate" (ngModelChange)="program.cRPValidStartDate = moment($event)"  [showWeeks]="true"></datepicker>

										<datepicker [ngModel]="program.cRPValidEndDate" (ngModelChange)="program.cRPValidEndDate = moment($event)" [showWeeks]="true"></datepicker>

结束时间大于开始时间

							*发放总量:

							<input class="inputtxt input-157" [disabled]="program.cRPId" pattern="^([1-9][0-9]{0,4}|100000)$" type="text" name="totalRewards" required [ngFormControl]="psForm.controls['totalRewards']" [(ngModel)]="program.totalRewards" placeholder="输入1~100,000的数字">张

								<input type="text" (keyup)="!additionalNumControl.hasError('required')&&!additionalNumControl.hasError('pattern')&&onEnterAddTotal($event)" [(ngModel)]="additionalNum" pattern="^([1-9][0-9]{0,4}|100000)$" [ngFormControl]="psForm.controls['additionalNumControl']" placeholder="输入1~100,000的数字">
								<button class="add-btn" (click)="onAddTotal()" [disabled]="additionalNumControl.hasError('pattern')"></button>

							输入不符合规则,请输入1~100,000的整数

							输入不符合规则,请输入1~100,000的整数

							输入不符合规则,请输入1~100,000的整数

发放规则:

							<input class="re-ckb re-ckb-radio" type="radio" name="cRPRate" [checked]="program.cRPRate===1"  (click)="program.cRPRate=1"  id="rule-type-1"> 人人有奖

							<input class="re-ckb re-ckb-radio" type="radio" name="cRPRate" [checked]="program.cRPRate===2"  (click)="program.cRPRate=2" id="rule-type-2"> 自定义比例
							<input class="inputtxt input-71" [disabled]="program.cRPRate===1" name="cRPRateContent" pattern="^([0-9]{1,2}((\.\d\d)|(\.\d))?|100)$" [ngFormControl]="psForm.controls['cRPRateContent']" [(ngModel)]="program.cRPRateContent" type="text">%
							输入1~100的数字

							输入1~100的数字,实际输入超出范围的数字,或者字母

							{{psForm.value.cRPName}}

							{{psForm.value.cRPSubtitle}}

</form>


text:
<?php

/**
 * @license Apache 2.0
 */

namespace Swagger\Processors;

use Swagger\Annotations\Property;
use Swagger\Annotations\Swagger;
use Swagger\Annotations\Definition;
use Swagger\Analysis;

/**
 * Copy the annotated properties from parent classes;
 */
class InheritProperties
{

    public function __invoke(Analysis $analysis)
    {
        $schemas = $analysis->getAnnotationsOfType('\Swagger\Annotations\Schema');
        foreach ($schemas as $schema) {
            if ($schema->_context->is('class')) {
                $existing = [];
                foreach ($schema->properties as $property) {
                    if ($property->property) {
                        $existing[] = $property->property;
                    }
                }
                $classes = $analysis->getSuperClasses($schema->_context->fullyQualifiedName($schema->_context->class));
                foreach ($classes as $class) {
                    foreach ($class['properties'] as $property) {
                        foreach ($property->annotations as $annotation) {
                            if ($annotation instanceof Property && in_array($annotation->property, $existing) === false) {
                                $existing[] = $annotation->property;
                                $schema->merge([$annotation], true);
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
package org.fax4j.spi.email;

import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Transport;
import org.fax4j.FaxException;

/**
 * This class provides basic implementation of the mail connection factory.
 *
 * @author Sagie Gur-Ari
 * @version 1.02
 * @since 0.39a
 */
public class MailConnectionFactoryImpl extends AbstractMailConnectionFactory {
    /**
     * This is the class constructor.
     */
    public MailConnectionFactoryImpl() {
        super();
    }

    /**
     * Creates and returns the resource.
     *
     * @return The resource
     */
    @Override
    protected MailResourcesHolder createResourceImpl() {
        // create authenticator
        Authenticator authenticator = null;
        if (this.password != null) {
            authenticator = new MailAuthenticator(this.userName, this.password);
        }

        // create session
        Session session = Session.getInstance(this.mailConnectionProperties, authenticator);

        // create transport
        Transport transport = this.createTransport(session);

        // create holder
        MailResourcesHolder resource = new MailResourcesHolder(session, transport);

        return resource;
    }

    /**
     * This function returns a transport for the provided session.
     *
     * @param session
     *            The mail session
     * @return The mail transport
     */
    protected Transport createTransport(Session session) {
        Transport transport = null;
        try {
            // get the transport
            transport = session.getTransport(this.transportProtocol);

            // connect
            if (this.transportPort > 0) {
                transport.connect(this.transportHost, this.transportPort, this.userName, this.password);
            } else {
                transport.connect(this.transportHost, this.userName, this.password);
            }
        } catch (Exception exception) {
            throw new FaxException("Error while connecting to mail host: " + this.transportHost, exception);
        }

        return transport;
    }

    /**
     * Releases the resource from the connection.
     *
     * @param resource
     *            The resource
     */
    @Override
    protected void releaseResourceImpl(MailResourcesHolder resource) {
        // get transport
        Transport transport = resource.getTransport();

        if (transport != null && transport.isConnected()) {
            try {
                // close connection
                transport.close();
            } catch (Throwable throwable) { // NOPMD
                // ignore
            }
        }
    }
}


text:
import ButtonGroup from '../../components/button-group'
import Code from '../../components/code'
import Layout from '../../components/layout'
import Link from '../../components/link'
import Subtitle from '../../components/subtitle'
import Title from '../../components/title'

export default () => (
  <Layout title="Wilderness shape function">
    <Title>
      The shape function
    </Title>

      Creates a <Link href="/api/definitions#shape">Shape</Link> when passed one
      or more <Link href="/api/definitions#plain-shape-object">Plain Shape
      Object</Link>.

    {`
shape(plainShapeObject1, plainShapeObject2, ..., options)
    `}

    <Subtitle id="arguments">
      Arguments
    </Subtitle>

        plainShapeObject1, plainShapeObject2, ...

      A list of one or more Plain Shape Object. Each Plain Shape Object will
      create a <Link href="/api/definitions#keyframe">Keyframe</Link>.

      A Plain Shape Object can also be created on the fly by passing a DOM node
      as the el property. For example, the following two
      Shapes could be identicle:

    {`
const shape1 = shape({ type: 'circle', cx: 10, cy: 10, r: 5, fill: 'yellow' })
const shape2 = shape({ el: document.querySelector('circle') })
    `}

        options
       {' '}
      (optional)

      An object, where:

        name (optional) is a string or
        number.

        replace (optional) is a DOM node to
        be replaced when this Shape is rendered.

    <Subtitle id="return-value">
      Return value
    </Subtitle>

      A Shape.

    <ButtonGroup>
      <Link href="/getting-started/create-a-shape" button primary>
        Lesson: Create a shape
      </Link>

      <Link href="/api/the-render-function" button>
        Next up: The render function
      </Link>
    </ButtonGroup>
  </Layout>
)


text:
using System.Collections.Generic;
using bytePassion.Lib.FrameworkExtensions;
using OQF.Bot.Contracts.GameElements;
using OQF.Bot.Contracts.Moves;

namespace OQF.Utils.BoardStateUtils
{
	public static class BoardStateTransition
	{
		public static BoardState CreateInitialBoadState(Player topPlayer, Player bottomPlayer)
		{
			return new BoardState(new List<Wall>(),
								  PlayerTransitions.InitialPlayerStateCreation(topPlayer),
								  PlayerTransitions.InitialPlayerStateCreation(bottomPlayer),
								  bottomPlayer,
								  null,
								  null);
		}

		public static BoardState ApplyMove (this BoardState currentBoardState, Move move)
		{
			var wallMove = move as WallMove;
			if (wallMove != null)
			{
				var topPlayerState = currentBoardState.TopPlayer.Player == currentBoardState.CurrentMover
											? currentBoardState.TopPlayer.SpendWall()
											: currentBoardState.TopPlayer;

				var bottomPlayerState = currentBoardState.BottomPlayer.Player == currentBoardState.CurrentMover
											? currentBoardState.BottomPlayer.SpendWall()
											: currentBoardState.BottomPlayer;

				return new BoardState(currentBoardState.PlacedWalls.Append(wallMove.PlacedWall),
									  topPlayerState,
									  bottomPlayerState,
									  currentBoardState.GetNextMover(),
									  currentBoardState,
									  move);
			}
			else if (move is FigureMove)
			{
				var fieldMove = (FigureMove) move;

				var topPlayerState = currentBoardState.TopPlayer.Player == currentBoardState.CurrentMover
					? currentBoardState.TopPlayer.MovePlayer(fieldMove.NewPosition)
					: currentBoardState.TopPlayer;

				var bottomPlayerState = currentBoardState.BottomPlayer.Player == currentBoardState.CurrentMover
					? currentBoardState.BottomPlayer.MovePlayer(fieldMove.NewPosition)
					: currentBoardState.BottomPlayer;

				return new BoardState(currentBoardState.PlacedWalls,
					topPlayerState,
					bottomPlayerState,
					currentBoardState.GetNextMover(),
					currentBoardState,
					move);
			}
			else
			{
				return new BoardState(currentBoardState.PlacedWalls,			//
									  currentBoardState.TopPlayer,				//
									  currentBoardState.BottomPlayer,			//	capitulation
									  currentBoardState.GetNextMover(),			//
									  currentBoardState,						//
									  move);									//
			}

		}

		private static Player GetNextMover(this BoardState currentBoardState)
		{
			return currentBoardState.CurrentMover == currentBoardState.TopPlayer.Player
						? currentBoardState.BottomPlayer.Player
						: currentBoardState.TopPlayer.Player;

		}
	}
}


text:
<!DOCTYPE HTML>

<title>QueryPlanCollector (ebean api 13.6.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-05-03">
<meta name="description" content="declaration: module: io.ebean.api, package: io.ebean.metric, interface: QueryPlanCollector">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Module io.ebean.api

Package io.ebean.metric

Interface QueryPlanCollector

public interface QueryPlanCollector

Object used to collect query plan metrics.

Method Summary

<button id="method-summary-table-tab0" role="tab" aria-selected="true" aria-controls="method-summary-table.tabpanel" tabindex="0" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table', 3)" class="active-table-tab">All Methods</button><button id="method-summary-table-tab2" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab2', 3)" class="table-tab">Instance Methods</button><button id="method-summary-table-tab3" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab3', 3)" class="table-tab">Abstract Methods</button>

Modifier and Type

Method

Description

void

add<wbr>(MetaQueryMetric stats)

Add the query plan statistic.

List<MetaQueryMetric>

complete()

Return all the collected query plan statistics.

boolean

isReset()

Return true if the statistics should be reset.

Method Details

isReset

boolean isReset()

Return true if the statistics should be reset.

add

void add<wbr>(MetaQueryMetric stats)

Add the query plan statistic.

complete

List<MetaQueryMetric> complete()

Return all the collected query plan statistics.

Copyright © 2022. All rights reserved.


text:
class Paymentstat < ActiveRecord::Base
    has_many :salaries
end


text:
* fix: fix Win32 builds

## v0.4.5

* feat: add support for Electron 5, Node 12

## v0.4.4

* hotfix: fix corrupted 0.4.3 release.

## v0.4.3

* feat: ability to build for a single platform/target.

## v0.4.2

* fix: use cmake-js fork to support Electron 4+ on Windows.

## v0.4.1

* fix: use VS C++ for Electron >= v4.

## v0.4.0

* feat: add support for Electron 4.

## v0.3.1

* fix: allow use of iohook.registerShortcut without a 3rd releaseCallback argument.

## v0.3.0

* feat: drop segfault-handler dependency.

## v0.2.6

* feat: add support for Node 10

## v0.2.5

* feat: git@github.com:wilix-team/iohook.git
* fix: fix documentation link.
* chore : repo transfered to wilix-team org.

## v0.2.4

* feat: ability to listen for when a keyboard shortcut has been released
* feat: ability to unregister a shortcut via the shortcut's keys

## v0.2.3

* feat: Bump libuiohook version
* chore: many travis build improvements

## v0.2.2
 * feat: Add support for Node 10 (for real this time...)

## v0.2.1

* feat: Add support for Electron 2.0
* feat: Drop support for node < 6, electron < 1.2

## v0.2.0

* feat: Add modifier keys support
* feat: Add online documentation
* feat: Add tests (reverted for now)

## v0.1.16

* feat: Add support for Electron 2.0
* feat: Add support for NodeJS 10.x
* deprecation: Drop support for Linux ia32 (like NodeJS itself)

## v0.1.15

* feat: Bump libiohook to version 1.1


text:
<!--
The `fin-hypergrid-behavior-qtree` element is a custom Polymer web component used to support the openfin [fin-hypergrid](http://github.com/openfin/fin-hypergrid) component.
@group OpenFin hypergrid
@element fin-hypergrid-behavior-qtree
@homepage http://github.com/openfin/fin-hypergrid
-->
<script src="../../../../numeral/min/numeral.min.js"></script>
<polymer-element name="fin-hypergrid-behavior-qtree" extends="fin-hypergrid-behavior-base" attributes="url">
  <template>
    <link rel="stylesheet" type="text/css" href="../../../polymer/css/behaviors/fin-hypergrid-behavior-qtree.css">
  </template>
  <script src="../../../polymer/js/behaviors/fin-hypergrid-behavior-qtree.js"></script>
</polymer-element>


text:
package io.kaif.kmark;

/**
 * Txtmark configuration.
 *
 * @author René Jeschke <rene_jeschke@yahoo.de>
 * @since 0.7
 */
public class Configuration {

  /**
   * Configuration builder.
   *
   * @author René Jeschke <rene_jeschke@yahoo.de>
   * @since 0.7
   */
  public static class Builder {

    private String encoding = "UTF-8";
    private Decorator decorator = new DefaultDecorator();
    private BlockEmitter codeBlockEmitter = new CodeBlockEmitter();

    /**
     * Constructor.
     */
    Builder() {
      // empty
    }

    /**
     * Sets the character encoding for txtmark.
     *

     * Default: "UTF-8"
     *
     * @param encoding
     *     The encoding
     * @return This builder
     * @since 0.7
     */
    public Builder setEncoding(String encoding) {
      this.encoding = encoding;
      return this;
    }

    /**
     * Sets the code block emitter.
     *

     * Default: null
     *
     * @param emitter
     *     The BlockEmitter
     * @return This builder
     * @see BlockEmitter
     * @since 0.7
     */
    public Builder setCodeBlockEmitter(BlockEmitter emitter) {
      this.codeBlockEmitter = emitter;
      return this;
    }

    /**
     * Builds a configuration instance.
     *
     * @return a Configuration instance
     * @since 0.7
     */
    public Configuration build() {
      return new Configuration(this.encoding, this.decorator, this.codeBlockEmitter);
    }

    public Decorator getDecorator() {
      return decorator;
    }

    /**
     * Sets the decorator for txtmark.
     *

     * Default: DefaultDecorator()
     *
     * @param decorator
     *     The decorator
     * @return This builder
     * @see DefaultDecorator
     * @since 0.7
     */
    public Builder setDecorator(Decorator decorator) {
      this.decorator = decorator;
      return this;
    }
  }

  /**
   * Creates a new Builder instance.
   *
   * @return A new Builder instance.
   */
  public static Builder builder() {
    return new Builder();
  }

  final String encoding;
  final Decorator decorator;
  final BlockEmitter codeBlockEmitter;

  Configuration(String encoding, Decorator decorator, BlockEmitter codeBlockEmitter) {
    this.encoding = encoding;
    this.decorator = decorator;
    this.codeBlockEmitter = codeBlockEmitter;
  }
}


text:
pimcore.registerNS("pimcore.object.classes.data.localizedfields");
pimcore.object.classes.data.localizedfields = Class.create(pimcore.object.classes.data.data, {

    type: "localizedfields",
    allowIndex: false,
    /**
     * define where this datatype is allowed
     */
    allowIn: {
        object: true,
        objectbrick: false,
        fieldcollection: false,
        localizedfield: false
    },

    initialize: function (treeNode, initData) {
        this.type = "localizedfields";

        initData.name = "localizedfields";
        treeNode.setText("localizedfields");

        this.initData(initData);
        this.treeNode = treeNode;
    },

    getTypeName: function () {
        return t("localizedfields");
    },

    getGroup: function () {
        return "structured";
    },

    getIconClass: function () {
        return "pimcore_icon_localizedfields";
    },

    getLayout: function ($super) {

        this.datax.name = "localizedfields";

        $super();

        this.specificPanel.removeAll();

        this.layout = new Ext.Panel({
            bodyStyle: "padding: 10px;",
            items: [
                {
                    xtype: "form",
                    title: t("general_settings"),
                    bodyStyle: "padding: 10px;",
                    style: "margin: 10px 0 10px 0",
                    items: [
                        {
                            xtype: "textfield",
                            fieldLabel: t("name"),
                            name: "name",
                            enableKeyEvents: true,
                            value: this.datax.name,
                            disabled: true
                        },
                        {
                            xtype: "combo",
                            fieldLabel: t("region"),
                            name: "region",
                            value: this.datax.region,
                            store: ["","center", "north", "south", "east", "west"],
                            triggerAction: 'all',
                            editable: false
                        },
                        {
                            xtype: "combo",
                            fieldLabel: t("layout"),
                            name: "layout",
                            value: this.datax.layout,
                            store: ["","fit"],
                            triggerAction: 'all',
                            editable: false
                        },
                        {
                            xtype: "textfield",
                            fieldLabel: t("title"),
                            name: "title",
                            value: this.datax.title
                        },
                        {
                            xtype: "spinnerfield",
                            fieldLabel: t("width"),
                            name: "width",
                            value: this.datax.width
                        },
                        {
                            xtype: "spinnerfield",
                            fieldLabel: t("height"),
                            name: "height",
                            value: this.datax.height
                        }
                    ]
                }
            ]
        });

        this.layout.on("render", this.layoutRendered.bind(this));

        return this.layout;

        return this.layout;
    },

    getData: function ($super) {
        var data = $super();

        data.name = "localizedfields";

        return data;
    }
});


text:
<?php

namespace Symfony\Component\Serializer\Tests\Normalizer\Features;

class TypedPropertiesObjectWithGetters extends TypedPropertiesObject
{
    public function getUnInitialized(): string
    {
        return $this->unInitialized;
    }

    public function setUnInitialized(string $unInitialized): self
    {
        $this->unInitialized = $unInitialized;

        return $this;
    }

    public function getInitialized(): string
    {
        return $this->initialized;
    }

    public function setInitialized(string $initialized): self
    {
        $this->initialized = $initialized;

        return $this;
    }

    public function getInitialized2(): string
    {
        return $this->initialized2;
    }

    public function setInitialized2(string $initialized2): self
    {
        $this->initialized2 = $initialized2;

        return $this;
    }
}


text:
**Severity Level: Error**

## Description

The use of the `AsPlainText` parameter with the `ConvertTo-SecureString` command can expose secure information.

## How

Use a standard encrypted variable to perform any SecureString conversions.

## Recommendations

If you do need an ability to retrieve the password from somewhere without prompting the user, consider using Windows Credential Store as used in the BetterCredentials module ( https://www.powershellgallery.com/packages/BetterCredentials/4.4/Content/BetterCredentials.psm1). If that does not work, consider using Azure KeyVault (https://azure.microsoft.com/en-us/services/key-vault/) or AWS KMS (https://aws.amazon.com/kms/).

## Example

### Wrong

``` PowerShell
$UserInput = Read-Host "Please enter your secure code"
$EncryptedInput = ConvertTo-SecureString -String $UserInput -AsPlainText -Force
```

### Correct

``` PowerShell
$SecureUserInput = Read-Host "Please enter your secure code" -AsSecureString
$EncryptedInput = ConvertFrom-SecureString -String $SecureUserInput
$SecureString = Convertto-SecureString -String $EncryptedInput
```


text:
#ifndef SHELL_UART_H__
#define SHELL_UART_H__

#include <zephyr/shell/shell.h>
#include <zephyr/sys/ring_buffer.h>
#include <zephyr/sys/atomic.h>
#include <zephyr/mgmt/mcumgr/smp_shell.h>

#ifdef __cplusplus
extern "C" {
#endif

extern const struct shell_transport_api shell_uart_transport_api;

/** @brief Shell UART transport instance control block (RW data). */
struct shell_uart_ctrl_blk {
	const struct device *dev;
	shell_transport_handler_t handler;
	void *context;
	atomic_t tx_busy;
	bool blocking_tx;
#ifdef CONFIG_MCUMGR_SMP_SHELL
	struct smp_shell_data smp;
#endif /* CONFIG_MCUMGR_SMP_SHELL */
};

#ifdef CONFIG_SHELL_BACKEND_SERIAL_INTERRUPT_DRIVEN
#define Z_UART_SHELL_TX_RINGBUF_DECLARE(_name, _size) \
	RING_BUF_DECLARE(_name##_tx_ringbuf, _size)

#define Z_UART_SHELL_RX_TIMER_DECLARE(_name) /* Empty */
#define Z_UART_SHELL_TX_RINGBUF_PTR(_name) (&_name##_tx_ringbuf)

#define Z_UART_SHELL_RX_TIMER_PTR(_name) NULL

#else /* CONFIG_SHELL_BACKEND_SERIAL_INTERRUPT_DRIVEN */
#define Z_UART_SHELL_TX_RINGBUF_DECLARE(_name, _size) /* Empty */
#define Z_UART_SHELL_RX_TIMER_DECLARE(_name) static struct k_timer _name##_timer
#define Z_UART_SHELL_TX_RINGBUF_PTR(_name) NULL
#define Z_UART_SHELL_RX_TIMER_PTR(_name) (&_name##_timer)
#endif /* CONFIG_SHELL_BACKEND_SERIAL_INTERRUPT_DRIVEN */

/** @brief Shell UART transport instance structure. */
struct shell_uart {
	struct shell_uart_ctrl_blk *ctrl_blk;
	struct k_timer *timer;
	struct ring_buf *tx_ringbuf;
	struct ring_buf *rx_ringbuf;
};

/** @brief Macro for creating shell UART transport instance. */
#define SHELL_UART_DEFINE(_name, _tx_ringbuf_size, _rx_ringbuf_size)	\
	static struct shell_uart_ctrl_blk _name##_ctrl_blk;		\
	Z_UART_SHELL_RX_TIMER_DECLARE(_name);				\
	Z_UART_SHELL_TX_RINGBUF_DECLARE(_name, _tx_ringbuf_size);	\
	RING_BUF_DECLARE(_name##_rx_ringbuf, _rx_ringbuf_size);		\
	static const struct shell_uart _name##_shell_uart = {		\
		.ctrl_blk = &_name##_ctrl_blk,				\
		.timer = Z_UART_SHELL_RX_TIMER_PTR(_name),		\
		.tx_ringbuf = Z_UART_SHELL_TX_RINGBUF_PTR(_name),	\
		.rx_ringbuf = &_name##_rx_ringbuf,			\
	};								\
	struct shell_transport _name = {				\
		.api = &shell_uart_transport_api,			\
		.ctx = (struct shell_uart *)&_name##_shell_uart		\
	}

/**
 * @brief This function provides pointer to shell uart backend instance.
 *
 * Function returns pointer to the shell uart instance. This instance can be
 * next used with shell_execute_cmd function in order to test commands behavior.
 *
 * @returns Pointer to the shell instance.
 */
const struct shell *shell_backend_uart_get_ptr(void);

#ifdef __cplusplus
}
#endif

#endif /* SHELL_UART_H__ */


text:
<?php

declare(strict_types=1);

namespace SolubleTest\DbWrapper;

use PHPUnit\Framework\TestCase;
use Soluble\DbWrapper\AdapterFactory;

class AdapterFactoryTest extends TestCase
{
    public function testCreateAdapterFromMysqliConnection()
    {
        $conn    = \SolubleTestFactories::getDbConnection('mysqli');
        $adapter = AdapterFactory::createAdapterFromResource($conn);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\MysqliAdapter::class, $adapter);
    }

    public function testCreateAdapterFromPDOMysqlConnection()
    {
        $conn    = \SolubleTestFactories::getDbConnection('pdo:mysql');
        $adapter = AdapterFactory::createAdapterFromResource($conn);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\PdoMysqlAdapter::class, $adapter);
    }

    public function testCreateAdapterFromPDOSqliteConnection()
    {
        $connection = new \PDO('sqlite::memory:');
        $adapter    = AdapterFactory::createAdapterFromResource($connection);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\PdoSqliteAdapter::class, $adapter);
    }

    public function testCreateAdapterFromZendDb2Adapter()
    {
        $zendAdapter = \SolubleTestFactories::getDbConnection('zend-db2-mysqli');
        $adapter     = AdapterFactory::createAdapterFromZendDb2($zendAdapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\Zend\ZendDb2Adapter::class, $adapter);
    }

    public function testCreateAdapterFromDoctrine2Test()
    {
        $doctrine = \SolubleTestFactories::getDbConnection('doctrine2-mysqli');

        $adapter = AdapterFactory::createAdapterFromDoctrine2($doctrine);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\Doctrine\Dbal2Adapter::class, $adapter);
    }

    public function testCreateAdapterFromCapsule5Test()
    {
        $capsule = \SolubleTestFactories::getDbConnection('capsule5-mysqli');

        $adapter = AdapterFactory::createAdapterFromCapsule5($capsule);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\AdapterInterface::class, $adapter);
        self::assertInstanceOf(\Soluble\DbWrapper\Adapter\Laravel\Capsule5Adapter::class, $adapter);
    }

    public function testCreateAdapterFromResourceThrowsException()
    {
        $this->expectException(\Soluble\DbWrapper\Exception\InvalidArgumentException::class);
        $fct = function () {
            return true;
        };
        AdapterFactory::createAdapterFromResource($fct);
    }

    public function testCreateAdapterFromResourceThrowsExceptionInvalidType()
    {
        $this->expectException(\Soluble\DbWrapper\Exception\InvalidArgumentException::class);
        AdapterFactory::createAdapterFromResource('a');
    }
}


text:
Security Policy
===============

If you found any issues that might have security implications,
please send a report to security[at]valkyrja.io
DO NOT PUBLISH SECURITY REPORTS PUBLICLY.

The full [Security Policy][1] is described in the official documentation.

  [1]: https://valkyrja.io/security


text:
import { Maybe } from '../../maybe';
import InternalNode from './InternalNode';
import { IIdentifiableObject } from './types';

// An AbstractNode has a required id and optional additional props
abstract class AbstractNode {
  protected words: string[] = [];
  protected letter: Maybe<string>;
  private id: string;
  private props: {};
  private parent?: InternalNode;

  constructor({ id, words, letter, ...props }: IIdentifiableObject) {
    this.id = id;
    this.words = words || [];
    this.letter = letter;
    this.props = props;
  }

  public setParent(parent: InternalNode) {
    this.parent = parent;
  }

  public getId() {
    return this.id;
  }

  public getProps() {
    return this.props;
  }

  public getParent() {
    return this.parent;
  }

  /**
   * @returns New vocabulary
   */
  public abstract getNewVocabulary(): string[];

  /**
   * @returns New and old vocabulary
   */
  public abstract getVocabulary(id: string): string[];

  /**
   * @returns New letter
   */
  public abstract getNewLetter(): Maybe<string>;

  /**
   * @returns New and old letters
   */
  public abstract getLetters(id: string): string[];

  public getStructure(): IIdentifiableObject {
    const parent = this.getParent();

    return {
      id: this.getId(),
      parent: parent && parent.getId()
    };
  }

  public getInfo(): IIdentifiableObject {
    return {
      ...this.getStructure(),
      props: this.props
    };
  }

  public getTree(level: number = Infinity): IIdentifiableObject {
    return this.getStructure();
  }

  public findEntity(id: string): Maybe<AbstractNode> {
    if (id === this.getId()) {
      return this;
    }

    return undefined;
  }
}

export default AbstractNode;


text:
package org.jbpm.services.task.identity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.kie.api.task.model.Group;
import org.kie.api.task.model.OrganizationalEntity;
import org.kie.api.task.model.User;
import org.kie.internal.task.api.TaskModelProvider;
import org.kie.internal.task.api.UserInfo;
import org.kie.internal.task.api.model.InternalOrganizationalEntity;

public class DefaultUserInfo extends AbstractUserGroupInfo implements UserInfo {

    protected Map<String, Map<String, Object>> registry = new HashMap<String, Map<String,Object>>();

    protected static final String DEFAULT_USER_PROPS_LOCATION = "classpath:/userinfo.properties";

    //no no-arg constructor to prevent cdi from auto deploy
    public DefaultUserInfo(boolean activate) {
        try {
            Properties registryProps = readProperties(DEFAULT_USER_PROPS_LOCATION, DEFAULT_USER_PROPS_LOCATION);
            buildRegistry(registryProps);
        } catch (Exception e) {
            throw new IllegalStateException("Problem loading userinfo properties", e);
        }
    }

    /**
     * Constructs default UserInfo implementation to provide required information to the escalation handler.
     * following is the string for every organizational entity
     * entityId=email:locale:displayname:[member,member]
     * members are optional and should be given for group entities
     * @param registryProps
     */
    public DefaultUserInfo(Properties registryProps) {
        buildRegistry(registryProps);
    }

    @Override
    public String getDisplayName(OrganizationalEntity entity) {
        Map<String, Object> entityInfo = registry.get(entity.getId());

        if (entityInfo != null) {
            return (String) entityInfo.get("name");
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Iterator<OrganizationalEntity> getMembersForGroup(Group group) {
        Map<String, Object> entityInfo = registry.get(group.getId());

        if (entityInfo != null && entityInfo.get("members") != null) {
            return  ((List<OrganizationalEntity>) entityInfo.get("members")).iterator();
        }
        return null;
    }

    @Override
    public boolean hasEmail(Group group) {
        Map<String, Object> entityInfo = registry.get(group.getId());

        if (entityInfo != null) {
            return entityInfo.containsKey("email");
        }
        return false;
    }

    @Override
    public String getEmailForEntity(OrganizationalEntity entity) {
        Map<String, Object> entityInfo = registry.get(entity.getId());

        if (entityInfo != null) {
            return (String) entityInfo.get("email");
        }
        return null;
    }

    @Override
    public String getLanguageForEntity(OrganizationalEntity entity) {
        Map<String, Object> entityInfo = registry.get(entity.getId());

        if (entityInfo != null) {
            return (String) entityInfo.get("locale");
        }
        return null;
    }

    @Override
    public String getEntityForEmail(String email) {
        for (Entry<String, Map<String, Object>> entry : registry.entrySet()) {
            if (entry.getValue().get("email").equals(email)) {
                return entry.getKey();
            }
        }
        return null;
    }

    protected void buildRegistry(Properties registryProps) {

        if (registryProps != null) {
            Iterator<Object> propertyKeys = registryProps.keySet().iterator();
            while (propertyKeys.hasNext()) {
                String propertyKey = (String) propertyKeys.next();

                // following is the string for every organizational entity
                // email:locale:displayname:[member,member]
                // members are optional and should be given for group entities

                String propertyValue = registryProps.getProperty(propertyKey);
                String[] elems = propertyValue.split(":");

                Map<String, Object> entityInfo = new HashMap<String, Object>();
                entityInfo.put("email", elems[0]);
                entityInfo.put("locale", elems[1]);
                entityInfo.put("name", elems[2]);

                if (elems.length == 4 && elems[3] != null) {
                    String memberList = elems[3];
                    if (memberList.startsWith("[")) {
                        memberList = memberList.substring(1);
                    }

                    if (memberList.endsWith("]")) {
                        memberList = memberList.substring(0, memberList.length()-1);
                    }
                    String[] members = memberList.split(",");

                    List<OrganizationalEntity> membersList = new ArrayList<OrganizationalEntity>();
                    for (String member : members) {
                    	User user = TaskModelProvider.getFactory().newUser();
                        ((InternalOrganizationalEntity) user).setId(member);
                        membersList.add(user);
                    }
                    entityInfo.put("members", membersList);
                }
                registry.put(propertyKey, entityInfo);

            }
        }
    }
}


text:
package com.lothrazar.cyclic.block.cable.energy;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.google.common.collect.Maps;
import com.lothrazar.cyclic.block.TileBlockEntityCyclic;
import com.lothrazar.cyclic.block.cable.CableBase;
import com.lothrazar.cyclic.block.cable.EnumConnectType;
import com.lothrazar.cyclic.capabilities.CustomEnergyStorage;
import com.lothrazar.cyclic.registry.TileRegistry;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.ForgeConfigSpec.IntValue;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;

public class TileCableEnergy extends TileBlockEntityCyclic {

  public static IntValue BUFFERSIZE;
  public static IntValue TRANSFER_RATE;
  CustomEnergyStorage energy;
  private LazyOptional<IEnergyStorage> energyCap;
  private Map<Direction, Integer> mapIncomingEnergy = Maps.newHashMap();

  public TileCableEnergy(BlockPos pos, BlockState state) {
    super(TileRegistry.ENERGY_PIPE.get(), pos, state);
    for (Direction f : Direction.values()) {
      mapIncomingEnergy.put(f, 0);
    }
    energy = new CustomEnergyStorage(BUFFERSIZE.get(), BUFFERSIZE.get());
    energyCap = LazyOptional.of(() -> energy);
  }

  public static void serverTick(Level level, BlockPos blockPos, BlockState blockState, TileCableEnergy e) {
    e.tick();
  }

  public static <E extends BlockEntity> void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileCableEnergy e) {
    e.tick();
  }

  //  @Override
  public void tick() {
    this.syncEnergy();
    this.tickDownIncomingPowerFaces();
    this.tickCableFlow();
    //extract mode conditionally
    for (Direction side : Direction.values()) {
      EnumConnectType connection = this.getBlockState().getValue(CableBase.FACING_TO_PROPERTY_MAP.get(side));
      if (connection.isExtraction()) {
        tryExtract(side);
      }
    }
  }

  @SuppressWarnings("unused")
  private void tryExtract(Direction extractSide) {
    if (extractSide == null) {
      return;
    }
    BlockPos posTarget = this.worldPosition.relative(extractSide);
    BlockEntity tile = level.getBlockEntity(posTarget);
    if (tile != null) {
      IEnergyStorage itemHandlerFrom = tile.getCapability(CapabilityEnergy.ENERGY, extractSide.getOpposite()).orElse(null);
      if (itemHandlerFrom != null) {
        //ok go
        //
        int extractSim = itemHandlerFrom.extractEnergy(TRANSFER_RATE.get(), true);
        if (extractSim > 0 && energy.receiveEnergy(extractSim, true) > 0) {
          //actually extract energy for real, whatever it accepted
          int actuallyEx = itemHandlerFrom.extractEnergy(energy.receiveEnergy(extractSim, false), false);
        }
      }
    }
  }

  private void tickCableFlow() {
    List<Integer> rawList = IntStream.rangeClosed(0, 5).boxed().collect(Collectors.toList());
    Collections.shuffle(rawList);
    for (Integer i : rawList) {
      Direction outgoingSide = Direction.values()[i];
      EnumConnectType connection = this.getBlockState().getValue(CableBase.FACING_TO_PROPERTY_MAP.get(outgoingSide));
      if (connection.isExtraction() || connection.isBlocked()) {
        continue;
      }
      if (this.isEnergyIncomingFromFace(outgoingSide) == false) {
        moveEnergy(outgoingSide, TRANSFER_RATE.get());
      }
    }
  }

  public void tickDownIncomingPowerFaces() {
    for (Direction f : Direction.values()) {
      if (mapIncomingEnergy.get(f) > 0) {
        mapIncomingEnergy.put(f, mapIncomingEnergy.get(f) - 1);
      }
    }
  }

  @Override
  public void invalidateCaps() {
    energyCap.invalidate();
    super.invalidateCaps();
  }

  @Override
  public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
    if (cap == CapabilityEnergy.ENERGY) {
      if (!CableBase.isCableBlocked(this.getBlockState(), side)) {
        return energyCap.cast();
      }
    }
    return super.getCapability(cap, side);
  }

  @Override
  public void load(CompoundTag tag) {
    for (Direction f : Direction.values()) {
      mapIncomingEnergy.put(f, tag.getInt(f.getSerializedName() + "_incenergy"));
    }
    energy.deserializeNBT(tag.getCompound(NBTENERGY));
    super.load(tag);
  }

  @Override
  public void saveAdditional(CompoundTag tag) {
    for (Direction f : Direction.values()) {
      tag.putInt(f.getSerializedName() + "_incenergy", mapIncomingEnergy.get(f));
    }
    tag.put(NBTENERGY, energy.serializeNBT());
    super.saveAdditional(tag);
  }

  private static final int TIMER_SIDE_INPUT = 15;

  private boolean isEnergyIncomingFromFace(Direction face) {
    return mapIncomingEnergy.get(face) > 0;
  }

  public void updateIncomingEnergyFace(Direction inputFrom) {
    mapIncomingEnergy.put(inputFrom, TIMER_SIDE_INPUT);
  }

  @Override
  public void setField(int field, int value) {}

  @Override
  public int getField(int field) {
    return 0;
  }
}


text:
package org.jetbrains.plugins.groovy.intentions.base;

import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils;
import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodFromUsageFix;
import com.intellij.codeInsight.template.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint;
import org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression;
import org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression;

/**
 * User: Dmitry.Krasilschikov
 * Date: 13.11.2007
 */
public class IntentionUtils {

  private static final Logger LOG = Logger.getInstance(IntentionUtils.class);

  public static void replaceExpression(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject());
    final GrExpression newCall = factory.createExpressionFromText(newExpression);
    expression.replaceWithExpression(newCall, true);
  }

  public static GrStatement replaceStatement(@NonNls @NotNull String newStatement, @NonNls @NotNull GrStatement statement)
    throws IncorrectOperationException {
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(statement.getProject());
    final GrStatement newCall = (GrStatement)factory.createTopElementFromText(newStatement);
    return statement.replaceWithStatement(newCall);
  }

  public static void createTemplateForMethod(PsiType[] argTypes,
                                             ChooseTypeExpression[] paramTypesExpressions,
                                             PsiMethod method,
                                             PsiClass owner,
                                             TypeConstraint[] constraints,
                                             boolean isConstructor,
                                             @NotNull final PsiElement context) {

    final Project project = owner.getProject();
    PsiTypeElement typeElement = method.getReturnTypeElement();
    ChooseTypeExpression expr =
      new ChooseTypeExpression(constraints, PsiManager.getInstance(project), method.getLanguage() == GroovyFileType.GROOVY_LANGUAGE,
                               context.getResolveScope());
    TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
    if (!isConstructor) {
      assert typeElement != null;
      builder.replaceElement(typeElement, expr);
    }
    PsiParameter[] parameters = method.getParameterList().getParameters();
    assert parameters.length == argTypes.length;
    for (int i = 0; i < parameters.length; i++) {
      PsiParameter parameter = parameters[i];
      PsiTypeElement parameterTypeElement = parameter.getTypeElement();
      builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]);
      builder.replaceElement(parameter.getNameIdentifier(), new ParameterNameExpression(null));
    }

    PsiCodeBlock body = method.getBody();
    if (body != null) {
      PsiElement lbrace = body.getLBrace();
      assert lbrace != null;
      builder.setEndVariableAfter(lbrace);
    }
    else {
      builder.setEndVariableAfter(method.getParameterList());
    }

    method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
    Template template = builder.buildTemplate();

    final PsiFile targetFile = owner.getContainingFile();
    final Editor newEditor = QuickfixUtil.positionCursor(project, targetFile, method);
    TextRange range = method.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());

    TemplateManager manager = TemplateManager.getInstance(project);

    TemplateEditingListener templateListener = new TemplateEditingAdapter() {
      @Override
      public void templateFinished(Template template, boolean brokenOff) {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          @Override
          public void run() {
            PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
            final int offset = newEditor.getCaretModel().getOffset();
            PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
            if (context instanceof PsiMethod) {
              final PsiTypeParameter[] typeParameters = ((PsiMethod)context).getTypeParameters();
              if (typeParameters.length > 0) {
                for (PsiTypeParameter typeParameter : typeParameters) {
                  if (CreateMethodFromUsageFix.checkTypeParam(method, typeParameter)) {
                    final JVMElementFactory factory = JVMElementFactories.getFactory(method.getLanguage(), method.getProject());
                    PsiTypeParameterList list = method.getTypeParameterList();
                    if (list == null) {
                      PsiTypeParameterList newList = factory.createTypeParameterList();
                      list = (PsiTypeParameterList)method.addAfter(newList, method.getModifierList());
                    }
                    list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes()));
                  }
                }
              }
            }
            if (method != null) {
              try {
                final boolean hasNoReturnType = method.getReturnTypeElement() == null && method instanceof GrMethod;
                if (hasNoReturnType) {
                  ((GrMethod)method).setReturnType(PsiType.VOID);
                }
                if (method.getBody() != null) {
                  CreateFromUsageUtils.setupMethodBody(method);
                }
                if (hasNoReturnType) {
                  ((GrMethod)method).setReturnType(null);
                }
              }
              catch (IncorrectOperationException e) {
                LOG.error(e);
              }

              CreateFromUsageUtils.setupEditor(method, newEditor);
            }
          }
        });
      }
    };
    manager.startTemplate(newEditor, template, templateListener);
  }
}


text:
package com.piticlistudio.playednext.company.model.repository;

import com.piticlistudio.playednext.company.model.entity.Company;

import io.reactivex.Observable;

/**
 * Definition methods
 * Created by jorge.garcia on 22/11/2016.
 */
public interface ICompanyRepository {

    /**
     * Loads the Company with the specified id.
     *
     * @param id the id to load.
     * @return an Observable that emits the collection loaded
     */
    Observable<Company> load(int id);
}


text:
"""
A component which allows you to send data to Dweet.io.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/dweet/
"""
import logging
from datetime import timedelta
import voluptuous as vol

from blumate.const import EVENT_STATE_CHANGED, STATE_UNKNOWN
import blumate.helpers.config_validation as cv
from blumate.helpers import state as state_helper
from blumate.util import Throttle

_LOGGER = logging.getLogger(__name__)

DOMAIN = "dweet"
DEPENDENCIES = []

REQUIREMENTS = ['dweepy==0.2.0']

CONF_NAME = 'name'
CONF_WHITELIST = 'whitelist'

MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_NAME): cv.string,
        vol.Required(CONF_WHITELIST): cv.string,
    }),
}, extra=vol.ALLOW_EXTRA)

# pylint: disable=too-many-locals
def setup(hass, config):
    """Setup the Dweet.io component."""
    conf = config[DOMAIN]
    name = conf[CONF_NAME]
    whitelist = conf.get(CONF_WHITELIST, [])
    json_body = {}

    def dweet_event_listener(event):
        """Listen for new messages on the bus and sends them to Dweet.io."""
        state = event.data.get('new_state')
        if state is None or state.state in (STATE_UNKNOWN, '') \
                or state.entity_id not in whitelist:
            return

        try:
            _state = state_helper.state_as_number(state)
        except ValueError:
            _state = state.state

        json_body[state.attributes.get('friendly_name')] = _state

        send_data(name, json_body)

    hass.bus.listen(EVENT_STATE_CHANGED, dweet_event_listener)

    return True

@Throttle(MIN_TIME_BETWEEN_UPDATES)
def send_data(name, msg):
    """Send the collected data to Dweet.io."""
    import dweepy
    try:
        dweepy.dweet_for(name, msg)
    except dweepy.DweepyError:
        _LOGGER.error("Error saving data '%s' to Dweet.io", msg)


text:
Home

Credit Application

Credit Application

			    <?php display_flashmsg($this->session->flashdata()); ?>

				<form action="#" class="clearfix" name="add_inventory"  method="post" enctype="multipart/form-data">

Basic Information

						<div class="form-group <?php echo (form_error('firstname'))?'has-error':'';?>">
					    	First Name*
					    	<input type="text" class="form-control" name="firstname" id="firstname" value="<?php echo set_value('firstname',$editdata['firstname']);?>">
					    	 <?php echo form_error('firstname'); ?>

					    	Middle Initial
					    	<input type="text" class="form-control" name="middlename" id="middlename" value="<?php echo set_value('middlename',$editdata['middlename']);?>">

						<div class="form-group <?php echo (form_error('lastname'))?'has-error':'';?>">
					    	Last Name
					    	<input type="text" class="form-control" name="lastname" id="lastname" value="<?php echo set_value('lastname',$editdata['lastname']);?>">
                        	<?php echo form_error('lastname'); ?>

					    	Birthdate
					    	<input type="text" class="form-control" name="birthday" id="birthday" value="<?php echo set_value('birthday',$editdata['birthday']);?>">

					    	Social Security Number
					    	<input type="text" class="form-control" name="security_number" id="security_number" value="<?php echo set_value('security_number',$editdata['security_number']);?>">

					    	Address
					    	<textarea class="form-control" name="address" id="address" ><?php echo set_value('address',$editdata['address']);?></textarea>

					    	City
					    	<input type="text" class="form-control" name="city" id="city" value="<?php echo set_value('city',$editdata['city']);?>">

					    	State
					    	<input type="text" class="form-control" name="state" id="state" value="<?php echo set_value('state',$editdata['state']);?>">

					    	zip
					    	<input type="text" class="form-control" name="zipcode" id="zipcode" value="<?php echo set_value('zipcode',$editdata['zipcode']);?>">

					    	Time at Residence
					    	<input type="text" class="form-control" name="residence_time" id="residence_time" value="<?php echo set_value('residence_time',$editdata['residence_time']);?>">

					    	Home Phone
					    	<input type="text" class="form-control" name="home_phone" id="home_phone" value="<?php echo set_value('home_phone',$editdata['home_phone']);?>">

					    	Cell Phone
					    	<input type="text" class="form-control" name="cell_phone" id="cell_phone" value="<?php echo set_value('cell_phone',$editdata['cell_phone']);?>">

						<div class="form-group <?php echo (form_error('email'))?'has-error':'';?>">
					    	Email Address
					    	<input type="text" class="form-control" name="email" id="email" value="<?php echo set_value('email',$editdata['email']);?>">
                            <?php echo form_error("email"); ?>

					    	Driver's License #
					    	<input type="text" class="form-control" name="drive_lisence" id="drive_lisence" value="<?php echo set_value('drive_lisence',$editdata['drive_lisence']);?>">

					    	Issue Date
					    	<input type="text" class="form-control" name="issue_date" id="issue_date" value="<?php echo set_value('issue_date',$editdata['issue_date']);?>">

					    	Expiration Date
					    	<input type="text" class="form-control" name="expir_date" id="expir_date" value="<?php echo set_value('expir_date',$editdata['expir_date']);?>">

					    	Expiration Date Previous Address
					    	<textarea class="form-control" name="pre_address" id="pre_address" ><?php echo set_value('pre_address',$editdata['pre_address']);?></textarea>

					    	City
					    	<input type="text" class="form-control" name="pre_city" id="pre_city" value="<?php echo set_value('pre_city',$editdata['pre_city']);?>">

					    	State
					    	<input type="text" class="form-control" name="pre_state" id="pre_state" value="<?php echo set_value('pre_state',$editdata['pre_state']);?>">
                            <?php echo form_error('pre_state'); ?>

					    	Zip
					    	<input type="text" class="form-control" name="pre_zipcode" id="pre_zipcode" value="<?php echo set_value('pre_zipcode',$editdata['pre_zipcode']);?>">

Employer Information

					    	Employer
					    	<input type="text" class="form-control" name="employer" id="employer" value="<?php echo set_value('employer',$editdata['employer']);?>">

					    	Occupation
					    	 <input type="text" class="form-control" name="occupation" id="occupation" value="<?php echo set_value('occupation',$editdata['occupation']);?>">

					    	Employer Address
					    	<textarea class="form-control" name="emp_address" id="emp_address" placeholder="Address"><?php echo set_value('emp_address',$editdata['emp_address']);?></textarea>

					    	City
					    	<input type="text" class="form-control" name="emp_city" id="emp_city" value="<?php echo set_value('emp_city',$editdata['emp_city']);?>">

					    	State
					    	<input type="text" class="form-control" name="emp_state" id="emp_state" value="<?php echo set_value('emp_state',$editdata['emp_state']);?>">

					    	Zip
					    	<input type="text" class="form-control" name="emp_zipcode" id="emp_zipcode" value="<?php echo set_value('emp_zipcode',$editdata['emp_zipcode']);?>">

					    	Work Phone
					    	<input type="text" class="form-control" name="work_phone" id="work_phone" value="<?php echo set_value('work_phone',$editdata['work_phone']);?>">

					    	How Long?
					    	<input type="text" class="form-control" name="howlong" id="howlong" value="<?php echo set_value('howlong',$editdata['howlong']);?>">

					    	Annual Salary
					    	<input type="text" class="form-control" name="annual_salary" id="annual_salary" value="<?php echo set_value('annual_salary',$editdata['annual_salary']);?>">

Financial Information

					    	Have you ever filed Bankruptcy?
							<select name="bankruptcy" size="1" class="form-control">
								<option value="">N/A</option>
								<option value="No"  <?php echo set_select('bankruptcy',$editdata['bankruptcy'],($editdata['bankruptcy']=='No')?TRUE:FALSE); ?> >No</option>
								<option value="Yes" <?php echo set_select('bankruptcy',$editdata['bankruptcy'],($editdata['bankruptcy']=='Yes')?TRUE:FALSE); ?>>Yes</option>
							</select>

					    	If YES, has the bankruptcy been discharged?
							<select name="bank_discharged" size="1" class="form-control">
								<option value="">N/A</option>
								<option value="No" <?php echo set_select('bank_discharged',$editdata['bank_discharged'],($editdata['bank_discharged']=='No')?TRUE:FALSE); ?>>No</option>
								<option value="Yes" <?php echo set_select('bank_discharged',$editdata['bank_discharged'],($editdata['bank_discharged']=='Yes')?TRUE:FALSE); ?>>Yes</option>
							</select>

					    	Have you ever financed a vehicle before?
							<select name="ever_finance" size="1" class="form-control">
								<option value="">N/A</option>
								<option value="No" <?php echo set_select('ever_finance',$editdata['ever_finance'],($editdata['ever_finance']=='No')?TRUE:FALSE); ?>>No</option>
								<option value="Yes" <?php echo set_select('ever_finance',$editdata['ever_finance'],($editdata['ever_finance']=='Yes')?TRUE:FALSE); ?>>Yes</option>
							</select>

					    	If YES, who financed the vehicle?
					    	 <input type="text" class="form-control" name="who_finance" id="who_finance" value="<?php echo set_value('who_finance',$editdata['who_finance']);?>">

					    	If trading in a vehicle, what kind of vehicle is it?
					    	<input type="text" class="form-control" name="trading_vehicle" id="trading_vehicle" value="<?php echo set_value('trading_vehicle',$editdata['trading_vehicle']);?>">

					    	What kind of vehicle are you looking to purchase?
					    	<input type="text" class="form-control" name="kind_vehicle" id="kind_vehicle " value="<?php echo set_value('kind_vehicle',$editdata['kind_vehicle']);?>">

					    	What is your down payment?
					    	<input type="text" class="form-control" name="down_payment" id="down_payment" value="<?php echo set_value('down_payment',$editdata['down_payment']);?>">

							By submitting the information you have listed above, you agree that you have accurately represented yourself and understand that the above information will be used for the purposes of attaining a credit history report to be used in determining your eligibility for financing from various financial institutions.
							None of the information above will be sold or distributed in any way

							<div class="form-group <?php echo (form_error('agree'))?'has-error':'';?>">

								<select name="agree" size="1" class="form-control small-select">
									Please Agree*
									<option value="1">I Agree</option>
									<option value="">I do not Agree</option>
								</select>

									<?php echo form_error('agree'); ?>

							<input type="submit" value="Submit" class="submit">

				</form>


text:
package main

import (
	"encoding/json"
	"goim/libs/define"
	inet "goim/libs/net"
	"goim/libs/net/xrpc"
	"goim/libs/proto"

	log "github.com/thinkboy/log4go"
	"strings"
	"sync/atomic"
)

var (
	cometServiceMap = make(map[int32]*Comet)
)

const (
	CometService              = "PushRPC"
	CometServicePing          = "PushRPC.Ping"
	CometServiceRooms         = "PushRPC.Rooms"
	CometServicePushMsg       = "PushRPC.PushMsg"
	CometServiceMPushMsg      = "PushRPC.MPushMsg"
	CometServiceBroadcast     = "PushRPC.Broadcast"
	CometServiceBroadcastRoom = "PushRPC.BroadcastRoom"
)

type CometOptions struct {
	RoutineSize int64
	RoutineChan int
}

type Comet struct {
	serverId             int32
	rpcClient            *xrpc.Clients
	pushRoutines         []chan *proto.MPushMsgArg
	broadcastRoutines    []chan *proto.BoardcastArg
	roomRoutines         []chan *proto.BoardcastRoomArg
	pushRoutinesNum      int64
	roomRoutinesNum      int64
	broadcastRoutinesNum int64
	options              CometOptions
}

// user push
func (c *Comet) Push(arg *proto.MPushMsgArg) (err error) {
	num := atomic.AddInt64(&c.pushRoutinesNum, 1) % c.options.RoutineSize
	c.pushRoutines[num] <- arg
	return
}

// room push
func (c *Comet) BroadcastRoom(arg *proto.BoardcastRoomArg) (err error) {
	num := atomic.AddInt64(&c.roomRoutinesNum, 1) % c.options.RoutineSize
	c.roomRoutines[num] <- arg
	return
}

// broadcast
func (c *Comet) Broadcast(arg *proto.BoardcastArg) (err error) {
	num := atomic.AddInt64(&c.broadcastRoutinesNum, 1) % c.options.RoutineSize
	c.broadcastRoutines[num] <- arg
	return
}

// process
func (c *Comet) process(pushChan chan *proto.MPushMsgArg, roomChan chan *proto.BoardcastRoomArg, broadcastChan chan *proto.BoardcastArg) {
	var (
		pushArg      *proto.MPushMsgArg
		roomArg      *proto.BoardcastRoomArg
		broadcastArg *proto.BoardcastArg
		reply        = &proto.NoReply{}
		err          error
	)
	for {
		select {
		case pushArg = <-pushChan:
			// push
			err = c.rpcClient.Call(CometServiceMPushMsg, pushArg, reply)
			if err != nil {
				log.Error("rpcClient.Call(%s, %v, reply) serverId:%d error(%v)", CometServiceMPushMsg, pushArg, c.serverId, err)
			}
			pushArg = nil
		case roomArg = <-roomChan:
			// room
			err = c.rpcClient.Call(CometServiceBroadcastRoom, roomArg, reply)
			if err != nil {
				log.Error("rpcClient.Call(%s, %v, reply) serverId:%d error(%v)", CometServiceBroadcastRoom, roomArg, c.serverId, err)
			}
			roomArg = nil
		case broadcastArg = <-broadcastChan:
			// broadcast
			err = c.rpcClient.Call(CometServiceBroadcast, broadcastArg, reply)
			if err != nil {
				log.Error("rpcClient.Call(%s, %v, reply) serverId:%d error(%v)", CometServiceBroadcast, broadcastArg, c.serverId, err)
			}
			broadcastArg = nil
		}
	}
}

func InitComet(addrs map[int32]string, options CometOptions) (err error) {
	var (
		serverId      int32
		bind          string
		network, addr string
	)
	for serverId, bind = range addrs {
		var rpcOptions []xrpc.ClientOptions
		for _, bind = range strings.Split(bind, ",") {
			if network, addr, err = inet.ParseNetwork(bind); err != nil {
				log.Error("inet.ParseNetwork() error(%v)", err)
				return
			}
			options := xrpc.ClientOptions{
				Proto: network,
				Addr:  addr,
			}
			rpcOptions = append(rpcOptions, options)
		}
		// rpc clients
		rpcClient := xrpc.Dials(rpcOptions)
		// ping & reconnect
		rpcClient.Ping(CometServicePing)
		// comet
		c := new(Comet)
		c.serverId = serverId
		c.rpcClient = rpcClient
		c.pushRoutines = make([]chan *proto.MPushMsgArg, options.RoutineSize)
		c.roomRoutines = make([]chan *proto.BoardcastRoomArg, options.RoutineSize)
		c.broadcastRoutines = make([]chan *proto.BoardcastArg, options.RoutineSize)
		c.options = options
		cometServiceMap[serverId] = c
		// process
		for i := int64(0); i < options.RoutineSize; i++ {
			pushChan := make(chan *proto.MPushMsgArg, options.RoutineChan)
			roomChan := make(chan *proto.BoardcastRoomArg, options.RoutineChan)
			broadcastChan := make(chan *proto.BoardcastArg, options.RoutineChan)
			c.pushRoutines[i] = pushChan
			c.roomRoutines[i] = roomChan
			c.broadcastRoutines[i] = broadcastChan
			go c.process(pushChan, roomChan, broadcastChan)
		}
		log.Info("init comet rpc: %v", rpcOptions)
	}
	return
}

// mPushComet push a message to a batch of subkeys
func mPushComet(serverId int32, subKeys []string, body json.RawMessage) {
	var args = proto.MPushMsgArg{
		Keys: subKeys, P: proto.Proto{Ver: 0, Operation: define.OP_SEND_SMS_REPLY, Body: body},
	}
	if c, ok := cometServiceMap[serverId]; ok {
		if err := c.Push(&args); err != nil {
			log.Error("c.Push(%v) serverId:%d error(%v)", args, serverId, err)
		}
	}
}

// broadcast broadcast a message to all
func broadcast(msg []byte) {
	var args = proto.BoardcastArg{
		P: proto.Proto{Ver: 0, Operation: define.OP_SEND_SMS_REPLY, Body: msg},
	}
	for serverId, c := range cometServiceMap {
		if err := c.Broadcast(&args); err != nil {
			log.Error("c.Broadcast(%v) serverId:%d error(%v)", args, serverId, err)
		}
	}
}

// broadcastRoomBytes broadcast aggregation messages to room
func broadcastRoomBytes(roomId int32, body []byte) {
	var (
		args     = proto.BoardcastRoomArg{P: proto.Proto{Ver: 0, Operation: define.OP_RAW, Body: body}, RoomId: roomId}
		c        *Comet
		serverId int32
		servers  map[int32]struct{}
		ok       bool
		err      error
	)
	if servers, ok = RoomServersMap[roomId]; ok {
		for serverId, _ = range servers {
			if c, ok = cometServiceMap[serverId]; ok {
				// push routines
				if err = c.BroadcastRoom(&args); err != nil {
					log.Error("c.BroadcastRoom(%v) roomId:%d error(%v)", args, roomId, err)
				}
			}
		}
	}
}

func roomsComet(c *xrpc.Clients) []int32 {
	var (
		args  = proto.NoArg{}
		reply = proto.RoomsReply{}
		err   error
	)
	if err = c.Call(CometServiceRooms, &args, &reply); err != nil {
		log.Error("c.Call(%s, args, reply) error(%v)", CometServiceRooms, err)
		return nil
	}
	return reply.RoomIds
}