text:
#ifndef _RRPRIMITIVEASSEMBLER_HPP
#define _RRPRIMITIVEASSEMBLER_HPP
/*!
 * \file
 * \brief Primitive assembler
 *//*--------------------------------------------------------------------*/

#include "rrDefs.hpp"
#include "rrVertexPacket.hpp"

namespace rr
{
namespace pa
{

struct Triangle
{
	enum
	{
		NUM_VERTICES = 3
	};

	Triangle (void)
		: v0				(DE_NULL)
		, v1				(DE_NULL)
		, v2				(DE_NULL)
		, provokingIndex	(-1)
	{
	}

	Triangle (VertexPacket* v0_, VertexPacket* v1_, VertexPacket* v2_, int provokingIndex_)
		: v0				(v0_)
		, v1				(v1_)
		, v2				(v2_)
		, provokingIndex	(provokingIndex_)
	{
	}

	VertexPacket* getProvokingVertex (void)
	{
		switch (provokingIndex)
		{
			case 0: return v0;
			case 1: return v1;
			case 2: return v2;
			default:
				DE_ASSERT(false);
				return DE_NULL;
		}
	}

	VertexPacket*	v0;
	VertexPacket*	v1;
	VertexPacket*	v2;

	int				provokingIndex;
};

struct Triangles
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		const int provokingOffset = (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (2);

		for (size_t ndx = 0; ndx + 2 < numVertices; ndx += 3)
			*(outputIterator++) = Triangle(vertices[ndx], vertices[ndx+1], vertices[ndx+2], provokingOffset);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return vertices / 3;
	}
};

struct TriangleStrip
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		if (numVertices < 3)
		{
		}
		else
		{
			VertexPacket* vert0 = vertices[0];
			VertexPacket* vert1 = vertices[1];
			size_t ndx = 2;

			for (;;)
			{
				{
					if (ndx >= numVertices)
						break;

					*(outputIterator++) = Triangle(vert0, vert1, vertices[ndx], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (2));
					vert0 = vertices[ndx];

					ndx++;
				}

				{
					if (ndx >= numVertices)
						break;

					*(outputIterator++) = Triangle(vert0, vert1, vertices[ndx], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (1) : (2));
					vert1 = vertices[ndx];

					ndx++;
				}
			}
		}
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 3) ? (0) : (vertices - 2);
	}
};

struct TriangleFan
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		if (numVertices == 0)
		{
		}
		else
		{
			const int			provokingOffset	= (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (1) : (2);
			VertexPacket* const	first			= vertices[0];

			for (size_t ndx = 1; ndx + 1 < numVertices; ++ndx)
				*(outputIterator++) = Triangle(first, vertices[ndx], vertices[ndx+1], provokingOffset);
		}
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 3) ? (0) : (vertices - 2);
	}
};

struct Line
{
	enum
	{
		NUM_VERTICES = 2
	};

	Line (void)
		: v0				(DE_NULL)
		, v1				(DE_NULL)
		, provokingIndex	(-1)
	{
	}

	Line (VertexPacket* v0_, VertexPacket* v1_, int provokingIndex_)
		: v0				(v0_)
		, v1				(v1_)
		, provokingIndex	(provokingIndex_)
	{
	}

	VertexPacket* getProvokingVertex (void)
	{
		switch (provokingIndex)
		{
			case 0: return v0;
			case 1: return v1;
			default:
				DE_ASSERT(false);
				return DE_NULL;
		}
	}

	VertexPacket*	v0;
	VertexPacket*	v1;

	int				provokingIndex;
};

struct Lines
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		const int provokingOffset = (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (1);

		for (size_t ndx = 0; ndx + 1 < numVertices; ndx += 2)
			*(outputIterator++) = Line(vertices[ndx], vertices[ndx+1], provokingOffset);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return vertices / 2;
	}
};

struct LineStrip
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		if (numVertices == 0)
		{
		}
		else
		{
			VertexPacket* prev = vertices[0];

			for (size_t ndx = 1; ndx < numVertices; ++ndx)
			{
				*(outputIterator++) = Line(prev, vertices[ndx], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (1));
				prev = vertices[ndx];
			}
		}
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 2) ? (0) : (vertices - 1);
	}
};

struct LineLoop
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		if (numVertices < 2)
		{
		}
		else
		{
			VertexPacket* prev = vertices[0];

			for (size_t ndx = 1; ndx < numVertices; ++ndx)
			{
				*(outputIterator++) = Line(prev, vertices[ndx], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (1));
				prev = vertices[ndx];
			}

			*(outputIterator++) = Line(prev, vertices[0], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (1));
		}
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 2) ? (0) : (vertices);
	}
};

struct Point
{
	enum
	{
		NUM_VERTICES = 1
	};

	Point (void)
		: v0(DE_NULL)
	{
	}

	Point (VertexPacket* v0_)
		: v0(v0_)
	{
	}

	VertexPacket* v0;
};

struct Points
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		DE_UNREF(provokingConvention);

		for (size_t ndx = 0; ndx < numVertices; ++ndx)
			*(outputIterator++) = Point(vertices[ndx]);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices);
	}
};

struct LineAdjacency
{
	enum
	{
		NUM_VERTICES = 4
	};

	LineAdjacency (void)
		: v0				(DE_NULL)
		, v1				(DE_NULL)
		, v2				(DE_NULL)
		, v3				(DE_NULL)
		, provokingIndex	(-1)
	{
	}

	LineAdjacency (VertexPacket* v0_, VertexPacket* v1_, VertexPacket* v2_, VertexPacket* v3_, int provokingIndex_)
		: v0				(v0_)
		, v1				(v1_)
		, v2				(v2_)
		, v3				(v3_)
		, provokingIndex	(provokingIndex_)
	{
	}

	VertexPacket* getProvokingVertex (void)
	{
		switch (provokingIndex)
		{
			case 1: return v1;
			case 2: return v2;
			default:
				DE_ASSERT(false);
				return DE_NULL;
		}
	}

	VertexPacket*	v0;
	VertexPacket*	v1;
	VertexPacket*	v2;
	VertexPacket*	v3;

	int				provokingIndex;
};

struct LinesAdjacency
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		const int provokingOffset = (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (1) : (2);

		for (size_t ndx = 0; ndx + 3 < numVertices; ndx += 4)
			*(outputIterator++) = LineAdjacency(vertices[ndx], vertices[ndx+1], vertices[ndx+2], vertices[ndx+3], provokingOffset);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return vertices / 4;
	}
};

struct LineStripAdjacency
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		const int provokingOffset = (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (1) : (2);

		for (size_t ndx = 0; ndx + 3 < numVertices; ++ndx)
			*(outputIterator++) = LineAdjacency(vertices[ndx], vertices[ndx+1], vertices[ndx+2], vertices[ndx+3], provokingOffset);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 4) ? (0) : (vertices - 3);
	}
};

struct TriangleAdjacency
{
	enum
	{
		NUM_VERTICES = 6
	};

	TriangleAdjacency (void)
		: v0				(DE_NULL)
		, v1				(DE_NULL)
		, v2				(DE_NULL)
		, v3				(DE_NULL)
		, v4				(DE_NULL)
		, v5				(DE_NULL)
		, provokingIndex	(-1)
	{
	}

	TriangleAdjacency (VertexPacket* v0_, VertexPacket* v1_, VertexPacket* v2_, VertexPacket* v3_, VertexPacket* v4_, VertexPacket* v5_, int provokingIndex_)
		: v0				(v0_)
		, v1				(v1_)
		, v2				(v2_)
		, v3				(v3_)
		, v4				(v4_)
		, v5				(v5_)
		, provokingIndex	(provokingIndex_)
	{
	}

	VertexPacket* getProvokingVertex (void)
	{
		switch (provokingIndex)
		{
			case 0: return v0;
			case 2: return v2;
			case 4: return v4;
			default:
				DE_ASSERT(false);
				return DE_NULL;
		}
	}

	VertexPacket*	v0;
	VertexPacket*	v1;	//!< adjacent
	VertexPacket*	v2;
	VertexPacket*	v3;	//!< adjacent
	VertexPacket*	v4;
	VertexPacket*	v5;	//!< adjacent

	int				provokingIndex;
};

struct TrianglesAdjacency
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		const int provokingOffset = (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (4);

		for (size_t ndx = 0; ndx + 5 < numVertices; ndx += 6)
			*(outputIterator++) = TriangleAdjacency(vertices[ndx], vertices[ndx+1], vertices[ndx+2], vertices[ndx+3], vertices[ndx+4], vertices[ndx+5], provokingOffset);
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return vertices / 6;
	}
};

struct TriangleStripAdjacency
{
	template <typename Iterator>
	static void exec (Iterator outputIterator, VertexPacket* const* vertices, size_t numVertices, rr::ProvokingVertex provokingConvention)
	{
		if (numVertices < 6)
		{
		}
		else if (numVertices < 8)
		{
			*(outputIterator++) = TriangleAdjacency(vertices[0], vertices[1], vertices[2], vertices[5], vertices[4], vertices[3], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (4));
		}
		else
		{
			const size_t primitiveCount = getPrimitiveCount(numVertices);
			size_t i;

			// first
			*(outputIterator++) = TriangleAdjacency(vertices[0], vertices[1], vertices[2], vertices[6], vertices[4], vertices[3], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (4));

			// middle
			for (i = 1; i + 1 < primitiveCount; ++i)
			{
				// odd
				if (i % 2 == 1)
				{
					*(outputIterator++) = TriangleAdjacency(vertices[2*i+2], vertices[2*i-2], vertices[2*i+0], vertices[2*i+3], vertices[2*i+4], vertices[2*i+6], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (2) : (4));
				}
				// even
				else
				{
					*(outputIterator++) = TriangleAdjacency(vertices[2*i+0], vertices[2*i-2], vertices[2*i+2], vertices[2*i+6], vertices[2*i+4], vertices[2*i+3], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (4));
				}
			}

			// last

			// odd
			if (i % 2 == 1)
				*(outputIterator++) = TriangleAdjacency(vertices[2*i+2], vertices[2*i-2], vertices[2*i+0], vertices[2*i+3], vertices[2*i+4], vertices[2*i+5], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (2) : (4));
			// even
			else
				*(outputIterator++) = TriangleAdjacency(vertices[2*i+0], vertices[2*i-2], vertices[2*i+2], vertices[2*i+5], vertices[2*i+4], vertices[2*i+3], (provokingConvention == rr::PROVOKINGVERTEX_FIRST) ? (0) : (4));
		}
	}

	static size_t getPrimitiveCount (size_t vertices)
	{
		return (vertices < 6) ? 0 : ((vertices - 4) / 2);
	}
};

} // pa
} // rr

#endif // _RRPRIMITIVEASSEMBLER_HPP


text:
module.exports = {
    parse: require("./file-parse"),
    lint: require("./lint"),
    transformAst: require("./transform-ast"),
    compile: require("./compile"),
};

redpajama_set_name: RedPajamaGithub


text:
cask 'sqlectron' do
  version '1.8.0'
  sha256 '3439536aff3793503c67d21080c52d5593c3435c431755223f8da7a6b6b9b329'

  # github.com/sqlectron/sqlectron-gui was verified as official when first introduced to the cask
  url "https://github.com/sqlectron/sqlectron-gui/releases/download/v#{version}/Sqlectron-#{version}-mac.zip"
  appcast 'https://github.com/sqlectron/sqlectron-gui/releases.atom',
          checkpoint: '11aad5e73fe048d6b6fc19a72c1fd785be9b11d9aa45cf165580057770e462c7'
  name 'Sqlectron'
  homepage 'https://sqlectron.github.io/'
  license :mit

  depends_on macos: '>= :mountain_lion'

  app 'Sqlectron.app'

  postflight do
    suppress_move_to_applications
  end

  zap delete: [
                '~/.sqlectron.json',
                '~/Library/Application Support/Sqlectron',
              ]
end


text:
from setuptools import setup, find_packages

import os

requires = [
    'boto3==1.1.1',
    'click==4.0',
    'PyYAML>=3.11'
]

setup(
    name='kappa',
    version=open(os.path.join('kappa', '_version')).read().strip(),
    description='A CLI tool for AWS Lambda developers',
    long_description=open('README.md').read(),
    author='Mitch Garnaat',
    author_email='mitch@garnaat.com',
    url='https://github.com/garnaat/kappa',
    packages=find_packages(exclude=['tests*']),
    package_data={'kappa': ['_version']},
    package_dir={'kappa': 'kappa'},
    scripts=['bin/kappa'],
    install_requires=requires,
    license=open("LICENSE").read(),
    classifiers=(
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'Natural Language :: English',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ),
)


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Lee, J. J. , R. Olea, M. Cevasco, X. Pochon, M. Correia, M. Shpigel & J. Pawlowski. 2003. A marine dinoflagellate, <i>Amphidinium eilatiensis</i> n. sp. , from the benthos of a mariculture sedimentation pond in Eilat, Israel. Journal of Eukaryotic Microbiology 50 (6): 439-448.

#### Original name
null

### Remarks
null


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

<title>PackageNameMapper (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tools.ant.util

Class PackageNameMapper

java.lang.Object

org.apache.tools.ant.util.GlobPatternMapper

org.apache.tools.ant.util.PackageNameMapper

All Implemented Interfaces:

FileNameMapper

public class PackageNameMapper
extends GlobPatternMapper

Maps directory name matches into a dotted package name. This is
 useful for matching JUnit test cases againt their XML formatter
 results.

 <mapper classname="org.apache.tools.ant.util.PackageNameMapper"
         from="*Test.java" to="${test.data.dir}/TEST-*Test.xml"/>

Field Summary

Fields inherited from class org.apache.tools.ant.util.GlobPatternMapper

fromPostfix, fromPrefix, postfixLength, prefixLength, toPostfix, toPrefix

Constructor Summary

Constructors

Constructor and Description

PackageNameMapper()

Method Summary

Methods

Modifier and Type
Method and Description

protected java.lang.String
extractVariablePart(java.lang.String name)

Returns the part of the given string that matches the * in the
  "from" pattern replacing file separators with dots

Methods inherited from class org.apache.tools.ant.util.GlobPatternMapper

getHandleDirSep, mapFileName, setCaseSensitive, setFrom, setHandleDirSep, setTo

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PackageNameMapper

public PackageNameMapper()

Method Detail

extractVariablePart

protected java.lang.String extractVariablePart(java.lang.String name)

Returns the part of the given string that matches the * in the
  "from" pattern replacing file separators with dots

Overrides:

extractVariablePart in class GlobPatternMapper

Parameters:

name - Source filename

Returns:

Replaced variable part

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
layout: post
title: Short and sweet introduction to RESTful services
date: 2010-03-12T11:48:00.001Z
author: Marcus Hammarberg
tags:
  - SOA
  - Life of a consultant
modified_time: 2010-03-12T11:48:40.891Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-340756781042224307
blogger_orig_url: http://www.marcusoft.net/2010/03/short-and-sweet-introduction-to-restful.html
---

I have heard a lot about
REST and RESTful services but never have had the
opportunity to work in project that uses that architectural style of
working. So sadly I haven't learned it.

Here is a short and sweet introduction to the
subject that explains REST in a good way.

So – as I understand it – it's just HTTP. The way HTTP is meant to be
(URL to each resource, stateless, hyperlinks between resources and
usages of the HTTP verbs). I like the simplicity.


text:
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using TROPHYParser;

namespace PS3TrophyIsGood
{
    public partial class Form1 : Form
    {
        private const long MINIMUM_POSSIBLE_DATE = 633347424000000000;

        TROPCONF tconf;
        TROPTRNS tpsn;
        TROPUSR tusr;
        string path;
        string pathTemp;
        DateTimePickForm dtpForm = null;
        DateTimePickForm dtpfForInstant = null;
        CopyFrom copyFrom = null;
        bool haveBeenEdited = false;

        DateTime ps3Time = new DateTime(MINIMUM_POSSIBLE_DATE);
        DateTime lastSyncTrophyTime = new DateTime(MINIMUM_POSSIBLE_DATE);
        DateTime randomEndTime = DateTime.Now;

        bool isOpen = false;
        int baseGamaCount;

        private string txtDateTimeTmp;

        public Form1()
        {
            CultureInfo curinfo = null;
            switch (Properties.Settings.Default.Language)
            {
                case 0:
                    curinfo = new CultureInfo("zh-TW");
                    break;
                case 2:
                    curinfo = new CultureInfo("pt-BR");
                    break;
                case 1:
                default:
                    curinfo = CultureInfo.CreateSpecificCulture("en");
                    break;
            }

            Thread.CurrentThread.CurrentCulture = curinfo;
            Thread.CurrentThread.CurrentUICulture = curinfo;
            InitializeComponent();
            toolStripComboBox1.SelectedIndexChanged -= toolStripComboBox1_SelectedIndexChanged;
            toolStripComboBox1.SelectedIndex = Properties.Settings.Default.Language;
            toolStripComboBox1.SelectedIndexChanged += toolStripComboBox1_SelectedIndexChanged;
            Directory.CreateDirectory("profiles");
            var profiles = new DirectoryInfo("profiles").GetFiles("*.sfo").Select(p => p.Name).ToArray();
            toolStripComboBox2.Items.Add("Default Profile");
            toolStripComboBox2.Items.AddRange(profiles);
            toolStripComboBox2.SelectedIndex = 0;
            dateTimePicker1.CustomFormat = Properties.strings.DateFormatString;
            copyFrom = new CopyFrom();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://github.com/darkautism/PS3TrophyIsGood");
            System.Diagnostics.Process.Start("https://www.youtube.com/user/TheDarkNachoXD");
        }

        private void 關閉ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseFile();
            Application.Exit();
        }

        private void 開啟ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                OpenFile(folderBrowserDialog1.SelectedPath);
            }
        }

        private bool ValidateSelectedDate(DateTime selectedDate)
        {
            if (DateTime.Compare(lastSyncTrophyTime, selectedDate) > 0)
            {
                MessageBox.Show(string.Format(Properties.strings.PsnSyncTime, lastSyncTrophyTime.ToString(Properties.strings.DateFormatString)));
                return false;
            }
            return true;
        }

        private void DeleteTrophy(int trophyId, ListViewItem lvi)
        {
            if (IsTrophySync(trophyId))
            {
                MessageBox.Show(Properties.strings.SyncedTrophyCanNotEdit);
            }
            else
            if (trophyId != 0 && tconf[trophyId].gid == 0 && IsTrophyGot(0))
            {
                MessageBox.Show(Properties.strings.CantLoclPlatinumBeforOther);
            }
            else
            if (MessageBox.Show(Properties.strings.DeleteTrophyConfirm, Properties.strings.Delete, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                tpsn.DeleteTrophyByID(trophyId);
                tusr.LockTrophy(trophyId);
                lvi.SubItems[4].Text = Properties.strings.no;
                lvi.BackColor = Color.LightGray;
                lvi.SubItems[6].Text = string.Empty;
                CompletionRates();
                haveBeenEdited = true;
            }
        }

        private bool UnlockTrophy(int trophyId, DateTime trophyTime, ListViewItem lvi)
        {
            if (trophyId == 0 && tconf.HasPlatinium && (GetCountBaseTrophiesGot() < baseGamaCount))
            {
                MessageBox.Show(Properties.strings.CantUnloclPlatinumBeforOther);
                return false;
            }
            else
            {
                if (ValidateSelectedDate(trophyTime))
                {
                    try
                    {
                        tpsn.PutTrophy(trophyId, tusr.trophyTypeTable[trophyId].Type, trophyTime);
                        tusr.UnlockTrophy(trophyId, trophyTime);
                        lvi.SubItems[4].Text = Properties.strings.yes;
                        lvi.BackColor = Color.White;
                        lvi.SubItems[6].Text = trophyTime.ToString(Properties.strings.DateFormatString);
                        CompletionRates();
                        haveBeenEdited = true;
                        return true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
        }

        private bool ChangeTrophyTime(int trophyId, DateTime trophyTime, ListViewItem lvi)
        {
            if (IsTrophySync(trophyId))
            {
                MessageBox.Show(Properties.strings.SyncedTrophyCanNotEdit);
                return false;
            }
            else
            {
                if (ValidateSelectedDate(trophyTime))
                {
                    try
                    {
                        tpsn.ChangeTime(trophyId, trophyTime);
                        TROPUSR.TrophyTimeInfo tti = tusr.trophyTimeInfoTable[trophyId];
                        tti.Time = trophyTime;
                        tusr.trophyTimeInfoTable[trophyId] = tti;
                        lvi.SubItems[6].Text = trophyTime.ToString(Properties.strings.DateFormatString);
                        haveBeenEdited = true;
                        return true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
        }

        private void RefreshComponents()
        {
            EmptyAllComponents();
            listViewEx1.BeginUpdate();
            for (int i = 0; i < tconf.Count; i++)
            {
                listViewEx1.LargeImageList.Images.Add("", Image.FromFile(path + @"\TROP" + string.Format("{0:000}", tconf[i].id) + ".PNG"));
                ListViewItem lvi = new ListViewItem();
                lvi.ImageIndex = i; // 在這裡imageid其實等於trophy ID   ex 白金0號, 1...
                lvi.Text = tconf[i].name;
                lvi.SubItems.Add(tconf[i].detail);
                lvi.SubItems.Add(tconf[i].ttype);
                lvi.SubItems.Add(tconf[i].hidden == "yes" ? Properties.strings.yes : Properties.strings.no);
                if (tpsn[i].HasValue)
                {
                    lvi.SubItems.Add(Properties.strings.yes);
                    lvi.SubItems.Add(tpsn[i].Value.IsSync ? Properties.strings.yes : Properties.strings.no);
                    lvi.SubItems.Add(tpsn[i].Value.Time.ToString(Properties.strings.DateFormatString));
                    lvi.BackColor = (tpsn[i].Value.IsSync ? Color.LightPink : lvi.BackColor = Color.White);
                }
                else
                {
                    lvi.SubItems.Add(tusr.trophyTimeInfoTable[i].IsGet ? Properties.strings.yes : Properties.strings.no);
                    lvi.SubItems.Add(tusr.trophyTimeInfoTable[i].IsSync ? Properties.strings.yes : Properties.strings.no);

                    var tropTimeTxt = string.Empty;
                    if (tusr.trophyTimeInfoTable[i].Time.Ticks > 0)
                    {
                        tropTimeTxt = tusr.trophyTimeInfoTable[i].Time.ToString(Properties.strings.DateFormatString);
                    }
                    lvi.SubItems.Add(tropTimeTxt);

                    if (tusr.trophyTimeInfoTable[i].IsSync)
                        lvi.BackColor = Color.LightPink;
                    else if (tusr.trophyTimeInfoTable[i].IsGet)
                        lvi.BackColor = Color.White;
                    else
                        lvi.BackColor = Color.LightGray;
                }
                if (tconf[i].gid == 0)
                {
                    lvi.SubItems.Add("BaseGame");
                    baseGamaCount = i;
                }
                else lvi.SubItems.Add($"DLC{tconf[i].gid}");

                listViewEx1.Items.Add(lvi);
            }
            listViewEx1.EndUpdate();
            CompletionRates();
        }

        private void EmptyAllComponents()
        {
            listViewEx1.Items.Clear();
            listViewEx1.LargeImageList.Images.Clear();
            listViewEx1.LargeImageList.ImageSize = new Size(50, 50);
            this.Text = Application.ProductName;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
            label2.Text = "00/00";
            label4.Text = "000/000";
        }

        private void CompletionRates()
        {
            int totalGrade = 0, getGrade = 0, isGetTrophyNumber = 0;
            for (int i = 0; i < tconf.Count; i++)
            {
                switch ((TropType)tusr.trophyTypeTable[i].Type)
                {
                    case TropType.Platinum:
                        totalGrade += (int)TropGrade.Platinum;
                        getGrade += IsTrophySync(i) ? (int)TropGrade.Platinum : 0;
                        break;
                    case TropType.Gold:
                        totalGrade += (int)TropGrade.Gold;
                        getGrade += IsTrophySync(i) ? (int)TropGrade.Gold : 0;
                        break;
                    case TropType.Silver:
                        totalGrade += (int)TropGrade.Silver;
                        getGrade += IsTrophySync(i) ? (int)TropGrade.Silver : 0;
                        break;
                    case TropType.Bronze:
                        totalGrade += (int)TropGrade.Bronze;
                        getGrade += IsTrophySync(i) ? (int)TropGrade.Bronze : 0;
                        break;
                }

                if (IsTrophySync(i)) isGetTrophyNumber++;
            }
            progressBar1.Maximum = totalGrade;
            progressBar1.Value = getGrade;
            label2.Text = isGetTrophyNumber + "/" + tconf.Count;
            label4.Text = getGrade + "/" + totalGrade;
            this.Text = Application.ProductName + "-[" + tconf.title_name + "]";
        }

        private bool IsTrophySync(int trophyID)
        {
            return (tpsn[trophyID].HasValue && tpsn[trophyID].Value.IsSync) || tusr.trophyTimeInfoTable[trophyID].IsSync;
        }

        private bool IsTrophyGot(int trophyID)
        {
            return tpsn[trophyID].HasValue || tusr.trophyTimeInfoTable[trophyID].IsGet;
        }

        private int GetCountBaseTrophiesGot()
        {
            int countBaseTrophiesGot = 0;
            for (int i = 0; i < tconf.trophys.Count; i++)
            {
                if (tconf[i].gid == 0 && IsTrophyGot(i))
                {
                    countBaseTrophiesGot++;
                }
            }
            return countBaseTrophiesGot;
        }

        private void listViewEx1_SubItemClicked(object sender, ListViewEx.SubItemEventArgs e)
        {
            int trophyID = e.Item.ImageIndex;// 在這裡imageid其實等於trophy ID   ex 白金0號, 1...
            if (e.SubItem == 6 && !IsTrophySync(trophyID))
            {
                DateTime trophyTime = DateTime.Now;
                if (IsTrophyGot(trophyID))
                {
                    if (tpsn[trophyID].HasValue)
                    {
                        trophyTime = tpsn[trophyID].Value.Time;
                    }
                    else
                    {
                        trophyTime = tusr.trophyTimeInfoTable[trophyID].Time;
                    }
                }
                txtDateTimeTmp = e.Item.SubItems[e.SubItem].Text;
                e.Item.SubItems[e.SubItem].Text = trophyTime.ToString(Properties.strings.DateFormatString);
                listViewEx1.StartEditing(dateTimePicker1, e.Item, e.SubItem);
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                String[] files = (String[])e.Data.GetData(DataFormats.FileDrop);
                if (Directory.Exists(files[0]))
                {
                    e.Effect = DragDropEffects.All;
                }
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            String[] files = (String[])e.Data.GetData(DataFormats.FileDrop);
            OpenFile(files[0]);
        }

        private void 重新整理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshComponents();
        }

        private void listViewEx1_SubItemEndEditing(object sender, ListViewEx.SubItemEndEditingEventArgs e)
        {
            if (isOpen)
            {
                DateTime selectedDate = Convert.ToDateTime(e.DisplayText);
                var trophyID = e.Item.ImageIndex;
                ListViewItem lvi = ((ListView)sender).SelectedItems[0];
                bool trophyChanged;
                if (tpsn[trophyID].HasValue)
                {
                    trophyChanged = ChangeTrophyTime(trophyID, selectedDate, lvi);
                }
                else
                {
                    trophyChanged = UnlockTrophy(trophyID, selectedDate, lvi);
                }

                if (!trophyChanged)
                {
                    e.DisplayText = txtDateTimeTmp;
                }
            }
        }

        private void listViewEx1_DoubleClick(object sender, EventArgs e)
        {
            int trophyID = ((ListView)sender).SelectedItems[0].ImageIndex;// 在這裡imageid其實等於trophy ID   ex 白金0號, 1...
            ListViewItem lvi = ((ListView)sender).SelectedItems[0];
            if (IsTrophySync(trophyID))
            { // 尚未同步的才可編輯
                MessageBox.Show(Properties.strings.SyncedTrophyCanNotEdit);
            }
            else if (tpsn[trophyID].HasValue)
            {
                DeleteTrophy(trophyID, lvi);
            }
            else
            {  // nonget
                if (trophyID == 0 && tconf.HasPlatinium && (GetCountBaseTrophiesGot() < baseGamaCount))
                {
                    MessageBox.Show(Properties.strings.CantUnloclPlatinumBeforOther);
                }
                else if (dtpForm.ShowDialog(this) == DialogResult.OK)
                {
                    UnlockTrophy(trophyID, dtpForm.dateTimePicker1.Value, lvi);
                }
            }
        }

        private void 存檔ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFile();
        }

        private void 關閉檔案CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseFile();
        }

        private DateTime LastTrophyTime()
        {
            if (DateTime.Compare(tpsn.LastTrophyTime, tusr.LastTrophyTime) > 0)
            {
                return tpsn.LastTrophyTime;
            }
            return tusr.LastTrophyTime;
        }

        private void OpenFile(string path_in)
        {
            try
            {
                if (isOpen)
                {
                    CloseFile();
                }
                path = path_in;
                pathTemp = Utility.CopyTrophyDirToTemp(path_in);
                Utility.decryptTrophy(pathTemp);
                tconf = new TROPCONF(pathTemp);
                tpsn = new TROPTRNS(pathTemp);
                tusr = new TROPUSR(pathTemp);

                lastSyncTrophyTime = tusr.LastSyncTime;
                if (DateTime.Compare(tpsn.LastSyncTime, tusr.LastSyncTime) > 0)
                    lastSyncTrophyTime = tpsn.LastSyncTime;

                ps3Time = lastSyncTrophyTime;
                dtpForm = new DateTimePickForm(ps3Time);
                dtpfForInstant = new DateTimePickForm(ps3Time);

                RefreshComponents();
                isOpen = true;
                重新整理ToolStripMenuItem.Enabled = true;
                進階ToolStripMenuItem.Enabled = true;
            }
            catch (FileNotFoundException ex)
            {
                tconf = null;
                tpsn = null;
                tusr = null;
                GC.Collect();
                MessageBox.Show(string.Format(Properties.strings.FileNotFoundMsg, Path.GetFileName(ex.FileName)));
            }
            catch (Exception ex)
            {
                tconf = null;
                tpsn = null;
                tusr = null;
                GC.Collect();
                Console.WriteLine(ex.StackTrace);
                MessageBox.Show(ex.Message);
            }
        }

        private void SaveFile()
        {
            if (isOpen)
            {
                if (listViewEx1.IsEditing)
                    listViewEx1.EndEditing(true);
                tpsn.Save();
                tusr.Save();
                haveBeenEdited = false;
                string encPathTemp = Utility.GetTemporaryDirectory();
                try
                {
                    Utility.CopyTrophyData(pathTemp, encPathTemp, false);
                    Utility.encryptTrophy(encPathTemp, toolStripComboBox2.Text);
                    Utility.CopyTrophyData(encPathTemp, path, true);
                }
                finally
                {
                    Utility.DeleteDirectory(encPathTemp);
                }
                RefreshComponents();
            }
        }

        public bool CloseFile()
        {
            if (listViewEx1.IsEditing)
                listViewEx1.EndEditing(true);
            if (haveBeenEdited)
            {
                DialogResult dr = MessageBox.Show(Properties.strings.CloseConfirm, Properties.strings.Close, MessageBoxButtons.YesNoCancel);
                if (dr == DialogResult.Yes)
                {
                    SaveFile();
                }
                else if (dr == DialogResult.No)
                {
                }
                else
                {
                    return false;
                }
            }

            tpsn = null;
            tusr = null;
            tconf = null;
            path = string.Empty;
            pathTemp = string.Empty;
            haveBeenEdited = false;
            重新整理ToolStripMenuItem.Enabled = false;
            進階ToolStripMenuItem.Enabled = false;
            isOpen = false;
            EmptyAllComponents();
            if (!string.IsNullOrEmpty(pathTemp))
            {
                Utility.DeleteDirectory(new DirectoryInfo(pathTemp).Parent.FullName);
            }
            return true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isOpen)
            {
                e.Cancel = !CloseFile();
            }
        }

        private void 瞬間白金ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Random rand = new Random((int)DateTime.Now.Ticks);
            int i;

            //Base game
            for (i = 1; i < tusr.trophyTimeInfoTable.Count && tconf[i].gid == 0; i++)
            {
                if (!IsTrophyGot(i))
                {
                    tusr.UnlockTrophy(i, new DateTime(Utility.LongRandom(ps3Time.Ticks, randomEndTime.Ticks, rand)));
                    tpsn.PutTrophy(i, tusr.trophyTypeTable[i].Type, new DateTime(Utility.LongRandom(ps3Time.Ticks, randomEndTime.Ticks, rand)));
                }
            }
            //Platinium game
            if (!IsTrophyGot(0))
            {
                tusr.UnlockTrophy(0, LastTrophyTime().AddSeconds(1));
                tpsn.PutTrophy(0, tusr.trophyTypeTable[0].Type, LastTrophyTime().AddSeconds(1));
            }

            //DLC
            for (; i < tusr.trophyTimeInfoTable.Count; i++)
            {
                if (!IsTrophyGot(i))
                {
                    tusr.UnlockTrophy(i, new DateTime(Utility.LongRandom(ps3Time.Ticks, randomEndTime.Ticks, rand)));
                    tpsn.PutTrophy(i, tusr.trophyTypeTable[i].Type, new DateTime(Utility.LongRandom(ps3Time.Ticks, randomEndTime.Ticks, rand)));
                }
            }
            haveBeenEdited = true;
            RefreshComponents();
        }

        private void 清除獎杯ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TROPTRNS.TrophyInfo? ti = tpsn.PopTrophy();
            while (ti.HasValue)
            {
                tusr.LockTrophy(ti.Value.TrophyID);
                ti = tpsn.PopTrophy();
            }
            haveBeenEdited = true;
            RefreshComponents();
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Language = toolStripComboBox1.SelectedIndex;
            Properties.Settings.Default.Save();
            MessageBox.Show(Properties.strings.RestartProgram);
        }

        private void setRandomStartTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtpfForInstant.Title.Text = Properties.strings.RandomStartTime;
            if (dtpfForInstant.ShowDialog() == DialogResult.OK)
            {
                ps3Time = dtpfForInstant.dateTimePicker1.Value;
            }
        }

        private void setRandomEndTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtpfForInstant.Title.Text = Properties.strings.RandomEndTime;
            if (dtpfForInstant.ShowDialog() == DialogResult.OK)
            {
                randomEndTime = dtpfForInstant.dateTimePicker1.Value;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (copyFrom.ShowDialog(this) == DialogResult.OK)
            {
                var _times = copyFrom.checkBox1.Checked ? copyFrom.smartCopy().ToList() : copyFrom.copyFrom().ToList();
                if (_times.Any()) 清除獎杯ToolStripMenuItem_Click(sender, e); // no idea why but sometimes it get bug and it don't update, so lockin first fix it
                try
                {
                    for (int i = 0; i < tusr.trophyTimeInfoTable.Count; ++i)
                    {

                        if (!tpsn[i].HasValue && _times[i] != 0)
                        {
                            var time = _times[i].TimeStampToDateTime();
                            tusr.UnlockTrophy(i, time);
                            tpsn.PutTrophy(i, tusr.trophyTypeTable[i].Type, time);
                        }
                    }
                    haveBeenEdited = true;
                    RefreshComponents();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void menuStrip1_Click(object sender, EventArgs e)
        {
            if (listViewEx1.IsEditing)
                listViewEx1.EndEditing(true);
        }
    }
}


text:
module Sidekiq::Status::Worker
  include Sidekiq::Status::Storage

  class Stopped < StandardError
  end

  attr_accessor :expiration

  # Stores multiple values into a job's status hash,
  # sets last update time
  # @param [Hash] status_updates updated values
  # @return [String] Redis operation status code
  def store(hash)
    store_for_id @jid, hash, @expiration
  end

  # Read value from job status hash
  # @param String|Symbol hask key
  # @return [String]
  def retrieve(name)
    read_field_for_id @jid, name
  end

  # Sets current task progress
  # (inspired by resque-status)
  # @param Fixnum number of tasks done
  # @param String optional message
  # @return [String]
  def at(num, message = nil)
    total(100) if retrieve(:total).nil?
    store(at: num, message: message)
  end

  # Sets total number of tasks
  # @param Fixnum total number of tasks
  # @return [String]
  def total(num)
    store(total: num)
  end

end


text:
@interface Peanut_SNSPart(){
    UIButton *btn1;
    UIButton *btn2;
    UIButton *btn3;
}
@end

@implementation Peanut_SNSPart

-(id)initWithType:(BottomSMSType)type andData:(id)data AndDelegate:(id<Delegate_SNS>)delegate AndTarget:(UIViewController *)target
{
    self=[super init];
    if (self) {
        [self init_Layout];
    }
    return self;
}

-(void)init_Layout
{
    btn1=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:like_icon] forState:UIControlStateNormal];
    [self addSubview:btn1];
    btn1.frame=CGRectMake(SelfScreenbounds.size.width*(0.f+1.f/15.f), self.frame.size.height*0.2, SelfScreenbounds.size.width*0.2, self.frame.size.height*0.6);

    btn2=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:comment_icon] forState:UIControlStateNormal];
    [self addSubview:btn2];
    btn2.frame=CGRectMake(SelfScreenbounds.size.width*(1.f/3.f+1.f/15.f), self.frame.size.height*0.2, SelfScreenbounds.size.width*0.2, self.frame.size.height*0.6);

    btn3=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn3 setImage:[UIImage imageNamed:forward_icon] forState:UIControlStateNormal];
    [self addSubview:btn3];
    btn3.frame=CGRectMake(SelfScreenbounds.size.width*(2.f/3.f+1.f/15.f), self.frame.size.height*0.2, SelfScreenbounds.size.width*0.2, self.frame.size.height*0.6);

}

@end


text:
package io.ontherocks.hellogrpc

import io.grpc.stub.StreamObserver
import io.ontherocks.hellogrpc.clock.ClockGrpc.Clock
import io.ontherocks.hellogrpc.clock.{ ClockGrpc, TimeRequest, TimeResponse }
import monix.execution.Scheduler
import monix.execution.Scheduler.{ global => scheduler }

import scala.concurrent.duration._

object ClockServer extends GrpcServer {

  class ClockService extends Clock {
    def streamTime(request: TimeRequest, responseObserver: StreamObserver[TimeResponse]): Unit =
      scheduler.scheduleWithFixedDelay(0.seconds, 3.seconds) {
        responseObserver.onNext(TimeResponse(System.currentTimeMillis()))
      }
  }

  def main(args: Array[String]): Unit = {
    val ssd = ClockGrpc.bindService(new ClockService(), Scheduler.global)
    runServer(ssd)
  }

}


text:
#include "filtereddatabasemodel.h"
#include "databasemodel.h"
#include <grypto/entry.h>
#include <gutil/variant.h>
USING_NAMESPACE_GUTIL1(Qt);
USING_NAMESPACE_GUTIL;

NAMESPACE_GRYPTO;

FilteredDatabaseModel::FilteredDatabaseModel(QObject *parent)
    :QSortFilterProxyModel(parent)
{
    setDynamicSortFilter(false);
}

void FilteredDatabaseModel::setSourceModel(QAbstractItemModel *m)
{
    if(m && dynamic_cast<DatabaseModel *>(m) == NULL)
        qDebug("Refusing to set model because it's not a DatabaseModel");
    else
        QSortFilterProxyModel::setSourceModel(m);
}

DatabaseModel *FilteredDatabaseModel::_get_database_model() const
{
    return static_cast<DatabaseModel *>(sourceModel());
}

void FilteredDatabaseModel::SetFilter(const FilterInfo_t &fi)
{
    m_index.clear();

    if(sourceModel() && fi.IsValid)
    {
        QRegExp rx(fi.SearchString,
                   fi.IgnoreCase ? ::Qt::CaseInsensitive : ::Qt::CaseSensitive,
                   fi.SearchStringType == fi.Wildcard ? QRegExp::Wildcard : QRegExp::RegExp);

        // Iterate through the entire model and populate the filter index
        _update_index(QModelIndex(), rx, fi);

        setFilterRegExp(rx);
    }
    else
    {
        invalidateFilter();
    }
}

// Returns true if the given row matches or a child row matches
bool FilteredDatabaseModel::_update_index(const QModelIndex &src_ind, const QRegExp &rx, const FilterInfo_t &fi)
{
    bool row_matches = false;
    bool show_anyway = !fi.FilterResults;
    DatabaseModel *m = _get_database_model();

    // First figure out if a child matches
    // Searching causes us to load the entire model
    if(sourceModel()->canFetchMore(src_ind))
        sourceModel()->fetchMore(src_ind);

    // Figure out if this row matches
    Entry const *e = m->GetEntryFromIndex(src_ind);
    if(src_ind.isValid())
    {
        // Check if the row fits the pre-filter criteria
        bool matches_pre_filters = true;
        if(matches_pre_filters && fi.ShowOnlyFavorites)
            matches_pre_filters = e->IsFavorite();

        if(matches_pre_filters && fi.ShowOnlyFiles)
            matches_pre_filters = !e->GetFileId().IsNull();

        // If it's outside the given date range then it doesn't match
        if(matches_pre_filters && (fi.StartTime.isValid() || fi.EndTime.isValid()))
        {
            if(fi.StartTime.isValid() && fi.EndTime.isValid())
                matches_pre_filters = fi.StartTime <= e->GetModifyDate() &&
                        e->GetModifyDate() <= fi.EndTime;
            else if(fi.StartTime.isValid())
                matches_pre_filters = fi.StartTime <= e->GetModifyDate();
            else
                matches_pre_filters = e->GetModifyDate() <= fi.EndTime;
        }

        if(matches_pre_filters)
        {
            // Only check the search string if the pre-filters matched
            if(rx.pattern().isEmpty())
                show_anyway = true;
            else
            {
                row_matches =
                        -1 != e->GetName().indexOf(rx) ||
                        -1 != e->GetDescription().indexOf(rx) ||
                        -1 != e->GetFileName().indexOf(rx);

                for(int i = 0; !row_matches && i < e->Values().count(); ++i)
                {
                    row_matches = -1 != e->Values()[i].GetNotes().indexOf(rx);

                    // Only search the secret values if the user elects to
                    if(!row_matches && fi.AlsoSearchSecrets)
                        row_matches = -1 != e->Values()[i].GetValue().indexOf(rx);
                }
            }
        }

        // Show a row if any of its ancestors matches
        if(!row_matches && !show_anyway && !e->GetParentId().IsNull())
        {
            QModelIndex par = src_ind.parent();
            while(!show_anyway && par.isValid()){
                if(m_index[m->GetEntryFromIndex(par)->GetId()].row_matches)
                    show_anyway = true;
                par = par.parent();
            }
        }

        m_index.insert(e->GetId(), filtered_state_t(show_anyway, row_matches));
    }

    // After updating the index with this node, descend to the child nodes
    bool show_afterwards = false;
    for(int i = 0; i < sourceModel()->rowCount(src_ind); ++i){
        if(_update_index(sourceModel()->index(i, 0, src_ind), rx, fi))
            show_afterwards = true;
    }

    if(src_ind.isValid() && !show_anyway && show_afterwards)
        m_index[e->GetId()].show_anyway = true;

    return show_anyway || show_afterwards || row_matches;
}

bool FilteredDatabaseModel::filterAcceptsRow(int src_row, const QModelIndex &src_par) const
{
    bool ret = true;
    if(!m_index.isEmpty())
    {
        Entry const *e = _get_database_model()->
                GetEntryFromIndex(sourceModel()->index(src_row, 0, src_par));

        if(m_index.contains(e->GetId())){
            const filtered_state_t &fs = m_index[e->GetId()];
            ret = fs.show_anyway | fs.row_matches;
        }
    }
    return ret;
}

QModelIndexList FilteredDatabaseModel::GetUnfilteredRows() const
{
    QModelIndexList ret;
    if(!m_index.isEmpty())
    {
        DatabaseModel *m = _get_database_model();
        foreach(const EntryId &eid, m_index.keys())
        {
            if(m_index[eid].row_matches)
            {
                QModelIndex src_ind = m->FindIndexById(eid);
                if(src_ind.isValid())
                    ret.append(mapFromSource(src_ind));
            }
        }
    }
    return ret;
}

QString FilterInfo_t::ToXml() const
{
    QVariantList vl;
    if(IsValid){
        vl.append(SearchString);
        vl.append(FilterResults);
        vl.append(IgnoreCase);
        vl.append(ShowOnlyFavorites);
        vl.append(ShowOnlyFiles);
        vl.append(AlsoSearchSecrets);
        vl.append((int)SearchStringType);
        vl.append(StartTime);
        vl.append(EndTime);
    }
    return Variant(vl).ToXmlQString();
}

FilterInfo_t FilterInfo_t::FromXml(const QString &xml)
{
    Variant v;
    v.FromXmlQString(xml);
    if(v.type() != QVariant::List)
        throw XmlException<>();

    QVariantList vl = v.toList();

    // Return an invalid filter info
    if(vl.length() != 6)
        return FilterInfo_t();

    FilterInfo_t ret(vl[0].toString(),
            vl[1].toBool(),
            vl[2].toBool(),
            vl[3].toBool(),
            vl[4].toBool(),
            vl[5].toBool(),
            (FilterInfo_t::StringType)vl[6].toInt());
    ret.StartTime = vl[7].toDateTime();
    ret.EndTime = vl[8].toDateTime();
    return ret;
}

END_NAMESPACE_GRYPTO;


text:
=================================
django-ckeditor-filebrowser-filer
=================================

|Gitter| |PyPiVersion| |PyVersion| |License|

A django-filer based CKEditor filebrowser

Supported versions
==================

Python: 2.7, 3.5, 3.6, 2.7

Django: 1.11 to 2.1

django-filer: 1.2 and above

Documentation
-------------

Original code is taken from `django-ckeditor-filer`_

It supports both ckeditor widget provided by `django-ckeditor`_ and the one provided
by `djangocms-text-ckeditor`_.

.. warning:: if you are using filer<1.2 this plugin requires `django CMS`_
  `cmsplugin_filer_image`_, thus you need to install and configure both according
  to their respective documentation.

Quickstart
----------

* Install django-ckeditor-filebrowser-filer::

    pip install django-ckeditor-filebrowser-filer

* Add it to INSTALLED_APPS along with its dependencies::

    'filer',
    'ckeditor_filebrowser_filer',

* Configure django-filer `Canonical URLs`_

* Add `ckeditor_filebrowser_filer` to urlconf::

    url(r'^filebrowser_filer/', include('ckeditor_filebrowser_filer.urls')),

  Currently only ``filebrowser_filer/`` is supported as url path

* Add `FilerImage` button to you CKEditor configuration:

  * Add ``'FilerImage'`` to a toolbar in ``CKEDITOR_CONFIGS``
  * Add ``'filerimage'`` in `` 'extraPlugins'`` in ``CKEDITOR_CONFIGS``
  * Add ``'image'`` in `` 'removePlugins'`` in ``CKEDITOR_CONFIGS``

Example::

    CKEDITOR_CONFIGS = {
        'default': {
            'toolbar': 'Custom',
            'toolbar_Custom': [
                ...
                ['FilerImage']
            ],
            'extraPlugins': 'filerimage',
            'removePlugins': 'image'
        },
    }

when using `djangocms-text-ckeditor`_ use ``CKEDITOR_SETTINGS`` instead of
``CKEDITOR_CONFIGS``.

.. _Canonical URLs: https://django-filer.readthedocs.io/en/latest/installation.html#canonical-urls
.. _django CMS: https://pypi.python.org/pypi/django-cms
.. _django-filer: https://pypi.python.org/pypi/django-filer
.. _cmsplugin_filer_image: https://pypi.python.org/pypi/cmsplugin_filer_image
.. _django-ckeditor: https://pypi.python.org/pypi/django-ckeditor
.. _djangocms-text-ckeditor: https://pypi.python.org/pypi/djangocms-text-ckeditor
.. _django-ckeditor-filer: https://github.com/ikresoft/django-ckeditor-filer/

.. |Gitter| image:: https://img.shields.io/badge/GITTER-join%20chat-brightgreen.svg?style=flat-square
    :target: https://gitter.im/nephila/applications
    :alt: Join the Gitter chat

.. |PyPiVersion| image:: https://img.shields.io/pypi/v/django-ckeditor-filebrowser-filer.svg?style=flat-square
    :target: https://pypi.python.org/pypi/django-ckeditor-filebrowser-filer
    :alt: Latest PyPI version

.. |PyVersion| image:: https://img.shields.io/pypi/pyversions/django-ckeditor-filebrowser-filer.svg?style=flat-square
    :target: https://pypi.python.org/pypi/django-ckeditor-filebrowser-filer
    :alt: Python versions

.. |Status| image:: https://img.shields.io/travis/nephila/django-ckeditor-filebrowser-filer.svg?style=flat-square
    :target: https://travis-ci.org/nephila/django-ckeditor-filebrowser-filer
    :alt: Latest Travis CI build status

.. |TestCoverage| image:: https://img.shields.io/coveralls/nephila/django-ckeditor-filebrowser-filer/master.svg?style=flat-square
    :target: https://coveralls.io/r/nephila/django-ckeditor-filebrowser-filer?branch=master
    :alt: Test coverage

.. |License| image:: https://img.shields.io/github/license/nephila/django-ckeditor-filebrowser-filer.svg?style=flat-square
   :target: https://pypi.python.org/pypi/django-ckeditor-filebrowser-filer/
    :alt: License

.. |CodeClimate| image:: https://codeclimate.com/github/nephila/django-ckeditor-filebrowser-filer/badges/gpa.svg?style=flat-square
   :target: https://codeclimate.com/github/nephila/django-ckeditor-filebrowser-filer
   :alt: Code Climate


text:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using DotAspect.BuildTask.PostProcessing;
using NUnit.Framework;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;

namespace DotAspect.BuildTask.Test
{
    [TestFixture]
    public class TypeAspectCodeInjectorBehavior
    {
        [Test]
        public void ShouldNotProcessClassWithoutAspects()
        {
            var module = TestTools.CreteTestModule();
            var сlassWithoutAspects = DefineTypeWithoutAspects(module);

            var classInjector = new ClassAspectCodeInjector(module) { MakeFiledPublic = true};
            var moduleInjector = new ModuleAspectCodeInjector(module, classInjector);
            moduleInjector.Process();

            var aspectCollectionField = сlassWithoutAspects.Fields.FirstOrDefault(f => f.Name == ClassAspectCodeInjector.AspectCollectionFieldName);

            Assert.IsNull(aspectCollectionField);
        }

        [Test]
        public void ShouldProcessClassWithAspects()
        {
            var assemblyResolver = new DefaultAssemblyResolver();
            assemblyResolver.AddSearchDirectory(TestContext.CurrentContext.TestDirectory);

            var assembly = AssemblyDefinition.CreateAssembly(
                new AssemblyNameDefinition("TestAssembly", new Version()),
                "TestModule",
                new ModuleParameters
                {
                    Kind = ModuleKind.Dll,
                    AssemblyResolver = assemblyResolver
                });
            var module = assembly.MainModule;

            var сlassWithAspects = DefineTypeWithAspects(module);

            var classInjector = new ClassAspectCodeInjector(module) { MakeFiledPublic = true };
            var moduleInjector = new ModuleAspectCodeInjector(module, classInjector);
            moduleInjector.Process();

            module.Assembly.Write("output.dll");

            Assembly a;
            using (var memory = new MemoryStream())
            {
                module.Assembly.Write(memory);
                a = Assembly.ReflectionOnlyLoad(memory.ToArray());
            }

            var type = a.GetTypes().Single(t => t.FullName == сlassWithAspects.FullName);
            var aspectField = type.GetField(ClassAspectCodeInjector.AspectCollectionFieldName);

            Assert.IsNotNull(aspectField);
            Assert.IsTrue(aspectField.IsPublic);//Only for test
            Assert.IsTrue(aspectField.IsStatic);
        }

        TypeDefinition DefineTypeWithoutAspects(ModuleDefinition module)
        {
            var type = new TypeDefinition("", "ClassWithoutAspects", TypeAttributes.Class);
            type.Methods.Add(new MethodDefinition("Foo", MethodAttributes.Public, module.ImportReference(typeof(void))));

            module.Types.Add(type);

            return type;
        }

        TypeDefinition DefineTypeWithAspects(ModuleDefinition module)
        {
            var objectType = module.ImportReference(typeof(object));
            var type = new TypeDefinition("", "ClassWithAspects", TypeAttributes.Class, objectType);

            module.Types.Add(type);

            var fooMethod = new MethodDefinition("Foo", MethodAttributes.Public, module.ImportReference(typeof(void)));
            var foo2Method = new MethodDefinition("Foo2", MethodAttributes.Public, module.ImportReference(typeof(int)));
            var foo3Method = new MethodDefinition("Foo3", MethodAttributes.Public, module.ImportReference(typeof(object)));
            type.Methods.Add(fooMethod);
            type.Methods.Add(foo2Method);
            type.Methods.Add(foo3Method);

            fooMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            foo2Method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, 10));
            foo2Method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            foo3Method.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "test"));
            foo3Method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            var aspAttrType = module.ImportReference(typeof(TestAspectAttribute)).Resolve();
            var aspectAttrCtor = aspAttrType.GetConstructors().Single(c => !c.HasParameters);

            var importedCtor = module.ImportReference(aspectAttrCtor);
            var aspectAttribute = new CustomAttribute(importedCtor);
            fooMethod.CustomAttributes.Add(aspectAttribute);
            foo2Method.CustomAttributes.Add(aspectAttribute);
            foo3Method.CustomAttributes.Add(aspectAttribute);

            return type;
        }
    }
}


text:
require 'spec_helper'

describe Isomer::Sources::Yaml do
  describe '#get' do
    context 'when the file exists' do
      before do
        allow(File).to receive(:exists?).and_return(true)
      end

      it 'only loads the file once' do
        expect(YAML).to receive(:load_file).with('/home/configuration.yml').once.and_return({})

        source = described_class.new('/home/configuration.yml')
        2.times { source.get('foo') }
      end

      context 'when file does not load into a hash' do
        it 'returns nil for configuration parameters' do
          allow(YAML).to receive(:load_file).and_return('string value')
          source = described_class.new('anything.yml')

          expect(source.get('foo')).to be_nil
        end
      end

      context 'when the file loads as a hash' do
        it 'returns configuration values from corresponding hash parameters' do
          allow(YAML).to receive(:load_file).and_return({'foo' => 'bar'})
          source = described_class.new('anything.yml')

          expect(source.get('foo')).to eq('bar')
        end

        it 'returns nil if the corresponding hash parameter does not exist' do
          allow(YAML).to receive(:load_file).and_return({})
          source = described_class.new('anything.yml')

          expect(source.get('foo')).to be_nil
        end

        context 'with a base' do
          it 'returns configuration values from corresponding hash parameters under the base node' do
            allow(YAML).to receive(:load_file).and_return('production' => {'limit' => 100})
            source = described_class.new(anything, base: 'production')

            expect(source.get('limit')).to eq(100)
          end

          it 'returns nil if the corresponding hash parameter does not exist under the base node' do
            allow(YAML).to receive(:load_file).and_return('production' => {})
            source = described_class.new(anything, base: 'production')

            expect(source.get('foo')).to be_nil
          end
        end
      end
    end

    context 'when the file does not exist' do
      before do
        allow(File).to receive(:exists?).and_return(false)
      end

      context 'when it is not required' do
        it 'does not blow up' do
          source = described_class.new('anything.yml')
          expect { source.get(anything) }.to_not raise_error
        end

        it 'returns nil for configuration values' do
          source = described_class.new('anything.yml')
          expect(source.get('anything')).to be_nil
        end
      end

      context 'when it is required' do
        it 'raises an error' do
          source = described_class.new('/home/configuration.yml', required: true)

          expect {
            source.get(anything)
          }.to raise_error(Isomer::Error, "Missing required configuration file '/home/configuration.yml'")
        end
      end
    end
  end
end


text:
package daemon

import (
	"fmt"
	"strings"

	"github.com/docker/docker/container"
	"github.com/docker/docker/daemon/names"
	"github.com/docker/docker/errdefs"
	"github.com/docker/docker/pkg/namesgenerator"
	"github.com/docker/docker/pkg/stringid"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

var (
	validContainerNameChars   = names.RestrictedNameChars
	validContainerNamePattern = names.RestrictedNamePattern
)

func (daemon *Daemon) registerName(container *container.Container) error {
	if daemon.Exists(container.ID) {
		return fmt.Errorf("Container is already loaded")
	}
	if err := validateID(container.ID); err != nil {
		return err
	}
	if container.Name == "" {
		name, err := daemon.generateNewName(container.ID)
		if err != nil {
			return err
		}
		container.Name = name
	}
	return daemon.containersReplica.ReserveName(container.Name, container.ID)
}

func (daemon *Daemon) generateIDAndName(name string) (string, string, error) {
	var (
		err error
		id  = stringid.GenerateNonCryptoID()
	)

	if name == "" {
		if name, err = daemon.generateNewName(id); err != nil {
			return "", "", err
		}
		return id, name, nil
	}

	if name, err = daemon.reserveName(id, name); err != nil {
		return "", "", err
	}

	return id, name, nil
}

func (daemon *Daemon) reserveName(id, name string) (string, error) {
	if !validContainerNamePattern.MatchString(strings.TrimPrefix(name, "/")) {
		return "", errdefs.InvalidParameter(errors.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars))
	}
	if name[0] != '/' {
		name = "/" + name
	}

	if err := daemon.containersReplica.ReserveName(name, id); err != nil {
		if err == container.ErrNameReserved {
			id, err := daemon.containersReplica.Snapshot().GetID(name)
			if err != nil {
				logrus.Errorf("got unexpected error while looking up reserved name: %v", err)
				return "", err
			}
			return "", nameConflictError{id: id, name: name}
		}
		return "", errors.Wrapf(err, "error reserving name: %q", name)
	}
	return name, nil
}

func (daemon *Daemon) releaseName(name string) {
	daemon.containersReplica.ReleaseName(name)
}

func (daemon *Daemon) generateNewName(id string) (string, error) {
	var name string
	for i := 0; i < 6; i++ {
		name = namesgenerator.GetRandomName(i)
		if name[0] != '/' {
			name = "/" + name
		}

		if err := daemon.containersReplica.ReserveName(name, id); err != nil {
			if err == container.ErrNameReserved {
				continue
			}
			return "", err
		}
		return name, nil
	}

	name = "/" + stringid.TruncateID(id)
	if err := daemon.containersReplica.ReserveName(name, id); err != nil {
		return "", err
	}
	return name, nil
}

func validateID(id string) error {
	if id == "" {
		return fmt.Errorf("Invalid empty id")
	}
	return nil
}


text:
<?xml version="1.0"?>

<!--
   Copyright 2008 University of Rochester

   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.
-->

<!DOCTYPE hibernate-mapping SYSTEM
			"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
	Mapping for an Personal Collection.

	@author Nathan Sarr
-->
<hibernate-mapping package="edu.ur.ir.user">
	<class name="PersonalCollection" table="ir_user.personal_collection"
		lazy="true">

		<!-- Common id property. -->
		<id name="id" type="long" column="personal_collection_id"
			unsaved-value="0" access="field">
			<generator class="sequence">
				<param name="sequence">ir_user.personal_collection_seq</param>
			</generator>
		</id>

		<!-- A versioned entity. -->
		<version name="version" column="version"
			access="org.hibernate.property.DirectPropertyAccessor" />

		<property name="name" column="name" type="string"
			not-null="true" access="field" />

		<property name="description" column="description" type="string"
			not-null="false" />

		<property name="leftValue" column="left_value" type="long"
			not-null="true" access="field" />

		<property name="rightValue" column="right_value" type="long"
			not-null="true" access="field" />

		<property name="path" column="path" type="string"
			not-null="false" access="field" />

		<!--  Parent Folder -->
		<many-to-one class="PersonalCollection"
			name="parent" column="parent_id" insert="true"
			update="true" access="field"/>

		<!--  Children collections - cannot cascade the delete orphan because child
		collections can be promoted to root  -->
		<set name="children" inverse="true"
		    cascade="all"
		    access="field"
		    optimistic-lock="false"
			fetch="subselect"
			lazy="true">
			<key column="parent_id"/>
			<one-to-many class="PersonalCollection"/>
		</set>

	    <!--  Root Personal Collection of the tree-->
		<many-to-one class="PersonalCollection"
			name="treeRoot"
			column="root_personal_collection_id"
			insert="true"
			update="true"
			access="field"/>

		<!--  Children items - cannot cascade the delete orphan because child
		collections can be promoted to root  -->
		<set name="personalItems"
		    inverse="true"
		    cascade="all"
		    optimistic-lock="false"
		    access="field"
		    lazy="true"
		    fetch="subselect">
			<key column="personal_collection_id" not-null="true"/>
			<one-to-many class="PersonalItem"/>
		</set>

	    <!-- User this personal collection belongs to -->
		<many-to-one class="IrUser"
			name="owner"
			column="user_id"
			insert="true"
			update="true"
			unique="true"/>
	</class>

	<!-- named query for getting a root personal collection by name/user -->
	<query name="getRootPersonalCollectionByNameUser">
		from PersonalCollection as PersonalCollection where
		PersonalCollection.name = ?
		and PersonalCollection.owner.id = ?
		and PersonalCollection.id = PersonalCollection.treeRoot.id
	</query>

	<query name="getAllPersonalItemsForCollection">
	    from PersonalItem as personalItem
	    where  personalItem.personalCollection.leftValue between ? and ?
	    and personalItem.personalCollection.treeRoot.id = ?
	</query>

	<!-- named query for getting a personal collection by name parent id -->
	<query name="getPersonalCollectionByNameParent">
		from PersonalCollection as PersonalCollection where
		PersonalCollection.name = ?
		and PersonalCollection.parent.id = ?
	</query>

	<!--  Get all personal collections that have a left or right value greater than the
           specified value -->
	<query name="getAllPersonalCollectionsValueGreaterEqual">
	   from PersonalCollection as personalCollection
	   where ( personalCollection.leftValue >= ?
	   or personalCollection.rightValue >= ? )
	   and personalCollection.treeRoot.id = ?
	</query>

	<!-- Gets the all personal collections within the specified tree
	     that are not within the child tree
         Specified.  This only works across the specified root personal collection -->
	<query name="getAllPersonalCollectionsNotInChildTree">
	    from PersonalCollection as personalCollection
	    where personalCollection.owner.id = ?
	    and personalCollection.treeRoot.id = ?
	    and personalCollection.leftValue not between ? and ?
	    order by personalCollection.name
	</query>

	<!-- Gets all collections for the specified repository-->
	<query name="getPersonalCollectionsForUser">
	    from PersonalCollection as personalCollection
	    where personalCollection.owner.id = ?
	    order by personalCollection.name
	</query>

    <!-- Gets the path for a given collection-->
	<query name="getPersonalCollectionPath">
	    from PersonalCollection as personalCollection
	    where ? between personalCollection.leftValue and personalCollection.rightValue
	    and personalCollection.treeRoot.id = ?
	    and personalCollection.owner.id = ?
	    order by personalCollection.leftValue
	</query>

	<!-- Get root collections for a user -->
	<query name="getRootPersonalCollections">
	    from PersonalCollection as personalCollection
	    where personalCollection.owner.id = ?
	    and personalCollection.id = personalCollection.treeRoot.id
	</query>

	<!-- Gets all sub collections within the parent collection -->
	<query name="getPersonalSubCollectionsForCollection">
	    from PersonalCollection as personalCollection
	    where personalCollection.owner.id = ?
	    and personalCollection.parent.id = ?
	</query>

	<!-- Get specified collections for user -->
	<query name="getAllPersonalCollectionsInList">
	   from PersonalCollection as personalCollection
	    where personalCollection.owner.id = :ownerId
	    and personalCollection.id in (:collections)
	</query>

	<!-- Get specified collections not in list for user -->
	<query name="getAllOtherRootCollections">
	   from PersonalCollection as personalCollection
	    where personalCollection.owner.id = :ownerId
	    and personalCollection.treeRoot.id not in (:collections)
	</query>

</hibernate-mapping>


text:
using System;

namespace Model
{
	public class Review
	{
		public Guid Id { set; get;}
		public string Text { set; get; }
		public int Rating { set; get; }
		public Guid UserId { get; set; }
		public Guid EventId { get; set; }
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  #%L
  wcm.io
  %%
  Copyright (C) 2015 wcm.io
  %%
  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.
  #L%
  -->

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

  <parent>
    <groupId>io.wcm.devops.conga</groupId>
    <artifactId>io.wcm.devops.conga.parent</artifactId>
    <version>1.14.13-SNAPSHOT</version>
    <relativePath>../parent/pom.xml</relativePath>
  </parent>

  <artifactId>io.wcm.devops.conga.model</artifactId>
  <packaging>jar</packaging>

  <name>CONGA Model</name>
  <description>wcm.io DevOps CONGA Model classes for java representation of definition files.</description>

  <dependencies>

    <dependency>
      <groupId>io.wcm.devops.conga</groupId>
      <artifactId>io.wcm.devops.conga.resource</artifactId>
      <version>1.14.13-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.yaml</groupId>
      <artifactId>snakeyaml</artifactId>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <scope>compile</scope>
    </dependency>

  </dependencies>

  <build>

    <plugins>

      <plugin>
        <groupId>io.wcm.devops.maven.plugins</groupId>
        <artifactId>eclipse-maven-plugin</artifactId>
        <configuration>
          <addVersionToProjectName>false</addVersionToProjectName>
        </configuration>
      </plugin>

      <!-- do not generate site for this project -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <inherited>false</inherited>
        <configuration>
          <skip>true</skip>
          <skipDeploy>true</skipDeploy>
        </configuration>
      </plugin>

    </plugins>
  </build>

</project>


text:
Mime::Type.register 'application/data_table', :data_table

ActionController::Responder.send :include, DataTablesResponder
InheritedResources::Responder.send :include, DataTablesResponder if defined? InheritedResources


text:
package com.github.dreamhead.moco.parser.model;

import com.github.dreamhead.moco.Moco;
import com.github.dreamhead.moco.RequestExtractor;
import com.github.dreamhead.moco.ResponseHandler;
import com.github.dreamhead.moco.handler.failover.Failover;
import com.github.dreamhead.moco.parser.ResponseHandlerFactory;
import com.github.dreamhead.moco.resource.ContentResource;
import com.github.dreamhead.moco.resource.Resource;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import static com.github.dreamhead.moco.Moco.attachment;
import static com.github.dreamhead.moco.Moco.latency;
import static com.github.dreamhead.moco.Moco.proxy;
import static com.github.dreamhead.moco.Moco.status;
import static com.github.dreamhead.moco.Moco.template;
import static com.github.dreamhead.moco.Moco.toJson;
import static com.github.dreamhead.moco.Moco.var;
import static com.github.dreamhead.moco.Moco.version;
import static com.github.dreamhead.moco.Moco.with;
import static com.github.dreamhead.moco.handler.AndResponseHandler.and;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.collect.ImmutableMap.copyOf;
import static com.google.common.collect.ImmutableSet.of;
import static java.lang.String.format;

public class DynamicResponseHandlerFactory extends Dynamics implements ResponseHandlerFactory {
    private static final ImmutableSet<String> RESOURCES = of("text", "file", "pathResource", "version");
    private static final ImmutableMap<String, String> COMPOSITES = ImmutableMap.<String, String>builder()
            .put("headers", "header")
            .put("cookies", "cookie")
            .build();

    @Override
    public ResponseHandler createResponseHandler(final ResponseSetting responseSetting) {
        FluentIterable<ResponseHandler> handlers = from(getFields(responseSetting.getClass()))
                .filter(isValidField(responseSetting))
                .transform(fieldToResponseHandler(responseSetting));
        return getResponseHandler(handlers.toList());
    }

    private ResponseHandler getResponseHandler(final ImmutableList<ResponseHandler> list) {
        if (list.size() == 1) {
            return list.get(0);
        }

        return and(list);
    }

    private boolean isResource(final String name) {
        return RESOURCES.contains(name);
    }

    private Function<Field, ResponseHandler> fieldToResponseHandler(final ResponseSetting response) {
        return new Function<Field, ResponseHandler>() {
            @Override
            public ResponseHandler apply(final Field field) {
                try {
                    Object value = field.get(response);
                    return createResponseHandler(field.getName(), value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    private ResponseHandler createResponseHandler(final String name, final Object value) {
        if ("json".equalsIgnoreCase(name)) {
            return toJson(value);
        }

        if (isResource(name) && TextContainer.class.isInstance(value)) {
            TextContainer container = TextContainer.class.cast(value);
            return with(resourceFrom(name, container));
        }

        if (Map.class.isInstance(value)) {
            return createCompositeHandler(name, castToMap(value));
        }

        if ("status".equalsIgnoreCase(name)) {
            return status(Integer.parseInt(value.toString()));
        }

        if ("latency".equalsIgnoreCase(name)) {
            LatencyContainer container = LatencyContainer.class.cast(value);
            return with(latency(container.getLatency(), container.getUnit()));
        }

        if (ProxyContainer.class.isInstance(value)) {
            return createProxy((ProxyContainer) value);
        }

        if ("attachment".equalsIgnoreCase(name)) {
            AttachmentSetting attachment = (AttachmentSetting) value;
            return attachment(attachment.getFilename(), resourceFrom(attachment));
        }

        throw new IllegalArgumentException(format("unknown field [%s]", name));
    }

    private Field getField(final Class<?> clazz, final String name) throws NoSuchFieldException {
        try {
            return clazz.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            Class<?> superclass = clazz.getSuperclass();
            if (superclass != null) {
                return getField(superclass, name);
            }
            throw e;
        }
    }

    private Resource resourceFrom(final BaseResourceSetting resourceSetting) {
        for (String resource : RESOURCES) {
            try {
                Field field = getField(resourceSetting.getClass(), resource);
                return resourceFrom(resource, (TextContainer) field.get(resourceSetting));
            } catch (Exception ignored) {
            }
        }

        throw new IllegalArgumentException("resourceSetting is expected");
    }

    private ResponseHandler createCompositeHandler(final String name, final Map<String, TextContainer> map) {
        ImmutableList<ResponseHandler> handlers = from(map.entrySet()).transform(toTargetHandler(name)).toList();
        return getResponseHandler(handlers);
    }

    private Function<Map.Entry<String, TextContainer>, ResponseHandler> toTargetHandler(final String name) {
        return new Function<Map.Entry<String, TextContainer>, ResponseHandler>() {
            @Override
            public ResponseHandler apply(final Map.Entry<String, TextContainer> pair) {
                String result = COMPOSITES.get(name);
                if (result == null) {
                    throw new RuntimeException("unknown composite handler name [" + name + "]");
                }

                return createResponseHandler(pair, result);
            }
        };
    }

    private ResponseHandler createResponseHandler(final Map.Entry<String, TextContainer> pair,
                                                  final String targetMethodName) {
        TextContainer container = pair.getValue();
        try {
            if (container.isForTemplate()) {
                Method method = Moco.class.getMethod(targetMethodName, String.class, Resource.class);
                return (ResponseHandler) method.invoke(null, pair.getKey(), template(container.getText()));
            }

            Method method = Moco.class.getMethod(targetMethodName, String.class, String.class);
            return (ResponseHandler) method.invoke(null, pair.getKey(), container.getText());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    private Map<String, TextContainer> castToMap(final Object value) {
        return Map.class.cast(value);
    }

    private Resource resourceFrom(final String name, final TextContainer container) {
        if (container.isRawText()) {
            return invokeTarget(name, container.getText(), Resource.class);
        }

        if (container.isForTemplate()) {
            if ("version".equalsIgnoreCase(name)) {
                return version(template(container.getText()));
            }

            return createTemplate(name, container);
        }

        if (container.isFileContainer()) {
            Optional<Resource> resource = fileResource(name, container);
            if (resource.isPresent()) {
                return resource.get();
            }
        }

        throw new IllegalArgumentException(format("unknown operation [%s]", container.getOperation()));
    }

    private Optional<Resource> fileResource(final String name, final TextContainer container) {
        FileContainer fileContainer = FileContainer.class.cast(container);
        TextContainer filename = fileContainer.getName();
        if (filename.isRawText()) {
            return Optional.of(invokeTarget(name, fileContainer.getName().getText(), fileContainer.getCharset(),
                    Resource.class, String.class, Optional.class));
        }

        if (filename.isForTemplate()) {
            return Optional.of(invokeTarget(name, createTemplate("text", filename), fileContainer.getCharset(),
                    Resource.class, Resource.class, Optional.class));
        }

        return Optional.absent();
    }

    private Resource createTemplate(final String name, final TextContainer container) {
        if (container.hasProperties()) {
            return template(invokeTarget(name, container.getText(), ContentResource.class),
                    toVariables(container.getProps()));
        }

        return template(invokeTarget(name, container.getText(), ContentResource.class));
    }

    public static ImmutableMap<String, RequestExtractor<?>> toVariables(final Map<String, TextContainer> props) {
        return copyOf(Maps.transformEntries(props, toVariable()));
    }

    private static Maps.EntryTransformer<String, TextContainer, RequestExtractor<?>> toVariable() {
        return new Maps.EntryTransformer<String, TextContainer, RequestExtractor<?>>() {
            @Override
            public RequestExtractor<?> transformEntry(final String key, final TextContainer value) {
                if (value.isRawText()) {
                    return var(value.getText());
                }

                return createRequestExtractor(getExtractorMethod(value.getOperation()), value.getText());
            }
        };
    }

    private ResponseHandler createProxy(final ProxyContainer proxy) {
        Failover failover = proxy.getFailover();

        if (proxy.hasProxyConfig()) {
            return proxy(proxy.getProxyConfig(), failover);
        }

        return proxy(proxy.getUrl(), failover);
    }
}


text:
<?php
namespace Moss\Http\Router;

class RouterTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var Router
     */
    protected $router;

    protected function mockRequest($path, $host = 'test.com')
    {
        $bag = $this->getMock('Moss\Bag\BagInterface');

        $request = $this->getMock('Moss\Http\request\RequestInterface');

        $request
            ->expects($this->any())
            ->method('query')
            ->will($this->returnValue($bag));

        $request
            ->expects($this->any())
            ->method('schema')
            ->will($this->returnValue('http'));

        $request
            ->expects($this->any())
            ->method('host')
            ->will($this->returnValue($host));

        $request
            ->expects($this->any())
            ->method('baseName')
            ->will($this->returnValue('http://'.$host));

        $request
            ->expects($this->any())
            ->method('path')
            ->will($this->returnValue($path));

        return $request;
    }

    public function testRetrieve()
    {
        $route = new Route('/router/', 'router');
        $expected['route'] = $route;

        $router = new Router();
        $router->register('route', $route);
        $this->assertEquals($expected, $router->retrieve());
    }

    /**
     * @expectedException \Moss\Http\Router\RouterException
     * @expectedExceptionMessage Route for "/missing-route/" not found!
     */
    public function testMatchRouteNotExists()
    {
        $router = new Router();
        $router->match($this->mockRequest('/missing-route/'));
    }

    public function testMatchWithMultipleArguments()
    {
        $router = new Router();
        $router->register('route', new Route('/router/{foo:\w}/({bar:\d})/', 'controller'));

        $controller = $router->match($this->mockRequest('/router/foo/123/', null));

        $this->assertEquals('controller', $controller);
    }

    public function testMatchWithoutOptionalArguments()
    {
        $router = new Router();
        $router->register('route', new Route('/router/{foo:\w}/({bar:\d})/', 'controller'));

        $controller = $router->match($this->mockRequest('/router/foo/', null));

        $this->assertEquals('controller', $controller);
    }

    public function testMatchWithSingleArgument()
    {
        $router = new Router();
        $router->register('route', new Route('/router/{foo:\w}/', 'controller'));

        $controller = $router->match($this->mockRequest('/router/foo/', null));
        $this->assertEquals('controller', $controller);
    }

    public function testMatchWithoutArguments()
    {
        $router = new Router();
        $router->register('route', new Route('/router/', 'controller'));

        $controller = $router->match($this->mockRequest('/router/', null));

        $this->assertEquals('controller', $controller);
    }

    public function testMatchWithDomain()
    {
        $route = new Route('/router/', 'controller');
        $route->host('domain.test.com');

        $router = new Router();
        $router->register('route', $route);

        $controller = $router->match($this->mockRequest('/router/', 'domain.test.com'));
        $this->assertEquals('controller', $controller);
    }

    public function testMatchWithAdaptiveDomain()
    {
        $route = new Route('/router/', 'controller');
        $route->host('domain.{basename}');

        $router = new Router();
        $router->register('route', $route);

        $controller = $router->match($this->mockRequest('/router/', 'domain.test.com'));
        $this->assertEquals('controller', $controller);
    }

    /**
     * @dataProvider matchProvider
     */
    public function testMatchWithEndingSlash($expected, $uri, $host = null)
    {
        $router = new Router();

        $route = new Route('/router/', 'domain_router');
        $route->host('domain.{basename}');
        $router->register('domain_router', $route);

        $route = new Route('/router/foo-foo/({bar:\d})/', 'router_foo_bar');
        $router->register('router_foo_bar', $route);

        $route = new Route('/router/{foo:\w}/', 'router_foo');
        $router->register('router_foo', $route);

        $route = new Route('/router/', 'router');
        $router->register('router', $route);

        $controller = $router->match($this->mockRequest(rtrim($uri, '/'), $host));
        $this->assertEquals($expected, $controller);
    }

    /**
     * @dataProvider matchProvider
     */
    public function testMatchWithWithoutSlash($expected, $uri, $host = null)
    {
        $router = new Router();

        $route = new Route('/router/', 'domain_router');
        $route->host('domain.{basename}');
        $router->register('domain_router', $route);

        $route = new Route('/router/foo-foo/({bar:\d})/', 'router_foo_bar');
        $router->register('router_foo_bar', $route);

        $route = new Route('/router/{foo:\w}/', 'router_foo');
        $router->register('router_foo', $route);

        $route = new Route('/router/', 'router');
        $router->register('router', $route);

        $controller = $router->match($this->mockRequest(rtrim($uri, '/') . '/', $host));
        $this->assertEquals($expected, $controller);
    }

    public function matchProvider()
    {
        return [
            ['router_foo_bar', '/router/foo-foo/123/', null],
            ['router_foo', '/router/foo/', null],
            ['router', '/router/', null],
            ['domain_router', '/router/', 'http://domain.test.com'],
        ];
    }

    public function testDefaults()
    {
        $request = $this->getMock('Moss\Http\Request\RequestInterface');

        $request
            ->expects($this->any())
            ->method('query')
            ->will($this->returnValue($this->getMock('Moss\Bag\BagInterface')));

        $request
            ->expects($this->any())
            ->method('path')
            ->will($this->returnValue('/router/'));

        $request
            ->expects($this->any())
            ->method('baseName')
            ->will($this->returnValue('http://test.com'));

        $request
            ->expects($this->any())
            ->method('controller')
            ->will($this->returnValue('controller'));

        $request
            ->expects($this->any())
            ->method('language')
            ->will($this->returnValue('fr'));

        $request
            ->expects($this->any())
            ->method('format')
            ->will($this->returnValue('yml'));

        $router = new Router();
        $router->register('router', new Route('/router/', 'router'));
        $router->match($request);

        $expected = [
            'host' => 'http://test.com',
            'route' => 'router',
            'language' => 'fr',
            'format' => 'yml'
        ];

        $this->assertAttributeEquals($expected, 'defaults', $router);
    }

    /**
     * @expectedException \Moss\Http\Router\RouterException
     * @expectedExceptionMessage Unable to make "self" url - default route was not defined.
     */
    public function testMakeWithoutDefaultRoute()
    {
        $router = new Router();
        $router->make();
    }

    public function testMakeWithDefaultRoute()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $router->match($this->mockRequest('/router/foo/123/'));
        $this->assertEquals('http://test.com/router/foo/123/', $router->make(null, ['foo' => 'foo', 'bar' => 123]));
    }

    /**
     * @expectedException \Moss\Http\Router\RouterException
     * @expectedExceptionMessage Unable to make url, matching route for
     */
    public function testUnableToMakeBecauseNoMatchingRoute()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'foo');
        $router->register('route', $route);

        $route = new Route('/router/', 'bar');
        $router->register('domain_router', $route);

        $router->match($this->mockRequest('/router/foo/123/', 'test.com'));
        $this->assertEquals('http://domain.test.com/router/', $router->make('yadayada'));
    }

    public function testMakeByName()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $route = new Route('/router/', 'domain_router');
        $route->host('domain.{basename}');
        $router->register('domain_router', $route);

        $router->match($this->mockRequest('/router/foo/123/', 'test.com'));
        $this->assertEquals('http://domain.test.com/router/', $router->make('domain_router'));
    }

    public function testMakeByController()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $route = new Route('/router/', 'domain_router');
        $route->host('domain.{basename}');
        $router->register('domain_router', $route);

        $router->match($this->mockRequest('/router/foo/123/', 'test.com'));
        $this->assertEquals('http://domain.test.com/router/', $router->make('domain_router'));
    }

    public function testMake()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $router->match($this->mockRequest('/router/foo/123/'));
        $this->assertEquals('http://test.com/router/foo/123/', $router->make('route', ['foo' => 'foo', 'bar' => 123], false, false));
    }

    public function testMakeWithQuery()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $router->match($this->mockRequest('/router/foo/123/'));
        $this->assertEquals('http://test.com/router/foo/123/?yada=yada', $router->make('route', ['foo' => 'foo', 'bar' => 123, 'yada' => 'yada']));
    }

    public function testMakeWithoutOptionalArguments()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $router->match($this->mockRequest('/router/foo/123/'));
        $this->assertEquals('http://test.com/router/foo/', $router->make('route', ['foo' => 'foo']));
    }

    public function testMakeWithOptionalArguments()
    {
        $router = new Router();

        $route = new Route('/router/{foo:\w}/({bar:\d})/', 'router_foo_bar');
        $router->register('route', $route);

        $router->match($this->mockRequest('/router/foo/123/'));
        $this->assertEquals('http://test.com/router/foo/123/', $router->make('route', ['foo' => 'foo', 'bar' => 123]));
    }
}


text:
import {Locale} from "../../../locale/LocaleManager.js";
import {Global} from "../../../Global.js";
import {TabGroup} from "../../../components/tabs/TabGroup.js";
import {TabComponent} from "../../../components/tabs/TabComponent.js";

function ProjectSettings(parent, closeable, container, index)
{
	TabComponent.call(this, parent, closeable, container, index, Locale.settings, Global.FILE_PATH + "icons/misc/settings.png");

	this.tab = new TabGroup(this, TabGroup.LEFT);
	this.tab.element.style.backgroundColor = "var(--bar-color)";
	this.tab.buttonSize.set(200, 25);
}

ProjectSettings.prototype = Object.create(TabComponent.prototype);

ProjectSettings.prototype.updateSize = function()
{
	TabComponent.prototype.updateSize.call(this);

	this.tab.size.copy(this.size);
	this.tab.updateInterface();
};
export {ProjectSettings};


text:
title: Themes
page_title: Themes - RadGroupBox
description: All RadGroupBox elements can be styled in Visual Style Builder. This article shows how you can change the header and footer back colors.
slug: winforms/panels-and-labels/groupbox/customizing-appearance/themes
tags: radgroupbox, appearance
published: True
position: 1
---

# Themes

This help article will demonstrate a step by step tutorial how to customize the **ControlDefault** theme for **RadGroupBox**.

1. Open [VisualStyleBuilder]({%slug winforms/tools/visual-style-builder/starting-vsb%}).

1. [Export the built-in themes] ({%slug winforms/tools/visual-style-builder/working-with-visual-style-builder/loading-predefined-themes%}). in a specific folder by selecting *File >> Export Built-in Themes*.

1. Load a desired theme from the just exported files by selecting *File >> Open Package*

1. Navigate to __RadGroupBox__ in `Controls Structure` on the left side. Then, expand to and select __GroupBoxElement__.
    ![groupbox-customizing-appearance-themes 001](images/groupbox-customizing-appearance-themes001.png)

1. Modify the applied fill repository item.
    ![groupbox-customizing-appearance-themes 002](images/groupbox-customizing-appearance-themes002.png)

1. Save the theme by selecting *File >> Save As*.

1. Now, you can apply your custom theme to __RadGroupBox__ by using the approach demonstrated in the following link: [Using custom themes]({%slug winforms/themes/using-custom-themes%})

    ![radribbonbar-customizing-appearance-themes 003](images/groupbox-customizing-appearance-themes003.png)

# See Also

* [Structure]({%slug winforms/panels-and-labels/groupbox/structure%})
* [Accessing and Customizing Elements]({%slug winforms/panels-and-labels/groupbox/customizing-appearance/accessing-and-customizing-elements %})