text:
package cn.xishan.oftenporter.demo.oftendb.test1.porter;

import cn.xishan.oftenporter.oftendb.data.DBSource;
import cn.xishan.oftenporter.oftendb.data.common;
import cn.xishan.oftenporter.oftendb.db.AdvancedExecutor;
import cn.xishan.oftenporter.oftendb.jbatis.JDao;
import cn.xishan.oftenporter.oftendb.jbatis.JS;
import cn.xishan.oftenporter.porter.core.annotation.AutoSet;
import cn.xishan.oftenporter.porter.core.base.WObject;
import cn.xishan.oftenporter.porter.core.util.KeyUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Date;

/**
 * Created by chenyg on 2017-04-29.
 */
public class DBUnit
{
    @AutoSet
    DBSource dbSource;

    @AutoSet
    JDao jDao;

    public Object add(WObject wObject)
    {
        JSONObject add = new JSONObject();
        add.put("_id", KeyUtil.randomUUID());
        add.put("name", "jdao");
        add.put("time", new Date());
        add.put("sex", "男");
        add.put("age", 12);
        AdvancedExecutor executor = jDao.execute(add, wObject);
        return common.advancedExecute(wObject, dbSource, executor);
    }

}


text:
Clients = require('../data/clients');

exports.run = function (socket, channel, event, data) {

  // Publish event
  if (event === 'publish') {

    socket.send(data);
  }
};

redpajama_set_name: RedPajamaGithub


text:
package dbfakes

import (
	"sync"

	"github.com/concourse/atc/db"
)

type FakePipelineFactory struct {
	PublicPipelinesStub        func() ([]db.Pipeline, error)
	publicPipelinesMutex       sync.RWMutex
	publicPipelinesArgsForCall []struct{}
	publicPipelinesReturns     struct {
		result1 []db.Pipeline
		result2 error
	}
	publicPipelinesReturnsOnCall map[int]struct {
		result1 []db.Pipeline
		result2 error
	}
	AllPipelinesStub        func() ([]db.Pipeline, error)
	allPipelinesMutex       sync.RWMutex
	allPipelinesArgsForCall []struct{}
	allPipelinesReturns     struct {
		result1 []db.Pipeline
		result2 error
	}
	allPipelinesReturnsOnCall map[int]struct {
		result1 []db.Pipeline
		result2 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakePipelineFactory) PublicPipelines() ([]db.Pipeline, error) {
	fake.publicPipelinesMutex.Lock()
	ret, specificReturn := fake.publicPipelinesReturnsOnCall[len(fake.publicPipelinesArgsForCall)]
	fake.publicPipelinesArgsForCall = append(fake.publicPipelinesArgsForCall, struct{}{})
	fake.recordInvocation("PublicPipelines", []interface{}{})
	fake.publicPipelinesMutex.Unlock()
	if fake.PublicPipelinesStub != nil {
		return fake.PublicPipelinesStub()
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fake.publicPipelinesReturns.result1, fake.publicPipelinesReturns.result2
}

func (fake *FakePipelineFactory) PublicPipelinesCallCount() int {
	fake.publicPipelinesMutex.RLock()
	defer fake.publicPipelinesMutex.RUnlock()
	return len(fake.publicPipelinesArgsForCall)
}

func (fake *FakePipelineFactory) PublicPipelinesReturns(result1 []db.Pipeline, result2 error) {
	fake.PublicPipelinesStub = nil
	fake.publicPipelinesReturns = struct {
		result1 []db.Pipeline
		result2 error
	}{result1, result2}
}

func (fake *FakePipelineFactory) PublicPipelinesReturnsOnCall(i int, result1 []db.Pipeline, result2 error) {
	fake.PublicPipelinesStub = nil
	if fake.publicPipelinesReturnsOnCall == nil {
		fake.publicPipelinesReturnsOnCall = make(map[int]struct {
			result1 []db.Pipeline
			result2 error
		})
	}
	fake.publicPipelinesReturnsOnCall[i] = struct {
		result1 []db.Pipeline
		result2 error
	}{result1, result2}
}

func (fake *FakePipelineFactory) AllPipelines() ([]db.Pipeline, error) {
	fake.allPipelinesMutex.Lock()
	ret, specificReturn := fake.allPipelinesReturnsOnCall[len(fake.allPipelinesArgsForCall)]
	fake.allPipelinesArgsForCall = append(fake.allPipelinesArgsForCall, struct{}{})
	fake.recordInvocation("AllPipelines", []interface{}{})
	fake.allPipelinesMutex.Unlock()
	if fake.AllPipelinesStub != nil {
		return fake.AllPipelinesStub()
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fake.allPipelinesReturns.result1, fake.allPipelinesReturns.result2
}

func (fake *FakePipelineFactory) AllPipelinesCallCount() int {
	fake.allPipelinesMutex.RLock()
	defer fake.allPipelinesMutex.RUnlock()
	return len(fake.allPipelinesArgsForCall)
}

func (fake *FakePipelineFactory) AllPipelinesReturns(result1 []db.Pipeline, result2 error) {
	fake.AllPipelinesStub = nil
	fake.allPipelinesReturns = struct {
		result1 []db.Pipeline
		result2 error
	}{result1, result2}
}

func (fake *FakePipelineFactory) AllPipelinesReturnsOnCall(i int, result1 []db.Pipeline, result2 error) {
	fake.AllPipelinesStub = nil
	if fake.allPipelinesReturnsOnCall == nil {
		fake.allPipelinesReturnsOnCall = make(map[int]struct {
			result1 []db.Pipeline
			result2 error
		})
	}
	fake.allPipelinesReturnsOnCall[i] = struct {
		result1 []db.Pipeline
		result2 error
	}{result1, result2}
}

func (fake *FakePipelineFactory) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.publicPipelinesMutex.RLock()
	defer fake.publicPipelinesMutex.RUnlock()
	fake.allPipelinesMutex.RLock()
	defer fake.allPipelinesMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakePipelineFactory) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ db.PipelineFactory = new(FakePipelineFactory)


text:
<?php

class XenAuction_Model_Tag extends XenForo_Model
{

	/**
	 * Get tag by ID
	 *
	 * @param int $tagId
	 *
	 * @return array|bool    Zend_Db_Adapter_Abstract::fetchRow
	 */
	public function getTagById($tagId)
	{
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM xf_auction_tag
			WHERE tag_id = ?
		', $tagId);
	}

	/**
	 * Get tag by name
	 *
	 * @param string $name
	 *
	 * @return array|bool    Zend_Db_Adapter_Abstract::fetchRow
	 */
	public function getTagByName($name)
	{
		return $this->_getDb()->fetchRow('
			SELECT *
			FROM xf_auction_tag
			WHERE name = ?
		', $name);
	}

	/**
	 * Get all tags
	 *
	 * @return array|bool    XenForo_Model::fetchAllKeyed
	 */
	public function getTags()
	{
		$dataModel 	= XenForo_Model::create('XenForo_Model_DataRegistry');
		$result 	= $dataModel->get('auctionTags');

		if ($result)
		{
			return $result;
		}

		$result = $this->fetchAllKeyed('
			SELECT *
			FROM xf_auction_tag
			ORDER BY name ASC
		', 'name');

		$dataModel->set('auctionTags', $result);

		return $result;
	}

	/**
	 * Get tags by auction ID
	 *
	 * @param int $auctionId
	 *
	 * @return array|bool    XenForo_Model::fetchAllKeyed
	 */
	public function getTagsByAuction($auctionId)
	{
		return $this->fetchAllKeyed('
			SELECT *
			FROM xf_auction_tag_rel rel
			JOIN xf_auction_tag tag ON
				tag.tag_id = rel.tag_id
			WHERE rel.auction_id = ?
		', 'tag_id', $auctionId);
	}

	/**
	 * Get tags by auction id's
	 *
	 * @param array   $auctionIds
	 *
	 * @return array|bool    self::fetchAllKeyGrouped
	 */
	public function getTagsByAuctions(array $auctionIds)
	{
		if (empty($auctionIds))
		{
			return false;
		}

		return $this->fetchAllKeyGrouped('
			SELECT *
			FROM xf_auction_tag_rel rel
			JOIN xf_auction_tag tag ON
				tag.tag_id = rel.tag_id
			WHERE rel.auction_id IN (' . $this->_getDb()->quote($auctionIds) . ')
		', 'auction_id');
	}

	/**
	 * Delete tags for specified auction id
	 *
	 * @param int $auctionId
	 *
	 * @return void
	 */
	public function deleteTagsFromAuction($auctionId)
	{
		$db = $this->_getDb();
		$db->delete('xf_auction_tag_rel', 'auction_id = ' . $db->quote($auctionId));
	}

	/**
	 * Add tags to auction
	 *
	 * @param array|string 	$tags
	 * @param int 			$auctionId
	 *
	 * @return void
	 */
	public function addTagToAuction($tags, $auctionId)
	{
		if ( ! is_array($tags))
		{
			$tags = array($tags);
		}

		$allTags 	= $this->getTags();

		// Loop through tags that are to be added / connected
		foreach ($tags AS $tagName)
		{

			// If the tag is not numeric (tag name) and is not defined already, add it
			if ( ! is_numeric($tagName) AND ! isset($allTags[$tagName]))
			{
				$dwTag 	= XenForo_DataWriter::create('XenAuction_DataWriter_Tag');
				$dwTag->set('name', trim($tagName));
				$dwTag->save();

				$tagData 	= $dwTag->getMergedData();
				$tagId 		= $tagData['tag_id'];
			}
			else // Otherwise just hook it up
			{
				if ( ! is_numeric($tagName) AND isset($allTags[$tagName]))
				{
					$tagId = $allTags[$tagName]['tag_id'];
				}
				else
				{
					$tagId = $tagName;
				}
			}

			// If the name is already in use MySQL will return an error
			// which is by design, so we don't care about it (saves us a query)
			try
			{
				$dwRel = XenForo_DataWriter::create('XenAuction_DataWriter_TagRel');
				$dwRel->set('tag_id', $tagId);
				$dwRel->set('auction_id', $auctionId);
				$dwRel->save();
			} catch (Zend_Db_Statement_Exception $e) {}

		}

		$dataModel = XenForo_Model::create('XenForo_Model_DataRegistry');
		$dataModel->delete('auctionTags');
	}

	/**
	 * Helper function to fetch entries by key and group them by key
	 *
	 * @param string $sql
	 * @param string $key
	 *
	 * @return array|bool
	 */
	protected function fetchAllKeyGrouped($sql, $key)
	{
		$results = array();
		$i = 0;

		$stmt = $this->_getDb()->query($sql, array(), Zend_Db::FETCH_ASSOC);
		while ($row = $stmt->fetch())
		{
			$i++;

			if ( ! isset($results[$row[$key]]))
			{
				$results[$row[$key]] = array();
			}

			$results[$row[$key]][] = $row;
		}

		return empty($results) ? false : $results;
	}

}


text:
"""
%HERE%
"""

import logging
logger = logging.getLogger(__name__)
import argparse
import datetime
import numpy as np

class TubeSkeletonBuilder:
    def __init__(self):
        """
        This function can be used as vessel_tree iterator. Just implement generator_class

        :param generator_class: class with function add_cylinder(p1pix, p2pix, rad_mm) and get_output()
        :param generator_params:
        """
        self.rawdata = None
        self.tube_skeleton = None
        self.data3d = None
        self.voxelsize_mm = [1, 1, 1]
        self.shape = None
        self.use_lar = False
        self.tree_label = None
        self.segments_progress_callback = self.finish_progress_callback
        self.stop_processing = False

        # if generator_class in ['vol', 'volume']:
        #     import tb_volume
        #     generator_class = tb_volume.TBVolume
        # elif generator_class in ['lar']:
        #     import tb_lar
        #     generator_class = tb_lar.TBLar
        # elif generator_class in ['vtk']:
        #     import tb_vtk
        #     generator_class = tb_vtk.TBVTK
        # elif generator_class in ['kunes']:
        #     import tb_lar_kunes
        #     generator_class = tb_lar_kunes.TBLar
        # elif generator_class in ['larsm']:
        #     import tb_lar_smooth
        #     generator_class = tb_lar_smooth.TBLarSmooth
        # elif generator_class in ['lar_nojoints']:
        #     import tb_lar
        #     generator_class = tb_lar.TBLar
        #     generator_params = {
        #         'endDistMultiplicator': 0,
        #         'use_joints': False
        #     }
        # self.generator_class = generator_class
        # self.generator_params = generator_params

    def importFromYaml(self, filename):
        tube_skeleton, rawdata = read_tube_skeleton_from_yaml(
            filename=filename,
            tree_label=self.tree_label,
            return_rawdata=True
        )
        self.rawdata = rawdata
        self.tube_skeleton = tube_skeleton

    def add_segment_to_tree(self, pointA, pointB, radius, id=None):
        """
        Before generation this can be used to add new segment
        :return:
        """
        if self.tube_skeleton is None:
            self.tube_skeleton = {}

        if id is None:
            id = len(self.tube_skeleton)

        self.tube_skeleton[id] = {
            'nodeA_ZYX_mm': pointA,
            'nodeB_ZYX_mm': pointB,
            'radius_mm': radius
        }

    def buildTree(self):
        """
        | Funkce na vygenerování objemu stromu ze zadaných dat.
        | Generates output by defined generator. If VolumeTreeGenerator is used, output is data3d.
        """
        # LAR init
        if self.use_lar:
            import lar_vessels
            self.lv = lar_vessels.LarVessels()

        # use generator init
        # if self.generator_params is None:
        #     self.generator = self.generator_class(self)
        # else:
        #     self.generator = self.generator_class(self, **self.generator_params)

        tree_output = self._build_tree_per_segments()

        logger.debug("before visualization - generateTree()")
        if self.use_lar:
            self.lv.show()

        return tree_output

    def _build_tree_per_segments(self):
        ln = len(self.tube_skeleton)
        if ln == 0:
            ln = 1
        progress_step = 1.0 / ln
        progress = 0.0

        for cyl_id in self.tube_skeleton:
            if self.stop_processing:
                break
            logger.debug("CylinderId: " + str(cyl_id))
            cyl_data = self.tube_skeleton[cyl_id]

            # try:
            #     cyl_data = self.data['graph']['porta'][cyl_id]
            # except:
            #     cyl_data = self.data['Graph'][cyl_id]

            # prvni a koncovy bod, v mm + radius v mm
            try:
                p1m = cyl_data['nodeA_ZYX_mm']  # souradnice ulozeny [Z,Y,X]
                p2m = cyl_data['nodeB_ZYX_mm']
                rad = cyl_data['radius_mm']
                self.add_cylinder(p1m, p2m, rad, cyl_id)
            except Exception as e:
                # import ipdb; ipdb.set_trace() #  noqa BREAKPOINT

                logger.error(
                    "Segment id " + str(cyl_id) + ": error reading data from yaml!: " + str(e))
                # return

                # if self.use_lar:
                #     self.generator.add_cylinder(p1m, p2m, rad, in)
            if self.segments_progress_callback is not None:
                self.segments_progress_callback(progress)
            progress += progress_step
        logger.debug("cylinders generated")

        # import ipdb; ipdb.set_trace()
        if "finish" in dir(self):
            # generator could have finish() function
            self.finish_progress_callback = self.finish_progress_callback
            self.finish()
            logger.debug("joints generated")
        else:
            import traceback
            # logger.debug(traceback.format_exc())
            logger.debug("no finish() function in tree constructor")
        # import ipdb; ipdb.set_trace()

        output = self.get_output()

        return output

    def finish_progress_callback(self, progress, *args, **kwargs):
        # if self.segments_progress_callback is not None:
        #     self.segments_progress_callback(progress)
        logger.debug("progess: {}\r".format(str(progress)))
        logger.debug(str(progress))

    def saveToFile(self, *args, **kwargs):
        self.save(*args, **kwargs)

    def stop(self):
        self.stop_processing = True

class TreeBuilder:
    def __init__(self, generator_class='volume', generator_params=None):
        """
        This function can be used as vessel_tree iterator. Just implement generator_class

        :param generator_class: class with function add_cylinder(p1pix, p2pix, rad_mm) and get_output()
        :param generator_params:
        """
        self.rawdata = None
        self.tree_data = None
        self.data3d = None
        self.voxelsize_mm = [1, 1, 1]
        self.shape = None
        self.use_lar = False
        self.tree_label = None
        self.segments_progress_callback = self.finish_progress_callback
        self.stop_processing = False

        if generator_class in ['vol', 'volume']:
            import tb_volume
            generator_class = tb_volume.TBVolume
        elif generator_class in ['lar']:
            import tb_lar
            generator_class = tb_lar.TBLar
        elif generator_class in ['vtk']:
            import tb_vtk
            generator_class = tb_vtk.TBVTK
        elif generator_class in ['kunes']:
            import tb_lar_kunes
            generator_class = tb_lar_kunes.TBLar
        elif generator_class in ['larsm']:
            import tb_lar_smooth
            generator_class = tb_lar_smooth.TBLarSmooth
        elif generator_class in ['lar_nojoints']:
            import tb_lar
            generator_class = tb_lar.TBLar
            generator_params = {
                'endDistMultiplicator': 0,
                'use_joints': False
            }
        self.generator_class = generator_class
        self.generator_params = generator_params

    def fix_tree_structure(self, tree_raw_data):
        """
        Fix backward compatibility
        :param tree_raw_data:
        :return: fixed tree_raw_data
        """
        if 'graph' in tree_raw_data:
            gr = tree_raw_data.pop('graph')
            tree_raw_data['Graph'] = gr  # {'tree1':gr}

        # if all keys in Graph a
        if all([type(k) != str for k in tree_raw_data['Graph'].keys()]):
            gr = tree_raw_data.pop('Graph')
            tree_raw_data['Graph'] = {'tree1': gr}

        # else:
        #     tree_raw_data = tree_raw_data['Graph']
        return tree_raw_data

    def importFromYaml(self, filename):
        from ruamel.yaml import YAML
        yaml = YAML()
        f = open(filename, 'rb')
        rawdata = yaml.load(f)
        f.close()
        self.rawdata = self.fix_tree_structure(rawdata)

        tkeys = self.rawdata['Graph'].keys()
        if (self.tree_label is None) or (self.tree_label not in tkeys):
            self.tree_label = tkeys[0]
        self.tree_data = self.rawdata['Graph'][self.tree_label]

    def add_segment_to_tree(self, pointA, pointB, radius, id=None):
        """
        Before generation this can be used to add new segment
        :return:
        """
        if self.tree_data is None:
            self.tree_data = {}

        if id is None:
            id = len(self.tree_data)

        self.tree_data[id] = {
            'nodeA_ZYX_mm': pointA,
            'nodeB_ZYX_mm': pointB,
            'radius_mm': radius
        }

    def buildTree(self):
        """
        | Funkce na vygenerování objemu stromu ze zadaných dat.
        | Generates output by defined generator. If VolumeTreeGenerator is used, output is data3d.
        """
        # LAR init
        if self.use_lar:
            import lar_vessels
            self.lv = lar_vessels.LarVessels()

        # use generator init
        if self.generator_params is None:
            self.generator = self.generator_class(self)
        else:
            self.generator = self.generator_class(self, **self.generator_params)

        tree_output = self._build_tree_per_segments()

        logger.debug("before visualization - generateTree()")
        if self.use_lar:
            self.lv.show()

        return tree_output

    def _build_tree_per_segments(self):
        ln = len(self.tree_data)
        if ln == 0:
            ln = 1
        progress_step = 1.0 / ln
        progress = 0.0

        for cyl_id in self.tree_data:
            if self.stop_processing:
                break
            logger.debug("CylinderId: " + str(cyl_id))
            cyl_data = self.tree_data[cyl_id]

            # try:
            #     cyl_data = self.data['graph']['porta'][cyl_id]
            # except:
            #     cyl_data = self.data['Graph'][cyl_id]

            # prvni a koncovy bod, v mm + radius v mm
            try:
                p1m = cyl_data['nodeA_ZYX_mm']  # souradnice ulozeny [Z,Y,X]
                p2m = cyl_data['nodeB_ZYX_mm']
                rad = cyl_data['radius_mm']
                self.generator.add_cylinder(p1m, p2m, rad, cyl_id)
            except Exception as e:
                # import ipdb; ipdb.set_trace() #  noqa BREAKPOINT

                logger.error(
                    "Segment id " + str(cyl_id) + ": error reading data from yaml!: " + str(e))
                # return

                # if self.use_lar:
                #     self.generator.add_cylinder(p1m, p2m, rad, in)
            if self.segments_progress_callback is not None:
                self.segments_progress_callback(progress)
            progress += progress_step
        logger.debug("cylinders generated")

        # import ipdb; ipdb.set_trace()
        if "finish" in dir(self.generator):
            # generator could have finish() function
            self.generator.finish_progress_callback = self.finish_progress_callback
            self.generator.finish()
            logger.debug("joints generated")
        else:
            import traceback
            # logger.debug(traceback.format_exc())
            logger.debug("no finish() function in tree constructor")
        # import ipdb; ipdb.set_trace()

        output = self.generator.get_output()

        return output

    def finish_progress_callback(self, progress, *args, **kwargs):
        # if self.segments_progress_callback is not None:
        #     self.segments_progress_callback(progress)
        logger.info("progress: {}\r".format(str(progress)))
        logger.debug(str(progress))

    def saveToFile(self, *args, **kwargs):
        self.generator.save(*args, **kwargs)

    def show(self):
        self.generator.show()

    def stop(self):
        self.stop_processing = True

def parse_area_properties(rawdata):
    def find_in_general_key(general):
        area = {}
        if "voxelsize_mm" in general:
            area["voxelsize_mm"] = general["voxelsize_mm"]
        if "shape_px" in general:
            area["areasize_px"] = general["shape_px"]
        if "areasize_px" in general:
            area["areasize_px"] = general["areasize_px"]
        return area

    area = {}
    if "general" in rawdata.keys():
        general = rawdata["general"]
        area = find_in_general_key(general)
    if "areasampling" in rawdata.keys():
        general = rawdata["areasampling"]
        area = find_in_general_key(general)

    # compatibility with older paper data
    if "voxelsize_mm" in rawdata.keys():
        area["voxelsize_mm"] = rawdata["voxelsize_mm"]
    if "voxelsize_px" in rawdata.keys():
        area["areasize_px"] = rawdata["voxelsize_px"]

    area["areasize_mm"] = np.asarray(area["areasize_px"]) * np.asarray(area["voxelsize_mm"])
    return area

def read_tube_skeleton_from_yaml(filename, tree_label=None, return_rawdata=False):
    """ Get tube skeleton and raw data from yaml file.

    :param self:
    :param filename: yaml filename
    :param tree_label: label of tree. The first tree is used if None.
    :return:
    """
    from ruamel.yaml import YAML
    yaml = YAML()
    f = open(filename, 'rb')
    rawdata = yaml.load(f)
    f.close()
    rawdataf = fix_tree_structure(rawdata)

    tkeys = list(rawdataf['Graph'].keys())
    if (tree_label is None) or (tree_label not in tkeys):
        tree_label = tkeys[0]
    tube_skeleton = rawdataf['Graph'][tree_label]
    if return_rawdata:
        return tube_skeleton, rawdataf
    else:
        return tube_skeleton

def fix_tree_structure(tree_raw_data):
    """
    Fix backward compatibility
    :param tree_raw_data:
    :return: fixed tree_raw_data
    """
    if 'graph' in tree_raw_data:
        gr = tree_raw_data.pop('graph')
        tree_raw_data['Graph'] = gr  # {'tree1':gr}

    # if all keys in Graph a
    if all([type(k) != str for k in tree_raw_data['Graph'].keys()]):
        gr = tree_raw_data.pop('Graph')
        tree_raw_data['Graph'] = {'tree1': gr}

    # else:
    #     tree_raw_data = tree_raw_data['Graph']
    return tree_raw_data

def main():
    logging.basicConfig()
    logger = logging.getLogger()
    logger.setLevel(logging.WARNING)

    # input parser
    parser = argparse.ArgumentParser(
        description='Histology analyser reporter. Try: \
python src/tb_volume.py -i ./tests/hist_stats_test.yaml'
    )
    parser.add_argument(
        '-i', '--inputfile',
        default=None,
        required=True,
        help='input file, yaml file'
    )
    parser.add_argument(
        '-o', '--outputfile',
        default=None,
        help='output file, .raw, .dcm, .tiff, given by extension '
    )
    parser.add_argument(
        '-ot', '--outputfiletype',
        default='pkl',
        help='output file type.  raw, dcm, tiff, or pkl,   default is pkl, '
    )
    parser.add_argument(
        '-vs', '--voxelsize',
        default=[1.0, 1.0, 1.0],
        type=float,
        metavar='N',
        nargs='+',
        help='size of voxel (ZYX)'
    )
    parser.add_argument(
        '-ds', '--datashape',
        default=[200, 200, 200],
        type=int,
        metavar='N',
        nargs='+',
        help='size of output data in pixels for each axis (ZYX)'
    )
    parser.add_argument(
        '-g', '--generator',
        default='vol',
        type=str,
        help='Volume or surface model can be generated by use this option. \
                Use "vol", "volume" for volumetric model. For LAR surface model\
                use "lar". For VTK file use "vtk".'
    )
    parser.add_argument(
        '-d', '--debug', action='store_true',
        help='Debug mode')
    parser.add_argument(
        '-l', '--useLar', action='store_true',
        help='Use LAR')
    args = parser.parse_args()

    if args.debug:
        logger.setLevel(logging.DEBUG)

    startTime = datetime.now()

    generator_params = None
    generator_class = args.generator

    # if args.generator == "vtk":
    #     import gen_vtk_tree
    #     gen_vtk_tree.vt2vtk_file(args.inputfile, args.outputfile)
    #     return

    tg = TreeBuilder(generator_class, generator_params)
    tg.importFromYaml(args.inputfile)
    tg.voxelsize_mm = args.voxelsize
    tg.shape = args.datashape
    tg.use_lar = args.useLar
    data3d = tg.buildTree()

    logger.info("TimeUsed:" + str(datetime.now() - startTime))
    # volume_px = sum(sum(sum(data3d)))
    # volume_mm3 = volume_px * \
    #     (tg.voxelsize_mm[0] * tg.voxelsize_mm[1] * tg.voxelsize_mm[2])
    # logger.info("Volume px:" + str(volume_px))
    # logger.info("Volume mm3:" + str(volume_mm3))

    # vizualizace
    logger.debug("before visualization")
    tg.show()
    logger.debug("after visualization")

    # ukládání do souboru
    if args.outputfile is not None:
        tg.saveToFile(args.outputfile, args.outputfiletype)

# class TreeGenerator(TreeConstructor):
#     """
#     back compatibility
#     """
#     pass

if __name__ == "__main__":
    main()


text:
package com.google.android.finsky.protos;

import com.google.protobuf.nano.CodedOutputByteBufferNano;
import com.google.protobuf.nano.InternalNano;
import com.google.protobuf.nano.MessageNano;
import com.google.protobuf.nano.WireFormatNano;
import java.io.IOException;
import java.util.Arrays;

public abstract interface Details
{
  public static final class BulkDetailsEntry
    extends MessageNano
  {
    private static volatile BulkDetailsEntry[] _emptyArray;
    public DocV2 doc = null;

    public BulkDetailsEntry()
    {
      this.cachedSize = -1;
    }

    public static BulkDetailsEntry[] emptyArray()
    {
      if (_emptyArray == null) {}
      synchronized (InternalNano.LAZY_INIT_LOCK)
      {
        if (_emptyArray == null) {
          _emptyArray = new BulkDetailsEntry[0];
        }
        return _emptyArray;
      }
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if (this.doc != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(1, this.doc);
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if (this.doc != null) {
        paramCodedOutputByteBufferNano.writeMessage(1, this.doc);
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class BulkDetailsRequest
    extends MessageNano
  {
    public String[] docid = WireFormatNano.EMPTY_STRING_ARRAY;
    public boolean hasIncludeChildDocs = false;
    public boolean hasIncludeDetails = false;
    public boolean hasSourcePackageName = false;
    public boolean includeChildDocs = true;
    public boolean includeDetails = false;
    public int[] installedVersionCode = WireFormatNano.EMPTY_INT_ARRAY;
    public String sourcePackageName = "";

    public BulkDetailsRequest()
    {
      this.cachedSize = -1;
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if ((this.docid != null) && (this.docid.length > 0))
      {
        int m = 0;
        int n = 0;
        for (int i1 = 0; i1 < this.docid.length; i1++)
        {
          String str = this.docid[i1];
          if (str != null)
          {
            m++;
            n += CodedOutputByteBufferNano.computeStringSizeNoTag(str);
          }
        }
        i = i + n + m * 1;
      }
      if ((this.hasIncludeChildDocs) || (this.includeChildDocs != true)) {
        i += 1 + CodedOutputByteBufferNano.computeTagSize(2);
      }
      if ((this.hasIncludeDetails) || (this.includeDetails)) {
        i += 1 + CodedOutputByteBufferNano.computeTagSize(3);
      }
      if ((this.hasSourcePackageName) || (!this.sourcePackageName.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(4, this.sourcePackageName);
      }
      if ((this.installedVersionCode != null) && (this.installedVersionCode.length > 0))
      {
        int j = 0;
        for (int k = 0; k < this.installedVersionCode.length; k++) {
          j += CodedOutputByteBufferNano.computeInt32SizeNoTag(this.installedVersionCode[k]);
        }
        i = i + j + 1 * this.installedVersionCode.length;
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if ((this.docid != null) && (this.docid.length > 0)) {
        for (int j = 0; j < this.docid.length; j++)
        {
          String str = this.docid[j];
          if (str != null) {
            paramCodedOutputByteBufferNano.writeString(1, str);
          }
        }
      }
      if ((this.hasIncludeChildDocs) || (this.includeChildDocs != true)) {
        paramCodedOutputByteBufferNano.writeBool(2, this.includeChildDocs);
      }
      if ((this.hasIncludeDetails) || (this.includeDetails)) {
        paramCodedOutputByteBufferNano.writeBool(3, this.includeDetails);
      }
      if ((this.hasSourcePackageName) || (!this.sourcePackageName.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(4, this.sourcePackageName);
      }
      if ((this.installedVersionCode != null) && (this.installedVersionCode.length > 0)) {
        for (int i = 0; i < this.installedVersionCode.length; i++) {
          paramCodedOutputByteBufferNano.writeInt32(7, this.installedVersionCode[i]);
        }
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class BulkDetailsResponse
    extends MessageNano
  {
    public Details.BulkDetailsEntry[] entry = Details.BulkDetailsEntry.emptyArray();

    public BulkDetailsResponse()
    {
      this.cachedSize = -1;
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if ((this.entry != null) && (this.entry.length > 0)) {
        for (int j = 0; j < this.entry.length; j++)
        {
          Details.BulkDetailsEntry localBulkDetailsEntry = this.entry[j];
          if (localBulkDetailsEntry != null) {
            i += CodedOutputByteBufferNano.computeMessageSize(1, localBulkDetailsEntry);
          }
        }
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if ((this.entry != null) && (this.entry.length > 0)) {
        for (int i = 0; i < this.entry.length; i++)
        {
          Details.BulkDetailsEntry localBulkDetailsEntry = this.entry[i];
          if (localBulkDetailsEntry != null) {
            paramCodedOutputByteBufferNano.writeMessage(1, localBulkDetailsEntry);
          }
        }
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class DetailsResponse
    extends MessageNano
  {
    public String analyticsCookie = "";
    public Details.DiscoveryBadge[] discoveryBadge = Details.DiscoveryBadge.emptyArray();
    public DocV1 docV1 = null;
    public DocV2 docV2 = null;
    public boolean enableReviews = true;
    public String footerHtml = "";
    public boolean hasAnalyticsCookie = false;
    public boolean hasEnableReviews = false;
    public boolean hasFooterHtml = false;
    public boolean hasServerLogsCookie = false;
    public byte[] serverLogsCookie = WireFormatNano.EMPTY_BYTES;
    public Review userReview = null;

    public DetailsResponse()
    {
      this.cachedSize = -1;
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if (this.docV1 != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(1, this.docV1);
      }
      if ((this.hasAnalyticsCookie) || (!this.analyticsCookie.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(2, this.analyticsCookie);
      }
      if (this.userReview != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(3, this.userReview);
      }
      if (this.docV2 != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(4, this.docV2);
      }
      if ((this.hasFooterHtml) || (!this.footerHtml.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(5, this.footerHtml);
      }
      if ((this.hasServerLogsCookie) || (!Arrays.equals(this.serverLogsCookie, WireFormatNano.EMPTY_BYTES))) {
        i += CodedOutputByteBufferNano.computeBytesSize(6, this.serverLogsCookie);
      }
      if ((this.discoveryBadge != null) && (this.discoveryBadge.length > 0)) {
        for (int j = 0; j < this.discoveryBadge.length; j++)
        {
          Details.DiscoveryBadge localDiscoveryBadge = this.discoveryBadge[j];
          if (localDiscoveryBadge != null) {
            i += CodedOutputByteBufferNano.computeMessageSize(7, localDiscoveryBadge);
          }
        }
      }
      if ((this.hasEnableReviews) || (this.enableReviews != true)) {
        i += 1 + CodedOutputByteBufferNano.computeTagSize(8);
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if (this.docV1 != null) {
        paramCodedOutputByteBufferNano.writeMessage(1, this.docV1);
      }
      if ((this.hasAnalyticsCookie) || (!this.analyticsCookie.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(2, this.analyticsCookie);
      }
      if (this.userReview != null) {
        paramCodedOutputByteBufferNano.writeMessage(3, this.userReview);
      }
      if (this.docV2 != null) {
        paramCodedOutputByteBufferNano.writeMessage(4, this.docV2);
      }
      if ((this.hasFooterHtml) || (!this.footerHtml.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(5, this.footerHtml);
      }
      if ((this.hasServerLogsCookie) || (!Arrays.equals(this.serverLogsCookie, WireFormatNano.EMPTY_BYTES))) {
        paramCodedOutputByteBufferNano.writeBytes(6, this.serverLogsCookie);
      }
      if ((this.discoveryBadge != null) && (this.discoveryBadge.length > 0)) {
        for (int i = 0; i < this.discoveryBadge.length; i++)
        {
          Details.DiscoveryBadge localDiscoveryBadge = this.discoveryBadge[i];
          if (localDiscoveryBadge != null) {
            paramCodedOutputByteBufferNano.writeMessage(7, localDiscoveryBadge);
          }
        }
      }
      if ((this.hasEnableReviews) || (this.enableReviews != true)) {
        paramCodedOutputByteBufferNano.writeBool(8, this.enableReviews);
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class DiscoveryBadge
    extends MessageNano
  {
    private static volatile DiscoveryBadge[] _emptyArray;
    public float aggregateRating = 0.0F;
    public int backgroundColor = 0;
    public String contentDescription = "";
    public Details.DiscoveryBadgeLink discoveryBadgeLink = null;
    public String downloadCount = "";
    public String downloadUnits = "";
    public Details.FamilyAgeRangeBadge familyAgeRangeBadge = null;
    public Details.FamilyCategoryBadge familyCategoryBadge = null;
    public boolean hasAggregateRating = false;
    public boolean hasBackgroundColor = false;
    public boolean hasContentDescription = false;
    public boolean hasDownloadCount = false;
    public boolean hasDownloadUnits = false;
    public boolean hasIsPlusOne = false;
    public boolean hasServerLogsCookie = false;
    public boolean hasTitle = false;
    public boolean hasUserStarRating = false;
    public Common.Image image = null;
    public boolean isPlusOne = false;
    public Details.PlayerBadge playerBadge = null;
    public byte[] serverLogsCookie = WireFormatNano.EMPTY_BYTES;
    public String title = "";
    public int userStarRating = 0;

    public DiscoveryBadge()
    {
      this.cachedSize = -1;
    }

    public static DiscoveryBadge[] emptyArray()
    {
      if (_emptyArray == null) {}
      synchronized (InternalNano.LAZY_INIT_LOCK)
      {
        if (_emptyArray == null) {
          _emptyArray = new DiscoveryBadge[0];
        }
        return _emptyArray;
      }
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if ((this.hasTitle) || (!this.title.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(1, this.title);
      }
      if (this.image != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(2, this.image);
      }
      if ((this.hasBackgroundColor) || (this.backgroundColor != 0)) {
        i += CodedOutputByteBufferNano.computeInt32Size(3, this.backgroundColor);
      }
      if (this.discoveryBadgeLink != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(4, this.discoveryBadgeLink);
      }
      if ((this.hasServerLogsCookie) || (!Arrays.equals(this.serverLogsCookie, WireFormatNano.EMPTY_BYTES))) {
        i += CodedOutputByteBufferNano.computeBytesSize(5, this.serverLogsCookie);
      }
      if ((this.hasIsPlusOne) || (this.isPlusOne)) {
        i += 1 + CodedOutputByteBufferNano.computeTagSize(6);
      }
      if ((this.hasAggregateRating) || (Float.floatToIntBits(this.aggregateRating) != Float.floatToIntBits(0.0F))) {
        i += 4 + CodedOutputByteBufferNano.computeTagSize(7);
      }
      if ((this.hasUserStarRating) || (this.userStarRating != 0)) {
        i += CodedOutputByteBufferNano.computeInt32Size(8, this.userStarRating);
      }
      if ((this.hasDownloadCount) || (!this.downloadCount.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(9, this.downloadCount);
      }
      if ((this.hasDownloadUnits) || (!this.downloadUnits.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(10, this.downloadUnits);
      }
      if ((this.hasContentDescription) || (!this.contentDescription.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(11, this.contentDescription);
      }
      if (this.playerBadge != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(12, this.playerBadge);
      }
      if (this.familyAgeRangeBadge != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(13, this.familyAgeRangeBadge);
      }
      if (this.familyCategoryBadge != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(14, this.familyCategoryBadge);
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if ((this.hasTitle) || (!this.title.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(1, this.title);
      }
      if (this.image != null) {
        paramCodedOutputByteBufferNano.writeMessage(2, this.image);
      }
      if ((this.hasBackgroundColor) || (this.backgroundColor != 0)) {
        paramCodedOutputByteBufferNano.writeInt32(3, this.backgroundColor);
      }
      if (this.discoveryBadgeLink != null) {
        paramCodedOutputByteBufferNano.writeMessage(4, this.discoveryBadgeLink);
      }
      if ((this.hasServerLogsCookie) || (!Arrays.equals(this.serverLogsCookie, WireFormatNano.EMPTY_BYTES))) {
        paramCodedOutputByteBufferNano.writeBytes(5, this.serverLogsCookie);
      }
      if ((this.hasIsPlusOne) || (this.isPlusOne)) {
        paramCodedOutputByteBufferNano.writeBool(6, this.isPlusOne);
      }
      if ((this.hasAggregateRating) || (Float.floatToIntBits(this.aggregateRating) != Float.floatToIntBits(0.0F))) {
        paramCodedOutputByteBufferNano.writeFloat(7, this.aggregateRating);
      }
      if ((this.hasUserStarRating) || (this.userStarRating != 0)) {
        paramCodedOutputByteBufferNano.writeInt32(8, this.userStarRating);
      }
      if ((this.hasDownloadCount) || (!this.downloadCount.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(9, this.downloadCount);
      }
      if ((this.hasDownloadUnits) || (!this.downloadUnits.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(10, this.downloadUnits);
      }
      if ((this.hasContentDescription) || (!this.contentDescription.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(11, this.contentDescription);
      }
      if (this.playerBadge != null) {
        paramCodedOutputByteBufferNano.writeMessage(12, this.playerBadge);
      }
      if (this.familyAgeRangeBadge != null) {
        paramCodedOutputByteBufferNano.writeMessage(13, this.familyAgeRangeBadge);
      }
      if (this.familyCategoryBadge != null) {
        paramCodedOutputByteBufferNano.writeMessage(14, this.familyCategoryBadge);
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class DiscoveryBadgeLink
    extends MessageNano
  {
    public String criticReviewsUrl = "";
    public boolean hasCriticReviewsUrl = false;
    public boolean hasUserReviewsUrl = false;
    public Link link = null;
    public String userReviewsUrl = "";

    public DiscoveryBadgeLink()
    {
      this.cachedSize = -1;
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if (this.link != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(1, this.link);
      }
      if ((this.hasUserReviewsUrl) || (!this.userReviewsUrl.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(2, this.userReviewsUrl);
      }
      if ((this.hasCriticReviewsUrl) || (!this.criticReviewsUrl.equals(""))) {
        i += CodedOutputByteBufferNano.computeStringSize(3, this.criticReviewsUrl);
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if (this.link != null) {
        paramCodedOutputByteBufferNano.writeMessage(1, this.link);
      }
      if ((this.hasUserReviewsUrl) || (!this.userReviewsUrl.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(2, this.userReviewsUrl);
      }
      if ((this.hasCriticReviewsUrl) || (!this.criticReviewsUrl.equals(""))) {
        paramCodedOutputByteBufferNano.writeString(3, this.criticReviewsUrl);
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }

  public static final class FamilyAgeRangeBadge
    extends MessageNano
  {
    public FamilyAgeRangeBadge()
    {
      this.cachedSize = -1;
    }
  }

  public static final class FamilyCategoryBadge
    extends MessageNano
  {
    public FamilyCategoryBadge()
    {
      this.cachedSize = -1;
    }
  }

  public static final class PlayerBadge
    extends MessageNano
  {
    public Common.Image overlayIcon = null;

    public PlayerBadge()
    {
      this.cachedSize = -1;
    }

    protected final int computeSerializedSize()
    {
      int i = super.computeSerializedSize();
      if (this.overlayIcon != null) {
        i += CodedOutputByteBufferNano.computeMessageSize(1, this.overlayIcon);
      }
      return i;
    }

    public final void writeTo(CodedOutputByteBufferNano paramCodedOutputByteBufferNano)
      throws IOException
    {
      if (this.overlayIcon != null) {
        paramCodedOutputByteBufferNano.writeMessage(1, this.overlayIcon);
      }
      super.writeTo(paramCodedOutputByteBufferNano);
    }
  }
}

/* Location:           F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar

 * Qualified Name:     com.google.android.finsky.protos.Details

 * JD-Core Version:    0.7.0.1

 */


text:
package jodd.json.mock;

public class Book extends Periodical {

	private String isbn;

	public Book(String isbn, String name) {
		super(name);
		this.isbn = isbn;
	}

	@Override
	public String getID() {
		return isbn;
	}

	@Override
	public void setID(String id) {
		isbn = id;
	}

	public void setID(Integer id) {
		isbn = Integer.toString(id);
	}

	public boolean isA() {
		return false;
	}

	public void setName(String name) {
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ElementPrototype
</TITLE>

<META NAME="date" CONTENT="2011-12-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.cmu.cs.stage3.alice.authoringtool.util

Class ElementPrototype

java.lang.Object
  edu.cmu.cs.stage3.alice.authoringtool.util.ElementPrototype

Direct Known Subclasses:
QuestionPrototype, ResponsePrototype

public class ElementPrototype
extends java.lang.Object

Author:

Jason Pratt

Constructor Summary

ElementPrototype(java.lang.Class elementClass,
                 StringObjectPair[] knownPropertyValues,
                 java.lang.String[] desiredProperties)

Method Summary

 ElementPrototype
createCopy(StringObjectPair newKnownPropertyValue)

 ElementPrototype
createCopy(StringObjectPair[] newKnownPropertyValues)

 Element
createNewElement()

 java.lang.String[]
getDesiredProperties()

 java.lang.Class
getElementClass()

 StringObjectPair[]
getKnownPropertyValues()

 java.lang.String
toString()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

ElementPrototype

public ElementPrototype(java.lang.Class elementClass,
                        StringObjectPair[] knownPropertyValues,
                        java.lang.String[] desiredProperties)

Method Detail

createNewElement

public Element createNewElement()

createCopy

public ElementPrototype createCopy(StringObjectPair newKnownPropertyValue)

createCopy

public ElementPrototype createCopy(StringObjectPair[] newKnownPropertyValues)

getElementClass

public java.lang.Class getElementClass()

getKnownPropertyValues

public StringObjectPair[] getKnownPropertyValues()

getDesiredProperties

public java.lang.String[] getDesiredProperties()

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package de.tudarmstadt.lt.structuredtopics.ddts;

import static org.apache.commons.lang3.StringUtils.lastIndexOf;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.io.LineIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;

import de.tudarmstadt.lt.structuredtopics.Utils;

public class Parser {
	private static final Logger LOG = LoggerFactory.getLogger(Parser.class);

	public List<SenseCluster> parseDDT(File ddt) throws IOException {
		List<SenseCluster> senseClusters = new ArrayList<>(100000);
		try (BufferedReader in = Utils.openReader(ddt)) {
			String line = null;
			int count = 0;
			while ((line = in.readLine()) != null) {
				count++;
				if (count % 1000 == 0) {
					LOG.info("Parsing cluster {}", count);
				}
				SenseCluster cluster = null;
				try {
					cluster = parseSenseClusterFromLine(line);
				} catch (Exception e) {
					LOG.error("Unexpected error while parsing line {} : {}", count, line, e);
				}
				if (cluster != null) {
					senseClusters.add(cluster);
				} else {
					LOG.warn("Unable to parse line {}: {}", count, line);
				}
			}
		}
		return senseClusters;
	}

	public DDTIterator iterateDDT(File ddt) throws IOException {
		return new DDTIterator(Utils.openReader(ddt));
	}

	/**
	 * Iterates over the senses of an DDT without keeping the entire file in
	 * memory. The Iterator may return null for some clusters if a line can not
	 * be parsed from the ddt.
	 *
	 */
	public class DDTIterator implements Iterator<SenseCluster>, Closeable {

		private org.apache.commons.io.LineIterator it;

		private BufferedReader in;
		private int count = 0;

		public DDTIterator(BufferedReader in) {
			this.in = in;
			it = new LineIterator(in);
		}

		@Override
		public boolean hasNext() {
			return it.hasNext();
		}

		@Override
		public SenseCluster next() {
			String line = it.next();
			count++;
			try {
				SenseCluster senseCluster = parseSenseClusterFromLine(line);
				return senseCluster;
			} catch (Exception e) {
				LOG.error("Unexpected error while parsing line {} : {}", count, line, e);
				return null;
			}
		}

		@Override
		public void close() throws IOException {
			in.close();
		}

	}

	@VisibleForTesting
	protected SenseCluster parseSenseClusterFromLine(String line) {
		String[] columns = line.split("\t");
		if (columns.length < 3) {
			return null;
		}
		List<SingleWord> senseWords = parseSenseWords(columns[0]);
		Integer senseId;
		try {
			senseId = Integer.valueOf(columns[1]);
		} catch (NumberFormatException e) {
			try {
				// some ids were saved in double format. However, this should be
				// the
				// exception not the default as the conversion from string to
				// double
				// to integer is more expensive
				senseId = Double.valueOf(columns[1]).intValue();
			} catch (NumberFormatException e2) {
				return null;
			}
		}
		Sense sense = new Sense(senseWords, senseId);
		List<ClusterWord> cluster = parseClusterWords(columns[2]);
		return new SenseCluster(sense, cluster);
	}

	private List<SingleWord> parseSenseWords(String senseColumn) {
		List<SingleWord> senseWords = Lists.newArrayListWithCapacity(1);
		String[] words = senseColumn.split("\\s+");
		for (String wordRaw : words) {
			int lastHash = lastIndexOf(wordRaw, "#");
			if (lastHash != -1) {
				String text = wordRaw.substring(0, lastHash);
				String pos = wordRaw.substring(lastHash + 1);
				SingleWord word = new SingleWord(text, pos);
				senseWords.add(word);
			} else {
				SingleWord word = new SingleWord(wordRaw, null);
				senseWords.add(word);
			}
		}
		return senseWords;
	}

	private static final Pattern SENSEID_WEIGHT_PATTERN = Pattern.compile("\\d+[:]\\d+[.]\\d+");

	private List<ClusterWord> parseClusterWords(String clusterColumn) {
		List<ClusterWord> clusterWords = new ArrayList<>(100);
		// words are a csv list
		String[] clusterWordsRaw = clusterColumn.split("[,]\\s*");
		for (String wordsRaw : clusterWordsRaw) {
			List<SingleWord> words = new ArrayList<>(1);
			Integer relatedSenseId = null;
			Double weight = null;
			// multi-words are separated by whitespace
			for (String wordRaw : wordsRaw.split("\\s+")) {
				String[] sections = wordRaw.split("[#]");
				String text;
				if (sections.length <= 1) {
					text = wordRaw;
				} else {
					text = sections[0];
				}
				String pos = null;
				for (int i = 1; i < sections.length; i++) {
					String section = sections[i];
					if (SENSEID_WEIGHT_PATTERN.matcher(section).matches()) {
						String[] senseIdWeightRaw = section.split("[:]");
						relatedSenseId = Integer.valueOf(senseIdWeightRaw[0]);
						weight = Double.valueOf(senseIdWeightRaw[1]);
					} else {
						// in case of multiple sections, the last one is the
						// pos-tag. The previous one will be overridden.
						pos = section;
					}
				}
				SingleWord word = new SingleWord(text, pos);
				words.add(word);
			}
			ClusterWord clusterWord = new ClusterWord(words, relatedSenseId, weight);
			clusterWords.add(clusterWord);
		}
		return clusterWords;
	}
}


text:
import os
import shutil

import unittest2 as unittest

from tinctest.lib.system import TINCSystem, TINCSystemException

class TINCSystemTests(unittest.TestCase):

    def test_make_dirs(self):
        test_dir = os.path.join(os.path.dirname(__file__), 'test_mkdirs')
        if os.path.exists(test_dir):
            shutil.rmtree(test_dir)
        self.assertFalse(os.path.exists(test_dir))
        TINCSystem.make_dirs(test_dir)
        self.assertTrue(os.path.exists(test_dir))

    def test_make_dirs_existing(self):
        test_dir = os.path.join(os.path.dirname(__file__), 'test_mkdirs')
        if os.path.exists(test_dir):
            shutil.rmtree(test_dir)
        self.assertFalse(os.path.exists(test_dir))
        TINCSystem.make_dirs(test_dir)
        self.assertTrue(os.path.exists(test_dir))

        # This should fail
        with self.assertRaises(OSError) as cm:
            TINCSystem.make_dirs(test_dir)

    def test_make_dirs_existing_ignore(self):
        test_dir = os.path.join(os.path.dirname(__file__), 'test_mkdirs')
        if os.path.exists(test_dir):
            shutil.rmtree(test_dir)
        self.assertFalse(os.path.exists(test_dir))
        TINCSystem.make_dirs(test_dir)
        self.assertTrue(os.path.exists(test_dir))

        # This should not fail and ignore existing error
        TINCSystem.make_dirs(test_dir, ignore_exists_error = True)

    def test_make_dirs_relative_path(self):
        test_dir = 'test/output'
        with self.assertRaises(TINCSystemException) as cm:
            TINCSystem.make_dirs(test_dir)

    def test_force_create_make_dirs(self):
        test_dir = os.path.join(os.path.dirname(__file__), 'test_force')
        if os.path.exists(test_dir):
            shutil.rmtree(test_dir)
        self.assertFalse(os.path.exists(test_dir))
        TINCSystem.make_dirs(test_dir)
        self.assertTrue(os.path.exists(test_dir))

        test_file = os.path.join(test_dir, 'testfile')
        with open(test_file, 'w') as f:
            f.write('test')

        self.assertTrue(os.path.exists(test_file))
        # Force create
        TINCSystem.make_dirs(test_dir, force_create = True)
        self.assertFalse(os.path.exists(test_file))


text:
package net.imglib2.meta;

import net.imglib2.AnnotatedSpace;

/**
 * A Euclidean space with typed dimensional axes.
 *
 * @author Curtis Rueden
 * @see TypedAxis
 * @deprecated Use {@link net.imagej.space.TypedSpace} instead.
 */
@Deprecated
public interface TypedSpace extends AnnotatedSpace {

	/**
	 * Gets the dimensional index of the axis with the given type.
	 *

	 * Note that by convention, each {@link AxisType} may only be used in a single
	 * dimension of the space.
	 *

	 *
	 * @return the dimensional index of the specified axis type. Return
	 * -1 if the specified axis type is not found.
	 */
	int dimensionIndex(final AxisType axisType);

}


text:
import torch
import torch.nn as nn
from torch.nn import Parameter
from torch.autograd import Variable, Function
from collections import defaultdict
import graphviz

"""
This is a rather distorted implementation of graph visualization in PyTorch.
This implementation is distorted because PyTorch's autograd is undergoing refactoring right now.
- neither func.next_functions nor func.previous_functions can be relied upon
- BatchNorm's C backend does not follow the python Function interface
- I'm not even sure whether to use var.creator or var.grad_fn (apparently the source tree and wheel builds use different
  interface now)
As a result, we are forced to manually trace the graph, using 2 redundant mechanisms:
- Function.__call__: this allows us to trace all Function creations. Function corresponds to Op in TF
- Module.forward_hook: this is needed because the above method doesn't work for BatchNorm, as the current C backend does
  not follow the Python Function interface.
To do graph visualization, follow these steps:
1. register hooks on model: register_vis_hooks(model)
2. pass data through model: output = model(input)
3. remove hooks           : remove_vis_hooks()
4. perform visualization  : save_visualization(name, format='svg') # name is a string without extension
"""

old_function__call__ = Function.__call__

def register_creator(inputs, creator, output):
    """
    In the forward pass, our Function.__call__ and BatchNorm.forward_hook both call this method to register the creators
    inputs: list of input variables
    creator: one of
        - Function
        - BatchNorm module
    output: a single output variable
    """
    cid = id(creator)
    oid = id(output)
    if oid in vars:
        return
    # connect creator to input
    for input in inputs:
        iid = id(input)
        func_trace[cid][iid] = input
        # register input
        vars[iid] = input
    # connect output to creator
    assert type(output) not in [tuple, list, dict]
    var_trace[oid][cid] = creator
    # register creator and output and all inputs
    vars[oid] = output
    funcs[cid] = creator

hooks = []

def register_vis_hooks(model):
    global var_trace, func_trace, vars, funcs
    remove_vis_hooks()
    var_trace  = defaultdict(lambda: {})     # map oid to {cid:creator}
    func_trace = defaultdict(lambda: {})     # map cid to {iid:input}
    vars  = {}                               # map vid to Variable/Parameter
    funcs = {}                               # map cid to Function/BatchNorm module
    hooks = []                               # contains the forward hooks, needed for hook removal

    def hook_func(module, inputs, output):
        assert 'BatchNorm' in mod.__class__.__name__        # batchnorms don't have shared superclass
        inputs = list(inputs)
        for p in [module.weight, module.bias]:
            if p is not None:
                inputs.append(p)
        register_creator(inputs, module, output)

    for mod in model.modules():
        if 'BatchNorm' in mod.__class__.__name__:           # batchnorms don't have shared superclass
            hook = mod.register_forward_hook(hook_func)
            hooks.append(hook)

    def new_function__call__(self, *args, **kwargs):
        inputs =  [a for a in args            if isinstance(a, Variable)]
        inputs += [a for a in kwargs.values() if isinstance(a, Variable)]
        output = old_function__call__(self, *args, **kwargs)
        register_creator(inputs, self, output)
        return output

    Function.__call__ = new_function__call__

def remove_vis_hooks():
    for hook in hooks:
        hook.remove()

    Function.__call__ = old_function__call__

def save_visualization(name, format='jpg'):
    g = graphviz.Digraph(format=format)
    def sizestr(var):
        size = [int(i) for i in list(var.size())]
        return str(size)
    # add variable nodes
    for vid, var in vars.items():
        if isinstance(var, nn.Parameter):
            g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='red')
        elif isinstance(var, Variable):
            g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='lightblue')
        else:
            assert False, var.__class__
    # add creator nodes
    for cid in func_trace:
        creator = funcs[cid]
        g.node(str(cid), label=str(creator.__class__.__name__), shape='rectangle', style='filled', fillcolor='orange')
    # add edges between creator and inputs
    for cid in func_trace:
        for iid in func_trace[cid]:
            g.edge(str(iid), str(cid))
    # add edges between outputs and creators
    for oid in var_trace:
        for cid in var_trace[oid]:
            g.edge(str(cid), str(oid))
    g.render(name)


text:
module RailsPwnerer::Config
  def self.init_ports(free_ports = [[8000, 16000]])
    self.create_db :free_ports
    self[:free_ports][:list] = free_ports
    self.flush_db :free_ports
  end

  # allocates a contiguous range of ports
  # returns the starting port or nil
  def self.alloc_ports(nports = 1)
    free_ports = self[:free_ports][:list]
    free_ports.each_index do |i|
      next if free_ports[i][1] - free_ports[i][0] < nports
      first_port = free_ports[i][0]
      free_ports[i][0] += nports
      free_ports.delete_at i if free_ports[i][0] == free_ports[i][1]
      self[:free_ports][:list] = free_ports
      self.flush_db :free_ports
      return first_port
    end
  end

  # returns a continuous range of ports to the free list
  def self.free_ports(start, count = 1)
    free_ports = self[:free_ports][:list]
    free_ports << [start, start + count]

    # concatenate duplicates
    free_ports.sort! { |a, b| a[0] <=> b[0]}
    new_ports = [free_ports.first]
    free_ports.each_index do |i|
      if new_ports.last[1] >= free_ports[i][0]
        new_ports.last[1] = [new_ports.last[1], free_ports[i][1]].max
      else
        new_ports << free_ports[i]
      end
    end

    # write the new database
    self[:free_ports][:list] = new_ports
    self.flush_db :free_ports
  end
end


text:
<?php

namespace Site\SiteBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * CategoryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CategoryRepository extends EntityRepository
{
    public function getTopCategories()
    {
        return $this->getCategories(0, 'top');
    }

    public function getCategories($parent_id = null, $location = null)
    {
        $qb = $this->createQueryBuilder('c')
                ->select('c')
                ->addOrderBy('c.sort', 'ASC')
                ->addOrderBy('c.title', 'ASC');

        if (!is_null($parent_id)) {
            $qb->andWhere('c.parent = :parent_id')
                ->setParameter('parent_id', $parent_id);
        }

        if (!is_null($location)) {
            $qb->andWhere('c.location = :location')
                ->setParameter('location', $location);
        }

        return $qb->getQuery()->getResult();
    }

    public function findBySlug($slug = '')
    {
        $qb = $this->createQueryBuilder('c')
                ->select('c')
                ->andWhere('c.slug = :slug')
                ->setParameter('slug', $slug);

        return $qb->getQuery()->getOneOrNullResult();
    }

    public function getCategoriesTree($parent_id = null, $location = null)
    {
        $categoiries = $this->getCategories($parent_id = null, $location = null);
    }

    protected function getSubCategoires($categories)
    {
        $sub = array();
        foreach ($categories as $category) {
            # code...
        }
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Subscriber extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('Datatables');
        $this->load->library('table');
        $this->load->database();

    }
    function index()
    {

        //set table id in table open tag
        $tmpl = array ( 'table_open'  => '<table id="big_table" border="1" cellpadding="2" cellspacing="1" class="mytable">' );
        $this->table->set_template($tmpl);

        $this->table->set_heading('Number','Name','Parent Name','Address','Phone Number');

        $this->load->view('studentListView');
    }
    //function to handle callbacks
    function datatable()
    {
        $this->datatables->select('id,name,parentname,address,phonenumber')
      //  ->unset_column('id')
        ->from('subscriber');

        echo $this->datatables->generate();
    }
}


text:
package net.md_5.specialsource.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * A pseudo class implementing the {@link List} like, but does not allow
 * duplicates. Is backed by an {@link ArrayList} and {@link HashSet} for speedy
 * contains lookups.
 *
 * @param <E> the type of elements contained in this 'list'
 */
public class NoDupeList<E> implements Iterable<E> {

    private final Set<E> set = new HashSet<E>();
    private final List<E> backing = new ArrayList<E>();

    public boolean add(E e) {
        if (set.contains(e)) {
            return false;
        } else {
            set.add(e);
            backing.add(e);
            return true;
        }
    }

    public E get(int index) {
        return backing.get(index);
    }

    public int size() {
        return backing.size();
    }

    @Override
    public Iterator<E> iterator() {
        return backing.iterator();
    }
}


text:
<?php

namespace Illuminate\Events;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\Traits\ForwardsCalls;

class NullDispatcher implements DispatcherContract
{
    use ForwardsCalls;

    /**
     * The underlying event dispatcher instance.
     *
     * @var \Illuminate\Contracts\Bus\Dispatcher
     */
    protected $dispatcher;

    /**
     * Create a new event dispatcher instance that does not fire.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $dispatcher
     * @return void
     */
    public function __construct(DispatcherContract $dispatcher)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * Don't fire an event.
     *
     * @param  string|object  $event
     * @param  mixed  $payload
     * @param  bool  $halt
     * @return void
     */
    public function dispatch($event, $payload = [], $halt = false)
    {
    }

    /**
     * Don't register an event and payload to be fired later.
     *
     * @param  string  $event
     * @param  array  $payload
     * @return void
     */
    public function push($event, $payload = [])
    {
    }

    /**
     * Don't dispatch an event.
     *
     * @param  string|object  $event
     * @param  mixed  $payload
     * @return array|null
     */
    public function until($event, $payload = [])
    {
    }

    /**
     * Register an event listener with the dispatcher.
     *
     * @param  string|array  $events
     * @param  \Closure|string  $listener
     * @return void
     */
    public function listen($events, $listener)
    {
        $this->dispatcher->listen($events, $listener);
    }

    /**
     * Determine if a given event has listeners.
     *
     * @param  string  $eventName
     * @return bool
     */
    public function hasListeners($eventName)
    {
        return $this->dispatcher->hasListeners($eventName);
    }

    /**
     * Register an event subscriber with the dispatcher.
     *
     * @param  object|string  $subscriber
     * @return void
     */
    public function subscribe($subscriber)
    {
        $this->dispatcher->subscribe($subscriber);
    }

    /**
     * Flush a set of pushed events.
     *
     * @param  string  $event
     * @return void
     */
    public function flush($event)
    {
        $this->dispatcher->flush($event);
    }

    /**
     * Remove a set of listeners from the dispatcher.
     *
     * @param  string  $event
     * @return void
     */
    public function forget($event)
    {
        $this->dispatcher->forget($event);
    }

    /**
     * Forget all of the queued listeners.
     *
     * @return void
     */
    public function forgetPushed()
    {
        $this->dispatcher->forgetPushed();
    }

    /**
     * Dynamically pass method calls to the underlying dispatcher.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return $this->forwardCallTo($this->dispatcher, $method, $parameters);
    }
}


text:
import React, { PropTypes, PureComponent } from 'react';
import { Provider } from 'react-redux';

import AppContainer from '../containers/AppContainer';

export default class Root extends PureComponent {
  static propTypes = {
    store: PropTypes.object.isRequired,
  };

  render() {
    return (
      <Provider store={this.props.store}>
        <AppContainer />
      </Provider>
    );
  }
}


text:
<?php echo __('admin_administrator_dashbord'); ?>

    <?php if (isset($form_status) && isset($form_status_message)) { ?>
    <div class="alert alert-<?php echo str_replace('error', 'danger', $form_status); ?>"><button type="button" class="close" data-dismiss="alert">×</button><?php echo $form_status_message; ?>

    <?php } ?>

Welcome to Fuel Start admin dashboard.

You can start modify this controller and theme to build your own admin dashboard.

The theme of this page is located at <?php echo __FILE__; ?>

The controller of this page is located at <?php echo APPPATH . 'classes' . DS . 'controller' . DS . 'admin' . DS . 'index.php'; ?>

<?php echo \Html::anchor('admin/account', __('index_account')); ?>

<?php echo __('index_total_accounts', array('total_accounts' => (isset($total_accounts) ? $total_accounts : 0))); ?>

News feed (example)

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Aenean eleifend libero ac velit vestibulum, nec bibendum est auctor.

Morbi viverra tellus id dolor accumsan consequat.

Suspendisse ut sollicitudin turpis.

Morbi vitae mi mauris.

Aliquam ornare lorem mauris, quis vehicula mi faucibus quis.

Maecenas consectetur enim at placerat maximus.

Cras ac nibh augue.

Statistic (example)

                                IP Address
                                Date/time

                                192.168.0.102
                                2014-10-22 14:31:18

                                127.0.0.1
                                2014-10-22 12:15:09

                                127.0.0.1
                                2014-10-22 12:11:09


text:
Date.prototype.getWeek = function(){
    // https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php#

    let d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
    let dayNum = d.getUTCDay() || 7;

    d.setUTCDate(d.getUTCDate() + 4 - dayNum);

    let yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));

    return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
};

/**
  * @desc {date} it's expected to be less than the current object
  */
Date.prototype.getWeekDiff = function(date){
    // Monday = 1, Sunday = 7

    // Reset the hours of the dates involved
    let date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    let date2 = new Date(this.getFullYear(), this.getMonth(), this.getDate());

    // Set the date1 to the same day of the current instance
    date1.setDate(date1.getDate() + (this.getDay() - date1.getDay()));

    let diff = date2 - date1;

    return Math.round(diff/1000/60/60/24/7);
};

export const DateHelper = {
    getMonday(date)
    {
        date = new Date(date.getFullYear(), date.getMonth(), date.getDate());

        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);

        let day = date.getDay(),
            diff = date.getDate() - day + (day == 0 ? -6 : 1);

        return new Date(date.setDate(diff));
    },

    getDateOfISOWeek(w, y) {
        let simple = new Date(Date.UTC(y, 0, 1 + (w - 1) * 7));
        let dow = simple.getDay();
        let ISOweekStart = simple;

        if (dow <= 4)
            ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
        else
            ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());

        return ISOweekStart;
    }
};


text:
package openweathermap

// Temperature is a floating point number that represents the a Kelvin
// temperature.
type Temperature float32

// ToK returns the Kelvin temperature as a float32 value.
func (t Temperature) ToK() float32 {
	return float32(t)
}

// ToC returns the calculated Celcius temperature as a float32 value.
func (t Temperature) ToC() float32 {
	// Cast to a float
	temp := float64(t)
	return float32(temp - 273.15)
} //ToC

// ToF returns the calculated Fahrenheit temperature as a float32 value.
func (t Temperature) ToF() float32 {
	// Cast to a float
	temp := float64(t)

	// Do the calculations
	return float32(temp*9.0/5.0 - 459.67)
} //ToF


text:
import datetime
import os
import socket
import tempfile
import urllib

from twisted.internet import defer, utils
from twisted.mail import smtp
from twisted.python import log
from buildbot.changes.base import PollingChangeSource
from buildbot.util import deferredLocked

from master.chromium_git_poller_bb8 import GitTagComparator

class RepoTagComparator(GitTagComparator):
  """Maintains a canonical ordering of commits across multiple git repos."""

  def addRevision(self, revision):
    """Unlike GitTagComparator, don't assert(revision not in self.tag_lookup);
    that can legitimately happen if two repos share common history."""
    self.tag_lookup[revision] = len(self.tag_order)
    self.tag_order.append(revision)

class RepoPoller(PollingChangeSource):
  """Polls a repo meta-repository and submits buildbot changes.

  repo is a layer over git that provides support for projects that span multiple
  git repositories.  This poller discovers changes in all of the underlying git
  repositories, and turns them into buildbot master changes.

  Buildbot doesn't provide very good support out of the box for displaying
  changes from multiple git repositories on a single console.  The biggest
  obstacle is that there is no inherent canonical ordering of commits across
  multiple independent repositories.

  This class addresses that by applying and enforcing an arbitrary (but
  generally useful) canonical ordering.  Changes in the git repositories are
  ordered by timestamp first (with one-second granularity).  In the event of
  collisions, ordering falls back to alphabetical ordering by repository name.
  """

  def __init__(self, repo_url, repo_branches=None, workdir=None,
               pollInterval=5*60, repo_bin='repo', git_bin='git',
               category='', revlinktmpl=None, encoding='utf-8',
               from_addr=None, to_addrs=None, smtp_host=None,
               manifest='manifest'):
    # In 'dry_run' mode poller won't fetch the repository.
    # Used when running master smoke tests.
    self.dry_run = 'POLLER_DRY_RUN' in os.environ

    if not workdir:
      workdir = tempfile.mkdtemp(prefix='repo_poller')
      log.msg('RepoPoller: using new working dir %s' % workdir)

    self.repo_url = repo_url
    self.repo_branches = repo_branches or ['master']
    # transition assertion, repo_branch (string) became repo_branches (list)
    assert issubclass(type(self.repo_branches), list), \
      'repo_branches must be a list'
    self.manifest_url = '/'.join([self.repo_url, manifest])
    self.workdir = workdir
    self.pollInterval = pollInterval
    self.repo_bin = repo_bin
    self.git_bin = git_bin
    self.category = category
    self.revlinktmpl = revlinktmpl
    self.encoding = encoding
    self.from_addr = from_addr
    self.to_addrs = to_addrs
    self.smtp_host = smtp_host
    self.initLock = defer.DeferredLock()
    self.comparator = RepoTagComparator()
    self.changeCount = 0
    self.errCount = 0

  def startService(self):
    if self.dry_run:
      PollingChangeSource.startService(self)
      return

    if not os.path.isabs(self.workdir):
      self.workdir = os.path.join(self.master.basedir, self.workdir)
      log.msg('RepoPoller: using workdir "%s"' % self.workdir)

    if not os.path.exists(os.path.join(self.workdir, '.repo')):
      d = self.initRepository()
      log.msg('RepoPoller: creating new repo checkout in %s' % self.workdir)
    else:
      d = defer.succeed(None)
      log.msg('RepoPoller: using pre-existing repo checkout.')

    d.addCallback(self.initHistory)
    def _success(*unused_args):
      self.comparator.initialized = True
    d.addCallback(_success)
    PollingChangeSource.startService(self)
    def _failure(failure):
      log.msg('RepoPoller: unable to start service.')
      self.stopService()
      return failure
    d.addErrback(_failure)

  def RunRepoCmd(self, args):
    return self.RunCmd(self.repo_bin, args, self.workdir)

  def RunCmd(self, binary, args, path):
    log.msg('RepoPoller: running "%s %s" (in %s)'
            % (binary, ' '.join(args), path))
    d = utils.getProcessOutputAndValue(binary, args, path=path, env=os.environ)
    def _check_status(result):
      (stdout, stderr, status) = result
      if status != 0:
        raise RuntimeError(('failure #%d: "%s" (in %s) failed with exit code '
                            '%d:\n%s\n%s') % (
            self.errCount+1,
            repr([binary] + args),
            path,
            status, stdout, stderr))
      return (stdout, stderr, status)
    d.addCallback(_check_status)
    return d

  @classmethod
  def TagFor(cls, branch_name):
    return 'repo_poller_' + branch_name

  def DoLog(self, unused_result, branch_tag):
    # Make sure that all git repo's have the branch_tag.  Failure indicates the
    # tag already exists on some repo's, which is expected.
    d = self.RunRepoCmd(['forall', '-c', self.git_bin, 'tag', branch_tag])
    d.addErrback(lambda *x: True)
    cb = lambda *x: self.RunRepoCmd(['forall', '-v', '-p', '-c', self.git_bin,
                                     'log', '--format=%H', branch_tag + '..'])
    d.addCallback(cb)
    return d

  def DoCheckoutRepoBranch(self, current_repo_branch):
    init = self.RunRepoCmd(['init', '-b', current_repo_branch])
    # TODO(szager): I pulled the number 4 out of thin air.  Better heuristic?
    init.addCallback(lambda *unused: self.RunRepoCmd(['sync', '-j', '4', '-c']))
    return init

  def DoTag(self, unused_result, branch_tag):
    if self.changeCount == 0:
      return defer.succeed(0)
    self.changeCount = 0
    return self.RunRepoCmd(['forall', '-v', '-c', self.git_bin,
                            '-c', 'user.email=repo_poller@chromium.org',
                            '-c', 'user.name=repo_poller', 'tag', '-a',
                            '-f', branch_tag, '-m', '"repo poller sync"'])

  @deferredLocked('initLock')
  def initRepository(self):
    if not os.path.exists(self.workdir):
      os.makedirs(self.workdir)
    repo_args = ['init', '-u', self.manifest_url]
    if self.repo_branches:
      repo_args.extend(['-b', self.repo_branches[0]])  # any branch will do
    d = self.RunRepoCmd(repo_args)
    # Bug 124131
    d.addCallback(lambda *unused: self.RunRepoCmd(['sync', '-j', '4']))
    def _success(*args):
      log.msg('RepoPoller: finished initializing.')
    d.addCallback(_success)
    return d

  @deferredLocked('initLock')
  def initHistory(self, *args):
    d = defer.succeed(0)
    for repo_branch in self.repo_branches:
      log.msg('RepoPoller: initializing revision history for branch '
              + repo_branch)
      d.addCallback(lambda x, b=repo_branch: self.DoCheckoutRepoBranch(b))
      def _log(*args):
        return self.RunRepoCmd(['forall', '-v', '-p', '-c',
                                self.git_bin, 'log', '--format=%H'])
      d.addCallback(_log)
      d.addCallback(self.ProcessInitialHistory)
      def _setChangeCount(*args):
        self.changeCount = 1  # To force DoTag.
      d.addCallback(_setChangeCount)
      d.addCallback(self.DoTag, RepoPoller.TagFor(repo_branch))
    return d

  @deferredLocked('initLock')
  def poll(self):
    if self.dry_run:
      return defer.succeed(None)

    d = defer.succeed(0)
    for repo_branch in self.repo_branches:
      d.addCallback(log.msg, 'RepoPoller: polling new changes for branch %s...'
                    % repo_branch)
      d.addCallback(lambda x, b=repo_branch: self.DoCheckoutRepoBranch(b))
      d.addCallback(self.DoLog, RepoPoller.TagFor(repo_branch))
      d.addCallback(self.ProcessChanges, repo_branch)
      d.addCallback(self.DoTag, RepoPoller.TagFor(repo_branch))
      def _success(ret_val, rb=repo_branch):
        log.msg('RepoPoller: finished polling ' + rb)
        self.errCount = 0
      def _failure(failure, rb=repo_branch):
        msg = ('RepoPoller is having problems...\n\n'
               'host: %s\n'
               'repo checkout: %s\n'
               'repo url: %s\n'
               'repo branch: %s\n\n'
               '%s') % (socket.gethostname(), self.workdir, self.repo_url,
                       rb, failure)
        log.err(msg)
        self.errCount += 1
        if self.errCount % 3 == 0 and self.smtp_host and self.to_addrs:
          smtp.sendmail(smtphost=self.smtp_host,
                        from_addr=self.from_addr,
                        to_addrs=self.to_addrs,
                        msg=msg)
        return failure
      d.addCallback(_success)
      d.addErrback(_failure)
    d.addCallback(log.msg, 'Done polling changes for branches in %s'
                  % self.repo_url)
    return d

  def GetCommitComments(self, project, rev):
    args = ['log', rev, '--no-walk', '--format=%s%n%b']
    d = utils.getProcessOutput(self.git_bin, args,
                               path=os.path.join(self.workdir, project),
                               env=os.environ, errortoo=False)
    def process(git_output):
      stripped_output = git_output.strip().decode(self.encoding)
      if len(stripped_output) == 0:
        raise RuntimeError('could not get commit comment for rev')
      return stripped_output
    d.addCallback(process)
    return d

  def GetCommitFiles(self, project, rev):
    args = ['log', rev, '--name-only', '--no-walk', '--format=%n']
    d = utils.getProcessOutput(self.git_bin, args,
                               path=os.path.join(self.workdir, project),
                               env=os.environ, errortoo=False)
    d.addCallback(lambda git_output: [x for x in git_output.splitlines() if x])
    return d

  def GetCommitName(self, project, rev):
    args = ['log', rev, '--no-walk', '--format=%aE']
    d = utils.getProcessOutput(self.git_bin, args,
                               path=os.path.join(self.workdir, project),
                               env=os.environ, errortoo=False)
    def process(git_output):
      stripped_output = git_output.strip().decode(self.encoding)
      if len(stripped_output) == 0:
        raise RuntimeError('RepoPoller: could not get commit name for rev')
      return stripped_output
    d.addCallback(process)
    return d

  def ParseRepoGitLogs(self, stdout):
    """Parse the output of `repo forall -c git log ...`

    Collate new revisions by project, and sort by commit order.
    """
    changes = {}  # changes[project] = [commit, commit, ...]
    project = None
    for line in stdout.splitlines():
      if not line:
        continue
      if line[:8] == 'project ':
        project = line[8:].rstrip('/')
        continue
      assert project
      changes.setdefault(project, []).append(line)

    # Put changes in forward commit order, earliest-to-latest.
    for project_changes in changes.itervalues():
      project_changes.reverse()

    for project in sorted(changes):
      for change in changes[project]:
        self.comparator.addRevision(change)

    return changes

  def ProcessInitialHistory(self, args):
    """Initialize comparator with existing commits."""
    (stdout, stderr, status) = args
    if status:
      log.msg('RepoPoller: could not initialize repo history '
              'from git logs: %s.' % stderr)
      return
    self.ParseRepoGitLogs(stdout)

  @defer.deferredGenerator
  def ProcessChanges(self, args, current_repo_branch):
    (stdout, stderr, status) = args
    if status:
      log.msg('RepoPoller: running `git log` '
              'across repo projects failed: %s' % stderr)
      return

    # TODO(szager): In a perfect world, we would use the time these changes were
    # merged into the main repository.  That time is not currently preserved,
    # so we use 'now' instead.  In the future, it would be nice if gerrit were
    # to run filter-branch to reset the committer timestamp to when the patch
    # was applied.
    timestamp = datetime.datetime.utcnow()

    for project, revisions in self.ParseRepoGitLogs(stdout).iteritems():
      for rev in revisions:
        dl = defer.DeferredList([
            self.GetCommitName(project, rev),
            self.GetCommitFiles(project, rev),
            self.GetCommitComments(project, rev),
            ], consumeErrors=True)

        wfd = defer.waitForDeferred(dl)
        yield wfd
        results = wfd.getResult()

        # check for failures
        failures = [r[1] for r in results if not r[0]]
        if failures:
          # just fail on the first error; they're probably all related!
          raise failures[0]

        revlink = ''
        if self.revlinktmpl and rev:
          revlink = self.revlinktmpl % (
              urllib.quote_plus(project), urllib.quote_plus(rev))

        name, files, comments = [r[1] for r in results]
        d = self.master.addChange(
            author=name,
            revision=rev,
            files=files,
            comments=comments,
            when_timestamp=timestamp,
            branch=current_repo_branch,
            category=self.category,
            project=project,
            repository='/'.join([self.repo_url, project]),
            revlink=revlink,
            properties={'manifest_url': self.manifest_url,
                        'manifest_branch': current_repo_branch})
        wfd = defer.waitForDeferred(d)
        yield wfd
        results = wfd.getResult()
        self.changeCount += 1


text:
/**
 */
package gluemodel.COSEM.InterfaceClasses.impl;

import gluemodel.COSEM.InterfaceClasses.InterfaceClassesPackage;
import gluemodel.COSEM.InterfaceClasses.M_Bus_master_port_setup;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'MBus master port setup'.
 *
 *
 * @generated
 */
public class M_Bus_master_port_setupImpl extends BaseImpl implements M_Bus_master_port_setup {
	/**
	 *
	 *
	 * @generated
	 */
	protected M_Bus_master_port_setupImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InterfaceClassesPackage.Literals.MBUS_MASTER_PORT_SETUP;
	}

} //M_Bus_master_port_setupImpl


text: Outline Mail


text:
using System;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace Akka.Monitoring.PerformanceCounters
{
    internal class AkkaCounter : AkkaMetric
    {
        readonly ConcurrentDictionary<string, Tuple<PerformanceCounter, PerformanceCounter>> _performanceCounters =
            new ConcurrentDictionary<string, Tuple<PerformanceCounter, PerformanceCounter>>();
        public AkkaCounter(string name, string categoryName)
            : base(name, categoryName)
        {
        }

        public override void RegisterIn(CounterCreationDataCollection collection)
        {
            var numberOfItems = new CounterCreationData
            {
                CounterType = PerformanceCounterType.NumberOfItems64,
                CounterName = Name,
            };

            var rates = new CounterCreationData
            {
                CounterType = PerformanceCounterType.RateOfCountsPerSecond64,
                CounterName = RatePerformanceCounterName(Name),
            };
            collection.Add(numberOfItems);
            collection.Add(rates);
        }

        public void Update(string instanceName, int delta)
        {
            if (!_performanceCounters.ContainsKey(instanceName))
            {
                _performanceCounters.TryAdd(instanceName, Tuple.Create(
                    new PerformanceCounter(CategoryName, Name, instanceName, false),
                    new PerformanceCounter(CategoryName, RatePerformanceCounterName(Name), instanceName, false)));
            }

            _performanceCounters[instanceName].Item1.IncrementBy(delta);
            _performanceCounters[instanceName].Item2.IncrementBy(delta);
        }

        public void ResetTotal(string instanceName)
        {
            if (!_performanceCounters.ContainsKey(instanceName))
            {
                _performanceCounters.TryAdd(instanceName, Tuple.Create(
                    new PerformanceCounter(CategoryName, Name, instanceName, false),
                    new PerformanceCounter(CategoryName, RatePerformanceCounterName(Name), instanceName, false)));
            }

            _performanceCounters[instanceName].Item1.RawValue = 0;
        }

        private static string RatePerformanceCounterName(string counterName) => $"{counterName} /sec";
    }
}


text:
/*
 * User: anna
 * Date: 04-Dec-2007
 */
package com.intellij.openapi.updateSettings.impl;

import com.intellij.CommonBundle;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerConfigurable;
import com.intellij.ide.plugins.PluginManagerUISettings;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Couple;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.TableUtil;
import com.intellij.util.ui.UIUtil;
import org.consulo.lombok.annotations.Logger;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Logger
public abstract class AbstractUpdateDialog extends DialogWrapper {
  private final boolean myEnableLink;
  protected final List<Couple<IdeaPluginDescriptor>> myUploadedPlugins;
  protected boolean myShowConfirmation = true;

  protected AbstractUpdateDialog(boolean canBeParent, boolean enableLink, final List<Couple<IdeaPluginDescriptor>> updatePlugins) {
    super(canBeParent);
    myEnableLink = enableLink;
    myUploadedPlugins = updatePlugins;
  }

  @Override
  protected void init() {
    setButtonsText();
    super.init();
  }

  protected void initPluginsPanel(final JPanel panel, JPanel pluginsPanel, JEditorPane updateLinkPane) {
    pluginsPanel.setVisible(myUploadedPlugins != null);
    if (myUploadedPlugins != null) {
      final DetectedPluginsPanel foundPluginsPanel = new DetectedPluginsPanel();

      foundPluginsPanel.addStateListener(new DetectedPluginsPanel.Listener() {
        @Override
        public void stateChanged() {
          setButtonsText();
        }
      });
      for (Couple<IdeaPluginDescriptor> uploadedPlugin : myUploadedPlugins) {
        foundPluginsPanel.add(uploadedPlugin);
      }
      TableUtil.ensureSelectionExists(foundPluginsPanel.getEntryTable());
      pluginsPanel.add(foundPluginsPanel, BorderLayout.CENTER);
    }
    updateLinkPane.setBackground(UIUtil.getPanelBackground());
    String css = UIUtil.getCssFontDeclaration(UIUtil.getLabelFont());
    if (UIUtil.isUnderDarcula()) {
      css += "<style>body {background: #" + ColorUtil.toHex(UIUtil.getPanelBackground()) + ";}</style>";
    }
    updateLinkPane.setBorder(IdeBorderFactory.createEmptyBorder(0));
    updateLinkPane.setText(IdeBundle.message("updates.configure.label", css));
    updateLinkPane.setEditable(false);
    LabelTextReplacingUtil.replaceText(panel);

    if (myEnableLink) {
      updateLinkPane.addHyperlinkListener(new HyperlinkListener() {
        @Override
        public void hyperlinkUpdate(final HyperlinkEvent e) {
          if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            final ShowSettingsUtil util = ShowSettingsUtil.getInstance();
            UpdateSettingsConfigurable updatesSettings = new UpdateSettingsConfigurable();
            updatesSettings.setCheckNowEnabled(false);
            util.editConfigurable(panel, updatesSettings);
          }
        }
      });
    }
  }

  private void setButtonsText() {
    setOKButtonText(getOkButtonText());
    setCancelButtonText(getCancelButtonText());
  }

  protected String getCancelButtonText() {
    return CommonBundle.getCancelButtonText();
  }

  protected String getOkButtonText() {
    return CommonBundle.getOkButtonText();
  }

  @Override
  protected void doOKAction() {
    if (doDownloadAndPrepare() && isShowConfirmation()) {
      final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
      // do not stack several modal dialogs (native & swing)
      app.invokeLater(new Runnable() {
        @Override
        public void run() {
          app.restart(true);
        }
      });
    }
    super.doOKAction();
  }

  protected boolean doDownloadAndPrepare() {
    if (myUploadedPlugins != null) {
      UpdateChecker.saveDisabledToUpdatePlugins();

      final List<IdeaPluginDescriptor> pluginsForDownload = new ArrayList<IdeaPluginDescriptor>();
      Set<String> disabledToUpdatePlugins = UpdateChecker.getDisabledToUpdatePlugins();
      for (Couple<IdeaPluginDescriptor> uploadedPlugin : myUploadedPlugins) {
        IdeaPluginDescriptor second = uploadedPlugin.getSecond();
        if (disabledToUpdatePlugins.contains(second.getPluginId().getIdString())) {
          continue;
        }

        pluginsForDownload.add(uploadedPlugin.getSecond());
      }
      if(pluginsForDownload.isEmpty()) {
        return false;
      }

      new Task.Backgroundable(null, IdeBundle.message("progress.download.plugins"), true, PluginManagerUISettings.getInstance()) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          for (IdeaPluginDescriptor pluginDescriptor : pluginsForDownload) {
            try {
              PluginDownloader downloader = PluginDownloader.createDownloader(pluginDescriptor);
              if (downloader.prepareToInstall(indicator)) {
                downloader.install(true);
              }
            }
            catch (Exception e) {
              LOGGER.error(e);
            }
          }

          UIUtil.invokeLaterIfNeeded(new Runnable() {
            @Override
            public void run() {
              if (PluginManagerConfigurable.showRestartIDEADialog() == Messages.YES) {
                ApplicationManagerEx.getApplicationEx().restart(true);
              }
            }
          });
        }
      }.queue();
    }
    return false;
  }

  public void setShowConfirmation(boolean showConfirmation) {
    myShowConfirmation = showConfirmation;
  }

  public boolean isShowConfirmation() {
    return myShowConfirmation;
  }
}


text:
Human::Human(const unsigned int &player_ID)
{
	if (player_ID < 1 || player_ID > 2)
		throw std::invalid_argument("Invalid player identification, must be 1 or 2");
	else
		player = player_ID;
}

void Human::makeMove(GameBoard &GB)
{
	const unsigned int position = validateMove(GB); // get valid input
	GB.board[stoi(GB.positions[position - 1].substr(0, 1))][stoi(GB.positions[position - 1].substr(1, 1))] = player;
}

const unsigned int Human::validateMove(const GameBoard &GB_ref)
{
	unsigned int input;
	while (true)
	{
		input = 0;
		std::cout << "Where to move? ";
		std::cin >> input;
		if (std::cin.fail() ||
			(input < 1 || input > 9) ||
			(GB_ref.board[stoi(GB_ref.positions[input - 1].substr(0, 1))][stoi(GB_ref.positions[input - 1].substr(1, 1))] != 0))
		{
			std::cin.clear();
			std::cin.ignore(std::numeric_limits<int>::max(), '\n');
			std::cout << "Can't proceed with move." << std::endl << std::endl;
		}
		else
		{
			return input;
			break;
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Resource\Generator;

interface RandomnessGeneratorInterface
{
    /**
     * @param int $length
     *
     * @return string
     */
    public function generateUriSafeString(int $length): string;

    /**
     * @param int $length
     *
     * @return string
     */
    public function generateNumeric(int $length): string;

    /**
     * @param int $min
     * @param int $max
     *
     * @return int
     */
    public function generateInt(int $min, int $max): int;
}