text:
<?php

namespace App\Entity;

use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Libs\Entity\AbstractEntity;

/**
* @ORM\Entity
*/
class CheckOut extends AbstractEntity
{
	/**
	* @ORM\Id
	* @ORM\GeneratedValue
	* @ORM\Column(type="integer")
	*/
	protected $id;

	/**
	* @ORM\ManyToOne(targetEntity="Bicycle", inversedBy="checkOuts")
	*/
	protected $bicycle;

	/**
	* @ORM\OneToMany(targetEntity="Gps", mappedBy="checkout", cascade={"persist"})
	* @ORM\OrderBy({"time"="ASC"})
	*/
	protected $gpsData;

	/**
	* @ORM\ManyToOne(targetEntity="Student", inversedBy="checkOuts")
	*/
	protected $student;

	/**
	* @ORM\OneToOne(targetEntity="Fee", inversedBy="checkout", cascade={"persist"})
	*/
	protected $fee;

	/**
	* @ORM\Column(type="datetime")
	*/
	protected $outTime;

	/**
	* @ORM\ManyToOne(targetEntity="Dock", inversedBy="checkOuts")
	*/
	protected $outDock;

	/**
	* @ORM\Column(type="datetime", nullable=true)
	*/
	protected $inTime;

	/**
	* @ORM\ManyToOne(targetEntity="Dock", inversedBy="checkIns")
	*/
	protected $inDock;

	public function __construct()
	{
		$this->gpsData = new ArrayCollection;
		$this->outTime = new DateTime;
	}

	public function getOutTime($format = false)
	{
		if ($format)
		{
			return $this->outTime->format('d M Y, h:i:s A');
		}

		return $this->outTime;
	}

	public function getInTime($format = false)
	{
		if ($format)
		{
			return $this->inTime ? $this->inTime->format('d M Y, h:i:s A') : 'None';
		}

		return $this->inTime;
	}

	public function feeToString()
	{
		return $this->fee ? '$' . "{$this->fee->getCharge()}, {$this->fee->paidToString()}" : 'N/A';
	}

	public function assignFees()
	{
		if (!$this->inTime)
		{
			return false;
		}
		$diff = strtotime($this->getInTime(true)) - strtotime($this->getOutTime(true));
		if ($diff > 10)
		{
			$fee = new Fee;
			if ($diff > 30)
			{
				$fee->setCharge(5);
			}
			elseif ($diff > 20)
			{
				$fee->setCharge(3);
			}
			elseif ($diff > 10)
			{
				$fee->setCharge(1);
			}
			$this->setFee($fee);
			return $fee;
		}

		return false;
	}

	public function addGps($gps)
	{
		$this->gpsData->add($gps);
		$gps->setCheckout($this);
	}
}


text:
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Module.Catalog.Models;
using SimplCommerce.Module.Catalog.ViewModels;
using SimplCommerce.Module.Search.ViewModels;
using Microsoft.EntityFrameworkCore;
using SimplCommerce.Module.Core.Services;
using SimplCommerce.Module.Search.Models;

namespace SimplCommerce.Module.Search.Controllers
{
    public class SearchController : Controller
    {
        private const int PageSize = 20;
        private readonly IRepository<Product> _productRepository;
        private readonly IRepository<Brand> _brandRepository;
        private readonly IRepository<Category> _categoryRepository;
        private readonly IMediaService _mediaService;
        private readonly IRepository<Query> _queryRepository;

        public SearchController(IRepository<Product> productRepository, IRepository<Brand> brandRepository, IRepository<Category> categoryRepository, IMediaService mediaService, IRepository<Query> queryRepository)
        {
            _productRepository = productRepository;
            _brandRepository = brandRepository;
            _categoryRepository = categoryRepository;
            _mediaService = mediaService;
            _queryRepository = queryRepository;
        }

        [HttpGet("search")]
        public IActionResult Index(SearchOption searchOption)
        {
            if (string.IsNullOrWhiteSpace(searchOption.Query))
            {
                return Redirect("~/");
            }

            var brand = _brandRepository.Query().FirstOrDefault(x => x.Name == searchOption.Query && x.IsPublished);
            if(brand != null)
            {
                return Redirect(string.Format("~/{0}", brand.SeoTitle));
            }

            var model = new SearchResult
            {
                CurrentSearchOption = searchOption,
                FilterOption = new FilterOption()
            };

            var query = _productRepository.Query().Where(x => x.Name.Contains(searchOption.Query) && x.IsPublished && x.IsVisibleIndividually);

            model.FilterOption.Price.MaxPrice = query.Max(x => x.Price);
            model.FilterOption.Price.MinPrice = query.Min(x => x.Price);

            if (searchOption.MinPrice.HasValue)
            {
                query = query.Where(x => x.Price >= searchOption.MinPrice.Value);
            }

            if (searchOption.MaxPrice.HasValue)
            {
                query = query.Where(x => x.Price <= searchOption.MaxPrice.Value);
            }

            AppendFilterOptionsToModel(model, query);
            if (string.Compare(model.CurrentSearchOption.Category, "all", StringComparison.OrdinalIgnoreCase) != 0)
            {
                var categories = searchOption.GetCategories();
                if (categories.Any())
                {
                    var categoryIds = _categoryRepository.Query().Where(x => categories.Contains(x.SeoTitle)).Select(x => x.Id).ToList();
                    query = query.Where(x => x.Categories.Any(c => categoryIds.Contains(c.CategoryId)));
                }
            }

            var brands = searchOption.GetBrands();
            if (brands.Any())
            {
                var brandIs = _brandRepository.Query().Where(x => brands.Contains(x.SeoTitle)).Select(x => x.Id).ToList();
                query = query.Where(x => x.BrandId.HasValue && brandIs.Contains(x.BrandId.Value));
            }

            model.TotalProduct = query.Count();
            var currentPageNum = searchOption.Page <= 0 ? 1 : searchOption.Page;
            var offset = (PageSize * currentPageNum) - PageSize;
            while (currentPageNum > 1 && offset >= model.TotalProduct)
            {
                currentPageNum--;
                offset = (PageSize * currentPageNum) - PageSize;
            }

            SaveSearchQuery(searchOption, model);

            query = query
                .Include(x => x.ThumbnailImage);

            query = AppySort(searchOption, query);

            var products = query
                .Select(x => new ProductThumbnail
                {
                    Id = x.Id,
                    Name = x.Name,
                    SeoTitle = x.SeoTitle,
                    Price = x.Price,
                    OldPrice = x.OldPrice,
                    ThumbnailImage = x.ThumbnailImage,
                    NumberVariation = x.ProductLinks.Count
                })
                .Skip(offset)
                .Take(PageSize)
                .ToList();

            foreach (var product in products)
            {
                product.ThumbnailUrl = _mediaService.GetThumbnailUrl(product.ThumbnailImage);
            }

            model.Products = products;
            model.CurrentSearchOption.PageSize = PageSize;
            model.CurrentSearchOption.Page = currentPageNum;

            return View(model);
        }

        private static IQueryable<Product> AppySort(SearchOption searchOption, IQueryable<Product> query)
        {
            var sortBy = searchOption.Sort ?? string.Empty;
            switch (sortBy.ToLower())
            {
                case "price-desc":
                    query = query.OrderByDescending(x => x.Price);
                    break;
                default:
                    query = query.OrderBy(x => x.Price);
                    break;
            }

            return query;
        }

        private static void AppendFilterOptionsToModel(SearchResult model, IQueryable<Product> query)
        {
            model.FilterOption.Categories = query
                .SelectMany(x => x.Categories).Where(x => x.Category.Parent == null)
                .GroupBy(x => new {
                    x.Category.Id,
                    x.Category.Name,
                    x.Category.SeoTitle
                })
                .Select(g => new FilterCategory
                {
                    Id = (int)g.Key.Id,
                    Name = g.Key.Name,
                    SeoTitle = g.Key.SeoTitle,
                    Count = g.Count()
                }).ToList();

            model.FilterOption.Brands = query
               .Where(x => x.BrandId != null)
               .GroupBy(x => x.Brand)
               .Select(g => new FilterBrand
               {
                   Id = (int)g.Key.Id,
                   Name = g.Key.Name,
                   SeoTitle = g.Key.SeoTitle,
                   Count = g.Count()
               }).ToList();
        }

        private void SaveSearchQuery(SearchOption searchOption, SearchResult model)
        {
            var query = new Query
            {
                CreatedOn = DateTimeOffset.Now,
                QueryText = searchOption.Query,
                ResultsCount = model.TotalProduct
            };

            _queryRepository.Add(query);
            _queryRepository.SaveChange();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package macvlan

import (
	"fmt"
	"net"

	log "github.com/Sirupsen/logrus"
	"github.com/vishvananda/netlink"
)

// Generate a mac addr
func makeMac(ip net.IP) string {
	hw := make(net.HardwareAddr, 6)
	hw[0] = 0x7a
	hw[1] = 0x42
	copy(hw[2:], ip.To4())
	return hw.String()
}

// Return the IPv4 address of a network interface
func getIfaceAddr(name string) (*net.IPNet, error) {
	iface, err := netlink.LinkByName(name)
	if err != nil {
		return nil, err
	}
	addrs, err := netlink.AddrList(iface, netlink.FAMILY_V4)
	if err != nil {
		return nil, err
	}
	if len(addrs) == 0 {
		return nil, fmt.Errorf("Interface %s has no IP addresses", name)
	}
	if len(addrs) > 1 {
		log.Infof("Interface [ %v ] has more than 1 IPv4 address. Defaulting to using [ %v ]\n", name, addrs[0].IP)
	}
	return addrs[0].IPNet, nil
}

// setVlanMode set the macvlan mode, currently only bridge is supported since others are rarely deployed
func setVlanMode(mode string) (netlink.MacvlanMode, error) {
	switch mode {
	case "private":
		return netlink.MACVLAN_MODE_PRIVATE, nil
	case "vepa":
		return netlink.MACVLAN_MODE_VEPA, nil
	case "bridge":
		return netlink.MACVLAN_MODE_BRIDGE, nil
	case "passthru":
		return netlink.MACVLAN_MODE_PASSTHRU, nil
	default:
		return 0, fmt.Errorf("Invalid macvlan mode [ %s ]", mode)
	}
}

// Increment a subnet
func ipIncrement(networkAddr net.IP) net.IP {
	for i := 15; i >= 0; i-- {
		b := networkAddr[i]
		if b < 255 {
			networkAddr[i] = b + 1
			for xi := i + 1; xi <= 15; xi++ {
				networkAddr[xi] = 0
			}
			break
		}
	}
	return networkAddr
}

// Check if a netlink interface exists in the default namespace
func validateHostIface(ifaceStr string) bool {
	_, err := net.InterfaceByName(ifaceStr)
	if err != nil {
		log.Debugf("The requested interface to delete [ %s ] was not found on the host: %s", ifaceStr, err)
		return false
	}
	return true
}

// parseIPNet returns a net.IP from a network cidr in string representation
func parseIPNet(s string) (*net.IPNet, error) {
	ip, ipNet, err := net.ParseCIDR(s)
	if err != nil {
		return nil, err
	}
	return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
}


text:
Based on the net/rpc and net/rpc/json package, it's a incomplete implementation of [JSON-RPC 2.0](http://www.jsonrpc.org/specification).

## Service methods with context
One of the differences witht he stdlib is that each method of a registered service must have an io.ReadWriteCloser as first argument. This enable the methods to have access to contexts. Here's an example:

```go

```


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e2cac6c6"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/title"
        >
        <RelativeLayout
            android:id="@+id/rl_back_fri"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/all_order_goback"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:padding="12dp"
                android:layout_centerVertical="true"
                android:src="@drawable/nav_back"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="返回"
                android:textSize="20sp"
                android:textColor="@android:color/black"
                android:layout_toRightOf="@id/all_order_goback"
                android:layout_centerInParent="true"/>

        </RelativeLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="详细信息"
            android:textSize="20sp"
            android:textColor="@android:color/black"/>

    </RelativeLayout>

    <View android:layout_width="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_height="5px"
        android:background="#C0C5C7"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#eeeeee"
        android:layout_below="@id/rl_back_fri">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#e2cac6c6"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/rl_modify_My"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:background="@drawable/bc">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:id="@+id/iv_fri_head"
                    android:src="@drawable/mine_gray"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="40dp"
                    />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/tv_fri_name"
                    android:text="用户名"
                    android:textSize="34sp"
                    android:textColor="@color/black"
                    android:layout_below="@+id/iv_fri_head"
                    android:layout_marginTop="30dp"
                    android:gravity="center"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/rl_fri_sex"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_marginTop="30dp"
                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="性别"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <TextView
                    android:id="@+id/tv_fri_sex"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    android:text="性别"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:textColor="@color/text_clo"

                    />

            </RelativeLayout>
            <RelativeLayout
                android:id="@+id/rl_fri_tel"
                android:layout_width="match_parent"
                android:layout_height="50dp"

                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="电话号码"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <TextView
                    android:id="@+id/tv_fri_tel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="电话号码"
                    android:textSize="15sp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:textColor="@color/text_clo"

                    />
            </RelativeLayout>
            <RelativeLayout
                android:id="@+id/rl_fri_address"
                android:layout_width="match_parent"
                android:layout_height="50dp"

                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="家庭住址"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <TextView
                    android:id="@+id/tv_fri_address"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="地址"
                    android:textSize="15sp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:textColor="@color/text_clo"

                    />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/rl_fri_profiles"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="个性签名"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <TextView
                    android:id="@+id/tv_fri_progiles"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="无"
                    android:textSize="15sp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:textColor="@color/text_clo"

                    />
            </RelativeLayout>
            <RelativeLayout
                android:id="@+id/rl_fri_life"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_marginTop="20dp"
                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="他的动态"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:src="@drawable/iv_editinfo"/>

                />
            </RelativeLayout>
            <RelativeLayout
                android:id="@+id/rl_fri_activity"
                android:layout_width="match_parent"
                android:layout_height="50dp"

                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="他的活动"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:src="@drawable/iv_editinfo"/>

                />
            </RelativeLayout>
            <RelativeLayout
                android:id="@+id/rl_fri_help"
                android:layout_width="match_parent"
                android:layout_height="50dp"

                android:background="#ffffff"

                >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:text="他的互帮"
                    android:layout_marginLeft="30dp"
                    android:textSize="20sp"
                    android:textColor="@color/black"/>

                <ImageView
                    android:id="@+id/iv_to_myName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10dp"
                    android:padding="6dp"
                    android:src="@drawable/iv_editinfo"/>

                />
            </RelativeLayout>

            <Button
                android:id="@+id/btn_fri_delete"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/shape_red"
                android:layout_margin="20dp"
                android:text="添加好友"
                android:textSize="20sp"
                android:gravity="center"
                android:textColor="@color/black"

                >

            </Button>

        </LinearLayout>

 </ScrollView>

</LinearLayout>


text:
package org.elixirian.jsonstatham.test;

import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 * @version 0.0.1 (2010-09-07)
 */
public interface ItemDefinition
{
  String getName();

  String getInstructions();

  List<Option> getOptions();
}


text:
"""
Copyright 2013 Parse.ly, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import logging
import pymongo
import time

from testinstances import utils
from testinstances.exceptions import ProcessNotStartingError
from testinstances.managed_instance import ManagedInstance

log = logging.getLogger(__name__)

class MongoInstance(ManagedInstance):
    """A managed mongo instance for testing"""
    def __init__(self, port, name='mongo', use_gevent=False, timeout=10):
        """Start mongoinstance on the given port.

        :param use_gevent: If True, use gevent instead of subprocess.
        :param timout:     Seconds to wait for the process to start.
        """
        self.port = port
        self.timeout = timeout
        ManagedInstance.__init__(self,
                                 '%s-%i' % (name, port),
                                 use_gevent=use_gevent)

    def _start_process(self):
        """Start the instance process"""
        log.info('Starting mongod on port %i...', self.port)
        self._process = utils.Popen(
            args=["mongod",
                  '--port', str(self.port),
                  '--bind_ip', '127.0.0.1',
                  '--dbpath', self._root_dir,
                  '--nojournal',
                  ],
            stderr=utils.STDOUT,
            stdout=open(self.logfile, 'w'),
            use_gevent=self.use_gevent,
            )

        # Connect to the shiny new instance
        self.conn = None
        fails = 0
        while self.conn is None:
            try:
                conn = pymongo.MongoClient(port=self.port,
                                           use_greenlets=self.use_gevent)
                if conn.alive():
                    self.conn = conn
            except:
                if fails >= self.timeout:
                    break
                fails += 1
                time.sleep(1)

        if self.conn is None or self._process.poll() is not None:
            log.info('Unable to start process. Trying to get process output.')
            try:
                log.info(open(self.logfile).read())
            except:
                pass  # file doesn't exist or whatever
            raise ProcessNotStartingError(
                "Unable to start mongod in {} seconds.".format(self.timeout)
            )

    def flush(self):
        """Flush all data in the db"""
        for dbname in self.conn.database_names():
            if dbname not in ('local', 'admin', 'config'):
                self.conn.drop_database(dbname)


text:
<!DOCTYPE html>

  <title>Reports</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="static/table.css" media="screen"/>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Report

        DateTime
        Incident
        Description
        Anonymous

    {% for item in reports %}
        {% if (item.isEmergency) %}

        {% else %}

        {% endif %}
            {{ item.human_time }}
            {% if (item.isEmergency) %}
                EMERGENCY!
            {% else %}
                Not Urgent
            {% endif %}

 {{ item.text }}

More details

This is text

This could be more text

This is text

                    Show more

            {% if (item.isAnonymous) %}
                ANONYMOUS
            {% else %}
                PUBLIC
            {% endif %}
             <form type="hidden" action = "/deleteReport" method="POST">
                <input type="hidden" value="{{item.id}}" name="id"></input>
                <input type="submit" value="X" class="btn btn-danger btn-circle delete-row" href="#" ></input>
                </form>

    {% endfor %}


text:
package com.spike.giantdataanalysis.neo4j.example;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.spike.giantdataanalysis.neo4j.example.SocialNetworkDomain.SNLabels;
import com.spike.giantdataanalysis.neo4j.example.SocialNetworkDomain.SNPropertyKeys;
import com.spike.giantdataanalysis.neo4j.supports.Neo4js;
import com.spike.giantdataanalysis.neo4j.supports.annotation.ShouldExecuteInTransaction;
import com.spike.giantdataanalysis.neo4j.supports.cypher.CypherQueryBuilder;

/**
 * <pre>
 * Cypher示例.
 *
 * 完整的语法见The Neo4j Developer Manual v3.2 5-12章.
 * </pre>
 */
public class CypherExample {
  private static final Logger LOG = LoggerFactory.getLogger(CypherExample.class);

  public static void main(String[] args) {

    GraphDatabaseService db = Neo4js.defaultDatabase();

    try (Transaction tx = db.beginTx();) {
      // simple(db);
      // node(db);
      // index(db);
      // skip_limit(db);
      // regular_expression(db);
      // create_node(db);
      update_node(db);

      tx.success();
    }

    db.shutdown();// 关闭数据库
  }

  /** 节点ID, 节点对象, 多个节点ID, 节点属性字符串字面量 */
  public static void node(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.MATCH("(n)");
    builder.WHERE("id(n) = $id"); // 节点ID
    builder.RETURN("n.name");
    String cql = builder.build().toString();
    Map<String, Object> parameters = Maps.newHashMap();
    parameters.put("id", 0);
    executeCypherQuery(db, cql, parameters);

    Node john = db.findNode(SNLabels.Users, SNPropertyKeys.name.name(), "John Johnson");
    builder = new CypherQueryBuilder();
    builder.MATCH("(n)");
    builder.WHERE("n = $john"); // 节点对象
    builder.RETURN("n.name");
    cql = builder.build().toString();
    parameters = Maps.newHashMap();
    parameters.put("john", john);
    executeCypherQuery(db, cql, parameters);

    builder = new CypherQueryBuilder();
    builder.MATCH("(n)");
    builder.WHERE("id(n) IN $ids"); // 多个借点
    builder.RETURN("n.name");
    cql = builder.build().toString();
    parameters = Maps.newHashMap();
    parameters.put("ids", Lists.newArrayList(0, 1, 2));
    executeCypherQuery(db, cql, parameters);

    builder = new CypherQueryBuilder();
    builder.MATCH("(n:Users)");
    builder.WHERE("n.name = $name"); // 节点属性字符串字面量
    builder.RETURN("n");
    cql = builder.build().toString();
    parameters = Maps.newHashMap();
    parameters.put("name", "John Johnson");
    executeCypherQuery(db, cql, parameters);
  }

  /**
   * 索引值和索引查询
   * @see {@link IndexingExample#explicit_indexing(GraphDatabaseService)}
   * @see {@link IndexingExample#update_with_explicit_indexing(GraphDatabaseService)}
   */
  public static void index(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.START("n=node:users(email = $email)"); // 注意$email不要加引号
    builder.RETURN("n");
    String cql = builder.build().toString();
    Map<String, Object> parameters = Maps.newHashMap();
    parameters.put("email", "jsmith@new.example.org");
    executeCypherQuery(db, cql, parameters);

    builder = new CypherQueryBuilder();
    builder.START("n=node:users($query)");
    builder.RETURN("n");
    cql = builder.build().toString();
    parameters = Maps.newHashMap();
    parameters.put("query", "email:jsmith@new.example.org"); // Lucene语法
    executeCypherQuery(db, cql, parameters);
  }

  /** SKIP和LIMIT */
  public static void skip_limit(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.MATCH("(n:Users)");
    builder.RETURN("n.name");
    builder.SKIP("$s");
    builder.LIMIT("$l");
    String cql = builder.build().toString();
    Map<String, Object> parameters = Maps.newHashMap();
    parameters.put("s", 1);
    parameters.put("l", 2);
    executeCypherQuery(db, cql, parameters);
  }

  /** 正则表达式 */
  public static void regular_expression(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.MATCH("(n:Users)");
    builder.WHERE("n.name =~ $regex");
    builder.RETURN("n.name");
    String cql = builder.build().toString();
    Map<String, Object> parameters = Maps.newHashMap();
    parameters.put("regex", ".*h.*"); // 包含h的名字
    executeCypherQuery(db, cql, parameters);
  }

  /** 创建带属性的节点 */
  public static void create_node(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.CREATE("n=($props)");
    builder.RETURN("n");
    String cql = builder.build().toString();
    Map<String, Object> props = Maps.newHashMap();
    props.put(SNPropertyKeys.name.name(), "Andres");
    props.put(SNPropertyKeys.age.name(), 30);
    Map<String, Object> parameters = Maps.newHashMap();
    parameters.put("props", props);
    executeCypherQuery(db, cql, parameters);

    // 创建多个节点
    List<Map<String, Object>> mapList = Lists.newArrayList();
    props = Maps.newHashMap();
    props.put(SNPropertyKeys.name.name(), "Bob");
    props.put(SNPropertyKeys.age.name(), 28);
    mapList.add(props);
    props = Maps.newHashMap();
    props.put(SNPropertyKeys.name.name(), "David");
    props.put(SNPropertyKeys.age.name(), 32);
    mapList.add(props);

    builder = new CypherQueryBuilder();
    builder.UNWIND("$props AS properties");
    builder.CREATE("(n:Users)");
    builder.SET("n = properties");
    builder.RETURN("n");
    cql = builder.build().toString();

    parameters = Maps.newHashMap();
    parameters.put("props", mapList);
    executeCypherQuery(db, cql, parameters);
  }

  /** 更新节点属性 */
  public static void update_node(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.MATCH("(n:Users)");
    builder.WHERE("n.name='Bob'");
    builder.SET("n = $props");
    builder.RETURN("n");
    String cql = builder.build().toString();

    Map<String, Object> parameters = Maps.newHashMap();
    Map<String, Object> props = Maps.newHashMap();
    props.put(SNPropertyKeys.age.name(), 29);
    props.put(SNPropertyKeys.email.name(), "bob@example.com");
    parameters.put("props", props);

    executeCypherQuery(db, cql, parameters);
  }

  public static void simple(GraphDatabaseService db) {
    CypherQueryBuilder builder = new CypherQueryBuilder();
    builder.MATCH("(n {name: 'John Johnson'})");
    builder.RETURN("n, n.name");
    // CQL和参数
    String cql = builder.build().toString();
    Map<String, Object> parameters = Maps.newHashMap();

    executeCypherQuery(db, cql, parameters);
  }

  @ShouldExecuteInTransaction
  private static void executeCypherQuery(final GraphDatabaseService db, final String cql,
      Map<String, Object> parameters) {
    Preconditions.checkArgument(db != null, "Argument db should not be null!");
    Preconditions.checkArgument(StringUtils.isNotBlank(cql),
      "Argument cql should not be null or empty!");

    LOG.info("\n" + cql);
    // 执行查询
    if (MapUtils.isEmpty(parameters)) {
      parameters = Maps.newHashMap();
    }
    Result result = db.execute(cql, parameters);
    LOG.info("\n" + Neo4js.asString(result));
  }

}


text:
package org.apache.logging.log4j.core.config.builder.api;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.util.Builder;

/**
 * Interface for building logging configurations.
 * @param <T> The Configuration type created by this builder.
 * @since 2.4
 */
public interface ConfigurationBuilder<T extends Configuration> extends Builder<T> {

    /**
     * Adds a ScriptComponent.
     * @param builder The ScriptComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(ScriptComponentBuilder builder);

    /**
     * Adds a ScriptFileComponent.
     * @param builder The ScriptFileComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(ScriptFileComponentBuilder builder);

    /**
     * Adds an AppenderComponent.
     * @param builder The AppenderComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(AppenderComponentBuilder builder);

    /**
     * Adds a CustomLevel component.
     * @param builder The CustomLevelComponentBuilder with all of its attributes set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(CustomLevelComponentBuilder builder);

    /**
     * Adds a Filter component.
     * @param builder the FilterComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(FilterComponentBuilder builder);

    /**
     * Adds a Logger component.
     * @param builder The LoggerComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(LoggerComponentBuilder builder);

    /**
     * Adds the root Logger component.
     * @param builder The RootLoggerComponentBuilder with all of its attributes and sub components set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> add(RootLoggerComponentBuilder builder);

    /**
     * Adds a Property key and value.
     * @param key The property key.
     * @param value The property value.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> addProperty(String key, String value);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the Logger.
     * @param language The script language
     * @param text The script to execute.
     * @return A new ScriptComponentBuilder.
     */
    ScriptComponentBuilder newScript(String name, String language, String text);

    /**
     * Returns a builder for creating Async Loggers.
     * @param path The location of the script file.
     * @return A new ScriptFileComponentBuilder.
     */
    ScriptFileComponentBuilder newScriptFile(String path);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the script file.
     * @param path The location of the script file.
     * @return A new ScriptFileComponentBuilder.
     */
    ScriptFileComponentBuilder newScriptFile(String name, String path);

    /**
     * Returns a builder for creating Appenders.
     * @param name The name of the Appender.
     * @param pluginName The Plugin type of the Appender.
     * @return A new AppenderComponentBuilder.
     */
    AppenderComponentBuilder newAppender(String name, String pluginName);

    /**
     * Returns a builder for creating AppenderRefs.
     * @param ref The name of the Appender being referenced.
     * @return A new AppenderRefComponentBuilder.
     */
    AppenderRefComponentBuilder newAppenderRef(String ref);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newAsyncLogger(String name, Level level);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @param includeLocation If true include location information.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newAsyncLogger(String name, Level level, boolean includeLocation);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newAsyncLogger(String name, String level);

    /**
     * Returns a builder for creating Async Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @param includeLocation If true include location information.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newAsyncLogger(String name, String level, boolean includeLocation);

    /**
     * Returns a builder for creating the async root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newAsyncRootLogger(Level level);

    /**
     * Returns a builder for creating the async root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @param includeLocation If true include location information.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newAsyncRootLogger(Level level, boolean includeLocation);

    /**
     * Returns a builder for creating the async root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newAsyncRootLogger(String level);

    /**
     * Returns a builder for creating the async root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @param includeLocation If true include location information.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newAsyncRootLogger(String level, boolean includeLocation);

    /**
     * Returns a builder for creating generic components.
     * @param <B> ComponentBuilder target type
     * @param pluginName The Plugin type of the component.
     * @return A new ComponentBuilder.
     */
    <B extends ComponentBuilder<B>> ComponentBuilder<B> newComponent(String pluginName);

    /**
     * Returns a builder for creating generic components.
     * @param <B> ComponentBuilder target type
     * @param name The name of the component (may be null).
     * @param pluginName The Plugin type of the component.
     * @return A new ComponentBuilder.
     */
    <B extends ComponentBuilder<B>> ComponentBuilder<B> newComponent(String name, String pluginName);

    /**
     * Returns a builder for creating generic components.
     * @param <B> ComponentBuilder target type
     * @param name The name of the component (may be null).
     * @param pluginName The Plugin type of the component.
     * @param value The value of the component.
     * @return A new ComponentBuilder.
     */
    <B extends ComponentBuilder<B>> ComponentBuilder<B> newComponent(String name, String pluginName, String value);

    /**
     * Returns a builder for creating Property:s
     * @param name The name of the property.
     * @param value The value of the component.
     * @return A new PropertyComponentBuilder.
     */
    PropertyComponentBuilder newProperty(String name, String value);

    /**
     * Returns a builder for creating KeyValuePair:s
     * @param key The name
     * @param value The value
     * @return A new KeyValuePairComponentBuilder.
     */
    KeyValuePairComponentBuilder newKeyValuePair(String key, String value);

    /**
     * Returns a builder for creating CustomLevels
     * @param name The name of the custom level.
     * @param level The integer value to be assigned to the level.
     * @return A new CustomLevelComponentBuilder.
     */
    CustomLevelComponentBuilder newCustomLevel(String name, int level);

    /**
     * Returns a builder for creating Filters.
     * @param pluginName The Plugin type of the Filter.
     * @param onMatch "ACCEPT", "DENY", or "NEUTRAL"
     * @param onMisMatch "ACCEPT", "DENY", or "NEUTRAL"
     * @return A new FilterComponentBuilder.
     */
    FilterComponentBuilder newFilter(String pluginName, Filter.Result onMatch, Filter.Result onMisMatch);

    /**
     * Returns a builder for creating Filters.
     * @param pluginName The Plugin type of the Filter.
     * @param onMatch "ACCEPT", "DENY", or "NEUTRAL"
     * @param onMisMatch "ACCEPT", "DENY", or "NEUTRAL"
     * @return A new FilterComponentBuilder.
     */
    FilterComponentBuilder newFilter(String pluginName, String onMatch, String onMisMatch);

    /**
     * Returns a builder for creating Layouts.
     * @param pluginName The Plugin type of the Layout.
     * @return A new LayoutComponentBuilder.
     */
    LayoutComponentBuilder newLayout(String pluginName);

    /**
     * Returns a builder for creating Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newLogger(String name, Level level);

    /**
     * Returns a builder for creating Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @param includeLocation If true include location information.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newLogger(String name, Level level, boolean includeLocation);

    /**
     * Returns a builder for creating Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newLogger(String name, String level);

    /**
     * Returns a builder for creating Loggers.
     * @param name The name of the Logger.
     * @param level The logging Level to be assigned to the Logger.
     * @param includeLocation If true include location information.
     * @return A new LoggerComponentBuilder.
     */
    LoggerComponentBuilder newLogger(String name, String level, boolean includeLocation);

    /**
     * Returns a builder for creating the root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newRootLogger(Level level);

    /**
     * Returns a builder for creating the root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     * @param includeLocation If true include location information.
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newRootLogger(Level level, boolean includeLocation);

    /**
     * Returns a builder for creating the root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     *
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newRootLogger(String level);

    /**
     * Returns a builder for creating the root Logger.
     * @param level The logging Level to be assigned to the root Logger.
     *
     * @return A new RootLoggerComponentBuilder.
     */
    RootLoggerComponentBuilder newRootLogger(String level, boolean includeLocation);

    /**
     * Set the Advertiser Plugin name.
     * @param advertiser The Advertiser Plugin name.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setAdvertiser(String advertiser);

    /**
     * Sets the name of the configuration.
     * @param name the name of the {@link Configuration}. By default is {@code "Constructed"}.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setConfigurationName(String name);

    /**
     * Sets the configuration source, if one exists.
     * @param configurationSource the ConfigurationSource.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setConfigurationSource(ConfigurationSource configurationSource);

    /**
     * Sets the interval at which the configuration file should be checked for changes.
     * @param intervalSeconds The number of seconds that should pass between checks of the configuration file.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setMonitorInterval(String intervalSeconds);

    /**
     * Sets the list of packages to search for plugins.
     * @param packages The comma separated list of packages.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setPackages(String packages);

    /**
     * Sets whether the shutdown hook should be disabled.
     * @param flag "disable" will prevent the shutdown hook from being set.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setShutdownHook(String flag);

    /**
     * How long appenders and background tasks will get to shutdown when the JVM shuts down.
     * Default is zero which mean that each appender uses its default timeout, and don't wait for background
     * tasks. Not all appenders will honor this, it is a hint and not an absolute guarantee that the shutdown
     * procedure will not take longer. Setting this too low increase the risk of losing outstanding log events
     * not yet written to the final destination. (Not used if {@link #setShutdownHook(String)} is set to "disable".)
     * @return this builder instance.
     *
     * @see LoggerContext#stop(long, TimeUnit)
     */
    ConfigurationBuilder<T> setShutdownTimeout(long timeout, TimeUnit timeUnit);

    /**
     * Sets the level of the StatusLogger.
     * @param level The logging level.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setStatusLevel(Level level);

    /**
     * Sets whether the logging should include constructing Plugins.
     * @param verbosity "disable" will hide messages from plugin construction.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setVerbosity(String verbosity);

    /**
     * Specifies the destination for StatusLogger events. This can be {@code out} (default) for using
     * {@link System#out standard out}, {@code err} for using {@link System#err standard error}, or a file URI to
     * which log events will be written. If the provided URI is invalid, then the default destination of standard
     * out will be used.
     *
     * @param destination where status log messages should be output.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> setDestination(String destination);

    /**
     * Sets the logger context.
     * @param loggerContext the logger context.
     */
    void setLoggerContext(LoggerContext loggerContext);

    /**
     * Add the properties for the root node.
     * @param key The property key.
     * @param value The property value.
     * @return this builder instance.
     */
    ConfigurationBuilder<T> addRootProperty(String key, String value);

    /**
     * Build the configuration and optionally initialize it.
     * @param initialize true if the configuration should be initialized, false otherwise. Generally, Configurations
     *                   should not be initialized when they are constructed.
     * @return The constructed Configuration.
     */
    T build(boolean initialize);

    /**
     * Constructs an XML configuration from this builder.
     *
     * @param output  OutputStream to write to, will not be closed
     *
     * @since 2.7
     */
    void writeXmlConfiguration(OutputStream output) throws IOException;

    /**
     * Constructs an XML configuration from this builder.
     *
     * @return  XML configuration
     *
     * @since 2.7
     */
    String toXmlConfiguration();
}


text:
#include <QtGui/QFont>
#include <QtCore/QTextCodec>
#include <QtCore/QTimer>

#include "trikTestApplication.h"
#include "launcher.h"

int main(int argc, char *argv[])
{
	TrikTestApplication a(argc, argv);

	QFont newFont(a.font());
	newFont.setPixelSize(12);
	a.setFont(newFont);
	a.setStyleSheet("QTableView::item:selected:active { background: white; color:black; border: 2px solid black }"
		"QMessageBox { background: white; color:black ; border: 2px solid black }"
		"QPushButton { background: white; color:black ; border: 2px solid black }");

	Launcher launcher;
	launcher.show();

	QTimer::singleShot(0, &launcher, SLOT(startTesting()));

	return a.exec();
}


text:
class AddTagCounterCache < ActiveRecord::Migration
  def change
    add_column :tags, :taggings_count, :integer, :null => false, :default => 0
  end
end


text:
<?php

require_once(dirname(__FILE__).'/sfPropelBaseTask.class.php');

/**
 * Inserts SQL for current model.
 *
 * @package    symfony
 * @subpackage propel
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     Jonathan H. Wage <jonwage@gmail.com>
 * @version    SVN: $Id: sfPropelGenerateMigrationTask.class.php 24390 2010-11-25 18:21:06Z Kris.Wallsmith $
 */
class sfPropelGenerateMigrationTask extends sfPropelBaseTask
{
  /**
   * @see sfTask
   */
  protected function configure()
  {
    $this->addArguments(array(
      new sfCommandArgument('name', sfCommandArgument::REQUIRED, 'The name of the migration'),
    ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', true),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('editor-cmd', null, sfCommandOption::PARAMETER_REQUIRED, 'Open script with this command upon creation'),
    ));

    $this->namespace = 'propel';
    $this->name = 'generate-migration';
    $this->briefDescription = 'Generate migration class';

    $this->detailedDescription = <<<EOF
The [propel:generate-migration|INFO] task generates migration template

  [./symfony propel:generate-migration AddUserEmailColumn|INFO]

You can provide an [--editor-cmd|COMMENT] option to open the new migration class in your
editor of choice upon creation:

  [./symfony propel:generate-migration AddUserEmailColumn --editor-cmd=mate|INFO]
EOF;
  }

  /**
   * @see sfTask
   */
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
    $config = $this->getCliConfig();

    $this->logSection('propel', sprintf('generating migration class named "%s"', $arguments['name']));

    if (!is_dir($config['migrations_path']))
    {
      $this->getFilesystem()->mkdirs($config['migrations_path']);
    }

    $this->callPropelCli('generate-migration', array('name' => $arguments['name']));

    $finder = sfFinder::type('file')->sort_by_name()->name('*.php');
    if ($files = $finder->in($config['migrations_path']))
    {
      $file = array_pop($files);

      $contents = file_get_contents($file);
      $contents = strtr(sfToolkit::stripComments($contents), array(
        "{\n\n" => "{\n",
        "\n}"   => "\n}\n",
        '    '  => '  ',
      ));
      file_put_contents($file, $contents);

      if (isset($options['editor-cmd']))
      {
        $this->getFilesystem()->execute($options['editor-cmd'].' '.escapeshellarg($file));
      }
    }
  }
}


text:
package quickfix.fix50.component;
import quickfix.FieldNotFound;

import quickfix.Group;

public class ExecAllocGrp extends quickfix.MessageComponent
{

  static final long serialVersionUID = 20050617;
  public static final String MSGTYPE = "";

  private int[] componentFields = {  };
  protected int[] getFields() { return componentFields; }
  private int[] componentGroups = { 124,  };
  protected int[] getGroupFields() { return componentGroups; }

  public ExecAllocGrp()
  {
    super();
  }

  public void set(quickfix.field.NoExecs value)
  {
    setField(value);
  }

  public quickfix.field.NoExecs get(quickfix.field.NoExecs  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.NoExecs getNoExecs() throws FieldNotFound
  {
    quickfix.field.NoExecs value = new quickfix.field.NoExecs();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.NoExecs field)
  {
    return isSetField(field);
  }

  public boolean isSetNoExecs()
  {
    return isSetField(124);
  }

  public static class NoExecs extends Group {
    static final long serialVersionUID = 20050617;
    public NoExecs() {
        super(124, 32,
            new int[] {32, 17, 527, 31, 669, 29, 1003, 1041,  0 } );
    }

  public void set(quickfix.field.LastQty value)
  {
    setField(value);
  }

  public quickfix.field.LastQty get(quickfix.field.LastQty  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LastQty getLastQty() throws FieldNotFound
  {
    quickfix.field.LastQty value = new quickfix.field.LastQty();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LastQty field)
  {
    return isSetField(field);
  }

  public boolean isSetLastQty()
  {
    return isSetField(32);
  }

  public void set(quickfix.field.ExecID value)
  {
    setField(value);
  }

  public quickfix.field.ExecID get(quickfix.field.ExecID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.ExecID getExecID() throws FieldNotFound
  {
    quickfix.field.ExecID value = new quickfix.field.ExecID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.ExecID field)
  {
    return isSetField(field);
  }

  public boolean isSetExecID()
  {
    return isSetField(17);
  }

  public void set(quickfix.field.SecondaryExecID value)
  {
    setField(value);
  }

  public quickfix.field.SecondaryExecID get(quickfix.field.SecondaryExecID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.SecondaryExecID getSecondaryExecID() throws FieldNotFound
  {
    quickfix.field.SecondaryExecID value = new quickfix.field.SecondaryExecID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.SecondaryExecID field)
  {
    return isSetField(field);
  }

  public boolean isSetSecondaryExecID()
  {
    return isSetField(527);
  }

  public void set(quickfix.field.LastPx value)
  {
    setField(value);
  }

  public quickfix.field.LastPx get(quickfix.field.LastPx  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LastPx getLastPx() throws FieldNotFound
  {
    quickfix.field.LastPx value = new quickfix.field.LastPx();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LastPx field)
  {
    return isSetField(field);
  }

  public boolean isSetLastPx()
  {
    return isSetField(31);
  }

  public void set(quickfix.field.LastParPx value)
  {
    setField(value);
  }

  public quickfix.field.LastParPx get(quickfix.field.LastParPx  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LastParPx getLastParPx() throws FieldNotFound
  {
    quickfix.field.LastParPx value = new quickfix.field.LastParPx();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LastParPx field)
  {
    return isSetField(field);
  }

  public boolean isSetLastParPx()
  {
    return isSetField(669);
  }

  public void set(quickfix.field.LastCapacity value)
  {
    setField(value);
  }

  public quickfix.field.LastCapacity get(quickfix.field.LastCapacity  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.LastCapacity getLastCapacity() throws FieldNotFound
  {
    quickfix.field.LastCapacity value = new quickfix.field.LastCapacity();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.LastCapacity field)
  {
    return isSetField(field);
  }

  public boolean isSetLastCapacity()
  {
    return isSetField(29);
  }

  public void set(quickfix.field.TradeID value)
  {
    setField(value);
  }

  public quickfix.field.TradeID get(quickfix.field.TradeID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.TradeID getTradeID() throws FieldNotFound
  {
    quickfix.field.TradeID value = new quickfix.field.TradeID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.TradeID field)
  {
    return isSetField(field);
  }

  public boolean isSetTradeID()
  {
    return isSetField(1003);
  }

  public void set(quickfix.field.FirmTradeID value)
  {
    setField(value);
  }

  public quickfix.field.FirmTradeID get(quickfix.field.FirmTradeID  value) throws FieldNotFound
  {
    getField(value);
    return value;
  }

  public quickfix.field.FirmTradeID getFirmTradeID() throws FieldNotFound
  {
    quickfix.field.FirmTradeID value = new quickfix.field.FirmTradeID();
    getField(value);
    return value;
  }

  public boolean isSet(quickfix.field.FirmTradeID field)
  {
    return isSetField(field);
  }

  public boolean isSetFirmTradeID()
  {
    return isSetField(1041);
  }

  }

}


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

import io.github.jass2125.locagames.core.excecoes.GameException;
import io.github.jass2125.locagames.core.observer.Observable;
import io.github.jass2125.locagames.core.observer.Observer;
import io.github.jass2125.locagames.core.state.GameState;
import io.github.jass2125.locagames.core.state.State;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.mail.EmailException;

/**
 * @author Anderson Souza
 * @since 14:17:38, 20-Feb-2016
 */
public class Jogo implements Serializable, Observable {

    private Long idDoJogo;
    private String nomeDoJogo;
    private String genero;
    private State estado;
    private Set<Observer> listaDeObservadores = new HashSet<>();

    public Jogo() {
//        estado = GameStateEnum.getAVAILABLE();
    }

    public Jogo(Long idDoJogo, String nome, String genero, String estado) {
        this.idDoJogo = idDoJogo;
        this.nomeDoJogo = nome;
        this.genero = estado;
        this.estado = GameState.valueOf(estado);
    }

    public Long getIdDoJogo() {
        return idDoJogo;
    }

    public String getNomeDoJogo() {
        return nomeDoJogo;
    }

    public void setNomeDoJogo(String nomeDoJogo) {
        this.nomeDoJogo = nomeDoJogo;
    }

    public String getGenero() {
        return genero;
    }

    public void setGenero(String genero) {
        this.genero = genero;
    }

    public State getEstado() {
        return estado;
    }

    public void setEstado(State estado) {
        this.estado = estado;
    }

    public Set<Observer> getListaDeObservadores() {
        return listaDeObservadores;
    }

    public void setListaDeObservadores(Set<Observer> listaDeObservadores) {
        this.listaDeObservadores = listaDeObservadores;
    }

    @Override
    public void notificarObservadores() throws EmailException {
        for (Observer it : listaDeObservadores) {
            it.update(this);
        }
    }

    @Override
    public void deleteObserver(Observer observer) {
        this.listaDeObservadores.remove(this);
    }

    @Override
    public void addObserver(Observer observer) {
        this.listaDeObservadores.add(observer);
    }

    public State devolution() throws SQLException, ClassNotFoundException, GameException {
        State state = this.estado.availableGame();
        this.setEstado(state);
        return state;
    }

    public State location() throws SQLException, ClassNotFoundException, GameException {
        State state = this.estado.rentedGame();
        this.setEstado(state);
        return state;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Microsoft.Extensions.Hosting;

namespace Orleans
{
    /// <summary>
    /// Client for communicating with clusters of Orleans silos.
    /// </summary>
    internal class ClusterClient : IInternalClusterClient, IHostedService
    {
        private readonly OutsideRuntimeClient _runtimeClient;
        private readonly ILogger<ClusterClient> _logger;
        private readonly ClusterClientLifecycle _clusterClientLifecycle;

        /// <summary>
        /// Initializes a new instance of the <see cref="ClusterClient"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="runtimeClient">The runtime client.</param>
        /// <param name="loggerFactory">Logger factory used to create loggers</param>
        /// <param name="clientMessagingOptions">Messaging parameters</param>
        public ClusterClient(IServiceProvider serviceProvider, OutsideRuntimeClient runtimeClient, ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> clientMessagingOptions)
        {
            ValidateSystemConfiguration(serviceProvider);

            _runtimeClient = runtimeClient;
            _logger = loggerFactory.CreateLogger<ClusterClient>();
            _clusterClientLifecycle = new ClusterClientLifecycle(_logger);

            // register all lifecycle participants
            IEnumerable<ILifecycleParticipant<IClusterClientLifecycle>> lifecycleParticipants = ServiceProvider.GetServices<ILifecycleParticipant<IClusterClientLifecycle>>();
            foreach (var participant in lifecycleParticipants)
            {
                participant?.Participate(_clusterClientLifecycle);
            }

            // register all named lifecycle participants
            var namedLifecycleParticipantCollection = ServiceProvider.GetService<IKeyedServiceCollection<string, ILifecycleParticipant<IClusterClientLifecycle>>>();
            if (namedLifecycleParticipantCollection?.GetServices(ServiceProvider)?.Select(s => s.GetService(ServiceProvider)) is { } namedParticipants)
            {
                foreach (var participant in namedParticipants)
                {
                    participant.Participate(_clusterClientLifecycle);
                }
            }

            static void ValidateSystemConfiguration(IServiceProvider serviceProvider)
            {
                var validators = serviceProvider.GetServices<IConfigurationValidator>();
                foreach (var validator in validators)
                {
                    validator.ValidateConfiguration();
                }
            }
        }

        /// <inheritdoc />
        public IServiceProvider ServiceProvider => _runtimeClient.ServiceProvider;

        /// <inheritdoc />
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await _runtimeClient.Start(cancellationToken).ConfigureAwait(false);
            await _clusterClientLifecycle.OnStart(cancellationToken).ConfigureAwait(false);
        }

        /// <inheritdoc />
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("Client shutting down");

                await _clusterClientLifecycle.OnStop(cancellationToken).ConfigureAwait(false);

                _runtimeClient?.Reset();
            }
            finally
            {
                _logger.LogInformation("Client shutdown completed");
            }
        }

        /// <inheritdoc />
        public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null)
            where TGrainInterface : IGrainWithGuidKey => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);

        /// <inheritdoc />
        public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null)
            where TGrainInterface : IGrainWithIntegerKey => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);

        /// <inheritdoc />
        public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null)
            where TGrainInterface : IGrainWithStringKey => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, grainClassNamePrefix);

        /// <inheritdoc />
        public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null)
            where TGrainInterface : IGrainWithGuidCompoundKey => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, keyExtension, grainClassNamePrefix);

        /// <inheritdoc />
        public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null)
            where TGrainInterface : IGrainWithIntegerCompoundKey => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(primaryKey, keyExtension, grainClassNamePrefix);

        /// <inheritdoc />
        public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj)
            where TGrainObserverInterface : IGrainObserver => ((IGrainFactory)_runtimeClient.InternalGrainFactory).CreateObjectReference<TGrainObserverInterface>(obj);

        /// <inheritdoc />
        public void DeleteObjectReference<TGrainObserverInterface>(IGrainObserver obj) where TGrainObserverInterface : IGrainObserver => _runtimeClient.InternalGrainFactory.DeleteObjectReference<TGrainObserverInterface>(obj);

        /// <inheritdoc />
        public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj)
            where TGrainObserverInterface : IAddressable => _runtimeClient.InternalGrainFactory.CreateObjectReference<TGrainObserverInterface>(obj);

        /// <inheritdoc />
        TGrainInterface IInternalGrainFactory.GetSystemTarget<TGrainInterface>(GrainType grainType, SiloAddress destination) => _runtimeClient.InternalGrainFactory.GetSystemTarget<TGrainInterface>(grainType, destination);

        public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId) where TGrainInterface : ISystemTarget => _runtimeClient.InternalGrainFactory.GetSystemTarget<TGrainInterface>(grainId);

        /// <inheritdoc />
        TGrainInterface IInternalGrainFactory.Cast<TGrainInterface>(IAddressable grain) => _runtimeClient.InternalGrainFactory.Cast<TGrainInterface>(grain);

        /// <inheritdoc />
        TGrainInterface IGrainFactory.GetGrain<TGrainInterface>(GrainId grainId) => _runtimeClient.InternalGrainFactory.GetGrain<TGrainInterface>(grainId);

        /// <inheritdoc />
        IAddressable IGrainFactory.GetGrain(GrainId grainId) => _runtimeClient.InternalGrainFactory.GetGrain(grainId);

        /// <inheritdoc />
        public IGrain GetGrain(Type grainInterfaceType, string grainPrimaryKey)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainInterfaceType, grainPrimaryKey);

        /// <inheritdoc />
        public IGrain GetGrain(Type grainInterfaceType, Guid grainPrimaryKey)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainInterfaceType, grainPrimaryKey);

        /// <inheritdoc />
        public IGrain GetGrain(Type grainInterfaceType, long grainPrimaryKey)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainInterfaceType, grainPrimaryKey);

        /// <inheritdoc />
        public IGrain GetGrain(Type grainInterfaceType, Guid grainPrimaryKey, string keyExtension)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainInterfaceType, grainPrimaryKey, keyExtension);

        /// <inheritdoc />
        public IGrain GetGrain(Type grainInterfaceType, long grainPrimaryKey, string keyExtension)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainInterfaceType, grainPrimaryKey, keyExtension);

        /// <inheritdoc />
        public object Cast(IAddressable grain, Type outputGrainInterfaceType)
            => _runtimeClient.InternalGrainFactory.Cast(grain, outputGrainInterfaceType);

        /// <inheritdoc />
        public IAddressable GetGrain(GrainId grainId, GrainInterfaceType interfaceType)
            => _runtimeClient.InternalGrainFactory.GetGrain(grainId, interfaceType);
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.profile.compiled;

import com.yahoo.search.query.profile.config.QueryProfilesConfig;
import org.junit.jupiter.api.Test;

import java.util.concurrent.Executors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author gjoranv
 */
public class CompiledQueryProfileRegistryTest {

    @Test
    void registry_can_be_created_from_config() {
        var config = new QueryProfilesConfig.Builder()
                .queryprofile(new QueryProfilesConfig.Queryprofile.Builder()
                        .id("profile1")
                        .property(new QueryProfilesConfig.Queryprofile.Property.Builder()
                                .name("hits")
                                .value("5")))
                .build();

        var executor = Executors.newCachedThreadPool();
        var registry = new CompiledQueryProfileRegistry(config, executor);
        assertTrue(executor.shutdownNow().isEmpty());
        var profile1 = registry.findQueryProfile("profile1");
        assertEquals("5", profile1.get("hits"));
    }

}


text:
<?php

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\InputFilter',
    'Zend\Filter',
    'Zend\Hydrator',
    'Zend\I18n',
    'Zend\ServiceManager\Di',
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Mvc\Console',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Application',
    'Album',
    'Abavo',
];


text:
package com.github.endoscope.storage.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class QueryRunnerExt extends QueryRunner {
    private ThreadLocal<Integer> fetchSize = ThreadLocal.withInitial(() -> null);

    public QueryRunnerExt() {
    }

    public QueryRunnerExt(boolean pmdKnownBroken) {
        super(pmdKnownBroken);
    }

    public QueryRunnerExt(DataSource ds) {
        super(ds);
    }

    public QueryRunnerExt(DataSource ds, boolean pmdKnownBroken) {
        super(ds, pmdKnownBroken);
    }

    public int getFetchSize() {
        return fetchSize.get();
    }

    public void setFetchSize(int fetchSize) {
        this.fetchSize.set(fetchSize);
    }

    private void applyFetchSize(PreparedStatement ps) throws SQLException {
        if( fetchSize.get() != null ){
            ps.setFetchSize(fetchSize.get());
        }
    }

    @Override
    protected PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {
        PreparedStatement ps = super.prepareStatement(conn, sql);
        applyFetchSize(ps);
        return ps;
    }

    @Override
    protected PreparedStatement prepareStatement(Connection conn, String sql, int returnedKeys) throws SQLException {
        PreparedStatement ps = super.prepareStatement(conn, sql, returnedKeys);
        applyFetchSize(ps);
        return ps;
    }

    public <T> T queryExt(int fetchSize, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
        Integer previous = this.fetchSize.get();
        this.fetchSize.set(fetchSize);
        try {
            return query(sql, rsh, params);
        }finally{
            this.fetchSize.set(previous);
        }
    }
}


text:
require 'natural_sort'
require 'natural_sort/kernel'


text:
/**@CFILE test_ops.c
 * @brief High-level test framework for Sofia SIP User Agent Engine
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Martti Mela <Martti Mela@nokia.com>
 *
 * @date Created: Wed Aug 17 12:12:12 EEST 2005 ppessi
 */

#include "config.h"

#include "test_nua.h"

#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
#define __func__ name
#endif

int save_events(CONDITION_PARAMS)
{
  return save_event_in_list(ctx, event, ep, call) == event_is_normal;
}

int until_final_response(CONDITION_PARAMS)
{
  return status >= 200;
}

int save_until_final_response(CONDITION_PARAMS)
{
  save_event_in_list(ctx, event, ep, call);
  return
    nua_r_set_params <= event && event < nua_i_network_changed
    && status >= 200;
}

/** Save events.
 *
 * Terminate when a event is saved.
 */
int save_until_received(CONDITION_PARAMS)
{
  return save_event_in_list(ctx, event, ep, call) == event_is_normal;
}

/** Save events until nua_i_outbound is received.  */
int save_until_special(CONDITION_PARAMS)
{
  return save_event_in_list(ctx, event, ep, call) == event_is_special;
}

/* Return call state from event tag list */
int callstate(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, nutag_callstate);
  return ti ? ti->t_value : -1;
}

/* Return true if offer is sent */
int is_offer_sent(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, nutag_offer_sent);
  return ti ? ti->t_value : 0;
}

/* Return true if answer is sent */
int is_answer_sent(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, nutag_answer_sent);
  return ti ? ti->t_value : 0;
}

/* Return true if offer is recv */
int is_offer_recv(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, nutag_offer_recv);
  return ti ? ti->t_value : 0;
}

/* Return true if answer is recv */
int is_answer_recv(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, nutag_answer_recv);
  return ti ? ti->t_value : 0;
}

/* Return true if offer/answer is sent/recv */
int is_offer_answer_done(tagi_t const *tags)
{
  tagi_t const *ti;

  return
    ((ti = tl_find(tags, nutag_answer_recv)) && ti->t_value) ||
    ((ti = tl_find(tags, nutag_offer_sent)) && ti->t_value) ||
    ((ti = tl_find(tags, nutag_offer_recv)) && ti->t_value) ||
    ((ti = tl_find(tags, nutag_answer_sent)) && ti->t_value);
}

/* Return audio state from event tag list */
int audio_activity(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, soatag_active_audio);
  return ti ? ti->t_value : -1;
}

/* Return video state from event tag list */
int video_activity(tagi_t const *tags)
{
  tagi_t const *ti = tl_find(tags, soatag_active_video);
  return ti ? ti->t_value : -1;
}

void print_event(nua_event_t event,
		 char const *operation,
		 int status, char const *phrase,
		 nua_t *nua, struct context *ctx,
		 struct endpoint *ep,
		 nua_handle_t *nh, struct call *call,
		 sip_t const *sip,
		 tagi_t tags[])
{
  tagi_t const *t;
  static su_nanotime_t started = 0;
  su_nanotime_t now;
  char timestamp[32];

  su_nanotime(&now);

  if (started == 0) started = now;

  now -= started; now /= 1000000;

  snprintf(timestamp, sizeof timestamp, "%03u.%03u",
	   (unsigned)(now / 1000), (unsigned)(now % 1000));

  if (event == nua_i_state) {
    fprintf(stderr, "%s %s.nua(%p): event %s %s\n", timestamp,
	    ep->name, (void *)nh, nua_event_name(event),
	    nua_callstate_name(callstate(tags)));
  }
  else if ((int)event >= nua_r_set_params) {
    t = tl_find(tags, nutag_substate);
    if (t) {
      fprintf(stderr, "%s %s.nua(%p): event %s status %u %s (%s)\n", timestamp,
	      ep->name, (void*)nh, nua_event_name(event), status, phrase,
	      nua_substate_name(t->t_value));
    }
    else {
      fprintf(stderr, "%s %s.nua(%p): event %s status %u %s\n", timestamp,
	      ep->name, (void *)nh, nua_event_name(event), status, phrase);
    }
  }
  else if (event == nua_i_notify) {
    t = tl_find(tags, nutag_substate);
    fprintf(stderr, "%s %s.nua(%p): event %s %s (%s)\n", timestamp,
	    ep->name, (void *)nh, nua_event_name(event), phrase,
	    nua_substate_name(t ? t->t_value : 0));
  }
  else if ((int)event >= nua_i_bye ||
	   event == nua_i_invite || event == nua_i_cancel ||
	   event == nua_i_ack) {
    fprintf(stderr, "%s %s.nua(%p): event %s %03d %s\n", timestamp,
	    ep->name, (void *)nh, nua_event_name(event), status, phrase);
  }
  else if ((int)event >= 0) {
    fprintf(stderr, "%s %s.nua(%p): event %s %s\n", timestamp,
	    ep->name, (void *)nh, nua_event_name(event), phrase);
  }
  else if (status > 0) {
    fprintf(stderr, "%s %s.nua(%p): call %s() with status %u %s\n", timestamp,
	    ep->name, (void *)nh, operation, status, phrase);
  }
  else {
    t = tl_find(tags, siptag_subject_str);
    if (t && t->t_value) {
      char const *subject = (char const *)t->t_value;
      fprintf(stderr, "%s %s.nua(%p): call %s() \"%s\"\n", timestamp,
	      ep->name, (void *)nh, operation, subject);
    }
    else
      fprintf(stderr, "%s %s.nua(%p): call %s()\n", timestamp,
	      ep->name, (void *)nh, operation);
  }

  if (tags &&
      ((tstflags & tst_verbatim) || ctx->print_tags || ep->print_tags))
    tl_print(stderr, "", tags);
}

void ep_callback(nua_event_t event,
		 int status, char const *phrase,
		 nua_t *nua, struct context *ctx,
		 struct endpoint *ep,
		 nua_handle_t *nh, struct call *call,
		 sip_t const *sip,
		 tagi_t tags[])
{
  if (ep->printer)
    ep->printer(event, "", status, phrase, nua, ctx, ep, nh, call, sip, tags);

  if (call == NULL && nh) {
    for (call = ep->call; call; call = call->next) {
      if (!call->nh)
	break;
      if (nh == call->nh)
	break;
    }

    if (call && call->nh == NULL) {
      call->nh = nh;
      nua_handle_bind(nh, call);
    }
  }

  if ((ep->next_condition == NULL ||
       ep->next_condition(event, status, phrase,
			  nua, ctx, ep, nh, call, sip, tags))
      &&
      (ep->next_event == -1 || ep->next_event == event))
    ep->running = 0;

  ep->last_event = event;

  if (call == NULL && nh)
    nua_handle_destroy(nh);
}

void a_callback(nua_event_t event,
		int status, char const *phrase,
		nua_t *nua, struct context *ctx,
		nua_handle_t *nh, struct call *call,
		sip_t const *sip,
		tagi_t tags[])
{
  ep_callback(event, status, phrase, nua, ctx, &ctx->a, nh, call, sip, tags);
}

void b_callback(nua_event_t event,
		int status, char const *phrase,
		nua_t *nua, struct context *ctx,
		nua_handle_t *nh, struct call *call,
		sip_t const *sip,
		tagi_t tags[])
{
  ep_callback(event, status, phrase, nua, ctx, &ctx->b, nh, call, sip, tags);
}

void c_callback(nua_event_t event,
		int status, char const *phrase,
		nua_t *nua, struct context *ctx,
		nua_handle_t *nh, struct call *call,
		sip_t const *sip,
		tagi_t tags[])
{
  ep_callback(event, status, phrase, nua, ctx, &ctx->c, nh, call, sip, tags);
}

void run_abc_until(struct context *ctx,
		   nua_event_t a_event, condition_function *a_condition,
		   nua_event_t b_event, condition_function *b_condition,
		   nua_event_t c_event, condition_function *c_condition)
{
  struct endpoint *a = &ctx->a, *b = &ctx->b, *c = &ctx->c;

  a->next_event = a_event;
  a->next_condition = a_condition;
  a->last_event = -1;
  a->running = a_condition != NULL && a_condition != save_events;
  a->running |= a_event != -1;
  memset(&a->flags, 0, sizeof a->flags);

  b->next_event = b_event;
  b->next_condition = b_condition;
  b->last_event = -1;
  b->running = b_condition != NULL && b_condition != save_events;
  b->running |= b_event != -1;
  memset(&b->flags, 0, sizeof b->flags);

  c->next_event = c_event;
  c->next_condition = c_condition;
  c->last_event = -1;
  c->running = c_condition != NULL && c_condition != save_events;
  c->running |= c_event != -1;
  memset(&c->flags, 0, sizeof c->flags);

  for (; a->running || b->running || c->running;) {
    su_root_step(ctx->root, 100);
  }
}

void run_ab_until(struct context *ctx,
		  nua_event_t a_event, condition_function *a_condition,
		  nua_event_t b_event, condition_function *b_condition)
{
  run_abc_until(ctx, a_event, a_condition, b_event, b_condition, -1, NULL);
}

void run_bc_until(struct context *ctx,
		  nua_event_t b_event, condition_function *b_condition,
		  nua_event_t c_event, condition_function *c_condition)
{
  run_abc_until(ctx, -1, NULL, b_event, b_condition, c_event, c_condition);
}

int run_a_until(struct context *ctx,
		nua_event_t a_event,
		condition_function *a_condition)
{
  run_abc_until(ctx, a_event, a_condition, -1, NULL, -1, NULL);
  return ctx->a.last_event;
}

int run_b_until(struct context *ctx,
		nua_event_t b_event,
		condition_function *b_condition)
{
  run_abc_until(ctx, -1, NULL, b_event, b_condition, -1, NULL);
  return ctx->b.last_event;
}

int run_c_until(struct context *ctx,
		nua_event_t event,
		condition_function *condition)
{
  run_abc_until(ctx, -1, NULL, -1, NULL, event, condition);
  return ctx->c.last_event;
}

#define OPERATION(X, x)	   \
int X(struct endpoint *ep, \
      struct call *call, nua_handle_t *nh, \
      tag_type_t tag, tag_value_t value, \
      ...) \
{ \
  ta_list ta; \
  ta_start(ta, tag, value); \
\
  if (ep->printer) \
    ep->printer(-1, "nua_" #x, 0, "", ep->nua, ep->ctx, ep, \
		nh, call, NULL, ta_args(ta)); \
\
  nua_##x(nh, ta_tags(ta)); \
\
  ta_end(ta); \
  return 0; \
} extern int dummy

OPERATION(INVITE, invite);
OPERATION(ACK, ack);
OPERATION(BYE, bye);
OPERATION(CANCEL, cancel);
OPERATION(AUTHENTICATE, authenticate);
OPERATION(UPDATE, update);
OPERATION(INFO, info);
OPERATION(PRACK, prack);
OPERATION(REFER, refer);
OPERATION(MESSAGE, message);
OPERATION(METHOD, method);
OPERATION(OPTIONS, options);
OPERATION(PUBLISH, publish);
OPERATION(UNPUBLISH, unpublish);
OPERATION(REGISTER, register);
OPERATION(UNREGISTER, unregister);
OPERATION(SUBSCRIBE, subscribe);
OPERATION(UNSUBSCRIBE, unsubscribe);
OPERATION(NOTIFY, notify);
OPERATION(NOTIFIER, notifier);
OPERATION(TERMINATE, terminate);
OPERATION(AUTHORIZE, authorize);

/* Respond via endpoint and handle */
int RESPOND(struct endpoint *ep,
	    struct call *call,
	    nua_handle_t *nh,
	    int status, char const *phrase,
	    tag_type_t tag, tag_value_t value,
	    ...)
{
  ta_list ta;

  ta_start(ta, tag, value);

  if (ep->printer)
    ep->printer(-1, "nua_respond", status, phrase, ep->nua, ep->ctx, ep,
		nh, call, NULL, ta_args(ta));

  nua_respond(nh, status, phrase, ta_tags(ta));
  ta_end(ta);

  return 0;
}

/* Destroy a handle */
int DESTROY(struct endpoint *ep,
	    struct call *call,
	    nua_handle_t *nh)
{
  if (ep->printer)
    ep->printer(-1, "nua_handle_destroy", 0, "", ep->nua, ep->ctx, ep,
		nh, call, NULL, NULL);

  nua_handle_destroy(nh);

  if (call->nh == nh)
    call->nh = NULL;

  return 0;
}

/* Reject all but currently used handles */
struct call *check_handle(struct endpoint *ep,
			  struct call *call,
			  nua_handle_t *nh,
			  int status, char const *phrase)
{
  if (call)
    return call;

  if (status)
    RESPOND(ep, call, nh, status, phrase, TAG_END());

  nua_handle_destroy(nh);
  return NULL;
}

/* Save nua event in call-specific list */
int save_event_in_list(struct context *ctx,
		       nua_event_t nevent,
		       struct endpoint *ep,
		       struct call *call)

{
  struct eventlist *list;
  struct event *e;
  int action = ep->is_special(nevent);

  if (action == event_is_extra)
    return 0;
  else if (action == event_is_special || call == NULL)
    list = ep->specials;
  else if (call->events)
    list = call->events;
  else
    list = ep->events;

  e = su_zalloc(ctx->home, sizeof *e);

  if (!e) { perror("su_zalloc"), abort(); }

  if (!nua_save_event(ep->nua, e->saved_event)) {
    su_free(ctx->home, e);
    return -1;
  }

  *(e->prev = list->tail) = e; list->tail = &e->next;

  e->call = call;
  e->data = nua_event_data(e->saved_event);

  return action;
}

/* Free nua events from endpoint list */
void free_events_in_list(struct context *ctx,
			 struct eventlist *list)
{
  struct event *e;

  while ((e = list->head)) {
    if ((*e->prev = e->next))
      e->next->prev = e->prev;
    nua_destroy_event(e->saved_event);
    su_free(ctx->home, e);
  }

  list->tail = &list->head;
}

void free_event_in_list(struct context *ctx,
			struct eventlist *list,
			struct event *e)
{
  if (e) {
    if ((*e->prev = e->next))
      e->next->prev = e->prev;
    nua_destroy_event(e->saved_event);
    su_free(ctx->home, e);

    if (list->head == NULL)
      list->tail = &list->head;
  }
}

struct event *event_by_type(struct event *e, nua_event_t etype)
{
  for (; e; e = e->next) {
    if (e->data->e_event == etype)
      break;
  }

  return e;
}

size_t count_events(struct event const *e)
{
  size_t n;

  for (n = 0; e; e = e->next)
    n++;

  return n;
}

int is_special(nua_event_t e)
{
  if (e == nua_i_active || e == nua_i_terminated)
    return event_is_extra;
  if (e == nua_i_outbound)
    return event_is_special;

  return event_is_normal;
}

void
endpoint_init(struct context *ctx, struct endpoint *e, char id)
{
  e->name[0] = id;
  e->ctx = ctx;

  e->is_special = is_special;

  call_init(e->call);
  call_init(e->reg);
  eventlist_init(e->events);
  eventlist_init(e->specials);
}

void nolog(void *stream, char const *fmt, va_list ap) {}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.07.24 at 05:36:05 PM EEST
//

package lt.registrucentras.esaskaita.service.invoice.ubl.etsi.v1_3;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.google.common.base.Objects;

/**
 *
Java class for RevocationValuesType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="RevocationValuesType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CRLValues" type="{http://uri.etsi.org/01903/v1.3.2#}CRLValuesType" minOccurs="0"/>
 *         <element name="OCSPValues" type="{http://uri.etsi.org/01903/v1.3.2#}OCSPValuesType" minOccurs="0"/>
 *         <element name="OtherValues" type="{http://uri.etsi.org/01903/v1.3.2#}OtherCertStatusValuesType" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RevocationValuesType", propOrder = {
    "crlValues",
    "ocspValues",
    "otherValues"
})
public class RevocationValuesType implements Serializable
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "CRLValues")
    protected CRLValuesType crlValues;
    @XmlElement(name = "OCSPValues")
    protected OCSPValuesType ocspValues;
    @XmlElement(name = "OtherValues")
    protected OtherCertStatusValuesType otherValues;
    @XmlAttribute(name = "Id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    protected String id;

    /**
     * Default no-arg constructor
     *
     */
    public RevocationValuesType() {
        super();
    }

    /**
     * Fully-initialising value constructor
     *
     */
    public RevocationValuesType(final CRLValuesType crlValues, final OCSPValuesType ocspValues, final OtherCertStatusValuesType otherValues, final String id) {
        this.crlValues = crlValues;
        this.ocspValues = ocspValues;
        this.otherValues = otherValues;
        this.id = id;
    }

    /**
     * Gets the value of the crlValues property.
     *
     * @return
     *     possible object is
     *     {@link CRLValuesType }
     *
     */
    public CRLValuesType getCRLValues() {
        return crlValues;
    }

    /**
     * Sets the value of the crlValues property.
     *
     * @param value
     *     allowed object is
     *     {@link CRLValuesType }
     *
     */
    public void setCRLValues(CRLValuesType value) {
        this.crlValues = value;
    }

    /**
     * Gets the value of the ocspValues property.
     *
     * @return
     *     possible object is
     *     {@link OCSPValuesType }
     *
     */
    public OCSPValuesType getOCSPValues() {
        return ocspValues;
    }

    /**
     * Sets the value of the ocspValues property.
     *
     * @param value
     *     allowed object is
     *     {@link OCSPValuesType }
     *
     */
    public void setOCSPValues(OCSPValuesType value) {
        this.ocspValues = value;
    }

    /**
     * Gets the value of the otherValues property.
     *
     * @return
     *     possible object is
     *     {@link OtherCertStatusValuesType }
     *
     */
    public OtherCertStatusValuesType getOtherValues() {
        return otherValues;
    }

    /**
     * Sets the value of the otherValues property.
     *
     * @param value
     *     allowed object is
     *     {@link OtherCertStatusValuesType }
     *
     */
    public void setOtherValues(OtherCertStatusValuesType value) {
        this.otherValues = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setId(String value) {
        this.id = value;
    }

    public RevocationValuesType withCRLValues(CRLValuesType value) {
        setCRLValues(value);
        return this;
    }

    public RevocationValuesType withOCSPValues(OCSPValuesType value) {
        setOCSPValues(value);
        return this;
    }

    public RevocationValuesType withOtherValues(OtherCertStatusValuesType value) {
        setOtherValues(value);
        return this;
    }

    public RevocationValuesType withId(String value) {
        setId(value);
        return this;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this).add("crlValues", crlValues).add("ocspValues", ocspValues).add("otherValues", otherValues).add("id", id).toString();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(crlValues, ocspValues, otherValues, id);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (getClass()!= other.getClass()) {
            return false;
        }
        final RevocationValuesType o = ((RevocationValuesType) other);
        return (((Objects.equal(crlValues, o.crlValues)&&Objects.equal(ocspValues, o.ocspValues))&&Objects.equal(otherValues, o.otherValues))&&Objects.equal(id, o.id));
    }

}


text:
package com.intellij.codeInspection.ui;

import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class InspectionNode extends InspectionTreeNode {
  @NotNull private final InspectionToolWrapper myToolWrapper;
  @NotNull private final InspectionProfileImpl myProfile;

  public InspectionNode(@NotNull InspectionToolWrapper toolWrapper,
                        @NotNull InspectionProfileImpl profile,
                        @NotNull InspectionTreeNode parent) {
    super(parent);
    myToolWrapper = toolWrapper;
    myProfile = profile;
  }

  @NotNull
  public InspectionToolWrapper getToolWrapper() {
    return myToolWrapper;
  }

  @Nullable
  @Override
  public String getTailText() {
    final String shortName = getToolWrapper().getShortName();
    return myProfile.getTools(shortName, null).isEnabled() ? null : InspectionsBundle.message("inspection.node.disabled.state");
  }

  @Override
  public String getPresentableText() {
    return getToolWrapper().getDisplayName();
  }
}