text:
__author__ = '3404199'

import numpy as np
import Parser
import itertools
import Tools
from Models import *
from multiprocessing import Pool

def evalSVD(config):
    pairs_lt = Tools.folder2pairs(r"../ml-100k/")
    m_score = 0.0
    for pair in pairs_lt:
        svd = SVD(pair[0], k=config[0])
        try:
            score = svd.predict(Parser.MatrixParser.txttocsc(pair[1]))
            m_score += score
        except FloatingPointError:
            score = -100
            m_score += score
            print "FP ERROR", pair[2], config
            break
        except:
            score = -500
            m_score += score
            print "PREDICT ERROR", pair[2], config
            break
        # m_score += score

    m_score /= len(pairs_lt)
    print "{:2d}, {:2.4f}".format(config[0], m_score)
    return m_score

def main():
    # Configs de test
    nZ = [2, 5, 10, 20, 50, 100, 200, 400, 800]

    configs = list(itertools.product(nZ))
    print "n configs: ", len(configs)
    # Loop en parallele
    nthreads = 7
    parallel_pool = Pool(nthreads)
    scores = []
    try:
        scores = parallel_pool.map(evalSVD, configs)
    except KeyboardInterrupt:
        print "Interrupt from keyboard, saving log"

    with open("log_svd.csv", 'w') as f:
        f.write("nZ,score\n")
        for i in xrange(len(configs)):
            config = configs[i]
            f.write("{},{}\n".format(config[0], scores[i]))

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace StrokerCacheTest\Options;

use StrokerCache\Options\ModuleOptions;

class ModuleOptionsTest extends \PHPUnit_Framework_TestCase
{
    /** @var ModuleOptions */
    protected $options;

    public function setUp()
    {
        $this->options = new ModuleOptions();
    }

    public function testGetSetStrategies()
    {
        $strategies = array('foo', 'bar');
        $this->options->setStrategies($strategies);
        $this->assertEquals($strategies, $this->options->getStrategies());
    }

    public function testGetSetStorageAdapter()
    {
        $storageAdapter = array(
            'name' => 'foo',
            'options' => array(
                'foo' => 'bar'
            )
        );
        $this->options->setStorageAdapter($storageAdapter);
        $this->assertEquals($storageAdapter, $this->options->getStorageAdapter());
    }

    public function testGetSetIdGenerator()
    {
        $this->options->setIdGenerator('foo');
        $this->assertEquals('foo', $this->options->getIdGenerator());
    }
}


text:
title: Barões detrás do morro
date: 2018-12-30 00:00:00 -02:00
categories:
- development
tags:
- Filme
- Drama
position: 9
lang: pt
team:
  director: Germano de Oliveira
  writer: Germano de Oliveira e Marcela Bordin
  copro: Avante Filmes, Besouro Filmes e Casa de Cinema de Porto Alegre
media:
  image: https://cldup.com/Yw42nJfuQ6.jpg
funds:
- Edital Plataforma FUMPROARTE 2016
---

Numa comunidade isolada, localizada entre morros e névoas, a jovem Ana percebe alguns seres estranhos vivendo nas florestas do outro lado do rio. Ela ouve a história de uma seita perigosa que foi brutalmente atacada muitos anos atrás no mesmo lugar, e então começa a procurar a história não contada a vila.

---

## Labs e mercados:

* **Olhar de Cinema** '16 / Curitiba_Lab


text:
import os
import time
import logging
from functools import wraps
from socket import socket, AF_INET, SOCK_DGRAM, error as SocketEror

log = logging.getLogger(name='carbonstat')

class MetricTimer(object):
    def __init__(self, metric):
        self.metric = metric
        self.start()

    def start(self):
        """Start measuring execution time"""
        self.running = True
        self.start_time = time.time()

    def stop(self):
        """Stop timer and save execution time"""
        if self.running:
            self.metric.add_ex(time.time() - self.start_time)
            self.running = False
        else:
            raise Exception('Timer is not running')

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.running:
            self.stop()

class Metric(object):
    """
    simple_metric = Metric('foo')
    for i in range(10):
        foo(i)
        simple_metric.add(1)  # increment simple metric value
    print(metric.simple_value)  # 10

    extended_metric = Metric('bar')
    with extended_metric.timer() as timer:
        for i in range(10):
            timer.start()
            bar(i)
            timer.stop()
    print(metric.min, metric.max, metric.avg)
    # here metric.avg is sum of [t(bar(0)), ..., t(bar(9))] / 10
    #      metric.min is min of [t(bar(0)), ..., t(bar(9))]
    #      metric.max is max of [t(bar(0)), ..., t(bar(9))]

    with extended_metric.timer():
        bar(10)
        # stopping the timer with exit
    """
    def __init__(self, name):
        self.name = name
        self.simple_value = None
        self.simple_timestamp = None
        self.min, self.max = float('inf'), float('-inf')
        self.sum, self.len = 0, 0
        self.timestamp = None
        self.accumulate = False
        self.extended = False

    def add(self, value):
        """Add a value to a simple value stored in metric"""
        try:
            self.simple_value += value
        except TypeError:
            self.simple_value = value
        self.simple_timestamp = time.time()

    def incr(self, amount=1):
        """Increment a simple value stored in metric"""
        self.add(amount)

    def decr(self, amount=1):
        """Decrement a simple value stored in metric"""
        self.add(-amount)

    def set(self, value):
        """Set a value to a simple value stored in metric"""
        self.simple_value = value
        self.simple_timestamp = time.time()

    def add_ex(self, value):
        """
        Add a value to "set" of values stored in metric

        For this "set" of values we can calculate min., max., avg. values.
        """
        self.sum += value
        self.len += 1
        if value < self.min:
            self.min = value
        if value > self.max:
            self.max = value
        self.timestamp = time.time()

    @property
    def avg(self):
        return self.sum / float(self.len)

    def timer(self):
        """Get timer for measuring execution time inside context manager"""
        self.extended = True
        return MetricTimer(self)

class CarbonMetric(Metric):
    def __init__(self, name, namespace):
        super(CarbonMetric, self).__init__(name)
        self.ns = namespace
        self.name = name

    def __str__(self):
        name = '%s.%s' % (self.ns, self.name) if self.ns else self.name
        ret = ''
        if self.simple_value is not None:
            ret += '%s %s %f\n' % (name, self.simple_value,
                                   self.simple_timestamp)
        if self.len:
            ret += '\n'.join(['%s.%s %s %s' % (name, value_name,
                                               getattr(self, value_name),
                                               self.timestamp)
                              for value_name in ['min', 'avg', 'max']]) + '\n'
        return ret

class CarbonStat(object):
    """
    stat = CarbonStat(host='127.0.0.1', port=2003)

    for i in range(10):
        foo(i)
        stat['simple'].add(1)  # increment simple metric value
    print(stat['simple'].simple_value)  # 10

    with stat.timer('extended') as timer:
        for i in range(10):
            timer.start()
            bar(i)
            timer.stop()
    print(stat['extended'].min, stat['extended'].max, stat['extended'].avg)
    # here stat['extended'].avg is sum of [t(bar(0)), ..., t(bar(9))] / 10
    #      stat['extended'].min is min of [t(bar(0)), ..., t(bar(9))]
    #      stat['extended'].max is max of [t(bar(0)), ..., t(bar(9))]

    with stat.timer('extended'):
        bar(10)
        # stopping the timer with exit

    stat.send()  # send packet to Carbon
    """
    def __init__(self, host='127.0.0.1', port=2003, namespace=''):
        self.host = host
        self.port = port
        self.ns = namespace
        self.metrics = {}
        self.__socket = None
        self.__heartbeat = -1
        self.__sending = False

    def __getitem__(self, name):
        """Get metric object with name `name`"""
        return self.metrics.setdefault(name, CarbonMetric(name, self.ns))

    @property
    def socket(self):
        if not self.__socket:
            try:
                self.__socket = socket(AF_INET, SOCK_DGRAM)
            except SocketEror as e:
                log.error('Could not create socket: %s', str(e))
                raise

        return self.__socket

    @property
    def heartbeat(self):
        self.__heartbeat = (self.__heartbeat + 1) % 2 ** 32
        return self.__heartbeat

    def set_namespace(self, namespace):
        """Set new namespace"""
        self.ns = namespace

    def timer(self, metric_name):
        """
        Get timer for measuring execution time inside context manager

        with stat.timer('foo') as timer:
            for a in range(10):
                timer.start()
                # some your code
                timer.stop()

        stat.send()  # send info about execution of your code 10 times
        """
        return self[metric_name].timer()

    def timeit(self, metric_name):
        """
        Decorator for measuring execution time of your function

        @stat.timeit('foo')
        def foo(a):
            sleep(a)

        for a in range(10):
            foo(a)

        stat.send()  # send info about execution of `foo` function 10 times
        """
        def decorator(function):
            @wraps(function)
            def wrapped(*args, **kwargs):
                with self.timer(metric_name):
                    return function(*args, **kwargs)
            return wrapped
        return decorator

    def make_header(self):
        header = 'heartbeat {} {}\n'.format(self.heartbeat, time.time())
        if self.ns:
            header = '{}.{}'.format(self.ns, header)
        return header

    def send(self):
        """Send group of collected metrics and clear the group"""
        if self.__sending:
            return
        else:
            self.__sending = True

        metrics, self.metrics = self.metrics, {}

        packet = self.make_header()
        for metric in metrics.values():
            if metric.accumulate:
                if not metric.extended:
                    self[metric.name].add(metric.simple_value)
                else:
                    self.metrics[metric.name] = metric
                self[metric.name].accumulate = True
            packet += str(metric)

        try:
            self.socket.sendto(packet, (self.host, self.port))
        except SocketEror as e:
            log.debug('Packet:\n%s', packet)
            log.error('Could not send packet to Carbon %s: %s', self.host, str(e))
            self.metrics.update(metrics)
        finally:
            self.__sending = False

host = os.environ.get('CARBON_HOST', '127.0.0.1')
port = int(os.environ.get('CARBON_PORT', '2003'))
namespace = os.environ.get('CARBON_NAMESPACE', 'carbonstat')
stat = CarbonStat(host=host, port=port, namespace=namespace)


text:
@implementation CBCentralManager(Ext)
- (NSString *)stateString
{
    switch (self.state) {
        case CBCentralManagerStatePoweredOff:
            return @"Powered Off";
            break;

        case CBCentralManagerStateResetting:
            return @"Resetting";
            break;

        case CBCentralManagerStatePoweredOn:
            return @"Powered On";
            break;

        case CBCentralManagerStateUnauthorized:
            return @"Unauthorized";
            break;

        case CBCentralManagerStateUnknown:
            return @"Unknown";
            break;

        case CBCentralManagerStateUnsupported:
            return @"Unsupported";
            break;
    }
}
@end


text:
package org.ec.jap.bo.sistema.impl;

import java.util.Date;
import java.util.HashMap;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.ec.jap.bo.saap.TipoFiltroBO;
import org.ec.jap.bo.sistema.FiltroBO;
import org.ec.jap.dao.sistema.impl.FiltroDAOImpl;
import org.ec.jap.entiti.saap.Usuario;
import org.ec.jap.entiti.sistema.ElementoSistema;
import org.ec.jap.entiti.sistema.Filtro;
import org.ec.jap.entiti.sistema.TipoFiltro;

/**
 * Session Bean implementation class DatAuditoriaBO
 */
@Stateless
public class FiltroBOImpl extends FiltroDAOImpl implements FiltroBO {

	@EJB
	TipoFiltroBO tipoFiltroBO;

	/**
	 * Default constructor.
	 */
	public FiltroBOImpl() {
	}

	@Override
	public Filtro getFiltro(Usuario idUser, String tipoFiltro, ElementoSistema elementoSistema, Object value) throws Exception {
		TipoFiltro tipoFiltro2 = tipoFiltroBO.findByPk(tipoFiltro);
		if (tipoFiltro2 == null) {
			tipoFiltro2 = new TipoFiltro();
			tipoFiltro2.setCodigo(tipoFiltro);
			tipoFiltro2.setDescripcion("Default");
			tipoFiltroBO.save(idUser, tipoFiltro2);
		}
		HashMap<String, Object> p = new HashMap<>();
		p.put("tp", tipoFiltro2);
		p.put("u", idUser);
		p.put("e", elementoSistema);
		Filtro filtro = findByNamedQuery("Filtro.findByTipoAndUser", p);
		if (filtro == null) {
			filtro = new Filtro();
			filtro.setCodigo(tipoFiltro2);
			filtro.setIdComunidad(idUser.getIdComunidad());
			filtro.setIdElementoSistema(elementoSistema);
			filtro.setIdUsuario(idUser);
			if (value instanceof Integer)
				filtro.setValorEntero((Integer) value);
			if (value instanceof String)
				filtro.setValorCadena(value.toString());
			if (value instanceof Double)
				filtro.setValorNumerico((Double) value);
			if (value instanceof Date)
				filtro.setValorFecha((Date) value);
			save(idUser, filtro);
		} else {

			if (value instanceof Integer) {
				filtro.setValorEntero((Integer) value);
			}
			if (value instanceof String) {
				filtro.setValorCadena(value.toString());
			}
			if (value instanceof Double) {
				filtro.setValorNumerico((Double) value);
			}
			if (value instanceof Date) {
				filtro.setValorFecha((Date) value);
			}
			if (value instanceof Boolean) {
				filtro.setValorBoolean((Boolean) value);
			}
			update(idUser, filtro);
		}

		return filtro;
	}

	@Override
	public Filtro getFiltro(Usuario idUser, String tipoFiltro, ElementoSistema elementoSistema, Object valueDefect, Filtro filtro, Boolean isParame) throws Exception {
		if (filtro != null) {
			update(idUser, filtro);
			return filtro;
		} else {

			TipoFiltro tipoFiltro2 = tipoFiltroBO.findByPk(tipoFiltro);
			if (tipoFiltro2 == null) {
				tipoFiltro2 = new TipoFiltro();
				tipoFiltro2.setCodigo(tipoFiltro);
				tipoFiltro2.setDescripcion("Default");
				tipoFiltroBO.save(idUser, tipoFiltro2);
			}
			HashMap<String, Object> p = new HashMap<>();
			p.put("tp", tipoFiltro2);
			p.put("u", idUser);
			p.put("e", elementoSistema);
			Filtro filtroFirst = findByNamedQuery("Filtro.findByTipoAndUser", p);
			if (filtroFirst == null) {
				filtroFirst = new Filtro();
				filtroFirst.setCodigo(tipoFiltro2);
				filtroFirst.setIdComunidad(idUser.getIdComunidad());
				filtroFirst.setIdElementoSistema(elementoSistema);
				filtroFirst.setIdUsuario(idUser);
				if (valueDefect instanceof Integer)
					filtroFirst.setValorEntero((Integer) valueDefect);
				if (valueDefect instanceof String)
					filtroFirst.setValorCadena(valueDefect.toString());
				if (valueDefect instanceof Double)
					filtroFirst.setValorNumerico((Double) valueDefect);
				if (valueDefect instanceof Date)
					filtroFirst.setValorFecha((Date) valueDefect);
				save(idUser, filtroFirst);
				return filtroFirst;
			} else {
				if (isParame) {
					if (valueDefect instanceof Integer)
						filtroFirst.setValorEntero((Integer) valueDefect);
					if (valueDefect instanceof String)
						filtroFirst.setValorCadena(valueDefect.toString());
					if (valueDefect instanceof Double)
						filtroFirst.setValorNumerico((Double) valueDefect);
					if (valueDefect instanceof Date)
						filtroFirst.setValorFecha((Date) valueDefect);
					update(idUser, filtroFirst);
				}
				return filtroFirst;
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<!-- The attributes in this XML file provide configuration information -->

<!--

android:settingsActivity="com.ghisguth.sun.WallpaperSettings"
-->
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
           android:thumbnail="@drawable/thumbnail"
           android:description="@string/description"
           android:settingsActivity="com.ghisguth.sun.WallpaperSettings"/>


text:
#include "k_python_dict.h"

namespace kroll
{
	KPythonDict::KPythonDict(PyObject *obj) :
		KObject("Python,KPythonDict"),
		object(obj)
	{
		PyLockGIL lock;
		Py_INCREF(this->object);
	}

	KPythonDict::~KPythonDict()
	{
		PyLockGIL lock;
		Py_DECREF(this->object);
		this->object = 0;
	}

	void KPythonDict::Set(const char* name, KValueRef value)
	{
		PyLockGIL lock;
		PyObject* pyval = PythonUtils::ToPyObject(value);
		int result = PyMapping_SetItemString(this->object, (char*)name, pyval);

		if (result == -1 && PyErr_Occurred() != 0)
		{
			THROW_PYTHON_EXCEPTION
		}
	}

	KValueRef KPythonDict::Get(const char *name)
	{
		PyLockGIL lock;

		if (PyMapping_HasKeyString(this->object, (char*) name) == 0)
			return Value::Undefined;

		PyObject* item = PyMapping_GetItemString(this->object, (char*) name);
		if (item == 0 && PyErr_Occurred())
		{
			THROW_PYTHON_EXCEPTION;
		}

		try
		{
			KValueRef value = PythonUtils::ToKrollValue(item);
			Py_DECREF(item);
			return value;
		}
		catch (...)
		{
			Py_DECREF(item);
			throw;
		}
	}

	bool KPythonDict::Equals(KObjectRef other)
	{
		AutoPtr<KPythonDict> pyOther = other.cast<KPythonDict>();

		// This is not a Python object
		if (pyOther.isNull())
			return false;

		return pyOther->ToPython() == this->ToPython();
	}

	SharedStringList KPythonDict::GetPropertyNames()
	{
		PyLockGIL lock;
		SharedStringList property_names = new StringList();

		// Avoid compiler warnings
		PyObject *items = PyObject_CallMethod(this->object, (char*) "items", 0);
		if (items == 0)
			return property_names;

		PyObject *iterator = PyObject_GetIter(items);
		if (iterator == 0)
			return property_names;

		PyObject *item;
		while ((item = PyIter_Next(iterator))) {
			PyObject* k = PyTuple_GetItem(item, 0);
			std::string sk = PythonUtils::ToString(k);
			property_names->push_back(new std::string(sk));
			Py_DECREF(item);
		}

		Py_DECREF(iterator);
		Py_DECREF(items);
		return property_names;
	}

	PyObject* KPythonDict::ToPython()
	{
		PyLockGIL lock;
		Py_INCREF(object);
		return this->object;
	}
}


text:
var mongoose = require('mongoose');
var setting = require('../../setting');
var deepPopulate = require('mongoose-deep-populate')(mongoose);

module.exports = function (config) {
// define the schema for openid connect provider
  const entitySchema = // mongoose.Schema({}, { strict: false });
    mongoose.Schema({
      '@id': {
        type: String
      },
      '@context': {
        type: String
      },
      name: {
        type: String,
        required: true
      },
      operatedBy: {
        id: {
          type: mongoose.Schema.Types.ObjectId
        },
        type: {
          type: String
        }
      },
      url: {
        type: String
      },
      description: {
        type: String
      },
      registeredBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'RegistrationAuthority'
      },
      federatedBy: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Federation'
      }],
      metadata: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Metadata'
      },
      category: {
        type: String
      },
      supports: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Schema'
      }]
    }, {
      strict: false,
      timestamps: true
    });

  entitySchema.plugin(deepPopulate, {
    whitelist: [
      'registeredBy',
      'federatedBy',
      'federatedBy.registeredBy',
      'federatedBy.sponsor',
      'federatedBy.federates',
      'federatedBy.member',
      'federatedBy.badgeSupported',
      'federatedBy.supports',
      'federatedBy.metadata',
      'metadata',
      'supports'
    ],
    populate: {
      'registeredBy': {
        select: '-_id -__v -updatedAt -createdAt'
      },
      'federatedBy': {
        select: '-_id -__v -updatedAt -createdAt'
      },
      'federatedBy.registeredBy': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.sponsor': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.federates': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.member': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.badgeSupported': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.supports': {
        select: {'@id': 1, _id: 0}
      },
      'federatedBy.metadata': {
        select: {'@id': 1, _id: 0}
      },
      'metadata': {
        select: '-_id -__v -updatedAt -createdAt'
      },
      'supports': {
        select: '-_id -__v -updatedAt -createdAt -supportedBy'
      }
    }
  });

  entitySchema.pre('save', function (next, done) {
    this['@id'] = config.baseURL + setting.entity + '/' + this._id;
    this['@context'] = config.contextEntity;
    this.registeredBy = config.RA_ID;
    next();
  });

  return mongoose.models.Entity || mongoose.model('Entity', entitySchema);
};


text:
#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using CodeNav.Models;
using CodeNav.Models.ViewModels;
using Microsoft.VisualStudio.Shell;
using Task = System.Threading.Tasks.Task;

namespace CodeNav.Helpers
{
    public static class VisibilityHelper
    {
        public static List<CodeItem> SetCodeItemVisibility(CodeDocumentViewModel model)
            => SetCodeItemVisibility(model.CodeDocument, model.FilterText, model.FilterOnBookmarks, model.Bookmarks);

        /// <summary>
        /// Loop through all codeItems and look into Settings to see if the item should be visible or not.
        /// </summary>
        /// <param name="document">List of codeItems</param>
        /// <param name="name">Filters items by name</param>
        /// <param name="filterOnBookmarks">Filters items by being bookmarked</param>
        /// <param name="bookmarks">List of bookmarked items</param>
        public static List<CodeItem> SetCodeItemVisibility(List<CodeItem> document, string name = "",
            bool filterOnBookmarks = false, Dictionary<string, int>? bookmarks = null)
        {
            if (document?.Any() != true)
            {
                // No code items have been found to filter on by name
                return new List<CodeItem>();
            }

            try
            {
                foreach (var item in document)
                {
                    if (item is IMembers hasMembersItem && hasMembersItem.Members.Any())
                    {
                        SetCodeItemVisibility(hasMembersItem.Members, name, filterOnBookmarks, bookmarks);
                    }

                    item.IsVisible = ShouldBeVisible(item, name, filterOnBookmarks, bookmarks)
                        ? Visibility.Visible
                        : Visibility.Collapsed;
                    item.Opacity = SetOpacity(item);
                }
            }
            catch (Exception e)
            {
                LogHelper.Log("Error during setting visibility", e);
            }

            return document;
        }

        /// <summary>
        /// Toggle visibility of the CodeNav margin
        /// </summary>
        /// <param name="row">the grid row of which the visibility will be toggled</param>
        /// <param name="document">the list of codeitems to determine if there is anything to show at all</param>
        public static async Task SetMarginHeight(RowDefinition row, List<CodeItem> document)
        {
            if (row == null)
            {
                return;
            }

            var general = await General.GetLiveInstanceAsync();

            if (!general.ShowMargin)
            {
                row.Height = new GridLength(0);
            }
            else
            {
                row.Height = IsEmpty(document) ? new GridLength(0) : new GridLength(0, GridUnitType.Star);
            }
        }

        /// <summary>
        /// Toggle visibility of the CodeNav margin
        /// </summary>
        /// <param name="column">the grid column of which the visibility will be toggled</param>
        /// <param name="condition">if condition is True visibility will be set to hidden</param>
        public static async Task SetMarginWidth(ColumnDefinition column, bool condition)
        {
            if (column == null)
            {
                return;
            }

            var general = await General.GetLiveInstanceAsync();

            column.Width = condition ? new GridLength(0) : new GridLength(general.Width);
        }

        /// <summary>
        /// Toggle visibility of the CodeNav margin
        /// </summary>
        /// <param name="column">the grid column of which the visibility will be toggled</param>
        /// <param name="document">the list of codeitems to determine if there is anything to show at all</param>
        public static async Task SetMarginWidth(ColumnDefinition column, List<CodeItem> document)
        {
            if (column == null)
            {
                return;
            }

            var general = await General.GetLiveInstanceAsync();

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (!general.ShowMargin || IsEmpty(document))
            {
                column.Width = new GridLength(0);
                return;
            }

            column.Width = new GridLength(general.Width);
        }

        public static bool IsEmpty(List<CodeItem> document)
        {
            if (document?.Any() != true)
            {
                return true;
            }

            var isEmpty = true;

            foreach (var item in document)
            {
                if (item is IMembers membersItem)
                {
                    isEmpty = !membersItem.Members.Any();
                }
            }

            return isEmpty;
        }

        /// <summary>
        /// Set opacity of code item to value given in the filter window
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private static double SetOpacity(CodeItem item)
        {
            var filterRule = GetFilterRule(item);

            if (filterRule != null)
            {
                return GetOpacityValue(filterRule.Opacity);
            }

            return 1.0;
        }

        /// <summary>
        /// Get opacity value from filter rule setting
        /// </summary>
        /// <param name="opacitySetting"></param>
        /// <returns></returns>
        private static double GetOpacityValue(string opacitySetting)
        {
            if (string.IsNullOrEmpty(opacitySetting))
            {
                return 1.0;
            }

            double.TryParse(opacitySetting, out var opacity);

            if (opacity < 0 || opacity > 1)
            {
                return 1.0;
            }

            return opacity;
        }

        /// <summary>
        /// Determine if an item should be visible
        /// </summary>
        /// <param name="item">CodeItem that is checked</param>
        /// <param name="name">Text filter</param>
        /// <param name="filterOnBookmarks">Are we only showing bookmarks?</param>
        /// <param name="bookmarks">List of current bookmarks</param>
        /// <returns></returns>
        private static bool ShouldBeVisible(CodeItem item, string name = "",
            bool filterOnBookmarks = false, Dictionary<string, int>? bookmarks = null)
        {
            var visible = true;

            var filterRule = GetFilterRule(item);

            if (filterRule != null && filterRule.Visible == false)
            {
                return false;
            }

            if (filterOnBookmarks)
            {
                visible = BookmarkHelper.IsBookmark(bookmarks, item);
            }

            if (!string.IsNullOrEmpty(name))
            {
                visible = visible && item.Name.Contains(name, StringComparison.OrdinalIgnoreCase);
            }

            // If an item has any visible members, it should be visible.
            // If an item does not have any visible members, hide it depending on an option
            if (item is IMembers hasMembersItem &&
                hasMembersItem?.Members != null)
            {
                if (hasMembersItem.Members.Any(m => m.IsVisible == Visibility.Visible))
                {
                    visible = true;
                }
                else if (!hasMembersItem.Members.Any(m => m.IsVisible == Visibility.Visible) && filterRule != null)
                {
                    visible = !filterRule.HideIfEmpty;
                }
            }

            return visible;
        }

        public static Visibility GetIgnoreVisibility(CodeItem item)
        {
            var filterRule = GetFilterRule(item);

            if (filterRule == null)
            {
                return Visibility.Visible;
            }

            return filterRule.Ignore ? Visibility.Collapsed : Visibility.Visible;
        }

        private static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
        }

        private static FilterRule? GetFilterRule(CodeItem item)
        {
            if (SettingsHelper.FilterRules == null)
            {
                return null;
            }

            var filterRule = SettingsHelper.FilterRules.LastOrDefault(f =>
                    (f.Access == item.Access || f.Access == CodeItemAccessEnum.All) &&
                    (f.Kind == item.Kind || f.Kind == CodeItemKindEnum.All));

            return filterRule;
        }
    }
}


text:
define(["jquery"], function (jQuery) {
    /**
     * @class Oskari.userinterface.bundle.ui.UserInterfaceBundleInstance
     *
     * Default DIV Manager implementation handles menu like and detached DIVs
     * handles hiding showing DIVS.
     * Draggability is enabled in top-border element when DIV is detached
     *
     */
    Oskari.clazz.define("Oskari.userinterface.bundle.ui.UserInterfaceBundleInstance",

        /**
         * @method init called on constructing this instance
         */

        function () {
            this.sandbox = null;

            /**
             * @property requestHandlers
             */
            this.requestHandlers = {};

            this.extensions = [];
            this.extensionsByName = {};

            /**
             * @property compiledTemplates
             *
             * HTML templates 'compiled' with jQuery - HTML code in static property templates
             */
            this.compiledTemplates = {};

            /**
             * @property flyoutContainer (document.body)
             */
            this.flyoutContainer = null;

            /**
             * @property tileContainer (#menubar)
             */
            this.tileContainer = null;

            /**
             * @property flyoutZIndexBase
             */
            this.flyoutZIndexBase = 1100;

            /**
             * @property menubarContainerId
             */
            this.menubarContainerId = "#menubar";

        }, {

            getName: function () {
                return "userinterface.DivManazer";
            },
            init: function (sandbox) {

            },
            getExtensionByName: function (name) {
                return this.extensionsByName[name];
            },
    	    /**
    	     * @method getSandbox
    	     */
            getSandbox: function () {
                return this.sandbox;
            },
            /**
             * @method start
             *
             * implements BundleInstance start methdod
             *
             * creates tile and flyout compiledTemplates
             * creates and registers request handlers
             *
             */
            "start": function () {

                /*
                 * setup templates
                 */
                this.compileTemplates();

                /*
                 * setup requests and handlers
                 */
                var conf = this.conf,
                    sandboxName = (conf ? conf.sandbox : null) || 'sandbox',
                    sandbox = Oskari.getSandbox(sandboxName),
                    //menubarContainerId,
                    toFix,
                    height,
                    ieFixClasses,
                    n,
                    fix;

                this.sandbox = sandbox;

                this.flyoutContainer = jQuery(document.body);

                //menubarContainerId = (conf ? conf.menubarContainerId : null) || this.menubarContainerId;
                this.tileContainer = jQuery(this.menubarContainerId);
                this.tileContainer.addClass("oskari-tile-container");

                this.sandbox.register(this);

                this.requestHandlers.add = Oskari.clazz.create('Oskari.userinterface.bundle.ui.request.AddExtensionRequestHandler', this);
                this.requestHandlers.remove = Oskari.clazz.create('Oskari.userinterface.bundle.ui.request.RemoveExtensionRequestHandler', this);
                this.requestHandlers.update = Oskari.clazz.create('Oskari.userinterface.bundle.ui.request.UpdateExtensionRequestHandler', this);

                sandbox.addRequestHandler('userinterface.AddExtensionRequest', this.requestHandlers.add);
                sandbox.addRequestHandler('userinterface.RemoveExtensionRequest', this.requestHandlers.remove);
                sandbox.addRequestHandler('userinterface.UpdateExtensionRequest', this.requestHandlers.update);

                this.requestHandlers.modal = Oskari.clazz.create('Oskari.userinterface.bundle.ui.request.ModalDialogRequestHandler', this);
                sandbox.addRequestHandler('userinterface.ModalDialogRequest', this.requestHandlers.modal);

                /* removed for some reason or another */
                //sandbox.registerAsStateful(this.mediator.bundleId, this);

                /* IE fixes for flyout height others use CSS media query */
                if (jQuery.browser.msie && jQuery.browser.version < "9.0") {
                    toFix = this.compiledTemplates['Oskari.userinterface.Flyout'].children('.oskari-flyoutcontentcontainer');
                    height = this.flyoutContainer.height();
                    ieFixClasses = this.ieFixClasses;
                    for (n = 0; n < ieFixClasses.length; n += 1) {
                        fix = ieFixClasses[n];

                        if (height >= fix.min && height <= fix.max) {
                            toFix.addClass(fix.cls);
                            break;
                        }
                    }

                }
            },
            /**
             * @method update
             *
             * implements bundle instance update method
             */
            "update": function () {

            },
            /**
             * @method stop
             *
             * implements bundle instance stop method
             *
             * removes request handlers
             */
            "stop": function () {
                sandbox.removeRequestHandler('userinterface.UpdateExtensionRequest', this.requestHandlers.update);
                sandbox.removeRequestHandler('userinterface.RemoveExtensionRequest', this.requestHandlers.remove);
                sandbox.removeRequestHandler('userinterface.AddExtensionRequest', this.requestHandlers.add);
                sandbox.removeRequestHandler('userinterface.ModalDialogRequest', this.requestHandlers.modal);

                //this.sandbox.unregisterStateful(this.mediator.bundleId);

                this.sandbox.unregister(this);
                this.started = false;

            },
            /**
             * HTML templates
             */
            "templates": {

                /* menu tile */
                "Oskari.userinterface.Tile": '
' + '

' + '

' + '
',

                /* flyout */
                "Oskari.userinterface.Flyout": '
' + '
' + '

' + '
' + '

' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '
' + '

' + '
' + '
',

                /* view */
                "Oskari.userinterface.View": '

'

            },

            /**
             * @method compileTemplates
             *
             * creates jQuery template to be cloned to any menubar Tiles
             */
            "compileTemplates": function () {
                /**
                 * Templates
                 */
                var me = this,
                    flyout;
                me.compiledTemplates['Oskari.userinterface.Tile'] = jQuery(this.templates['Oskari.userinterface.Tile']);

                flyout = jQuery(me.templates['Oskari.userinterface.Flyout']);

    		/*flyout.css('left', '-3195px');
    		 flyout.css('top', '-3100px');*/
                flyout.css('left', me.defaults.attach.left);
                flyout.css('top', me.defaults.attach.top);

                me.compiledTemplates['Oskari.userinterface.Flyout'] = flyout;

                me.compiledTemplates['Oskari.userinterface.View'] = jQuery(this.templates['Oskari.userinterface.View']);
            },
            /**
             * @method addExtension
             *
             * adds extension to Oskari DIV Manager in response to a
             * AddExtensionRequest
             */
            "addExtension": function (extension) {

                var me = this,
                    plugins,
                    //plugin,
                    extensions,
                    extensionsByName,
                    extensionInfo,
                    count,
                    name,
                    flyoutPlugin,
                    flyout,
                    el,
                    fcc,
                    //fcccc,
                    tilePlugin,
                    tile,
                    viewPlugin,
                    view;
                extension.startExtension();

                plugins = extension.getPlugins();

                //plugin = null;
                extensions = me.extensions;
                extensionsByName = me.extensionsByName;

                extensionInfo = {
                    state: 'close',
                    extension: extension,
                    draggable: null,
                    draggableTarget: null,
                    draggableHandle: null,
                    viewState: {},
                    extensionUpdatedEvent: null
                };

                extensionInfo.extensionUpdatedEvent = me.sandbox.getEventBuilder('userinterface.ExtensionUpdatedEvent')(extension, extensionInfo.state);

                count = extensions.length;
                name = extension.getName();

                flyoutPlugin = plugins['Oskari.userinterface.Flyout'];
                flyout = null;
                el = null;
                if (flyoutPlugin !== null && flyoutPlugin !== undefined) {
                    flyout = me.createFlyout(extension, flyoutPlugin, count, extensionInfo);

                    me._applyDraggableToFlyout(flyout, extensionInfo, '.oskari-flyouttoolbar');

                    fcc = flyout.children('.oskari-flyoutcontentcontainer');
                    //fcccc = fcc.children('.oskari-flyoutcontent');

                    el = fcc.children('.oskari-flyoutcontent');

                    flyoutPlugin.setEl(el.get());

                    me.flyoutContainer.append(flyout);

                    flyoutPlugin.startPlugin();

                }

                tilePlugin = plugins['Oskari.userinterface.Tile'];
                tile = null;
                if (tilePlugin !== null && tilePlugin !== undefined) {
                    tile = me.createTile(extension, tilePlugin, count, extensionInfo);

                    tilePlugin.startPlugin();

                    tile.fadeIn(200);

                    me.tileContainer.append(tile);
                }

                viewPlugin = plugins['Oskari.userinterface.View'];
                view = null;
                if (viewPlugin !== null && viewPlugin !== undefined) {
                    view = me.createView(extension, viewPlugin, count, extensionInfo);
                    el = view;
                    viewPlugin.setEl(el.get());
                    viewPlugin.startPlugin();

                }

                /*
                 * store these for further usage
                 */
                extensionInfo.plugins = {};

                if (tilePlugin) {
                    extensionInfo.plugins['Oskari.userinterface.Tile'] = {
                        plugin: tilePlugin,
                        el: tile
                    };
                }
                if (flyoutPlugin) {
                    extensionInfo.plugins['Oskari.userinterface.Flyout'] = {
                        plugin: flyoutPlugin,
                        el: flyout
                    };
                }
                if (viewPlugin) {
                    extensionInfo.plugins['Oskari.userinterface.View'] = {
                        plugin: viewPlugin,
                        el: view
                    };
                }

                extensions.push(extensionInfo);
                extensionsByName[name] = extensionInfo;

                return extensionInfo;
            },
            /**
             * @method _applyDraggableToFlyout
             * applies draggable handle to flyouts title bar
             */
            _applyDraggableToFlyout: function (flyout, extensionInfo, cls) {
                var me = this,
                    handle = flyout.children(cls).get()[0],
                    flyoutTarget = flyout.get()[0],
                    useHelper = false,
                    el;

                extensionInfo.draggableHandle = handle;
                extensionInfo.draggableTarget = flyoutTarget;

                extensionInfo.draggable = jQuery(flyout).draggable({
                    handle: jQuery(handle),
                    helper: useHelper ? function () {
                        el = jQuery('
');

                        el.css("width", flyout.css("width"));
                        el.css("height", flyout.css("height"));
                        el.css("border", "2px solid rgba(0,0,0,.5)");
                        el.css("z-index", flyout.css("z-index"));

                        return el;
                    } : null,
                    scroll: false,
                    stack: '.oskari-flyout',
                    create: function (event, ui) {
                        /* IE8 works fine BUT IE9 needs fixed width to not jump flyout width during and after dragging */
                        if (jQuery.browser.msie && jQuery.browser.version[0] === "9") {
                            flyout.css('width', flyout.width() + "px");
                        }
                    },
                    start: function () {
                        if (useHelper) {
                            flyout.css("display", "none");
                        } else {
                            /* Attempt to fix IE9 vs. draggable flyout width issues */
                            /* this did not work */
                            /* if(jQuery.browser.msie && jQuery.browser.version[0] === "9") {
                            flyout.css('width',flyout.width()+"px");
                           }
                           */

                        }
                    },
                    drag: function () {

                    },
                    stop: function (event, ui) {
                        var viewState;
                        if (useHelper) {
                            flyout.css("top", ui.helper.css("top"));
                            flyout.css("left", ui.helper.css("left"));
                        } else {

                        }
                        me.shuffleZIndices(flyout);
                        if (useHelper) {
                            flyout.css("display", "");
                        }
                        viewState = me.getFlyoutViewState(flyout, "detach");

                        extensionInfo.viewState = viewState;
                        me.notifyExtensionViewStateChange(extensionInfo);

                    }
                });
            },
            /**
             * @method createTile
             *
             * creates menubar tile using the tile template
             */

            createTile: function (extension, plugin, count, extensionInfo) {
                var me = this,
                    //container = jQuery('#menubar'),
                    tile = this.compiledTemplates['Oskari.userinterface.Tile'].clone(true, true),
                    title = tile.children('.oskari-tile-title');
                //status;
                title.append(plugin.getTitle());
                //status = tile.children('.oskari-tile-status');

                tile.click(function () {
                    //plugin.setExtensionState();

                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'toggle']);
                });

                plugin.setEl(tile.get());

                return tile;
            },
            /**
             * @method createFlyout
             *
             * creates flyout DIV using the flyout template adds a bunch
             * of tools to the DIV toolbar
             *
             */
            createFlyout: function (extension, plugin, count, extensionInfo) {
                var me = this,
                    flyout = this.compiledTemplates['Oskari.userinterface.Flyout'].clone(true, true),
                    flyouttools,
                    toolage;
                flyout.find('.oskari-flyout-title p').append(plugin.getTitle());

                flyouttools = flyout.children('.oskari-flyouttoolbar').children('.oskari-flyouttools');
                toolage = {
                    attach: flyouttools.children('.oskari-flyouttool-attach'),
                    detach: flyouttools.children('.oskari-flyouttool-detach'),
                    minimize: flyouttools.children('.oskari-flyouttool-minimize'),
                    restore: flyouttools.children('.oskari-flyouttool-restore'),
                    close: flyouttools.children('.oskari-flyouttool-close'),
                    help: flyouttools.children('.oskari-flyouttool-help')
                };

                toolage.detach.click(function () {
                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'detach']);

                });
                toolage.attach.click(function () {
                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'attach']);

                });
                toolage.minimize.click(function () {
                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'minimize']);

                });
                toolage.restore.click(function () {
                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'restore']);

                });
                toolage.close.click(function () {
                    me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, 'close']);

                });
                toolage.help.click(function () {
                    me.getSandbox().postRequestByName('userguide.ShowUserGuideRequest', [{
                        placement: 'bottom',
                        el: toolage.help,
                        extension: extension.getName(),
                        toggle: true
                    }]);

                });
                return flyout;

            },

            /**
             * @method createFlyout
             *
             * creates flyout DIV using the flyout template adds a bunch
             * of tools to the DIV toolbar
             *
             */
            createView: function (extension, plugin, count, extensionInfo) {
                var me = this,
                    view = me.compiledTemplates['Oskari.userinterface.View'].clone(true, true);

                return view;

            },
            /**
             * @method removeExtension TBD
             */

            "removeExtension": function (extension) {

                /*
                 * to-do:
                 * - remove tile
                 * - remove flyout
                 */

                var me = this,
                    extensions = me.extensions,
                    extensionsByName = this.extensionsByName,
                    extensionInfo = extensionsByName[extension.getName()],
                    //extensionState = extensionInfo.state,
                    flyoutInfo = extensionInfo.plugins['Oskari.userinterface.Flyout'],
                    flyoutPlugin,
                    flyout,
                    ops,
                    closeOp,
                    tileInfo,
                    //tilePlugin,
                    tile,
                    after,
                    n,
                    len;

                if (flyoutInfo) {
                    flyoutPlugin = flyoutInfo.plugin;
                    flyout = flyoutInfo.el;

                    ops = this.flyoutOps;
                    closeOp = ops.close;

                    closeOp.apply(this, [flyout, flyoutPlugin, extensionInfo]);

                    flyout.remove();
                }

                tileInfo = extensionInfo.plugins['Oskari.userinterface.Tile'];
                if (tileInfo) {
                    //tilePlugin = tileInfo.plugin;
                    tile = tileInfo.el;

                    tile.remove();
                }

                extensionsByName[extension.getName()] = null;

                after = [];

                for (n = 0, len = extensions.length; n < len; n += 1) {
                    if (extensions[n] !== extensionInfo) {
                        after.push(extensions[n]);
                    }
                }

                me.extensions = after;

                extension.stopExtension();

            },
            /**
             * @method updateExtension updates extension state
             *
             */
            "updateExtension": function (extension, request) {
                var me = this,
                    extensions = me.extensions,
                    i,
                    extensionsByName,
                    extensionInfo,
                    extensionState,
                    state,
                    ops,
                    op,
                    flyoutInfo,
                    closeOp,
                    n,
                    otherExtensionInfo,
                    otherState,
                    plgnfo,
                    otherFlyoutInfo,
                    otherFlyoutPlugin,
                    otherFlyout,
                    otherTileInfo,
                    //otherTilePlugin,
                    otherTile,
                    flyoutPlugin,
                    flyout,
                    tileInfo,
                    //tilePlugin,
                    tile,
                    viewInfo,
                    viewPlugin,
                    view,
                    len;
                if (!extension) {
                    // if extension not spesified, do it for all
                    for (i = 0; i < extensions.length; i += 1) {
                        this.updateExtension(extensions[i].extension, request);
                    }
                    return;
                }
                extensionsByName = this.extensionsByName;
                extensionInfo = extensionsByName[extension.getName()];
                extensionState = extensionInfo.state;

                state = request.getState();

                if (state === 'toggle') {

                    if (extensionState === 'close') {
                        state = 'attach';
                    } else if (extensionState === 'attach') {
                        state = 'close';
                    } else if (extensionState === 'detach') {
                        state = 'minimize';
                    } else if (extensionState === 'minimize') {
                        state = 'restore';
                    } else if (extensionState === 'restore') {
                        state = 'minimize';
                    }

                }

                flyoutInfo = extensionInfo.plugins['Oskari.userinterface.Flyout'];

                /* opening  flyouts 'attached' closes previously attachily opened  flyout(s) */
                if (state === 'attach' && flyoutInfo) {
                    var extTop = null,
                        extLeft = null;

                    if (request.getExtensionLocation().top || request.getExtensionLocation().left) {
                        me.origExtensionLocation = {};
                    }

                    var extLocation = function (request, me, axis) {
                        if (me.origExtensionLocation) {
                            if (request.getExtensionLocation()[axis]) {
                                me.origExtensionLocation[axis] = jQuery(flyoutInfo.el).css(axis);
                                jQuery(flyoutInfo.el).css(axis, request.getExtensionLocation()[axis] + 'px');
                            } else if (me.origExtensionLocation[axis]) {
                                jQuery(flyoutInfo.el).css(axis, me.origExtensionLocation[axis]);
                            }
                        }
                    };
                    extLocation(request, me, 'top');
                    extLocation(request, me, 'left');

                    ops = me.flyoutOps;
                    closeOp = ops.close;
                    for (n = 0, len = extensions.length; n < len; n += 1) {
                        otherExtensionInfo = extensions[n];
                        if (otherExtensionInfo === extensionInfo) {
                            continue;
                        }

                        if (otherExtensionInfo.state !== 'attach') {
                            continue;
                        }

                        otherState = 'close';

                        plgnfo = otherExtensionInfo.plugins;
                        otherFlyoutInfo = plgnfo['Oskari.userinterface.Flyout'];
                        if (otherFlyoutInfo) {
                            otherFlyoutPlugin = otherFlyoutInfo.plugin;
                            otherFlyout = otherFlyoutInfo.el;

                            otherExtensionInfo.state = otherState;
                            closeOp.apply(this, [otherFlyout, otherFlyoutPlugin, otherExtensionInfo]);

                            me.notifyExtensionViewStateChange(otherExtensionInfo);
                        } else {
                            continue;
                        }

                        otherTileInfo = plgnfo['Oskari.userinterface.Tile'];
                        if (otherTileInfo) {
                            //otherTilePlugin = otherTileInfo.plugin;
                            otherTile = otherTileInfo.el;

                            me.applyTransition(otherTile, otherState, me.tileTransitions);

                        }
                    }
                }

                /* let's transition flyout if one exists */
                if (flyoutInfo) {
                    flyoutPlugin = flyoutInfo.plugin;
                    flyout = flyoutInfo.el;

                    /**
                     * do the op for this extension
                     */
                    ops = me.flyoutOps;
                    op = ops[state];
                    op.apply(this, [flyout, flyoutPlugin, extensionInfo, extensions]);

                }

                /* let's transition menu tile if one exists */
                tileInfo = extensionInfo.plugins['Oskari.userinterface.Tile'];
                if (tileInfo) {
                    //tilePlugin = tileInfo.plugin;
                    tile = tileInfo.el;

                    me.applyTransition(tile, state, me.tileTransitions);

                }

                /* let's transition menu tile if one exists */
                viewInfo = extensionInfo.plugins['Oskari.userinterface.View'];
                if (viewInfo) {
                    viewPlugin = viewInfo.plugin;
                    view = viewInfo.el;

                    ops = me.viewOps;
                    op = ops[state];
                    if (op) {
                        op.apply(this, [view, viewPlugin, extensionInfo, extensions]);
                    }
                }

                extensionInfo.state = state;

                me.notifyExtensionViewStateChange(extensionInfo);
            },
            /**
             * @method notifyExtensionViewStateChange
             */
            "notifyExtensionViewStateChange": function (extensionInfo) {
                var evt = extensionInfo.extensionUpdatedEvent;
                evt.setViewState(extensionInfo.state);
                evt.setViewInfo(extensionInfo.viewState);

                this.sandbox.notifyAll(evt, true);
            },
            /*
             * @static @property validStates
             */
            "validStates": {
                "attach": {
                    "attach": true,
                    "detach": false,
                    "close": false,
                    "minimize": false,
                    "restore": false,
                    "drawer": false,
                    "sidebar": false
                },
                "detach": {
                    "attach": false,
                    "detach": true,
                    "close": false,
                    "minimize": false,
                    "restore": false,
                    "drawer": false,
                    "sidebar": false
                },
                "minimize": {
                    "attach": true,
                    "detach": true,
                    "close": false,
                    "minimize": true,
                    "restore": false,
                    "drawer": false,
                    "sidebar": false
                },
                "restore": {
                    "attach": false,
                    "detach": true,
                    "close": false,
                    "minimize": false,
                    "restore": true,
                    "drawer": false,
                    "sidebar": false
                },
                "close": {
                    "attach": false,
                    "detach": false,
                    "close": true,
                    "minimize": false,
                    "restore": false,
                    "drawer": false,
                    "sidebar": false
                },
                "drawer": {
                    "attach": false,
                    "detach": false,
                    "close": false,
                    "minimize": false,
                    "restore": false,
                    "drawer": true,
                    "sidebar": false
                },
                "sidebar": {
                    "attach": false,
                    "detach": false,
                    "close": false,
                    "minimize": false,
                    "restore": false,
                    "drawer": false,
                    "sidebar": true
                }
            },

            /**
             * @static @property flyout default positioning
             */
            "defaults": {
                "detach": {
                    "left": "212px",
                    "top": "50px"
                },
                "attach": {
                    "left": "192px",
                    "top": "30px"
                }
            },

            /**
             * @static
             * @property tileTransitions
             * CSS transitions for menu tiles
             */
            "tileTransitions": {
                "attach": {
                    "oskari-tile-attached": true,
                    "oskari-tile-detached": false,
                    "oskari-tile-closed": false
                },
                "detach": {
                    "oskari-tile-attached": false,
                    "oskari-tile-detached": true,
                    "oskari-tile-minimized": false,
                    "oskari-tile-closed": false
                },
                "minimize": {
                    "oskari-tile-minimized": true,
                    "oskari-tile-closed": false,
                    "oskari-tile-detached": false
                },
                "restore": {
                    "oskari-tile-minimized": false,
                    "oskari-tile-detached": true
                },
                "close": {
                    "oskari-tile-closed": true,
                    "oskari-tile-attached": false,
                    "oskari-tile-detached": false
                }

            },

            /**
             * @static @property flyoutTransitions
             * CSS transitions for flyouts
             */
            "flyoutTransitions": {
                "attach": {
                    "oskari-attached": true,
                    "oskari-detached": false,
                    "oskari-closed": false
                },
                "detach": {
                    "oskari-attached": false,
                    "oskari-detached": true,
                    "oskari-closed": false
                },
                "minimize": {
                    "oskari-minimized": true,
                    "oskari-closed": false,
                    "oskari-detached": false
                },
                "restore": {
                    "oskari-minimized": false,
                    "oskari-closed": false,
                    "oskari-detached": true,
                    "oskari-attached": false
                },
                "close": {
                    "oskari-closed": true,
                    "oskari-minimized": false,
                    "oskari-detached": false,
                    "oskari-attached": false
                }

            },

            /**
             * @method applyTransition
             * adds and removes CSS classes from element
             *
             */
            "applyTransition": function (obj, state, transitions) {
                var transition = transitions[state],
                    t;
                if (!transition) {
                    return;
                }
                for (t in transition) {
                    if (transition.hasOwnProperty(t)) {
                        if (transition[t]) {
                            obj.addClass(t);
                        } else {
                            obj.removeClass(t);
                        }
                    }
                }
            },
            /**
             * @method getFlyoutViewState
             *
             */
            "getFlyoutViewState": function (flyout, state) {
                var viewState = {
                    "left": flyout.css("left"),
                    "top": flyout.css("top"),
                    "width": flyout.width(),
                    "height": flyout.height(),
                    "z-index": flyout.css("z-index"),
                    "viewState": state
                };
                return viewState;
            },
            /**
             * @static
             * @property flyoutOps a set of (jQuery) operations to be
             *           performed on flyout to
             *           show/hide/minimize/restore/attach/detach
             */
            "flyoutOps": {
                /** @method detach */
                "detach": function (flyout, flyoutPlugin, extensionInfo, extensions) {
                    var me = this,
                        //toState,
                        viewState;

                    if ((!extensionInfo.viewState.left || !extensionInfo.viewState.top) || (extensionInfo.viewState.left === me.defaults.attach.left && extensionInfo.viewState.top === me.defaults.attach.top)) {
                        extensionInfo.viewState.left = me.defaults.detach.left;
                        extensionInfo.viewState.top = me.defaults.detach.top;
                    }
                    /*toState = {
                        "left": extensionInfo.viewState.left,
                        "top": extensionInfo.viewState.top
                    };*/

                    /*
                     * to top
                     */
                    me.shuffleZIndices(flyout);

                    /*
                     * with style
                     */
                    me.applyTransition(flyout, "detach", me.flyoutTransitions);

                    viewState = me.getFlyoutViewState(flyout, "detach");
                    extensionInfo.viewState = viewState;

                },
                /** @method attach */
                "attach": function (flyout, flyoutPlugin, extensionInfo, extensions) {
                    var me = this,
                        viewState;

                    /*
                     * to top
                     */
                    me.shuffleZIndices(flyout);

                    /*
                     * with style
                     */

                    me.applyTransition(flyout, "attach", me.flyoutTransitions);

                    viewState = me.getFlyoutViewState(flyout, "attach");
                    extensionInfo.viewState = viewState;

                },
                /** @method minimize */
                "minimize": function (flyout, flyoutPlugin, extensionInfo) {
                    var me = this,
                        viewState = me.getFlyoutViewState(flyout, "minimize");

                    me.applyTransition(flyout, "minimize", me.flyoutTransitions);

                    extensionInfo.viewState = viewState;
                },
                /** @method restore */
                "restore": function (flyout, flyoutPlugin, extensionInfo) {
                    var me = this;
                    //    viewState;
                    me.applyTransition(flyout, "restore", me.flyoutTransitions);
                    //viewState = extensionInfo.viewState;

                },
                /** @method close */
                "close": function (flyout, flyoutPlugin, extensionInfo) {
                    var me = this;

                    extensionInfo.viewState = {
                        viewState: "close"
                    };
                    me.applyTransition(flyout, "close", me.flyoutTransitions);

                }
            },

            /**
             * @static
             * @property flyoutOps a set of (jQuery) operations to be
             *           performed on flyout to
             *           show/hide/minimize/restore/attach/detach
             */
            "viewOps": {
                /** @method detach */
                "view": function (flyout, flyoutPlugin, extensionInfo, extensions) {
                },
                /** @method close */
                "close": function (flyout, flyoutPlugin, extensionInfo) {
                }

            },

            /**
             * @method setState
             *
             * restores state from state snapshot
             *
             * @param {Object} state bundle state as JSON
             */
            setState: function (state) {
                var me = this,
                    divmanazerState = state,
                    e,
                    extensionInfo,
                    restoredState;

                if (!divmanazerState) {
                    return;
                }

                for (e in me.extensionsByName) {
                    if (me.extensionsByName.hasOwnProperty(e)) {
                        extensionInfo = me.extensionsByName[e];
                        restoredState = divmanazerState.extensionStatesByName[e];
                        if (restoredState) {
                            extensionInfo.state = restoredState.state;
                            extensionInfo.viewState = restoredState.viewState || {};
                        }
                    }
                }

                /* let's not Bundles may not have been loaded */
                /* me.restoreExtensionViewStates(); */

            },
            /**
             * @method getState
             *
             * builds a state snapshot
             *
             * @return {Object} bundle state as JSON
             */
            getState: function () {
                var me = this,
                    divmanazerState,
                    e,
                    extensionInfo;
                me.refreshExtensionViewStates();

                divmanazerState = {
                    extensionStatesByName: {}
                };

                for (e in me.extensionsByName) {
                    if (me.extensionsByName.hasOwnProperty(e)) {
                        extensionInfo = me.extensionsByName[e];
                        divmanazerState.extensionStatesByName[e] = {
                            state: extensionInfo.state,
                            viewState: extensionInfo.viewState
                        };
                    }
                }

                return divmanazerState;

            },
            /**
             * @method applyState
             *
             * called after all bundles go will restore view states
             *
             */
            applyState: function () {
                var me = this;
                me.restoreExtensionViewStates();
            },
            /**
             * @method refreshExtensionStates
             * moves state to cache
             */
            refreshExtensionViewStates: function () {
                var me = this,
                    e,
                    extensionInfo,
                    flyoutInfo,
                    //flyoutPlugin,
                    flyout,
                    viewState;
                for (e in me.extensionsByName) {
                    if (me.extensionsByName.hasOwnProperty(e)) {
                        extensionInfo = me.extensionsByName[e];

                        flyoutInfo = extensionInfo.plugins['Oskari.userinterface.Flyout'];
                        if (flyoutInfo) {
                            //flyoutPlugin = flyoutInfo.plugin;
                            flyout = flyoutInfo.el;

                            viewState = me.getFlyoutViewState(flyout, extensionInfo.state);

                            extensionInfo.viewState = viewState;
                        }
                    }
                }
            },
            /**
             * @method restoreExtensionViewStates
             */
            restoreExtensionViewStates: function () {
                var me = this,
                    ops = me.flyoutOps,
                    extensions = me.extensions,
                    e,
                    extensionInfo,
                    //extension,
                    flyoutInfo,
                    flyoutPlugin,
                    flyout,
                    viewState,
                    op,
                    tileInfo,
                    //tilePlugin,
                    tile;

                for (e in me.extensionsByName) {
                    if (me.extensionsByName.hasOwnProperty(e)) {
                        extensionInfo = me.extensionsByName[e];
                        //extension = extensionInfo.extension;

                        flyoutInfo = extensionInfo.plugins['Oskari.userinterface.Flyout'];
                        if (flyoutInfo) {
                            flyoutPlugin = flyoutInfo.plugin;
                            flyout = flyoutInfo.el;

                            viewState = extensionInfo.viewState;
                            flyout.removeAttr("style");
                            flyout.css("left", viewState.left);
                            flyout.css("top", viewState.top);
                            flyout.width(viewState.width);
                            flyout.height(viewState.height);
                            flyout.css("z-index", viewState['z-index']);

                            op = ops[extensionInfo.state];
                            /*me.getSandbox().postRequestByName('userinterface.UpdateExtensionRequest', [extension, viewState]);*/
                            op.apply(me, [flyout, flyoutPlugin, extensionInfo, extensions]);

                        }
                        tileInfo = extensionInfo.plugins['Oskari.userinterface.Tile'];
                        if (tileInfo) {
                            //tilePlugin = tileInfo.plugin;
                            tile = tileInfo.el;

                            me.applyTransition(tile, extensionInfo.state, me.tileTransitions);

                        }
                    }

                }
            },

            /**
             * @method _toggleMapWindowFullScreen
             * Sends a request to toggle between the normal and the full screen view
             * of the map window.
             */
            _toggleMapWindowFullScreen: function () {
                var me = this,
                    reqBuilder = me.sandbox.getRequestBuilder('MapFull.MapWindowFullScreenRequest');

                if (reqBuilder) {
                    me.sandbox.request(me.getName(), reqBuilder());
                }
            },

            /**
             *
             * @method shuffleZIndexes
             *
             * called after dragStop (or updateExtension) to restore some reasonable z-indexes
             * as well as bump the requested flyout on top of others
             *
             */
            shuffleZIndices: function (toTop) {
                var me = this,
                    //extensions = me.extensions,
                    zarray = [],
                    zprops = {},
                    zextns = {},
                    zflyout = {},
                    min = 1100,
                    idx,
                    e,
                    extensionInfo,
                    //extension,
                    flyoutInfo,
                    //flyoutPlugin,
                    flyout,
                    zIndex,
                    n;

                for (e in me.extensionsByName) {
                    if (me.extensionsByName.hasOwnProperty(e)) {
                        extensionInfo = me.extensionsByName[e];
                        //extension = extensionInfo.extension;
                        flyoutInfo = extensionInfo.plugins['Oskari.userinterface.Flyout'];
                        if (flyoutInfo) {
                            //flyoutPlugin = flyoutInfo.plugin;
                            flyout = flyoutInfo.el;
                            zIndex = flyout.css("z-index");

                            zarray.push(zIndex);
                            idx = String(zIndex);
                            zprops[idx] = zIndex;
                            zflyout[idx] = flyout;
                            zextns[idx] = extensionInfo;
                        }
                    }
                }

                zarray.sort();

                for (n = 0; n < zarray.length; n += 1) {
                    idx = zarray[n];
                    zprops[idx] = min + n;

                    zflyout[idx].css("z-index", zprops[zarray[n]]);
                }

                /*
                 * finally bump the requested flyout to top
                 */
                toTop.css("z-index", min + zarray.length + 2);

            },
            ieFixClasses: [{
                min: 400,
                max: 599,
                cls: "oskari-flyoutcontentcontainer_IE_400_599"
            }, {
                min: 600,
                max: 799,
                cls: "oskari-flyoutcontentcontainer_IE_600_799"
            }, {
                min: 800,
                max: 999,
                cls: "oskari-flyoutcontentcontainer_IE_800_999"
            }, {
                min: 1000,
                max: 1199,
                cls: "oskari-flyoutcontentcontainer_IE_1000_1199"
            }, {
                min: 1200,
                max: 1399,
                cls: "oskari-flyoutcontentcontainer_IE_1200_1399"
            }, {
                min: 1400,
                max: 9999,
                cls: "oskari-flyoutcontentcontainer_IE_1400"
            }]

        }, {
            "protocol": ["Oskari.bundle.BundleInstance", 'Oskari.mapframework.module.Module', 'Oskari.userinterface.Stateful']
        });
});


text:
package com.netflix.spinnaker.clouddriver.ecs.provider.agent;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.ecs.AmazonECS;
import com.amazonaws.services.ecs.model.DescribeServicesRequest;
import com.amazonaws.services.ecs.model.ListServicesRequest;
import com.amazonaws.services.ecs.model.ListServicesResult;
import com.amazonaws.services.ecs.model.Service;
import com.netflix.spectator.api.Registry;
import com.netflix.spinnaker.cats.agent.AgentDataType;
import com.netflix.spinnaker.cats.cache.CacheData;
import com.netflix.spinnaker.cats.cache.DefaultCacheData;
import com.netflix.spinnaker.cats.provider.ProviderCache;
import com.netflix.spinnaker.clouddriver.aws.security.AmazonClientProvider;
import com.netflix.spinnaker.clouddriver.ecs.cache.Keys;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.netflix.spinnaker.cats.agent.AgentDataType.Authority.AUTHORITATIVE;
import static com.netflix.spinnaker.cats.agent.AgentDataType.Authority.INFORMATIVE;
import static com.netflix.spinnaker.clouddriver.ecs.cache.Keys.Namespace.ECS_CLUSTERS;
import static com.netflix.spinnaker.clouddriver.ecs.cache.Keys.Namespace.SERVICES;

public class ServiceCachingAgent extends AbstractEcsOnDemandAgent<Service> {
  private static final Collection<AgentDataType> types = Collections.unmodifiableCollection(Arrays.asList(
    AUTHORITATIVE.forType(SERVICES.toString()),
    INFORMATIVE.forType(ECS_CLUSTERS.toString())
  ));
  private final Logger log = LoggerFactory.getLogger(getClass());

  public ServiceCachingAgent(String accountName, String region, AmazonClientProvider amazonClientProvider, AWSCredentialsProvider awsCredentialsProvider, Registry registry) {
    super(accountName, region, amazonClientProvider, awsCredentialsProvider, registry);
  }

  public static Map<String, Object> convertServiceToAttributes(String accountName, String region, Service service) {
    Map<String, Object> attributes = new HashMap<>();
    String applicationName = service.getServiceName().contains("-") ? StringUtils.substringBefore(service.getServiceName(), "-") : service.getServiceName();
    String clusterName = StringUtils.substringAfterLast(service.getClusterArn(), "/");

    attributes.put("account", accountName);
    attributes.put("region", region);
    attributes.put("applicationName", applicationName);
    attributes.put("serviceName", service.getServiceName());
    attributes.put("serviceArn", service.getServiceArn());
    attributes.put("clusterName", clusterName);
    attributes.put("clusterArn", service.getClusterArn());
    attributes.put("roleArn", service.getRoleArn());
    attributes.put("taskDefinition", service.getTaskDefinition());
    attributes.put("desiredCount", service.getDesiredCount());
    attributes.put("maximumPercent", service.getDeploymentConfiguration().getMaximumPercent());
    attributes.put("minimumHealthyPercent", service.getDeploymentConfiguration().getMinimumHealthyPercent());
    attributes.put("loadBalancers", service.getLoadBalancers());
    attributes.put("createdAt", service.getCreatedAt().getTime());

    return attributes;
  }

  @Override
  public String getAgentType() {
    return ServiceCachingAgent.class.getSimpleName();
  }

  @Override
  public Collection<AgentDataType> getProvidedDataTypes() {
    return types;
  }

  @Override
  protected List<Service> getItems(AmazonECS ecs, ProviderCache providerCache) {
    List<Service> serviceList = new LinkedList<>();
    Set<String> clusters = getClusters(ecs, providerCache);

    for (String cluster : clusters) {
      String nextToken = null;
      do {
        ListServicesRequest listServicesRequest = new ListServicesRequest().withCluster(cluster);
        if (nextToken != null) {
          listServicesRequest.setNextToken(nextToken);
        }
        ListServicesResult listServicesResult = ecs.listServices(listServicesRequest);
        List<String> serviceArns = listServicesResult.getServiceArns();
        if (serviceArns.size() == 0) {
          continue;
        }

        List<Service> services = ecs.describeServices(new DescribeServicesRequest().withCluster(cluster).withServices(serviceArns)).getServices();
        serviceList.addAll(services);

        nextToken = listServicesResult.getNextToken();
      } while (nextToken != null && nextToken.length() != 0);
    }
    return serviceList;
  }

  @Override
  protected Map<String, Collection<CacheData>> generateFreshData(Collection<Service> services) {
    Collection<CacheData> dataPoints = new LinkedList<>();
    Map<String, CacheData> clusterDataPoints = new HashMap<>();

    for (Service service : services) {
      Map<String, Object> attributes = convertServiceToAttributes(accountName, region, service);

      String key = Keys.getServiceKey(accountName, region, service.getServiceName());
      dataPoints.add(new DefaultCacheData(key, attributes, Collections.emptyMap()));

      Map<String, Object> clusterAttributes = EcsClusterCachingAgent.convertClusterArnToAttributes(accountName, region, service.getClusterArn());
      String clusterName = StringUtils.substringAfterLast(service.getClusterArn(), "/");
      key = Keys.getClusterKey(accountName, region, clusterName);
      clusterDataPoints.put(key, new DefaultCacheData(key, clusterAttributes, Collections.emptyMap()));
    }

    log.info("Caching " + dataPoints.size() + " services in " + getAgentType());
    Map<String, Collection<CacheData>> dataMap = new HashMap<>();
    dataMap.put(SERVICES.toString(), dataPoints);

    log.info("Caching " + clusterDataPoints.size() + " ECS clusters in " + getAgentType());
    dataMap.put(ECS_CLUSTERS.toString(), clusterDataPoints.values());

    return dataMap;
  }
}


text:
<resources>
    <string name="app_name">Colorize</string>

    <string name="hello_world">Hello colorful world!</string>
    <string name="button">Button</string>
    <string name="button_disabled">Disabled</string>
</resources>


text:
Sample chat application for "How to set up a Clojure environment with Ansible"

### Environment variables

The application reads configuration from the following environment variables:

- HTTP_PORT
- MONGODB_URI
- RABBITMQ_URI


text:
<?php

namespace Josser\Client\Transport;

/**
 * JSON-RPC transport interface.
 *
 * @author Alan Gabriel Bem <alan.bem@gmail.com>
 */
interface TransportInterface
{
    /**
     * Send data to remote JSON-RPC service.
     *
     * @throws \Josser\Exception\TransportFailureException
     * @param mixed $data
     * @return string
     */
    public function send($data);
}


text:
<?php

namespace Gini\Controller\CLI\CI;

class PHPUnit extends \Gini\Controller\CLI
{
    public function __index($args)
    {
        echo "gini ci phpunit init\n";
        echo "gini ci phpunit create <Class/For/Test>\n";
    }

    public function actionInit()
    {
        echo "Preparing PHPUnit environment...\n";

        $sysPath = SYS_PATH;
        $phpunit_content = <<<TEMPL
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="$sysPath/lib/bootstrap.php">
    <testsuites>
        <testsuite name="gini">
            <directory suffix=".php">./ci/test</directory>
            <exclude>gini.php</exclude>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
          <directory suffix=".php">class</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="junit" target="reports/unit.xml"/>
        <log type="coverage-clover" target="reports/coverage.xml"/>
    </logging>
</phpunit>
TEMPL;

        file_exists(APP_PATH.'/phpunit.xml')
            or file_put_contents(APP_PATH.'/phpunit.xml', $phpunit_content);

        echo "   \e[32mdone.\e[0m\n";
    }

    public function actionCreate($args)
    {
        count($args) > 0 or die("Usage: gini ci phpunit create <Class/For/Test>\n");

        $class = $args[0];
        preg_match('|^[\w\\\/]+$|', $class) or die("Usage: gini ci phpunit create <Class/For/Test>\n");

        echo "Creating $class\n";

        // convert all '/' to '\\'
        $class = strtr($class, [ '/' => '\\' ]);
        $pos = strrpos($class, '\\');
        if ($pos === false) {
            $namespace = '';
            $name = $class;
        } else {
            $namespace = '\\'.trim(substr($class, 0, $pos), '\\');
            $name = trim(substr($class, $pos + 1), '\\');
        }

        $content = <<<TEMPL
<?php

namespace Gini\PHPUnit{$namespace};

class {$name} extends \Gini\PHPUnit\TestCase\CLI {

    public function testHello()
    {
        \$this->assertTrue(false, "PLEASE IMPLEMENT THIS!");
    }

}

TEMPL;

        $dir = APP_PATH.'/ci/test';
        if ($namespace) {
            $dir .= strtr($namespace, '\\', '/');
        }

        if (!file_exists($dir.'/'.$name.'.php')) {
            \Gini\File::ensureDir($dir);
            file_put_contents($dir.'/'.$name.'.php', $content);
            echo "   \e[32mdone.\e[0m\n";
        } else {
            echo "   \e[31mfile exists!\e[0m\n";
        }
    }
}


text:
/*
 * HomeReducer
 *
 * The reducer takes care of our data. Using actions, we can change our
 * application state.
 * To add a new action, add it to the switch statement in the reducer function
 *
 * Example:
 * case YOUR_ACTION_CONSTANT:
 *   return state.set('yourStateVariable', true);
 */
import { fromJS } from 'immutable';

import {
    LOAD_FEEDSLIST_SUCCESS,
    LOAD_FEEDSLIST,
    LOAD_FEEDSLIST_ERROR,
    LOAD_FEEDSENTRIES,
    LOAD_FEEDSENTRIES_SUCCESS,
    LOAD_FEEDSENTRIES_ERROR,
    ENTRY_FAV,
    ENTRY_READ,
    UNREAD_ONLY,
} from './constants';

// The initial state of the App
const initialState = fromJS({
    feedsLoading: true,
    feedsError: false,
    feedsList: [],
    entriesLoading: true,
    entriesError: false,
    entriesList: [],
    unReadOnly: false,
});

function homeReducer(state = initialState, action) {
    switch (action.type) {
        case LOAD_FEEDSLIST:
            return state
            .set('feedsLoading', true)
            .set('feedsError', false)
            .setIn(['feedsList'], fromJS( [] ));
        case LOAD_FEEDSLIST_SUCCESS:
            return state
            .setIn(['feedsList'], fromJS( action.feeds))
            .set('feedsLoading', false);
        case LOAD_FEEDSLIST_ERROR:
            return state
            .set('feedsError', action.error)
            .set('feedsLoading', false);
        case LOAD_FEEDSENTRIES:
            return state
            .set('entriesLoading', true)
            .set('entriesError', false)
            .setIn(['entriesList'], fromJS( [] ));
        case LOAD_FEEDSENTRIES_SUCCESS:
            return state
            .setIn(['entriesList'], fromJS( action.entries))
            .set('entriesLoading', false);
        case LOAD_FEEDSENTRIES_ERROR:
            return state
            .set('entriesError', action.error)
            .set('entriesLoading', false);
        case ENTRY_FAV:
            return state
            .setIn(['entriesList', action.id, 'favorite'], !state.getIn(['entriesList', action.id, 'favorite']));
        case ENTRY_READ:
            return state
            .setIn(['entriesList', action.id, 'read'], true);
        case UNREAD_ONLY:
            return state
            .setIn(['unReadOnly'], !state.getIn(['unReadOnly']));
        default:
            return state;
    }
}

export default homeReducer;


text:
#include "TRFont.hpp"

TRFont::TRFont()
{
    const char *font_name = "Arial";
    m_fontName = TRString(font_name);
    m_fontStyle = 1;
    m_fontColor.SetColor(0, 0, 0);
    m_fontSize = 16;
}

TRFont::TRFont(TRString fontName, TRColor fontColor, int fontSize, int fontStyle)
//TRFont::TRFont(std::wstring fontName, TRColor fontColor,int fontSize, int fontStyle)
{
    m_fontName = fontName;
    m_fontStyle = fontStyle;
    m_fontColor = fontColor;
    m_fontSize = fontSize;
}

TRFont::TRFont(const TRFont &object)
{
    m_fontName = object.m_fontName;
    m_fontStyle = object.m_fontStyle;
    m_fontColor = object.m_fontColor;
    m_fontSize = object.m_fontSize;
}

TRFont &TRFont::operator=(const TRFont &object)
{
    m_fontName = object.m_fontName;
    m_fontStyle = object.m_fontStyle;
    m_fontColor = object.m_fontColor;
    m_fontSize = object.m_fontSize;
    return *this;
}

TRFont::~TRFont()
{

}

TRString &TRFont::FontName()
{
    return m_fontName;
}

int &TRFont::Style()
{
    return m_fontStyle;
}

TRColor &TRFont::Color()
{
    return m_fontColor;
}

int &TRFont::Size()
{
    return m_fontSize;
}


text:
package org.apache.flink.table.runtime.arrow.writers;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.data.ArrayData;
import org.apache.flink.table.data.RowData;

import org.apache.arrow.vector.SmallIntVector;

/**
 * {@link ArrowFieldWriter} for SmallInt.
 */
@Internal
public abstract class SmallIntWriter<T> extends ArrowFieldWriter<T> {

	public static SmallIntWriter<RowData> forRow(SmallIntVector intVector) {
		return new SmallIntWriterForRow(intVector);
	}

	public static SmallIntWriter<ArrayData> forArray(SmallIntVector intVector) {
		return new SmallIntWriterForArray(intVector);
	}

	// ------------------------------------------------------------------------------------------

	private SmallIntWriter(SmallIntVector intVector) {
		super(intVector);
	}

	abstract boolean isNullAt(T in, int ordinal);

	abstract short readShort(T in, int ordinal);

	@Override
	public void doWrite(T in, int ordinal) {
		if (isNullAt(in, ordinal)) {
			((SmallIntVector) getValueVector()).setNull(getCount());
		} else {
			((SmallIntVector) getValueVector()).setSafe(getCount(), readShort(in, ordinal));
		}
	}

	// ------------------------------------------------------------------------------------------

	/**
	 * {@link SmallIntWriter} for {@link RowData} input.
	 */
	public static final class SmallIntWriterForRow extends SmallIntWriter<RowData> {

		private SmallIntWriterForRow(SmallIntVector intVector) {
			super(intVector);
		}

		@Override
		boolean isNullAt(RowData in, int ordinal) {
			return in.isNullAt(ordinal);
		}

		@Override
		short readShort(RowData in, int ordinal) {
			return in.getShort(ordinal);
		}
	}

	/**
	 * {@link SmallIntWriter} for {@link ArrayData} input.
	 */
	public static final class SmallIntWriterForArray extends SmallIntWriter<ArrayData> {

		private SmallIntWriterForArray(SmallIntVector intVector) {
			super(intVector);
		}

		@Override
		boolean isNullAt(ArrayData in, int ordinal) {
			return in.isNullAt(ordinal);
		}

		@Override
		short readShort(ArrayData in, int ordinal) {
			return in.getShort(ordinal);
		}
	}
}


text:
"""Tests for the Windows Scheduled Task job file parser."""

import unittest

from plaso.formatters import winjob  # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib import timelib
from plaso.parsers import winjob

from tests import test_lib as shared_test_lib
from tests.parsers import test_lib

class WinJobTest(test_lib.ParserTestCase):
  """Tests for the Windows Scheduled Task job file parser."""

  @shared_test_lib.skipUnlessHasTestFile([u'wintask.job'])
  def testParse(self):
    """Tests the Parse function."""
    parser_object = winjob.WinJobParser()
    storage_writer = self._ParseFile([u'wintask.job'], parser_object)

    self.assertEqual(len(storage_writer.events), 2)

    event_object = storage_writer.events[0]

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-08-24 12:42:00.112')
    self.assertEqual(event_object.timestamp, expected_timestamp)
    self.assertEqual(
        event_object.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)

    expected_application = (
        u'C:\\Program Files (x86)\\Google\\Update\\GoogleUpdate.exe')
    self.assertEqual(event_object.application, expected_application)

    self.assertEqual(event_object.username, u'Brian')

    expected_comment = (
        u'Keeps your Google software up to date. If this task is disabled or '
        u'stopped, your Google software will not be kept up to date, meaning '
        u'security vulnerabilities that may arise cannot be fixed and '
        u'features may not work. This task uninstalls itself when there is '
        u'no Google software using it.')
    self.assertEqual(event_object.comment, expected_comment)

    # Parse second event. Same metadata; different timestamp event.
    event_object = storage_writer.events[1]

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-07-12 15:42:00')
    self.assertEqual(event_object.timestamp, expected_timestamp)
    self.assertEqual(event_object.timestamp_desc, u'Scheduled to start')

    self.assertEqual(event_object.trigger_type, 1)

    expected_message = (
        u'Application: {0:s} /ua /installsource scheduler '
        u'Scheduled by: Brian '
        u'Trigger type: DAILY').format(expected_application)

    expected_short_message = (
        u'Application: {0:s} /ua /insta...').format(expected_application)

    self._TestGetMessageStrings(
        event_object, expected_message, expected_short_message)

if __name__ == '__main__':
  unittest.main()


text:
import tornado.options
import random
tornado.options.define("environment", default="dev", help="environment")

def randomize(values):
    """ this is a wrapper that returns a function which when called returns a random value"""
    def picker():
        return random.choice(values)
    return picker

options = {
    'dev' : {
        'mongo_database' : {'host' : '127.0.0.1', 'port' : 27017, 'dbname' : 'testdb', 'maxconnections':5}
    }
}

default = {}

def get(key):
    env = tornado.options.options.environment
    if env not in options:
        raise Exception("Invalid Environment (%s)" % env)
    v = options.get(env).get(key) or default.get(key)
    if callable(v):
        return v()
    return v


text:
<?php $placeholder = 'Write Something Here "HAHA" Nothing'; ?>

<?=form_open('form', array('method'=>'get', 'role'=>'form'));?>
<?=form_fieldset('Fill Up for Registration');?>

    <?php
    echo form_label('Username:', 'username');
    $username_data = array(
        'name'      => 'username',
        'id'        => 'username',
        'class'     => 'form-control',
        'required'  => 'required',
    );
    echo form_input($username_data);
    ?>

    <?php
    echo form_label('Password:', 'password');
    $password_data = array(
        'name'      => 'password',
        'id'        => 'password',
        'class'     => 'form-control',
        'required'  => 'required',
    );
    echo form_password($password_data);
    ?>

    Select Gender:
    <input type="radio" name="gender" value="male" checked="checked">Male
    <input type="radio" name="gender" value="female">Female
    <input type="radio" name="gender" value="female">Other

    <?php
    echo form_label('Write Something:', 'text');
    $text_data = array(
        'name'      => 'text',
        'id'        => 'text',
        'rows'      => '4',
        'class'     => 'form-control',
        'placeholder' => $placeholder,
    );
    echo form_textarea($text_data);
    ?>

    <?php
    echo form_label('Address:', 'address');
    $address_data = array(
        'name'      => 'address',
        'id'        => 'address',
        'rows'      => '2',
        'class'     => 'form-control',
        'placeholder' => html_escape($placeholder),
    );
    echo form_textarea($address_data);
    ?>

    Programming :

        <input type="checkbox" value="">PHP

        <input type="checkbox" value="">C++

        <input type="checkbox" value="">Java

    <?php
    echo form_label('Select Country:', 'country');
    $country_extra = array(
        'class' => 'form-control',
        'id'    => 'country'
    );
    $options = array(
        'maldives'      => 'Maldives',
        'afghanistan'   => 'Afghanistan',
        'srilanka'      => 'Srilanka',
        'india'         => 'India',
        'nepal'         => 'Nepal'
    );
    echo form_dropdown('country', $options, 'Nepal', $country_extra);
    ?>

<?php
$data = array(
    'id'        => 'submit',
    'type'      => 'submit',
    'class'     => 'btn btn-default',
    'content'   => 'Post'
);
echo form_button($data);
echo form_fieldset_close();
echo form_close();
?>


text:
#include "read_discrete_inputs.hpp"
#include <cstddef>

namespace controller
{
    namespace modbus
    {
        ReadDiscreteInputsResponse::ReadDiscreteInputsResponse(Header& header)
        {
            transaction_id.word = header.getTransition();
            protocol.word = 0u;
            length.word = 0u;
        }

        void ReadDiscreteInputsResponse::appendByte(uint8_t word)
        {
            data.emplace_back(word);
            length.word++;
        }

        std::vector<uint8_t> ReadDiscreteInputsResponse::getData() const
        {
            std::vector<uint8_t> total;
            total.reserve(7 + data.size());

            total.push_back(transaction_id.low);
            total.push_back(transaction_id.high);
            total.push_back(protocol.low);
            total.push_back(protocol.high);
            total.push_back(length.low);
            total.push_back(length.high);
            total.push_back(unit);

            for(size_t i = 0u; i < data.size(); i++)
            {
                total.push_back(data[i]);
            }

            return total;
        }
    }
}