text:
from __future__ import division

import errno
import json
import os
import shutil
import subprocess
import sys

from vistrails.core.modules.vistrails_module import Module, ModuleError, IncompleteImplementation, new_module
import vistrails.core.modules.module_registry
from vistrails.core import debug
from vistrails.core.packagemanager import get_package_manager
import vistrails.core.system
from vistrails.core.system import packages_directory, vistrails_root_directory

import identifiers

cl_tools = {}

class CLTools(Module):
    """ CLTools is the base Module.
     We will create a SUDSWebService Module for each method published by
     the web service.

    """
    def compute(self):
        raise IncompleteImplementation # pragma: no cover

SUFFIX = '.clt'
DEFAULTFILESUFFIX = '.cld'

def _eintr_retry_call(func, *args):
    """Fixes OSErrors and IOErrors

    From: http://code.google.com/p/seascope/source/detail?spec=svn8dbe5e23d41db673727ce90fd338e9a43f8877e8&name=8dbe5e23d41d&r=8dbe5e23d41db673727ce90fd338e9a43f8877e8
    IOError added
    """
    while True:
        try:
            return func(*args)
        except (OSError, IOError), e: # pragma: no cover
            if e.errno == errno.EINTR:
                continue
            raise

def _add_tool(path):
    # first create classes
    tool_name = os.path.basename(path)
    if isinstance(tool_name, unicode):
        tool_name = tool_name.encode('utf-8')
    if not tool_name.endswith(SUFFIX): # pragma: no cover
        return
    (tool_name, _) = os.path.splitext(tool_name)

    if tool_name in cl_tools: # pragma: no cover
        debug.critical("Package CLTools already added: '%s'" % tool_name)
    try:
        conf = json.load(open(path))
    except ValueError as exc: # pragma: no cover
        debug.critical("Package CLTools could not parse '%s'" % path, exc)
        return

    def compute(self):
        """ 1. read inputs
            2. call with inputs
            3. set outputs
        """
        # add all arguments as an unordered list
        args = [self.conf['command']]
        file_std = 'options' in self.conf and 'std_using_files' in self.conf['options']
        fail_with_cmd = 'options' in self.conf and 'fail_with_cmd' in self.conf['options']
        setOutput = [] # (name, File) - set File contents as output for name
        open_files = []
        stdin = None
        kwargs = {}
        for type, name, klass, options in self.conf['args']:
            type = type.lower()
            klass = klass.lower()
            if "constant" == type:
                flag = 'flag' in options and options['flag']
                if flag:
                    args.append(flag)
                if name:
                    # if flag==name we assume user tried to name a constant
                    if not name == flag:
                        args.append('%s%s' % (options.get('prefix', ''), name))
            elif "input" == type:
                # handle multiple inputs
                values = self.force_get_input_list(name)
                if values and 'list' == klass:
                    values = values[0]
                    klass = options['type'].lower() \
                      if 'type' in options else 'string'
                for value in values:
                    if 'flag' == klass:
                        if not value:
                            continue
                        if 'flag' in options and options['flag']:
                            value = options['flag']
                        else:
                            # use name as flag
                            value = name
                    elif klass in ('file', 'directory', 'path'):
                        value = value.name
                    # check for flag and append file name
                    if not 'flag' == klass and 'flag' in options:
                        args.append(options['flag'])
                    value = '%s%s' % (options.get('prefix', ''),
                                      value)
                    args.append(value)
            elif "output" == type:
                # output must be a filename but we may convert the result to a string
                # create new file
                file = self.interpreter.filePool.create_file(
                        suffix=options.get('suffix', DEFAULTFILESUFFIX))
                fname = file.name
                if 'prefix' in options:
                    fname = options['prefix'] + fname
                if 'flag' in options:
                    args.append(options['flag'])
                args.append(fname)
                if "file" == klass:
                    self.set_output(name, file)
                elif "string" == klass:
                    setOutput.append((name, file))
                else:
                    raise ValueError
            elif "inputoutput" == type:
                # handle single file that is both input and output
                value = self.get_input(name)

                # create copy of infile to operate on
                outfile = self.interpreter.filePool.create_file(
                        suffix=options.get('suffix', DEFAULTFILESUFFIX))
                try:
                    shutil.copyfile(value.name, outfile.name)
                except IOError, e: # pragma: no cover
                    raise ModuleError(self,
                                      "Error copying file '%s': %s" %
                                      (value.name, debug.format_exception(e)))
                value = '%s%s' % (options.get('prefix', ''), outfile.name)
                # check for flag and append file name
                if 'flag' in options:
                    args.append(options['flag'])
                args.append(value)
                self.set_output(name, outfile)
        if "stdin" in self.conf:
            name, type, options = self.conf["stdin"]
            type = type.lower()
            if self.has_input(name):
                value = self.get_input(name)
                if "file" == type:
                    if file_std:
                        f = open(value.name, 'rb')
                    else:
                        f = open(value.name, 'rb')
                        stdin = f.read()
                        f.close()
                elif "string" == type:
                    if file_std:
                        file = self.interpreter.filePool.create_file()
                        f = open(file.name, 'wb')
                        f.write(value)
                        f.close()
                        f = open(file.name, 'rb')
                    else:
                        stdin = value
                else: # pragma: no cover
                    raise ValueError
                if file_std:
                    open_files.append(f)
                    kwargs['stdin'] = f.fileno()
                else:
                    kwargs['stdin'] = subprocess.PIPE
        if "stdout" in self.conf:
            if file_std:
                name, type, options = self.conf["stdout"]
                type = type.lower()
                file = self.interpreter.filePool.create_file(
                        suffix=DEFAULTFILESUFFIX)
                if "file" == type:
                    self.set_output(name, file)
                elif "string" == type:
                    setOutput.append((name, file))
                else: # pragma: no cover
                    raise ValueError
                f = open(file.name, 'wb')
                open_files.append(f)
                kwargs['stdout'] = f.fileno()
            else:
                kwargs['stdout'] = subprocess.PIPE
        if "stderr" in self.conf:
            if file_std:
                name, type, options = self.conf["stderr"]
                type = type.lower()
                file = self.interpreter.filePool.create_file(
                        suffix=DEFAULTFILESUFFIX)
                if "file" == type:
                    self.set_output(name, file)
                elif "string" == type:
                    setOutput.append((name, file))
                else: # pragma: no cover
                    raise ValueError
                f = open(file.name, 'wb')
                open_files.append(f)
                kwargs['stderr'] = f.fileno()
            else:
                kwargs['stderr'] = subprocess.PIPE

        if fail_with_cmd:
            return_code = 0
        else:
            return_code = self.conf.get('return_code', None)

        env = {}
        # 0. add defaults
        # 1. add from configuration
        # 2. add from module env
        # 3. add from env port
        if configuration.check('env'):
            try:
                for var in configuration.env.split(";"):
                    key, value = var.split('=')
                    key = key.strip()
                    value = value.strip()
                    if key:
                        env[key] = value
            except Exception, e: # pragma: no cover
                raise ModuleError(self,
                                  "Error parsing configuration env: %s" % (
                                  debug.format_exception(e)))

        if 'options' in self.conf and 'env' in self.conf['options']:
            try:
                for var in self.conf['options']['env'].split(";"):
                    key, value = var.split('=')
                    key = key.strip()
                    value = value.strip()
                    if key:
                        env[key] = value
            except Exception, e: # pragma: no cover
                raise ModuleError(self,
                                  "Error parsing module env: %s" % (
                                  debug.format_exception(e)))

        if 'options' in self.conf and 'env_port' in self.conf['options']:
            for e in self.force_get_input_list('env'):
                try:
                    for var in e.split(';'):
                        if not var:
                            continue
                        key, value = var.split('=')
                        key = key.strip()
                        value = value.strip()
                        if key:
                            env[key] = value
                except Exception, e: # pragma: no cover
                    raise ModuleError(self,
                                      "Error parsing env port: %s" % (
                                      debug.format_exception(e)))

        if env:
            kwargs['env'] = dict(os.environ)
            kwargs['env'].update(env)
            # write to execution provenance
            env = ';'.join(['%s=%s'%(k,v) for k,v in env.iteritems()])
            self.annotate({'execution_env': env})

        if 'dir' in self.conf:
            kwargs['cwd'] = self.conf['dir']

        process = subprocess.Popen(args, **kwargs)
        if file_std:
            process.wait()
        else:
            #if stdin:
            #    print "stdin:", len(stdin), stdin[:30]
            stdout, stderr = _eintr_retry_call(process.communicate, stdin)
            #stdout, stderr = process.communicate(stdin)
            #if stdout:
            #    print "stdout:", len(stdout), stdout[:30]
            #if stderr:
            #    print "stderr:", len(stderr), stderr[:30]

        if return_code is not None:
            if process.returncode != return_code:
                raise ModuleError(self, "Command returned %d (!= %d)" % (
                                  process.returncode, return_code))
        self.set_output('return_code', process.returncode)

        for f in open_files:
            f.close()

        for name, file in setOutput:
            f = open(file.name, 'rb')
            self.set_output(name, f.read())
            f.close()

        if not file_std:
            if "stdout" in self.conf:
                name, type, options = self.conf["stdout"]
                type = type.lower()
                if "file" == type:
                    file = self.interpreter.filePool.create_file(
                            suffix=DEFAULTFILESUFFIX)
                    f = open(file.name, 'wb')
                    f.write(stdout)
                    f.close()
                    self.set_output(name, file)
                elif "string" == type:
                    self.set_output(name, stdout)
                else: # pragma: no cover
                    raise ValueError
            if "stderr" in self.conf:
                name, type, options = self.conf["stderr"]
                type = type.lower()
                if "file" == type:
                    file = self.interpreter.filePool.create_file(
                            suffix=DEFAULTFILESUFFIX)
                    f = open(file.name, 'wb')
                    f.write(stderr)
                    f.close()
                    self.set_output(name, file)
                elif "string" == type:
                    self.set_output(name, stderr)
                else: # pragma: no cover
                    raise ValueError

    # create docstring
    d = """This module is a wrapper for the command line tool '%s'""" % \
        conf['command']
    # create module
    M = new_module(CLTools, tool_name, {"compute": compute,
                                        "conf": conf,
                                        "tool_name": tool_name,
                                        "__doc__": d})
    reg = vistrails.core.modules.module_registry.get_module_registry()
    reg.add_module(M, package=identifiers.identifier,
                   package_version=identifiers.version)

    def to_vt_type(s):
        # add recognized types here - default is String
        return '(basic:%s)' % \
          {'file':'File', 'path':'Path', 'directory': 'Directory',
           'flag':'Boolean', 'list':'List',
           'float':'Float','integer':'Integer'
          }.get(s.lower(), 'String')
    # add module ports
    if 'stdin' in conf:
        name, type, options = conf['stdin']
        optional = 'required' not in options
        reg.add_input_port(M, name, to_vt_type(type), optional=optional)
    if 'stdout' in conf:
        name, type, options = conf['stdout']
        optional = 'required' not in options
        reg.add_output_port(M, name, to_vt_type(type), optional=optional)
    if 'stderr' in conf:
        name, type, options = conf['stderr']
        optional = 'required' not in options
        reg.add_output_port(M, name, to_vt_type(type), optional=optional)
    if 'options' in conf and 'env_port' in conf['options']:
        reg.add_input_port(M, 'env', to_vt_type('string'))
    for type, name, klass, options in conf['args']:
        optional = 'required' not in options
        if 'input' == type.lower():
            reg.add_input_port(M, name, to_vt_type(klass), optional=optional)
        elif 'output' == type.lower():
            reg.add_output_port(M, name, to_vt_type(klass), optional=optional)
        elif 'inputoutput' == type.lower():
            reg.add_input_port(M, name, to_vt_type('file'), optional=optional)
            reg.add_output_port(M, name, to_vt_type('file'), optional=optional)
    reg.add_output_port(M, 'return_code', to_vt_type('integer'))
    cl_tools[tool_name] = M

def add_tool(path):
    try:
        _add_tool(path)
    except Exception as exc:  # pragma: no cover
        import traceback
        debug.critical("Package CLTools failed to create module "
           "from '%s': %s" % (path, exc),
           traceback.format_exc())

def initialize(*args, **keywords):
    reload_scripts(initial=True)

def remove_all_scripts():
    reg = vistrails.core.modules.module_registry.get_module_registry()
    for tool_name in cl_tools.keys():
        del cl_tools[tool_name]
        reg.delete_module(identifiers.identifier, tool_name)

def reload_scripts(initial=False, name=None):
    reg = vistrails.core.modules.module_registry.get_module_registry()
    if not initial:
        if name is None:
            remove_all_scripts()
        else:
            del cl_tools[name]
            reg.delete_module(identifiers.identifier, name)

    if "CLTools" == identifiers.name:
        # this is the original package
        location = os.path.join(vistrails.core.system.current_dot_vistrails(),
                                "CLTools")
        # make sure dir exist
        if not os.path.isdir(location): # pragma: no cover # pragma: no branch
            try:
                debug.log("Creating CLTools directory...")
                os.mkdir(location)
            except Exception, e:
                debug.critical("Could not create CLTools directory. Make "
                               "sure '%s' does not exist and parent directory "
                               "is writable" % location,
                               e)
                sys.exit(1)
    else:  # pragma: no cover
        # this is a standalone package so modules are placed in this directory
        location = os.path.dirname(__file__)

    if initial:
        reg.add_module(CLTools, abstract=True)
    if name is None:
        for path in os.listdir(location):
            if path.endswith(SUFFIX):  # pragma: no branch
                add_tool(os.path.join(location, path))
    else:
        path = os.path.join(location, name + SUFFIX)
        if os.path.exists(path):
            add_tool(path)

    if not initial:
        from vistrails.core.interpreter.cached import CachedInterpreter
        CachedInterpreter.clear_package(identifiers.identifier)

        from vistrails.gui.vistrails_window import _app
        _app.invalidate_pipelines()

wizards_list = []

def menu_items():
    """menu_items() -> tuple of (str,function)
    It returns a list of pairs containing text for the menu and a
    callback function that will be executed when that menu item is selected.

    """
    try:
        from wizard import QCLToolsWizardWindow
    except Exception, e: # pragma: no cover
        if "CLTools" == identifiers.name:
            debug.unexpected_exception(e)
            raise
        else:
            return
    lst = []
    if "CLTools" == identifiers.name: # pragma: no branch
        def open_wizard():
            window = QCLToolsWizardWindow(reload_scripts=reload_scripts)
            wizards_list.append(window)
            window.show()
        lst.append(("Open Wizard", open_wizard))
    lst.append(("Reload All Scripts", reload_scripts))
    return tuple(lst)

def finalize():
    pass

def contextMenuName(name):
    if "CLTools" == name:
        return "Reload All Scripts"
    else:
        return "Reload Script"

def callContextMenu(name):
    if "CLTools" == name:
        reload_scripts()
    else:
        reload_scripts(name=name)

###############################################################################

import unittest
from vistrails.tests.utils import execute, intercept_results

class TestCLTools(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # first make sure CLTools is loaded
        pm = get_package_manager()
        if 'CLTools' not in pm._package_list: # pragma: no cover # pragma: no branch
            pm.late_enable_package('CLTools')
        remove_all_scripts()
        cls.testdir = os.path.join(packages_directory(), 'CLTools', 'test_files')
        cls._tools = {}
        for name in os.listdir(cls.testdir):
            if not name.endswith(SUFFIX):
                continue
            _add_tool(os.path.join(cls.testdir, name))
            toolname = os.path.splitext(name)[0]
            cls._tools[toolname] = cl_tools[toolname]
        cls._old_dir = os.getcwd()
        os.chdir(vistrails_root_directory())

    @classmethod
    def tearDownClass(cls):
        os.chdir(cls._old_dir)
        reload_scripts()

    def do_the_test(self, toolname):
        with intercept_results(
                self._tools[toolname],
                'return_code', 'f_out', 'stdout') as (
                return_code, f_out, stdout):
            self.assertFalse(execute([
                    (toolname, 'org.vistrails.vistrails.cltools', [
                        ('f_in', [('File', self.testdir + '/test_1.cltest')]),
                        ('chars', [('List', '["a", "b", "c"]')]),
                        ('false', [('Boolean', 'False')]),
                        ('true', [('Boolean', 'True')]),
                        ('nb', [('Integer', '42')]),
                        ('stdin', [('String', 'some line\nignored')]),
                    ]),
                ]))
        self.assertEqual(return_code, [0])
        self.assertEqual(f_out, ['ok\nmessage received'])
        self.assertEqual(stdout, ['program output here'])

    def test_with_pipes(self):
        """Without std_using_files: use pipes instead of files.
        """
        self.do_the_test('intern_cltools_1')

    def test_with_files(self):
        """With std_using_files: use files instead of pipes.
        """
        self.do_the_test('intern_cltools_2')


text:
module CloudCostTracker
  module Coding
    class ResourceCodingPolicy

      # Creates an object that implements a billing policy
      # that attaches no billing codes
      # @param [Hash] options optional parameters:
      #  - :logger - a Ruby Logger-compatible object
      def initialize(options={})
        @log = options[:logger] || FogTracker.default_logger
      end

      # Used by subclasses to perform setup each time an account's
      # resources are coded
      # High-latency operations like network transactions that are not
      # per-resource should be performed here
      def setup(resources) ; end

      # Attaches Billing Codes (String pairs) to resource, as billing_codes
      def code(resource) ; end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
layout: default
---

{{page.title}}

{{page.date | date: '%B %d, %Y'}}

{{content}}


text:
from __future__ import division, unicode_literals
import numpy as np

import six

from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.core.periodic_table import get_el_sp
from pymatgen.core.structure import Structure
from pymatgen.core.spectrum import Spectrum
from pymatgen.util.coord import get_linear_interpolated_value
from monty.json import MSONable

"""
This module defines classes to represent the density of states, etc.
"""

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "2.0"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Mar 20, 2012"

class DOS(Spectrum):
    """
    Replacement basic DOS object. All other DOS objects are extended versions
    of this object. Work in progress.

    Args:
        energies: A sequence of energies
        densities (ndarray): Either a Nx1 or a Nx2 array. If former, it is
            interpreted as a Spin.up only density. Otherwise, the first column
            is interpreted as Spin.up and the other is Spin.down.
        efermi: Fermi level energy.

    .. attribute: energies

        The sequence of energies

    .. attribute: densities

        A dict of spin densities, e.g., {Spin.up: [...], Spin.down: [...]}

    .. attribute: efermi

        Fermi level
    """
    XLABEL = "Energy"
    YLABEL = "Density"

    def __init__(self, energies, densities, efermi):
        super(DOS, self).__init__(energies, densities, efermi)
        self.efermi = efermi

    def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the gap

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: Set to True for an absolute tolerance and False for a
                relative one.
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            (gap, cbm, vbm):
                Tuple of floats in eV corresponding to the gap, cbm and vbm.
        """

        tdos = self.y if len(self.ydim) == 1 else np.sum(self.y, axis=1)
        if not abs_tol:
            tol = tol * tdos.sum() / tdos.shape[0]
        energies = self.x
        below_fermi = [i for i in range(len(energies))
                       if energies[i] < self.efermi and tdos[i] > tol]
        above_fermi = [i for i in range(len(energies))
                       if energies[i] > self.efermi and tdos[i] > tol]
        vbm_start = max(below_fermi)
        cbm_start = min(above_fermi)
        if vbm_start == cbm_start:
            return 0.0, self.efermi, self.efermi
        else:
            # Interpolate between adjacent values
            terminal_dens = tdos[vbm_start:vbm_start + 2][::-1]
            terminal_energies = energies[vbm_start:vbm_start + 2][::-1]
            start = get_linear_interpolated_value(terminal_dens,
                                                  terminal_energies, tol)
            terminal_dens = tdos[cbm_start - 1:cbm_start + 1]
            terminal_energies = energies[cbm_start - 1:cbm_start + 1]
            end = get_linear_interpolated_value(terminal_dens,
                                                terminal_energies, tol)
            return end - start, end, start

    def get_cbm_vbm(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the cbm and vbm.

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: An absolute tolerance (True) and a relative one (False)
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            (cbm, vbm): float in eV corresponding to the gap
        """
        # determine tolerance
        if spin is None:
            tdos = self.y if len(self.ydim) == 1 else np.sum(self.y, axis=1)
        elif spin == Spin.up:
            tdos = self.y[:, 0]
        else:
            tdos = self.y[:, 1]

        if not abs_tol:
            tol = tol * tdos.sum() / tdos.shape[0]

        # find index of fermi energy
        i_fermi = 0
        while self.x[i_fermi] <= self.efermi:
            i_fermi += 1

        # work backwards until tolerance is reached
        i_gap_start = i_fermi
        while i_gap_start - 1 >= 0 and tdos[i_gap_start - 1] <= tol:
            i_gap_start -= 1

        # work forwards until tolerance is reached
        i_gap_end = i_gap_start
        while i_gap_end < tdos.shape[0] and tdos[i_gap_end] <= tol:
            i_gap_end += 1
        i_gap_end -= 1
        return self.x[i_gap_end], self.x[i_gap_start]

    def get_gap(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the gap.

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: An absolute tolerance (True) and a relative one (False)
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            gap in eV
        """
        (cbm, vbm) = self.get_cbm_vbm(tol, abs_tol, spin)
        return max(cbm - vbm, 0.0)

    def __str__(self):
        """
        Returns a string which can be easily plotted (using gnuplot).
        """
        if Spin.down in self.densities:
            stringarray = ["#{:30s} {:30s} {:30s}".format("Energy",
                                                          "DensityUp",
                                                          "DensityDown")]
            for i, energy in enumerate(self.energies):
                stringarray.append("{:.5f} {:.5f} {:.5f}"
                                   .format(energy, self.densities[Spin.up][i],
                                           self.densities[Spin.down][i]))
        else:
            stringarray = ["#{:30s} {:30s}".format("Energy", "DensityUp")]
            for i, energy in enumerate(self.energies):
                stringarray.append("{:.5f} {:.5f}"
                                   .format(energy, self.densities[Spin.up][i]))
        return "\n".join(stringarray)

class Dos(MSONable):
    """
    Basic DOS object. All other DOS objects are extended versions of this
    object.

    Args:
        efermi: Fermi level energy
        energies: A sequences of energies
        densities ({Spin: np.array}): representing the density of states
            for each Spin.

    .. attribute: energies

        The sequence of energies

    .. attribute: densities

        A dict of spin densities, e.g., {Spin.up: [...], Spin.down: [...]}

    .. attribute: efermi

        Fermi level
    """

    def __init__(self, efermi, energies, densities):
        self.efermi = efermi
        self.energies = np.array(energies)
        self.densities = {k: np.array(d) for k, d in densities.items()}

    def get_densities(self, spin=None):
        """
        Returns the density of states for a particular spin.

        Args:
            spin: Spin

        Returns:
            Returns the density of states for a particular spin. If Spin is
            None, the sum of all spins is returned.
        """
        if self.densities is None:
            result = None
        elif spin is None:
            if Spin.down in self.densities:
                result = self.densities[Spin.up] + self.densities[Spin.down]
            else:
                result = self.densities[Spin.up]
        else:
            result = self.densities[spin]
        return result

    def get_smeared_densities(self, sigma):
        """
        Returns the Dict representation of the densities, {Spin: densities},
        but with a Gaussian smearing of std dev sigma applied about the fermi
        level.

        Args:
            sigma: Std dev of Gaussian smearing function.

        Returns:
            Dict of Gaussian-smeared densities.
        """
        from scipy.ndimage.filters import gaussian_filter1d
        smeared_dens = {}
        diff = [self.energies[i + 1] - self.energies[i]
                for i in range(len(self.energies) - 1)]
        avgdiff = sum(diff) / len(diff)
        for spin, dens in self.densities.items():
            smeared_dens[spin] = gaussian_filter1d(dens, sigma / avgdiff)
        return smeared_dens

    def __add__(self, other):
        """
        Adds two DOS together. Checks that energy scales are the same.
        Otherwise, a ValueError is thrown.

        Args:
            other: Another DOS object.

        Returns:
            Sum of the two DOSs.
        """
        if not all(np.equal(self.energies, other.energies)):
            raise ValueError("Energies of both DOS are not compatible!")
        densities = {spin: self.densities[spin] + other.densities[spin]
                     for spin in self.densities.keys()}
        return Dos(self.efermi, self.energies, densities)

    def get_interpolated_value(self, energy):
        """
        Returns interpolated density for a particular energy.

        Args:
            energy: Energy to return the density for.
        """
        f = {}
        for spin in self.densities.keys():
            f[spin] = get_linear_interpolated_value(self.energies,
                                                    self.densities[spin],
                                                    energy)
        return f

    def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the gap

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: Set to True for an absolute tolerance and False for a
                relative one.
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            (gap, cbm, vbm):
                Tuple of floats in eV corresponding to the gap, cbm and vbm.
        """

        tdos = self.get_densities(spin)
        if not abs_tol:
            tol = tol * tdos.sum() / tdos.shape[0]
        energies = self.energies
        below_fermi = [i for i in range(len(energies))
                       if energies[i] < self.efermi and tdos[i] > tol]
        above_fermi = [i for i in range(len(energies))
                       if energies[i] > self.efermi and tdos[i] > tol]
        vbm_start = max(below_fermi)
        cbm_start = min(above_fermi)
        if vbm_start == cbm_start:
            return 0.0, self.efermi, self.efermi
        else:
            # Interpolate between adjacent values
            terminal_dens = tdos[vbm_start:vbm_start + 2][::-1]
            terminal_energies = energies[vbm_start:vbm_start + 2][::-1]
            start = get_linear_interpolated_value(terminal_dens,
                                                  terminal_energies, tol)
            terminal_dens = tdos[cbm_start - 1:cbm_start + 1]
            terminal_energies = energies[cbm_start - 1:cbm_start + 1]
            end = get_linear_interpolated_value(terminal_dens,
                                                terminal_energies, tol)
            return end - start, end, start

    def get_cbm_vbm(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the cbm and vbm.

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: An absolute tolerance (True) and a relative one (False)
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            (cbm, vbm): float in eV corresponding to the gap
        """
        #determine tolerance
        tdos = self.get_densities(spin)
        if not abs_tol:
            tol = tol * tdos.sum() / tdos.shape[0]

        # find index of fermi energy
        i_fermi = 0
        while self.energies[i_fermi] <= self.efermi:
            i_fermi += 1

        # work backwards until tolerance is reached
        i_gap_start = i_fermi
        while i_gap_start - 1 >= 0 and tdos[i_gap_start - 1] <= tol:
            i_gap_start -= 1

        # work forwards until tolerance is reached
        i_gap_end = i_gap_start
        while i_gap_end < tdos.shape[0] and tdos[i_gap_end] <= tol:
            i_gap_end += 1
        i_gap_end -= 1
        return self.energies[i_gap_end], self.energies[i_gap_start]

    def get_gap(self, tol=0.001, abs_tol=False, spin=None):
        """
        Expects a DOS object and finds the gap.

        Args:
            tol: tolerance in occupations for determining the gap
            abs_tol: An absolute tolerance (True) and a relative one (False)
            spin: Possible values are None - finds the gap in the summed
                densities, Up - finds the gap in the up spin channel,
                Down - finds the gap in the down spin channel.

        Returns:
            gap in eV
        """
        (cbm, vbm) = self.get_cbm_vbm(tol, abs_tol, spin)
        return max(cbm - vbm, 0.0)

    def __str__(self):
        """
        Returns a string which can be easily plotted (using gnuplot).
        """
        if Spin.down in self.densities:
            stringarray = ["#{:30s} {:30s} {:30s}".format("Energy",
                                                          "DensityUp",
                                                          "DensityDown")]
            for i, energy in enumerate(self.energies):
                stringarray.append("{:.5f} {:.5f} {:.5f}"
                                   .format(energy, self.densities[Spin.up][i],
                                           self.densities[Spin.down][i]))
        else:
            stringarray = ["#{:30s} {:30s}".format("Energy", "DensityUp")]
            for i, energy in enumerate(self.energies):
                stringarray.append("{:.5f} {:.5f}"
                                   .format(energy, self.densities[Spin.up][i]))
        return "\n".join(stringarray)

    @classmethod
    def from_dict(cls, d):
        """
        Returns Dos object from dict representation of Dos.
        """
        return Dos(d["efermi"], d["energies"],
                   {Spin(int(k)): v
                    for k, v in d["densities"].items()})

    def as_dict(self):
        """
        Json-serializable dict representation of Dos.
        """
        return {"@module": self.__class__.__module__,
                "@class": self.__class__.__name__, "efermi": self.efermi,
                "energies": list(self.energies),
                "densities": {str(spin): list(dens)
                              for spin, dens in self.densities.items()}}

class CompleteDos(Dos):
    """
    This wrapper class defines a total dos, and also provides a list of PDos.
    Mainly used by pymatgen.io.vasp.Vasprun to create a complete Dos from
    a vasprun.xml file. You are unlikely to try to generate this object
    manually.

    Args:
        structure: Structure associated with this particular DOS.
        total_dos: total Dos for structure
        pdoss: The pdoss are supplied as an {Site:{Orbital:{
            Spin:Densities}}}

    .. attribute:: structure

        Structure associated with the CompleteDos.

    .. attribute:: pdos

        Dict of partial densities of the form {Site:{Orbital:{Spin:Densities}}}
    """
    def __init__(self, structure, total_dos, pdoss):
        super(CompleteDos, self).__init__(
            total_dos.efermi, energies=total_dos.energies,
            densities={k: np.array(d) for k, d in total_dos.densities.items()})
        self.pdos = pdoss
        self.structure = structure

    def get_site_orbital_dos(self, site, orbital):
        """
        Get the Dos for a particular orbital of a particular site.

        Args:
            site: Site in Structure associated with CompleteDos.
            orbital: Orbital in the site.

        Returns:
            Dos containing densities for orbital of site.
        """
        return Dos(self.efermi, self.energies, self.pdos[site][orbital])

    def get_site_dos(self, site):
        """
        Get the total Dos for a site (all orbitals).

        Args:
            site: Site in Structure associated with CompleteDos.

        Returns:
            Dos containing summed orbital densities for site.
        """
        site_dos = six.moves.reduce(add_densities, self.pdos[site].values())
        return Dos(self.efermi, self.energies, site_dos)

    def get_site_spd_dos(self, site):
        """
        Get orbital projected Dos of a particular site

        Args:
            site: Site in Structure associated with CompleteDos.

        Returns:
            dict of {orbital: Dos}, e.g. {"s": Dos object, ...}
        """
        spd_dos = dict()
        for orb, pdos in self.pdos[site].items():
            orbital_type = _get_orb_type(orb)
            if orbital_type in spd_dos:
                spd_dos[orbital_type] = add_densities(spd_dos[orbital_type], pdos)
            else:
                spd_dos[orbital_type] = pdos
        return {orb: Dos(self.efermi, self.energies, densities)
                for orb, densities in spd_dos.items()}

    def get_site_t2g_eg_resolved_dos(self, site):
        """
        Get the t2g, eg projected DOS for a particular site.

        Args:
            site: Site in Structure associated with CompleteDos.

        Returns:
            A dict {"e_g": Dos, "t2g": Dos} containing summed e_g and t2g DOS
            for the site.
        """
        t2g_dos = []
        eg_dos = []
        for s, atom_dos in self.pdos.items():
            if s == site:
                for orb, pdos in atom_dos.items():
                    if orb in (Orbital.dxy, Orbital.dxz, Orbital.dyz):
                        t2g_dos.append(pdos)
                    elif orb in (Orbital.dx2, Orbital.dz2):
                        eg_dos.append(pdos)
        return {"t2g": Dos(self.efermi, self.energies,
                           six.moves.reduce(add_densities, t2g_dos)),
                "e_g": Dos(self.efermi, self.energies,
                           six.moves.reduce(add_densities, eg_dos))}

    def get_spd_dos(self):
        """
        Get orbital projected Dos.

        Returns:
            dict of {orbital: Dos}, e.g. {"s": Dos object, ...}
        """
        spd_dos = {}
        for atom_dos in self.pdos.values():
            for orb, pdos in atom_dos.items():
                orbital_type = _get_orb_type(orb)
                if orbital_type not in spd_dos:
                    spd_dos[orbital_type] = pdos
                else:
                    spd_dos[orbital_type] = \
                        add_densities(spd_dos[orbital_type], pdos)
        return {orb: Dos(self.efermi, self.energies, densities)
                for orb, densities in spd_dos.items()}

    def get_element_dos(self):
        """
        Get element projected Dos.

        Returns:
            dict of {Element: Dos}
        """

        el_dos = {}
        for site, atom_dos in self.pdos.items():
            el = site.specie
            for pdos in atom_dos.values():
                if el not in el_dos:
                    el_dos[el] = pdos
                else:
                    el_dos[el] = add_densities(el_dos[el], pdos)
        return {el: Dos(self.efermi, self.energies, densities)
                for el, densities in el_dos.items()}

    def get_element_spd_dos(self, el):
        """
        Get element and spd projected Dos

        Args:
            el: Element in Structure.composition associated with CompleteDos

        Returns:
            dict of {Element: {"S": densities, "P": densities, "D": densities}}
        """
        el = get_el_sp(el)
        el_dos = {}
        for site, atom_dos in self.pdos.items():
            if site.specie == el:
                for orb, pdos in atom_dos.items():
                    orbital_type = _get_orb_type(orb)
                    if orbital_type not in el_dos:
                        el_dos[orbital_type] = pdos
                    else:
                        el_dos[orbital_type] = \
                            add_densities(el_dos[orbital_type], pdos)

        return {orb: Dos(self.efermi, self.energies, densities)
                for orb, densities in el_dos.items()}

    @classmethod
    def from_dict(cls, d):
        """
        Returns CompleteDos object from dict representation.
        """
        tdos = Dos.from_dict(d)
        struct = Structure.from_dict(d["structure"])
        pdoss = {}
        for i in range(len(d["pdos"])):
            at = struct[i]
            orb_dos = {}
            for orb_str, odos in d["pdos"][i].items():
                orb = Orbital[orb_str]
                orb_dos[orb] = {Spin(int(k)): v
                                for k, v in odos["densities"].items()}
            pdoss[at] = orb_dos
        return CompleteDos(struct, tdos, pdoss)

    def as_dict(self):
        """
        Json-serializable dict representation of CompleteDos.
        """
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__, "efermi": self.efermi,
             "structure": self.structure.as_dict(),
             "energies": list(self.energies),
             "densities": {str(spin): list(dens)
                           for spin, dens in self.densities.items()},
             "pdos": []}
        if len(self.pdos) > 0:
            for at in self.structure:
                dd = {}
                for orb, pdos in self.pdos[at].items():
                    dd[str(orb)] = {"densities": {str(int(spin)): list(dens)
                                                  for spin,
                                                  dens in pdos.items()}}
                d["pdos"].append(dd)
            d["atom_dos"] = {str(at): dos.as_dict() for at,
                             dos in self.get_element_dos().items()}
            d["spd_dos"] = {str(orb): dos.as_dict() for orb,
                            dos in self.get_spd_dos().items()}
        return d

    def __str__(self):
        return "Complete DOS for " + str(self.structure)

def add_densities(density1, density2):
    """
    Method to sum two densities.

    Args:
        density1: First density.
        density2: Second density.

    Returns:
        Dict of {spin: density}.
    """
    return {spin: np.array(density1[spin]) + np.array(density2[spin])
            for spin in density1.keys()}

def _get_orb_type(orb):
    try:
        return orb.orbital_type
    except AttributeError:
        return orb


text:
#pragma once
#include <aws/codedeploy/CodeDeploy_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace CodeDeploy
{
namespace Model
{
  enum class ApplicationRevisionSortBy
  {
    NOT_SET,
    registerTime,
    firstUsedTime,
    lastUsedTime
  };

namespace ApplicationRevisionSortByMapper
{
AWS_CODEDEPLOY_API ApplicationRevisionSortBy GetApplicationRevisionSortByForName(const Aws::String& name);

AWS_CODEDEPLOY_API Aws::String GetNameForApplicationRevisionSortBy(ApplicationRevisionSortBy value);
} // namespace ApplicationRevisionSortByMapper
} // namespace Model
} // namespace CodeDeploy
} // namespace Aws


text:
using System.Collections.Generic;
using MLAPI;
using UnityEngine;

namespace UnityEditor
{
    [CustomEditor(typeof(NetworkObject), true)]
    [CanEditMultipleObjects]
    public class NetworkObjectEditor : Editor
    {
        private bool m_Initialized;
        private NetworkObject m_NetworkObject;
        private bool m_ShowObservers;

        private void Init()
        {
            if (m_Initialized) return;

            m_Initialized = true;
            m_NetworkObject = (NetworkObject)target;
        }

        public override void OnInspectorGUI()
        {
            Init();

            if (!m_NetworkObject.IsSpawned && NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(new GUIContent("Spawn", "Spawns the object across the network"));
                if (GUILayout.Toggle(false, "Spawn", EditorStyles.miniButtonLeft))
                {
                    m_NetworkObject.Spawn();
                    EditorUtility.SetDirty(target);
                }

                EditorGUILayout.EndHorizontal();
            }
            else if (m_NetworkObject.IsSpawned)
            {
                EditorGUILayout.LabelField("PrefabHashGenerator: ", m_NetworkObject.PrefabHashGenerator, EditorStyles.label);
                EditorGUILayout.LabelField("PrefabHash: ", m_NetworkObject.PrefabHash.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("InstanceId: ", m_NetworkObject.NetworkInstanceId.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("NetworkId: ", m_NetworkObject.NetworkObjectId.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("OwnerId: ", m_NetworkObject.OwnerClientId.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsSpawned: ", m_NetworkObject.IsSpawned.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsLocalPlayer: ", m_NetworkObject.IsLocalPlayer.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsOwner: ", m_NetworkObject.IsOwner.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsOwnedByServer: ", m_NetworkObject.IsOwnedByServer.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsPlayerObject: ", m_NetworkObject.IsPlayerObject.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("IsSceneObject: ", (m_NetworkObject.IsSceneObject == null ? "Null" : m_NetworkObject.IsSceneObject.Value.ToString()), EditorStyles.label);

                if (NetworkManager.Singleton != null && NetworkManager.Singleton.IsServer)
                {
                    m_ShowObservers = EditorGUILayout.Foldout(m_ShowObservers, "Observers");

                    if (m_ShowObservers)
                    {
                        HashSet<ulong>.Enumerator observerClientIds = m_NetworkObject.GetObservers();

                        EditorGUI.indentLevel += 1;

                        while (observerClientIds.MoveNext())
                        {
                            if (NetworkManager.Singleton.ConnectedClients[observerClientIds.Current].PlayerObject != null)
                            {
                                EditorGUILayout.ObjectField("ClientId: " + observerClientIds.Current, NetworkManager.Singleton.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
                            }
                            else
                            {
                                EditorGUILayout.TextField("ClientId: " + observerClientIds.Current, EditorStyles.label);
                            }
                        }

                        EditorGUI.indentLevel -= 1;
                    }
                }
            }
            else
            {
                base.OnInspectorGUI();
                EditorGUILayout.LabelField("PrefabHash: ", m_NetworkObject.PrefabHash.ToString(), EditorStyles.label);
                EditorGUILayout.LabelField("InstanceId: ", m_NetworkObject.NetworkInstanceId.ToString(), EditorStyles.label);
            }
        }
    }
}


text:
package pkcs11config

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"

	"github.com/containers/ocicrypt/crypto/pkcs11"
	"github.com/pkg/errors"
	"gopkg.in/yaml.v2"
)

// OcicryptConfig represents the format of an imgcrypt.conf config file
type OcicryptConfig struct {
	Pkcs11Config pkcs11.Pkcs11Config `yaml:"pkcs11"`
}

const CONFIGFILE = "ocicrypt.conf"
const ENVVARNAME = "OCICRYPT_CONFIG"

// parseConfigFile parses a configuration file; it is not an error if the configuration file does
// not exist, so no error is returned.
// A config file may look like this:
// module-directories:
//   - /usr/lib64/pkcs11/
//   - /usr/lib/pkcs11/
// allowed-module-paths:
//   - /usr/lib64/pkcs11/
//   - /usr/lib/pkcs11/
func parseConfigFile(filename string) (*OcicryptConfig, error) {
	// a non-existent config file is not an error
	_, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return nil, nil
	}

	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	ic := &OcicryptConfig{}
	err = yaml.Unmarshal(data, ic)
	return ic, err
}

// getConfiguration tries to read the configuration file at the following locations
// 1) ${OCICRYPT_CONFIG} == "internal": use internal default allow-all policy
// 2) ${OCICRYPT_CONFIG}
// 3) ${XDG_CONFIG_HOME}/ocicrypt-pkcs11.conf
// 4) ${HOME}/.config/ocicrypt-pkcs11.conf
// 5) /etc/ocicrypt-pkcs11.conf
// If no configuration file could be found or read a null pointer is returned
func getConfiguration() (*OcicryptConfig, error) {
	filename := os.Getenv(ENVVARNAME)
	if len(filename) > 0 {
		if filename == "internal" {
			return getDefaultCryptoConfigOpts()
		}
		ic, err := parseConfigFile(filename)
		if err != nil || ic != nil {
			return ic, err
		}
	}
	envvar := os.Getenv("XDG_CONFIG_HOME")
	if len(envvar) > 0 {
		ic, err := parseConfigFile(path.Join(envvar, CONFIGFILE))
		if err != nil || ic != nil {
			return ic, err
		}
	}
	envvar = os.Getenv("HOME")
	if len(envvar) > 0 {
		ic, err := parseConfigFile(path.Join(envvar, ".config", CONFIGFILE))
		if err != nil || ic != nil {
			return ic, err
		}
	}
	return parseConfigFile(path.Join("etc", CONFIGFILE))
}

// getDefaultCryptoConfigOpts returns default crypto config opts needed for pkcs11 module access
func getDefaultCryptoConfigOpts() (*OcicryptConfig, error) {
	mdyaml := pkcs11.GetDefaultModuleDirectoriesYaml("")
	config := fmt.Sprintf("module-directories:\n"+
		"%s"+
		"allowed-module-paths:\n"+
		"%s", mdyaml, mdyaml)
	p11conf, err := pkcs11.ParsePkcs11ConfigFile([]byte(config))
	return &OcicryptConfig{
		Pkcs11Config: *p11conf,
	}, err
}

// GetUserPkcs11Config gets the user's Pkcs11Conig either from a configuration file or if none is
// found the default ones are returned
func GetUserPkcs11Config() (*pkcs11.Pkcs11Config, error) {
	fmt.Print("Note: pkcs11 support is currently experimental\n")
	ic, err := getConfiguration()
	if err != nil {
		return &pkcs11.Pkcs11Config{}, err
	}
	if ic == nil {
		return &pkcs11.Pkcs11Config{}, errors.New("No ocicrypt config file was found")
	}
	return &ic.Pkcs11Config, nil
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="cache-control" content="max-age=0" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
  <meta http-equiv="pragma" content="no-cache" />
  <title>Tool Test VR</title>
  <meta name="description" content="Tool Test VR">


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.MachineLearningServices.Models;

namespace Azure.ResourceManager.MachineLearningServices
{
    /// <summary> The EnvironmentSpecificationVersions service client. </summary>
    public partial class EnvironmentSpecificationVersionsOperations
    {
        private readonly ClientDiagnostics _clientDiagnostics;
        private readonly HttpPipeline _pipeline;
        internal EnvironmentSpecificationVersionsRestOperations RestClient { get; }

        /// <summary> Initializes a new instance of EnvironmentSpecificationVersionsOperations for mocking. </summary>
        protected EnvironmentSpecificationVersionsOperations()
        {
        }

        /// <summary> Initializes a new instance of EnvironmentSpecificationVersionsOperations. </summary>
        /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
        /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
        /// <param name="subscriptionId"> Azure subscription identifier. </param>
        /// <param name="endpoint"> server parameter. </param>
        /// <param name="apiVersion"> Api Version. </param>
        internal EnvironmentSpecificationVersionsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2020-09-01-preview")
        {
            RestClient = new EnvironmentSpecificationVersionsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint, apiVersion);
            _clientDiagnostics = clientDiagnostics;
            _pipeline = pipeline;
        }

        /// <param name="name"> The String to use. </param>
        /// <param name="version"> The String to use. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="body"> The EnvironmentSpecificationVersionResource to use. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<EnvironmentSpecificationVersionResource>> CreateOrUpdateAsync(string name, string version, string resourceGroupName, string workspaceName, EnvironmentSpecificationVersionResource body = null, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.CreateOrUpdate");
            scope.Start();
            try
            {
                return await RestClient.CreateOrUpdateAsync(name, version, resourceGroupName, workspaceName, body, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <param name="name"> The String to use. </param>
        /// <param name="version"> The String to use. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="body"> The EnvironmentSpecificationVersionResource to use. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<EnvironmentSpecificationVersionResource> CreateOrUpdate(string name, string version, string resourceGroupName, string workspaceName, EnvironmentSpecificationVersionResource body = null, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.CreateOrUpdate");
            scope.Start();
            try
            {
                return RestClient.CreateOrUpdate(name, version, resourceGroupName, workspaceName, body, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Get version. </summary>
        /// <param name="name"> Container name. </param>
        /// <param name="version"> Version identifier. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<EnvironmentSpecificationVersionResource>> GetAsync(string name, string version, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.Get");
            scope.Start();
            try
            {
                return await RestClient.GetAsync(name, version, resourceGroupName, workspaceName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Get version. </summary>
        /// <param name="name"> Container name. </param>
        /// <param name="version"> Version identifier. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<EnvironmentSpecificationVersionResource> Get(string name, string version, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.Get");
            scope.Start();
            try
            {
                return RestClient.Get(name, version, resourceGroupName, workspaceName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Delete version. </summary>
        /// <param name="name"> Container name. </param>
        /// <param name="version"> Version identifier. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response> DeleteAsync(string name, string version, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.Delete");
            scope.Start();
            try
            {
                return await RestClient.DeleteAsync(name, version, resourceGroupName, workspaceName, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary> Delete version. </summary>
        /// <param name="name"> Container name. </param>
        /// <param name="version"> Version identifier. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response Delete(string name, string version, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default)
        {
            using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.Delete");
            scope.Start();
            try
            {
                return RestClient.Delete(name, version, resourceGroupName, workspaceName, cancellationToken);
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <param name="name"> The String to use. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="orderby"> The String to use. </param>
        /// <param name="top"> The String to use. </param>
        /// <param name="skiptoken"> Continuation token for pagination. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="name"/>, <paramref name="resourceGroupName"/>, or <paramref name="workspaceName"/> is null. </exception>
        public virtual AsyncPageable<EnvironmentSpecificationVersionResource> ListAsync(string name, string resourceGroupName, string workspaceName, string orderby = null, string top = null, string skiptoken = null, CancellationToken cancellationToken = default)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (workspaceName == null)
            {
                throw new ArgumentNullException(nameof(workspaceName));
            }

            async Task<Page<EnvironmentSpecificationVersionResource>> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.List");
                scope.Start();
                try
                {
                    var response = await RestClient.ListAsync(name, resourceGroupName, workspaceName, orderby, top, skiptoken, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            async Task<Page<EnvironmentSpecificationVersionResource>> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.List");
                scope.Start();
                try
                {
                    var response = await RestClient.ListNextPageAsync(nextLink, name, resourceGroupName, workspaceName, orderby, top, skiptoken, cancellationToken).ConfigureAwait(false);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
        }

        /// <param name="name"> The String to use. </param>
        /// <param name="resourceGroupName"> Name of the resource group in which workspace is located. </param>
        /// <param name="workspaceName"> Name of Azure Machine Learning workspace. </param>
        /// <param name="orderby"> The String to use. </param>
        /// <param name="top"> The String to use. </param>
        /// <param name="skiptoken"> Continuation token for pagination. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="name"/>, <paramref name="resourceGroupName"/>, or <paramref name="workspaceName"/> is null. </exception>
        public virtual Pageable<EnvironmentSpecificationVersionResource> List(string name, string resourceGroupName, string workspaceName, string orderby = null, string top = null, string skiptoken = null, CancellationToken cancellationToken = default)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException(nameof(resourceGroupName));
            }
            if (workspaceName == null)
            {
                throw new ArgumentNullException(nameof(workspaceName));
            }

            Page<EnvironmentSpecificationVersionResource> FirstPageFunc(int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.List");
                scope.Start();
                try
                {
                    var response = RestClient.List(name, resourceGroupName, workspaceName, orderby, top, skiptoken, cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            Page<EnvironmentSpecificationVersionResource> NextPageFunc(string nextLink, int? pageSizeHint)
            {
                using var scope = _clientDiagnostics.CreateScope("EnvironmentSpecificationVersionsOperations.List");
                scope.Start();
                try
                {
                    var response = RestClient.ListNextPage(nextLink, name, resourceGroupName, workspaceName, orderby, top, skiptoken, cancellationToken);
                    return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse());
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }
            return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
        }
    }
}


text:
package io.enmasse.model.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import io.enmasse.common.model.AbstractHasMetadata;

public class HasMetadataValidator implements ConstraintValidator<HasMetadata, AbstractHasMetadata<?>> {

    private boolean needsNamespace;
    private boolean needsName;

    @Override
    public void initialize(HasMetadata constraintAnnotation) {
        this.needsNamespace = constraintAnnotation.needsNamespace();
        this.needsName = constraintAnnotation.needsName();
    }

    @Override
    public boolean isValid(final AbstractHasMetadata<?> value, final ConstraintValidatorContext context) {

        if (value == null) {
            return true;
        }

        if (value.getMetadata() == null) {
            return false;
        }

        if (this.needsNamespace) {
            if (value.getMetadata().getNamespace() == null) {
                return false;
            }
        }

        if (this.needsName) {
            if (value.getMetadata().getName() == null) {
                return false;
            }
        }

        return true;

    }
}


text:
\*TEMPLATE\* These are our template's recommeneded conventions, adjust to these to fit your needs. Some conventions are examples and are not demonstrated in this template. Please keep these updated with any other good conventions.

## Prismic.io Custom types

[Prismic.io custom types](https://prismic.io/docs/custom-types) are the way to define the Prismic content's document types, e.g. 'Blog post' or 'Author'. The custom types structure how the content is created in the editor UI and how it is returned by the API. The API's returned content can be viewed with [Prismic's API browser](https://metalsmith-prismic-template.prismic.io/api/documents/search?ref=Vsz0KiUAAB0AEhiu&q=%5B%5B%3Ad+%3D+at(document.type%2C+%22i18n-blog-post%22)%5D%5D&q=%5B%5B%3Ad+%3D+at(document.tags%2C+%5B%22language%3Afi%22%5D)%5D%5D#format=html).

Design your custom types carefully, it's tedious to change later when you have content and collaborate with the content creators early!

Prismic does not version custom types. To be safe and track changes, it's a good idea to keep manual copies in `prismic-custom-types`. Each file should be named in the format <custom type name>.json.

Custom types are defined as JSON files in the Prismic.io settings and should in this project follow the conventions outlined below.

## Prismic.io Fragments

Fragments are gathered in tab sections (e.g. "Main information", "Meta"); this is only used to organize fragment by tabs in the writing-room's editor, and doesn't impact the outcome through the API.

## Naming conventions

| Prismic element               | Naming                       | Example  |
| ----------------------------- |------------------------------| ---------|
| Custom types                  | kebab-case                   | `blog-post` |
| Fragments in Main section     | snake_case                   |  `title` for `<title>` element |
| Fragments in other sections   | {SECTION_NAME}_snake_case    |  `meta_title` for `<title>` element |
| uid fragments                 | snake_case                   |  `uid` |

**Important: Removing or renaming fragment fields will not automatically update the contents of the documents** Removing or renaming fields will not remove, nor hide, the existing content in existing documents. This means that they will be returned by the API, but are not accessible in the editor. Saving and publishing a new version of the document will remove any fields not present in the fragment, but until that is done for each document with a specific type, the API results and fragment field definition might be out of sync.

## Fragment conventions

Fragments should follow the conventions below to ease the work for both content creators and template developers.

### Headers

Each page should contain a `h1` level page title with the name `title`. Each page can also contain a `title_image` which will be used as the hero image of the page. Prismic.io recommends to have at least one StructuredText fragment in a document in order to be able to display a title in editor.

### Metadata

Each page can contain following metadata properties:

  * `uid`: unique identifier that is part of the page url, e.g. uid `minna` will result in url `/fi/author/minna`. If not included in the meta fragment, the automatically generated slug will be used, e.g. `/blog-post/my-first-blog-post`.
  * `meta_title`: HTML `<title>` element content

### Links

Links should **not** be defined as a `StructuredText` fields, unless links are directly part of a longer piece of content because it makes the content creator UI quite cumbersome. Additionally it makes it difficult to style the link or separate links from text in the templates.

Instead links should be defined as groups with two fields `target` and `text` which contain the link target and link text. See Link could also include additional fields like `image` or `popup` to further control the link behavior. For example:

```json
{
  "author_link" : {
    "type" : "Group",
    "config" : {
      "fields" : {
        "target" : {
          "type" : "Link",
          "config" : {
            "select" : "document",
            "customtypes" : [ "author" ],
            "placeholder" : "Select blog post authors..."
          }
        },
        "text" : {
          "type" : "Text",
          "config" : {
            "placeholder" : "Author link text here...",
            "label" : "Author link text"
          }
        }
      }
    }
  }
}
```

If due to nesting restrictions the link cannot be defined as a group, the link should be composed of multiple fields, each one prefixed with the link name, e.g. `author_link_target`.

Note: Anchor tags have to be manually added to links in the templates.

### StructuredText styling

To keep StructuredText field styling consistent across the application, content creators should be given as limited options as possible for styling. Also don't give in to the temptation of using structured text for everything.

Headings should be updated as needed for proper page structuring.

In addition StructuredText fragments can be extended with [labels](https://blog.prismic.io/VAcbSjEAADMAtjS8/label-your-structured-text-for-richer-display-experience-quotes-tips-captions). These labels can even have icons ([undocumented feature](https://qa.prismic.io/250/label-icons-and-validity-documentation)).

#### Simple description (one paragraph)

Should be used for simple description texts, e.g. in headers. Includes only the minimum styling options.

```json
{
  "single": "paragraph,strong,em"
}
```

#### Simple content (multiple paragraphs)

Should be used for short descriptions in pages with limited styling options.

```json
{
  "multi": "heading3,heading4,heading5,heading6,preformatted,paragraph,strong,em,hyperlink,image"
}
```

#### Full content (multiple paragraphs)

Should be used for full content pages, such as blog posts. Includes all styling options except for `h1`, which should be a separate `title` fragment.

```json
{
  "multi": "heading2,heading3,heading4,heading5,heading6,preformatted,paragraph,strong,em,hyperlink,olist,o-list-item,ulist,list-item,image,embed"
}
```

### Other notes on custom types

* Prismic does *not* support nested lists in fragments
  * You can't put a group within a group
  * You can't use the array notation within a group

## Media library

"Tag" your images and documents in the media library by writing something in the "Private notes" fields. Otherwise it will be hard to find anything once there is a lot of content.

## i18n conventions

Prismic's recommendation for i18n is explained [here](https://qa.prismic.io/29/will-multi-lingual-sites-be-supported-in-the-future). It might not make sense to have a parent document in every case, so this project uses language tags instead.

Each document should have only one language tag of the format: `language:<ISO 639-1 language code>`, e.g. `language:fi`.

## Development and Production environments

We recommend keeping two copies of your Prismic repositories: development and production. After development ends and all production data is entered into a repository, you can ask Prismic.io to copy your repository. As default in development you should use the production Prismic content. But when changes to Prismic content are needed (especially custom types), you can switch to the development Prismic repository and freely play around with the content and try custom types changes. Changes that should go into production can be documented with the custom-type backups. When the changes are tested, they can be copied to the production Prismic repository.

## Resources

* [Old Prismic.io docs](https://developers.prismic.io/)
* [New Prismic.io docs (non-comprehensive)](https://prismic.io/docs#?lang=node)
* [Forums](https://qa.prismic.io/)


text:
"use strict";

module.exports = {

    /**
     * Subscribe on collections entries' events
     * @param {function(Spec|string, Object, {deliver: function()})} callback
     * @this Set|Vector
     */
    onObjectEvent: function (callback) {
        this._proxy.owner = this;
        this._proxy.on(callback);
    },

    /**
     * Unsubscribe from collections entries' events
     * @param {function(*)} callback
     * @this Set|Vector
     */
    offObjectEvent: function (callback) {
        this._proxy.off(callback);
    },

    /**
     * Waits for collection to receive state from cache or uplink and then invokes passed callback
     *
     * @param {function()} callback
     * @this Set|Vector
     */
    onObjectStateReady: function (callback) { // TODO timeout ?
        var self = this;
        function checker() {
            var notInitedYet = self.filter(function (entry) {
                return !entry._version;
            });
            if (!notInitedYet.length) {
                // all entries are inited
                callback();
            } else {
                // wait for some entry not ready yet
                var randomIdx = (Math.random() * (notInitedYet.length - 1)) | 0;
                notInitedYet[randomIdx].once('init', checker);
            }
        }
        if (this._version) {
            checker();
        } else {
            this.once('init', checker);
        }
    }
};


text:
<?php
/*
Template Name: Show Projects
*/

get_template_part('templates/content', 'projects'); ?>


text:
package com.thoughtworks.go.config.materials;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.SecretParamAware;
import com.thoughtworks.go.config.SecretParams;
import com.thoughtworks.go.domain.MaterialRevision;
import com.thoughtworks.go.domain.materials.*;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import com.thoughtworks.go.util.command.InMemoryStreamConsumer;
import com.thoughtworks.go.util.command.ProcessOutputStreamConsumer;
import com.thoughtworks.go.util.command.UrlArgument;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Map;
import java.util.Optional;

import static com.thoughtworks.go.util.command.EnvironmentVariableContext.escapeEnvironmentVariable;

/**
 * @understands a source control repository and its configuration
 */
public abstract class ScmMaterial extends AbstractMaterial implements SecretParamAware {

    public static final String GO_REVISION = "GO_REVISION";
    public static final String GO_TO_REVISION = "GO_TO_REVISION";
    public static final String GO_FROM_REVISION = "GO_FROM_REVISION";
    public static final String GO_MATERIAL_URL = "GO_MATERIAL_URL";

    protected Filter filter;
    protected String folder;
    protected boolean autoUpdate = true;
    protected boolean invertFilter = false;
    protected String userName;
    protected String password;
    protected SecretParams secretParamsForPassword;

    public ScmMaterial(String typeName) {
        super(typeName);
    }

    @Override
    protected void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria) {
        basicCriteria.put("dest", folder);
    }

    public File workingdir(File baseFolder) {
        if (getFolder() == null) {
            return baseFolder;
        }
        return new File(baseFolder, getFolder());
    }

    public String updatingTarget() {
        return StringUtils.isEmpty(getFolder()) ? "files" : getFolder();
    }

    @Override
    public void toJson(Map json, Revision revision) {
        json.put("folder", getFolder() == null ? "" : getFolder());
        json.put("scmType", getTypeForDisplay());
        json.put("location", getLocation());
        if (!CaseInsensitiveString.isBlank(getName())) {
            json.put("materialName", CaseInsensitiveString.str(getName()));
        }
        json.put("action", "Modified");
    }

    //most of the material such as hg, git, p4 all print the file from the root without '/'
    //but subversion print it with '/', we standarize it here. look at the implementation of subversion as well.

    @Override
    public boolean matches(String name, String regex) {
        if (regex.startsWith("/")) {
            regex = regex.substring(1);
        }
        return name.matches(regex);
    }

    public void checkout(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {
        InMemoryStreamConsumer output = ProcessOutputStreamConsumer.inMemoryConsumer();
        this.updateTo(output, baseDir, new RevisionContext(revision), execCtx);
    }

    public String getUserName() {
        return this.userName;
    }

    /* Needed although there is a getUserName above */
    public String getUsername() {
        return userName;
    }

    public final void setPassword(String password) {
        resetPassword(password);
    }

    private void resetPassword(String passwordToSet) {
        setPasswordIfNotBlank(passwordToSet);
    }

    private void setPasswordIfNotBlank(String password) {
        this.password = StringUtils.stripToNull(password);
        this.secretParamsForPassword = SecretParams.parse(password);
    }

    @PostConstruct
    public void ensureEncrypted() {
        this.userName = StringUtils.stripToNull(this.userName);
        setPasswordIfNotBlank(password);
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public String passwordForCommandLine() {
        return secretParamsForPassword == null || secretParamsForPassword.isEmpty() ? getPassword() : secretParamsForPassword.substitute(getPassword());
    }

    @Override
    public boolean hasSecretParams() {
        return this.secretParamsForPassword != null && !this.secretParamsForPassword.isEmpty();
    }

    @Override
    public SecretParams getSecretParams() {
        return secretParamsForPassword;
    }

    public abstract boolean isCheckExternals();

    public abstract String getUrl();

    public abstract String urlForCommandLine();

    protected abstract UrlArgument getUrlArgument();

    protected abstract String getLocation();

    public void setFilter(Filter filter) {
        this.filter = filter;
    }

    @Override
    public void emailContent(StringBuilder content, Modification modification) {
        content.append(getTypeForDisplay() + ": " + getLocation()).append('\n').append(
                String.format("revision: %s, modified by %s on %s", modification.getRevision(),
                        modification.getUserName(), modification.getModifiedTime()))
                .append('\n')
                .append(Optional.ofNullable(modification.getComment()).orElse(""));

    }

    @Override
    public String getDescription() {
        return getUriForDisplay();
    }

    @Override
    public String getUriForDisplay() {
        return this.getUrlArgument().forDisplay();
    }

    @Override
    public void populateEnvironmentContext(EnvironmentVariableContext environmentVariableContext, MaterialRevision materialRevision, File workingDir) {
        String toRevision = materialRevision.getRevision().getRevision();
        String fromRevision = materialRevision.getOldestRevision().getRevision();

        setGoRevisionVariables(environmentVariableContext, fromRevision, toRevision);
        setGoMaterialVariables(environmentVariableContext);
    }

    protected void setGoMaterialVariables(EnvironmentVariableContext environmentVariableContext) {
        setVariableWithName(environmentVariableContext, this.getUrlArgument().withoutCredentials(), GO_MATERIAL_URL);
    }

    private void setGoRevisionVariables(EnvironmentVariableContext environmentVariableContext, String fromRevision, String toRevision) {
        setVariableWithName(environmentVariableContext, toRevision, GO_REVISION);
        setVariableWithName(environmentVariableContext, toRevision, GO_TO_REVISION);
        setVariableWithName(environmentVariableContext, fromRevision, GO_FROM_REVISION);
    }

    protected void setVariableWithName(EnvironmentVariableContext environmentVariableContext, String value, String propertyName) {
        String materialNameForEnvironmentVariable = getMaterialNameForEnvironmentVariable();
        if (StringUtils.isNotBlank(materialNameForEnvironmentVariable)) {
            environmentVariableContext.setProperty(propertyName + "_" + materialNameForEnvironmentVariable, value, false);
        } else {
            environmentVariableContext.setProperty(propertyName, value, false);
        }
    }

    @Override
    public String getMaterialNameForEnvironmentVariable() {
        if (!CaseInsensitiveString.isBlank(this.name)) {
            return escapeEnvironmentVariable(this.name.toUpper());
        }

        return escapeEnvironmentVariable(folder);
    }

    @Override
    public String getFolder() {
        return folder;
    }

    @Override
    public String getDisplayName() {
        return name == null ? getUriForDisplay() : CaseInsensitiveString.str(name);
    }

    @Override
    public boolean isAutoUpdate() {
        return autoUpdate;
    }

    public boolean getAutoUpdate() {
        return autoUpdate;
    }

    public void setAutoUpdate(boolean value) {
        autoUpdate = value;
    }

    public boolean isInvertFilter() {
        return invertFilter;
    }

    public boolean getInvertFilter() {
        return invertFilter;
    }

    public void setInvertFilter(boolean value) {
        invertFilter = value;
    }

    @Override
    public final MatchedRevision createMatchedRevision(Modification modification, String searchString) {
        return new MatchedRevision(searchString, getShortRevision(modification.getRevision()), modification.getRevision(), modification.getUserName(), modification.getModifiedTime(), modification.getComment());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }

        ScmMaterial that = (ScmMaterial) o;

        return folder != null ? folder.equals(that.folder) : that.folder == null;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (folder != null ? folder.hashCode() : 0);
        return result;
    }

    public static String changesetUrl(Modification modification, String baseUrl, final long id) {
        return baseUrl + "/api/materials/" + id + "/changeset/" + modification.getRevision() + ".xml";
    }

    @Override
    public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) {
        return false;
    }

    // TODO: Consider renaming this to dest since we use that word in the UI & Config
    public void setFolder(String folder) {
        this.folder = folder;
    }

    @Override
    public Revision oldestRevision(Modifications modifications) {
        return Modification.oldestRevision(modifications);
    }

    @Override
    public boolean supportsDestinationFolder() {
        return true;
    }
}


text:
This is a set of PHP classes which you can use to generate fine-looking avatars from Minecraft skins.

## Types

There are currently 4 different types available.

#### Avatar

Generates image from the face region of player's Minecraft skin.

![Avatar](img/avatar.png)

#### Skin

Generates image from the body region (front) of player's Minecraft skin.

![Skin](img/skin.png)

#### Combo

Generates image combining face and body region of player's Minecraft skin.

![Combo](img/combo.png)

#### Isometric

Generates 3D-like image from the head region of player's Minecraft skin.

![Isometric](img/isometric.png)

## Usage

All 4 classes are used in a very similar fashion.

```php
require_once("avatar.class.php");

// parameters: Minecraft username (case sensitive!), size
$avatar = new Avatar("The_HusKy", 64);
$avatar->show()
```

Combo class has 2 special methods `setX` and `setY` which allow you to move the skin around.

## License

MIT. See `LICENSE`.


text:
package org.openksavi.sponge.core.rule;

import org.openksavi.sponge.event.Event;
import org.openksavi.sponge.rule.Rule;

/**
 * Script knowledge base rule event condition.
 */
public class ScriptKnowledgeBaseEventCondition extends MethodNameEventCondition {

    /**
     * Creates a new knowledge base rule event condition.
     *
     * @param methodName knowledge base rule method name.
     */
    public ScriptKnowledgeBaseEventCondition(String methodName) {
        super(methodName);
    }

    /**
     * Checks rule event condition by evaluating the defined knowledge base rule method.
     *
     * @param rule rule.
     * @param event event.
     * @return {@code true} if this condition is met.
     */
    @Override
    public boolean condition(Rule rule, Event event) {
        Object result = rule.getKnowledgeBase().getInterpreter().invokeMethod(rule, getMethodName(), event);

        if (!(result instanceof Boolean)) {
            throw new IllegalArgumentException("Condition method must return boolean value");
        }

        return (Boolean) result;
    }
}


text:
package testtask.avast.budgetbuddy.controller;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import testtask.avast.budgetbuddy.model.BudgetTransaction;

public class TransactionDBController extends AbstractDBController<BudgetTransaction> {

	public static final String TABLE_NAME = "transactions";
	public static final String COLUMN_ID = "_id";
	public static final String COLUMN_GUID = "guid";
	public static final String COLUMN_DESC = "desc";
	public static final String COLUMN_TIMESTAMP = "timestamp";
	public static final String COLUMN_VALUE = "amount";
	public static final String COLUMN_DELETED = "deleted";
	public static final String COLUMN_SYNCED = "synced";

    public static final String SQL_READ_ALL_STATEMENT = "SELECT " + TransactionDBController.COLUMN_ID
			+ ", " + TransactionDBController.COLUMN_GUID
			+ ", " + TransactionDBController.COLUMN_DESC
			+ ", " + TransactionDBController.COLUMN_TIMESTAMP
			+ ", " + TransactionDBController.COLUMN_VALUE
			+ ", " + TransactionDBController.COLUMN_DELETED
			+ " FROM " + TransactionDBController.TABLE_NAME + " ORDER BY " + TransactionDBController.COLUMN_TIMESTAMP;

    public static final String SQL_DONT_READ_DELETED_STATEMENT = "SELECT " + TransactionDBController.COLUMN_ID
			+ ", " + TransactionDBController.COLUMN_GUID
			+ ", " + TransactionDBController.COLUMN_DESC
			+ ", " + TransactionDBController.COLUMN_TIMESTAMP
			+ ", " + TransactionDBController.COLUMN_VALUE
			+ ", " + TransactionDBController.COLUMN_DELETED
			+ " FROM " + TransactionDBController.TABLE_NAME
			+ " WHERE " + TransactionDBController.COLUMN_DELETED + " = '0'"
			 + " ORDER BY " + TransactionDBController.COLUMN_TIMESTAMP;

	public TransactionDBController(SQLiteDatabase database) {
		super(database);
	}

	@Override
	public boolean insert(BudgetTransaction obj) {
		if (obj == null)
			return false;

		long res = mDatabase.insert(TABLE_NAME, null, getContentValues(obj));

		return res != -1;
	}

	@Override
	public boolean delete(BudgetTransaction obj) {
		if (obj == null)
			return false;

		int res = mDatabase.delete(TABLE_NAME, COLUMN_ID + " = " + obj.getID(), null);

		return res != 0;
	}

	@Override
	public boolean update(BudgetTransaction obj) {
		if (obj == null)
			return false;

		int res = mDatabase.update(TABLE_NAME, getContentValues(obj), COLUMN_ID + " = " + obj.getID(), null);

		return res != 0;
	}

	@Override
	public List<BudgetTransaction> read() {
		Cursor cursor = mDatabase.query(TABLE_NAME, getAllColumns(), null, null, null, null, null);
		List<BudgetTransaction> transactions = new ArrayList<BudgetTransaction>();
		if ( cursor != null && cursor.moveToFirst() ) {
			while (!cursor.isAfterLast()) {
				transactions.add( getBudgetTransaction(cursor) );
				cursor.moveToNext();
			}
			cursor.close();
		}

		return transactions;
	}

	@Override
	public List<BudgetTransaction> read(String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
		Cursor cursor = mDatabase.query(TABLE_NAME, getAllColumns(), selection, selectionArgs, groupBy, having, orderBy);
		List<BudgetTransaction> transactions = new ArrayList<BudgetTransaction>();
		if ( cursor != null && cursor.moveToFirst() ) {
			while ( !cursor.isAfterLast() ) {
				transactions.add( getBudgetTransaction(cursor) );
				cursor.moveToNext();
			}
			cursor.close();
		}

		return transactions;
	}

	public String[] getAllColumns() {
		return new String[] { COLUMN_ID, COLUMN_GUID, COLUMN_DESC, COLUMN_TIMESTAMP, COLUMN_VALUE, COLUMN_DELETED, COLUMN_SYNCED };
	}

	public BudgetTransaction getBudgetTransaction(Cursor cursor) {
		if (cursor == null)
			return null;

		BudgetTransaction transaction = new BudgetTransaction();
		transaction.setID( cursor.getInt(cursor.getColumnIndex(COLUMN_ID)) );
		transaction.setGUID( cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) );
		transaction.setDesc( cursor.getString(cursor.getColumnIndex(COLUMN_DESC)) );
		transaction.setTimestamp( cursor.getLong(cursor.getColumnIndex(COLUMN_TIMESTAMP)) );
		transaction.setAmount( cursor.getDouble(cursor.getColumnIndex(COLUMN_VALUE)) );
		transaction.setDeleted( cursor.getInt(cursor.getColumnIndex(COLUMN_DELETED)) > 0 );
		transaction.setSynced( cursor.getInt(cursor.getColumnIndex(COLUMN_SYNCED)) > 0 );

		return transaction;
	}

	public ContentValues getContentValues(BudgetTransaction obj) {
		if (obj == null)
			return null;

		ContentValues values = new ContentValues();
		values.put(COLUMN_GUID, obj.getGUID());
		values.put(COLUMN_DESC, obj.getDesc());
		values.put(COLUMN_TIMESTAMP, obj.getTimestamp());
		values.put(COLUMN_VALUE, obj.getAmount());
		values.put(COLUMN_DELETED, obj.isDeleted() ? "1" : "0");
		values.put(COLUMN_SYNCED, obj.isSynced());
		return values;
	}

}


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

public class CircularBuffer<T>
{
    private readonly int capacity;
    private List<T> items;

    public CircularBuffer(int capacity)
    {
        this.capacity = capacity;
        items = new List<T>(capacity);
    }

    public T Read()
    {
        if (items.Count == 0)
        {
            throw new InvalidOperationException("Cannot read from empty buffer");
        }

        var value = items[0];

        DequeueHead();

        return value;
    }

    public void Write(T value)
    {
        if (items.Count == capacity)
        {
            throw new InvalidOperationException("Cannot write to full buffer");
        }

        items.Add(value);
    }

    public void Overwrite(T value)
    {
        if (items.Count == capacity)
        {
            DequeueHead();
        }

        Write(value);
    }

    public void Clear() => items.Clear();

    private void DequeueHead() => items = items.Skip(1).ToList();
}