text:
package org.apache.flink.graph.library.clustering.undirected;

import org.apache.flink.api.common.accumulators.DoubleCounter;
import org.apache.flink.api.common.accumulators.LongCounter;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.graph.AnalyticHelper;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAnalyticBase;
import org.apache.flink.graph.asm.result.PrintableResult;
import org.apache.flink.graph.library.clustering.undirected.AverageClusteringCoefficient.Result;
import org.apache.flink.types.CopyableValue;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.io.IOException;

/**
 * The average clustering coefficient measures the mean connectedness of a
 * graph. Scores range from 0.0 (no triangles) to 1.0 (complete graph).
 *
 * @param <K> graph ID type
 * @param <VV> vertex value type
 * @param <EV> edge value type
 */
public class AverageClusteringCoefficient<K extends Comparable<K> & CopyableValue<K>, VV, EV>
extends GraphAnalyticBase<K, VV, EV, Result> {

	private static final String VERTEX_COUNT = "vertexCount";

	private static final String SUM_OF_LOCAL_CLUSTERING_COEFFICIENT = "sumOfLocalClusteringCoefficient";

	private AverageClusteringCoefficientHelper<K> averageClusteringCoefficientHelper;

	/*
	 * Implementation notes:
	 *
	 * The requirement that "K extends CopyableValue<K>" can be removed when
	 *   removed from LocalClusteringCoefficient.
	 */

	@Override
	public AverageClusteringCoefficient<K, VV, EV> run(Graph<K, VV, EV> input)
			throws Exception {
		super.run(input);

		DataSet<LocalClusteringCoefficient.Result<K>> localClusteringCoefficient = input
			.run(new LocalClusteringCoefficient<K, VV, EV>()
				.setParallelism(parallelism));

		averageClusteringCoefficientHelper = new AverageClusteringCoefficientHelper<>();

		localClusteringCoefficient
			.output(averageClusteringCoefficientHelper)
				.name("Average clustering coefficient");

		return this;
	}

	@Override
	public Result getResult() {
		long vertexCount = averageClusteringCoefficientHelper.getAccumulator(env, VERTEX_COUNT);
		double sumOfLocalClusteringCoefficient = averageClusteringCoefficientHelper.getAccumulator(env, SUM_OF_LOCAL_CLUSTERING_COEFFICIENT);

		return new Result(vertexCount, sumOfLocalClusteringCoefficient);
	}

	/**
	 * Helper class to collect the average clustering coefficient.
	 *
	 * @param <T> ID type
	 */
	private static class AverageClusteringCoefficientHelper<T>
	extends AnalyticHelper<LocalClusteringCoefficient.Result<T>> {
		private long vertexCount;
		private double sumOfLocalClusteringCoefficient;

		@Override
		public void writeRecord(LocalClusteringCoefficient.Result<T> record) throws IOException {
			vertexCount++;

			// local clustering coefficient is only defined on vertices with
			// at least two neighbors yielding at least one pair of neighbors
			if (record.getDegree().getValue() > 1) {
				sumOfLocalClusteringCoefficient += record.getLocalClusteringCoefficientScore();
			}
		}

		@Override
		public void close() throws IOException {
			addAccumulator(VERTEX_COUNT, new LongCounter(vertexCount));
			addAccumulator(SUM_OF_LOCAL_CLUSTERING_COEFFICIENT, new DoubleCounter(sumOfLocalClusteringCoefficient));
		}
	}

	/**
	 * Wraps global clustering coefficient metrics.
	 */
	public static class Result
	implements PrintableResult {
		private long vertexCount;
		private double averageLocalClusteringCoefficient;

		/**
		 * Instantiate an immutable result.
		 *
		 * @param vertexCount vertex count
		 * @param sumOfLocalClusteringCoefficient sum over the vertices' local
		 *                                        clustering coefficients
		 */
		public Result(long vertexCount, double sumOfLocalClusteringCoefficient) {
			this.vertexCount = vertexCount;
			this.averageLocalClusteringCoefficient = sumOfLocalClusteringCoefficient / vertexCount;
		}

		/**
		 * Get the number of vertices.
		 *
		 * @return number of vertices
		 */
		public long getNumberOfVertices() {
			return vertexCount;
		}

		/**
		 * Get the average clustering coefficient.
		 *
		 * @return number of triangles
		 */
		public double getAverageClusteringCoefficient() {
			return averageLocalClusteringCoefficient;
		}

		@Override
		public String toPrintableString() {
			return "vertex count: " + vertexCount
				+ ", average clustering coefficient: " + averageLocalClusteringCoefficient;
		}

		@Override
		public int hashCode() {
			return new HashCodeBuilder()
				.append(vertexCount)
				.append(averageLocalClusteringCoefficient)
				.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}

			if (obj == this) {
				return true;
			}

			if (obj.getClass() != getClass()) {
				return false;
			}

			Result rhs = (Result) obj;

			return new EqualsBuilder()
				.append(vertexCount, rhs.vertexCount)
				.append(averageLocalClusteringCoefficient, rhs.averageLocalClusteringCoefficient)
				.isEquals();
		}
	}
}


text:
"""Functions to aid in preserving the test database between test runs.

The code in this module is heavily inspired by django-nose:
https://github.com/jbalogh/django-nose/
"""
import sys
import types

def is_in_memory_db(connection):
    """Return whether it makes any sense to use REUSE_DB with the backend of a
    connection."""
    # This is a SQLite in-memory DB. Those are created implicitly when
    # you try to connect to them, so our test below doesn't work.
    return connection.settings_dict['NAME'] == ':memory:'

def test_database_exists_from_previous_run(connection):
    # Check for sqlite memory databases
    if is_in_memory_db(connection):
        return False

    # Try to open a cursor to the test database
    orig_db_name = connection.settings_dict['NAME']
    connection.settings_dict['NAME'] = connection.creation._get_test_db_name()

    try:
        connection.cursor()
        return True
    except Exception:  # TODO: Be more discerning but still DB agnostic.
        return False
    finally:
        connection.close()
        connection.settings_dict['NAME'] = orig_db_name

def _monkeypatch(obj, method_name, new_method):
    assert hasattr(obj, method_name)

    if sys.version_info < (3, 0):
        wrapped_method = types.MethodType(new_method, obj, obj.__class__)
    else:
        wrapped_method = types.MethodType(new_method, obj)

    setattr(obj, method_name, wrapped_method)

def monkey_patch_creation_for_db_suffix(suffix=None):
    from django.db import connections

    if suffix is not None:
        def _get_test_db_name(self):
            """
            Internal implementation - returns the name of the test DB that will be
            created. Only useful when called from create_test_db() and
            _create_test_db() and when no external munging is done with the 'NAME'
            or 'TEST_NAME' settings.
            """

            if self.connection.settings_dict['TEST_NAME']:
                original = self.connection.settings_dict['TEST_NAME']
            original = 'test_' + self.connection.settings_dict['NAME']

            if suffix:
                return '%s_%s' % (original, suffix)

            return original

        for connection in connections.all():

            _monkeypatch(connection.creation, '_get_test_db_name', _get_test_db_name)

def create_test_db_with_reuse(self, verbosity=1, autoclobber=False):
    """
    This method is a monkey patched version of create_test_db that
    will not actually create a new database, but just reuse the
    existing.
    """
    test_database_name = self._get_test_db_name()
    self.connection.settings_dict['NAME'] = test_database_name

    if verbosity >= 1:
        test_db_repr = ''
        if verbosity >= 2:
            test_db_repr = " ('%s')" % test_database_name
        print("Re-using existing test database for alias '%s'%s..." % (
            self.connection.alias, test_db_repr))

    # confirm() is not needed/available in Django >= 1.5
    # See https://code.djangoproject.com/ticket/17760
    if hasattr(self.connection.features, 'confirm'):
        self.connection.features.confirm()

    return test_database_name

def monkey_patch_creation_for_db_reuse():
    from django.db import connections

    for connection in connections.all():
        if test_database_exists_from_previous_run(connection):
            _monkeypatch(connection.creation, 'create_test_db', create_test_db_with_reuse)

redpajama_set_name: RedPajamaGithub


text:
from .base import *

class BlogPosts(ListableApiResource, CreateableApiResource,
              UpdateableApiResource, DeleteableApiResource,
              CountableApiResource, CollectionDeleteableApiResource):
    resource_name = 'blog/posts'


text:
#include <aws/ec2/model/IpamManagementState.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace IpamManagementStateMapper
      {

        static const int managed_HASH = HashingUtils::HashString("managed");
        static const int unmanaged_HASH = HashingUtils::HashString("unmanaged");
        static const int ignored_HASH = HashingUtils::HashString("ignored");

        IpamManagementState GetIpamManagementStateForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == managed_HASH)
          {
            return IpamManagementState::managed;
          }
          else if (hashCode == unmanaged_HASH)
          {
            return IpamManagementState::unmanaged;
          }
          else if (hashCode == ignored_HASH)
          {
            return IpamManagementState::ignored;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<IpamManagementState>(hashCode);
          }

          return IpamManagementState::NOT_SET;
        }

        Aws::String GetNameForIpamManagementState(IpamManagementState enumValue)
        {
          switch(enumValue)
          {
          case IpamManagementState::managed:
            return "managed";
          case IpamManagementState::unmanaged:
            return "unmanaged";
          case IpamManagementState::ignored:
            return "ignored";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace IpamManagementStateMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


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

namespace TelerikAcademy.TripyMate.Web.Models.Account
{
    public class ExternalLoginListViewModel
    {
        public string ReturnUrl { get; set; }
    }
}


text:
<?php
function rozwiaz_szpiegow($event){
	//zabezpiecz zmienne
	fx('wiadomosc_wyslij');
	$login = one($q="select login from warcry_gracze inner join warcry_miasta on gracz_id = gracz  where miasto = ".$event['miasto_id']);

	call("update warcry_jednostki_miasta set ilosc = ilosc + ".$event['ilosc']." where (jednostka_id = 3 or jednostka_id = 18) and miasto_id = ".$event['miasto_id']);

	$a = wiadomosc_wyslij(1,$login,"Szpiedzy powrócili do miasta");

}
?>


text:
package io.spine.server.storage.jdbc.delivery;

import com.google.common.collect.ImmutableList;
import io.spine.server.delivery.InboxMessage;
import io.spine.server.delivery.Page;

import java.util.Iterator;
import java.util.Optional;

/**
 * A page of messages obtained from the {@link JdbcInboxStorage}.
 *
 * <p>Will be no bigger than the specified {@link #batchSize}.
 */
final class InboxPage implements Page<InboxMessage> {

    private final Iterator<InboxMessage> iterator;
    private final int batchSize;
    private final ImmutableList<InboxMessage> contents;

    InboxPage(Iterator<InboxMessage> iterator, int size) {
        this.iterator = iterator;
        this.batchSize = size;
        ImmutableList.Builder<InboxMessage> builder = transform(iterator, size);
        contents = builder.build();
    }

    private static ImmutableList.Builder<InboxMessage> transform(Iterator<InboxMessage> it,
                                                                 int size) {
        ImmutableList.Builder<InboxMessage> builder = ImmutableList.builder();
        int contentSize = 0;
        while (contentSize < size && it.hasNext()) {
            InboxMessage message = it.next();
            builder.add(message);
            contentSize++;
        }
        return builder;
    }

    @Override
    public ImmutableList<InboxMessage> contents() {
        return contents;
    }

    @Override
    public int size() {
        return contents.size();
    }

    @Override
    public Optional<Page<InboxMessage>> next() {
        if (!iterator.hasNext()) {
            return Optional.empty();
        }
        InboxPage page = new InboxPage(iterator, batchSize);
        return Optional.of(page);
    }
}


text:
package jp.co.acroquest.endosnipe.javelin.converter.file.monitor;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import jp.co.acroquest.endosnipe.common.logger.SystemLogger;
import jp.co.acroquest.endosnipe.javelin.util.StatsUtil;

public class FileOpenCloseMonitor
{
    private static Map<String, String> fileMap = new ConcurrentHashMap<String, String>();

    public static void open(Object obj, File file)
    {
        if (isExcludeThread())
        {
            return;
        }

        fileMap.put(StatsUtil.getObjectID(obj), file.getAbsolutePath());

        SystemLogger.getInstance().warn("open file:" + file.getAbsolutePath());
    }

    private static boolean isExcludeThread()
    {
        String threadName = Thread.currentThread().getName();
        return threadName.contains("Javelin") || threadName.contains("Finalizer");
    }

    public static void close(Object obj)
    {
        if (isExcludeThread())
        {
            return;
        }

        String fileName = fileMap.remove(StatsUtil.getObjectID(obj));
        if (fileName != null)
        {
            SystemLogger.getInstance().warn("close file:" + fileName);
        }
    }
}


text:
package eu.euporias.api.service;

import static eu.euporias.api.util.DSLNames.field;
import static eu.euporias.api.util.DSLNames.table;

import java.util.List;

import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.SelectForUpdateStep;
import org.jooq.Table;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import eu.euporias.api.model.Application;
import eu.euporias.api.model.Product;

@Service("outcomeMetadataService")
public class OutcomeMetadataServiceImpl implements OutcomeMetadataService {

	@Override
	public Integer countByParameterName(Application application, Product product, String parameterName){
		Table<Record> outcomeTable = table("outcome");
		Table<Record> outcomeParamsTable = table("outcome_parameters");
		Field<String> parametersField = field(String.class, outcomeParamsTable, "parameters");
		Field<Integer> countDistinctParametersField = DSL.countDistinct(parametersField);
		SelectForUpdateStep<Record1<Integer>> query = dslContext.select(countDistinctParametersField)
			.from(outcomeTable).join(outcomeParamsTable)
				.on(field(outcomeTable, "id").eq(field(outcomeParamsTable, "outcome_id")))
			.where(
				field(outcomeTable, "application_id").eq(application.getId()),
				field(outcomeTable, "product_id").eq(product.getId()),
				field(outcomeParamsTable, "parameters_key").eq(parameterName)
			);
		Integer result = query.fetchOne().value1();
		return result != null ? result : 0;
	}

	@Override
	public List<String> findByParameterName(Application application, Product product, String parameterName, Pageable pageable){
    	Table<Record> outcomeTable = table("outcome");
		Table<Record> outcomeParamsTable = table("outcome_parameters");
		Field<String> parametersField = field(String.class, outcomeParamsTable, "parameters");
		SelectForUpdateStep<Record1<String>> query = dslContext.selectDistinct(parametersField)
			.from(outcomeTable).join(outcomeParamsTable)
				.on(field(outcomeTable, "id").eq(field(outcomeParamsTable, "outcome_id")))
			.where(
				field(outcomeTable, "application_id").eq(application.getId()),
				field(outcomeTable, "product_id").eq(product.getId()),
				field(outcomeParamsTable, "parameters_key").eq(parameterName)
			)
			.orderBy(parametersField.desc())
			.limit(pageable.getPageSize())
			.offset(pageable.getOffset());
		return query.fetch(parametersField);
	}

	@Autowired private DSLContext dslContext;

}


text:
var Aria = require("../../Aria");
require("./ErrorListController");
var ariaWidgetsTemplateBasedWidget = require("../TemplateBasedWidget");
var ariaUtilsJson = require("../../utils/Json");
var ariaUtilsString = require("../../utils/String");

/**
 * Error list widget, which is a template-based widget. Most of the logic of the error list widget is implemented in the
 * ErrorListController class. This class only does the link between the properties of the error list widget and the
 * error list controller.
 */
module.exports = Aria.classDefinition({
    $classpath : "aria.widgets.errorlist.ErrorList",
    $extends : ariaWidgetsTemplateBasedWidget,
    $onload : function () {
        /*
         * Preload the default template here, to improve performances TODO: find a better way, to also improve
         * performances for custom templates
         */
        Aria.load({
            templates : ['aria.widgets.errorlist.ErrorListTemplate']
        });
    },
    $constructor : function (cfg, ctxt) {
        this.$TemplateBasedWidget.constructor.apply(this, arguments);
        var skinObj = aria.widgets.AriaSkinInterface.getSkinObject(this._skinnableClass, this._cfg.sclass);
        var divCfg = ariaUtilsJson.copy(cfg, true, ['width', 'minWidth', 'maxWidth', 'height', 'minHeight', 'block',
                'maxHeight']);
        divCfg.sclass = skinObj.divsclass;
        divCfg.margins = "0 0 0 0";
        divCfg.id = cfg.id + "_div";

        if (cfg.waiAria) {
            if (cfg.ariaLive) {
                if (!cfg.role) {
                    cfg.role = "status";
                }
                this._extraAttributes = ' aria-live="assertive" ';
            }
            if (cfg.role) {
                this._extraAttributes += ' role="' + ariaUtilsString.escapeHTML(cfg.role) + '" ';
            }
        }

        this._initTemplate({
            moduleCtrl : {
                classpath : "aria.widgets.errorlist.ErrorListController",
                initArgs : {
                    waiAria: cfg.waiAria,
                    divCfg : divCfg,
                    filterTypes : cfg.filterTypes,
                    displayCodes : cfg.displayCodes,
                    title : cfg.title,
                    titleTag : cfg.titleTag,
                    titleClassName : cfg.titleClassName,
                    messages : cfg.messages,
                    displayOptions : cfg.displayOptions
                }
            }
        });
    },

    $destructor : function () {
        this.$TemplateBasedWidget.$destructor.call(this);
    },
    $prototype : {
        /**
         * Skinnable class to use for this widget.
         * @type String
         * @protected
         */
        _skinnableClass : "ErrorList",

        /**
         * Give focus to the widget
         */
        focus : function () {
            this._tplWidget.focus();
        },

        _onBoundPropertyChange : function (propertyName, newValue, oldValue) {
            this._inOnBoundPropertyChange = true;
            try {
                if (propertyName == "messages") {
                    var domId = this._domElt;
                    this._subTplModuleCtrl.setMessages(newValue, domId);
                    this._cfg[propertyName] = newValue;
                } else if (propertyName === "requireFocus") {
                    if (!newValue) {
                        // nothing to do if the focus is not required, if we have no
                        // focus method, or if
                        // the widget is disabled
                        return;
                    }
                    // The requireFocus binding is a special one as we change back
                    // the property
                    // to false as soon as a widget handles the property.
                    var binding = this._cfg.bind[propertyName];
                    var curValue = binding.inside[binding.to];
                    // We check the actual value in the data model because there can
                    // be several widgets
                    // linked to the same part of the data model.
                    // Only one will have the focus: the first non disabled widget
                    // whose _onBoundPropertyChange is called.
                    if (curValue) {
                        // the value is still true in the data model
                        // we set the focus on the input and immediately set the
                        // value back to false in the data model
                        this.focus();
                        ariaUtilsJson.setValue(binding.inside, binding.to, false);
                    }
                } else {
                    this._cfg[propertyName] = newValue;
                }
            } finally {
                this._inOnBoundPropertyChange = false;
            }
        }
    }
});


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import base64
import time
import traceback

from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleConnectionFailure, AnsibleActionFail, AnsibleActionSkip
from ansible.executor.task_result import TaskResult
from ansible.module_utils.six import iteritems, string_types, binary_type
from ansible.module_utils._text import to_text
from ansible.playbook.conditional import Conditional
from ansible.playbook.task import Task
from ansible.plugins.connection import ConnectionBase
from ansible.template import Templar
from ansible.utils.encrypt import key_for_hostname
from ansible.utils.listify import listify_lookup_plugin_terms
from ansible.utils.unsafe_proxy import UnsafeProxy, wrap_var

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

__all__ = ['TaskExecutor']

class TaskExecutor:

    '''
    This is the main worker class for the executor pipeline, which
    handles loading an action plugin to actually dispatch the task to
    a given host. This class roughly corresponds to the old Runner()
    class.
    '''

    # Modules that we optimize by squashing loop items into a single call to
    # the module
    SQUASH_ACTIONS = frozenset(C.DEFAULT_SQUASH_ACTIONS)

    def __init__(self, host, task, job_vars, play_context, new_stdin, loader, shared_loader_obj, rslt_q):
        self._host = host
        self._task = task
        self._job_vars = job_vars
        self._play_context = play_context
        self._new_stdin = new_stdin
        self._loader = loader
        self._shared_loader_obj = shared_loader_obj
        self._connection = None
        self._rslt_q = rslt_q
        self._loop_eval_error = None

        self._task.squash()

    def run(self):
        '''
        The main executor entrypoint, where we determine if the specified
        task requires looping and either runs the task with self._run_loop()
        or self._execute(). After that, the returned results are parsed and
        returned as a dict.
        '''

        display.debug("in run() - task %s" % self._task._uuid)

        try:
            try:
                items = self._get_loop_items()
            except AnsibleUndefinedVariable as e:
                # save the error raised here for use later
                items = None
                self._loop_eval_error = e

            if items is not None:
                if len(items) > 0:
                    item_results = self._run_loop(items)

                    # create the overall result item
                    res = dict(results=item_results)

                    # loop through the item results, and set the global changed/failed result flags based on any item.
                    for item in item_results:
                        if 'changed' in item and item['changed'] and not res.get('changed'):
                            res['changed'] = True
                        if 'failed' in item and item['failed'] and not res.get('failed'):
                            res['failed'] = True
                            res['msg'] = 'One or more items failed'

                        # ensure to accumulate these
                        for array in ['warnings', 'deprecations']:
                            if array in item and item[array]:
                                if array not in res:
                                    res[array] = []
                                if not isinstance(item[array], list):
                                    item[array] = [item[array]]
                                res[array] = res[array] + item[array]
                                del item[array]

                    if not res.get('Failed', False):
                        res['msg'] = 'All items completed'
                else:
                    res = dict(changed=False, skipped=True, skipped_reason='No items in the list', results=[])
            else:
                display.debug("calling self._execute()")
                res = self._execute()
                display.debug("_execute() done")

            # make sure changed is set in the result, if it's not present
            if 'changed' not in res:
                res['changed'] = False

            def _clean_res(res, errors='surrogate_or_strict'):
                if isinstance(res, UnsafeProxy):
                    return res._obj
                elif isinstance(res, binary_type):
                    return to_text(res, errors=errors)
                elif isinstance(res, dict):
                    for k in res:
                        try:
                            res[k] = _clean_res(res[k], errors=errors)
                        except UnicodeError:
                            if k == 'diff':
                                # If this is a diff, substitute a replacement character if the value
                                # is undecodable as utf8.  (Fix #21804)
                                display.warning("We were unable to decode all characters in the module return data."
                                                " Replaced some in an effort to return as much as possible")
                                res[k] = _clean_res(res[k], errors='surrogate_then_replace')
                            else:
                                raise
                elif isinstance(res, list):
                    for idx, item in enumerate(res):
                        res[idx] = _clean_res(item, errors=errors)
                return res

            display.debug("dumping result to json")
            res = _clean_res(res)
            display.debug("done dumping result, returning")
            return res
        except AnsibleError as e:
            return dict(failed=True, msg=to_text(e, nonstring='simplerepr'))
        except Exception as e:
            return dict(failed=True, msg='Unexpected failure during module execution.', exception=to_text(traceback.format_exc()), stdout='')
        finally:
            try:
                self._connection.close()
            except AttributeError:
                pass
            except Exception as e:
                display.debug(u"error closing connection: %s" % to_text(e))

    def _get_loop_items(self):
        '''
        Loads a lookup plugin to handle the with_* portion of a task (if specified),
        and returns the items result.
        '''

        # save the play context variables to a temporary dictionary,
        # so that we can modify the job vars without doing a full copy
        # and later restore them to avoid modifying things too early
        play_context_vars = dict()
        self._play_context.update_vars(play_context_vars)

        old_vars = dict()
        for k in play_context_vars:
            if k in self._job_vars:
                old_vars[k] = self._job_vars[k]
            self._job_vars[k] = play_context_vars[k]

        # get search path for this task to pass to lookup plugins
        self._job_vars['ansible_search_path'] = self._task.get_search_path()

        templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
        items = None
        if self._task.loop:
            if self._task.loop in self._shared_loader_obj.lookup_loader:
                fail = True
                if self._task.loop == 'first_found':
                    # first_found loops are special. If the item is undefined then we want to fall through to the next value rather than failing.
                    fail = False

                loop_terms = listify_lookup_plugin_terms(terms=self._task.loop_args, templar=templar, loader=self._loader, fail_on_undefined=fail,
                                                         convert_bare=False)
                if not fail:
                    loop_terms = [t for t in loop_terms if not templar._contains_vars(t)]

                # get lookup
                mylookup = self._shared_loader_obj.lookup_loader.get(self._task.loop, loader=self._loader, templar=templar)

                # give lookup task 'context' for subdir (mostly needed for first_found)
                for subdir in ['template', 'var', 'file']:  # TODO: move this to constants?
                    if subdir in self._task.action:
                        break
                setattr(mylookup, '_subdir', subdir + 's')

                # run lookup
                items = mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True)
            else:
                raise AnsibleError("Unexpected failure in finding the lookup named '%s' in the available lookup plugins" % self._task.loop)

        # now we restore any old job variables that may have been modified,
        # and delete them if they were in the play context vars but not in
        # the old variables dictionary
        for k in play_context_vars:
            if k in old_vars:
                self._job_vars[k] = old_vars[k]
            else:
                del self._job_vars[k]

        if items:
            for idx, item in enumerate(items):
                if item is not None and not isinstance(item, UnsafeProxy):
                    items[idx] = UnsafeProxy(item)

        # ensure basedir is always in (dwim already searches here but we need to display it)
        if self._loader.get_basedir() not in self._job_vars['ansible_search_path']:
            self._job_vars['ansible_search_path'].append(self._loader.get_basedir())

        return items

    def _run_loop(self, items):
        '''
        Runs the task with the loop items specified and collates the result
        into an array named 'results' which is inserted into the final result
        along with the item for which the loop ran.
        '''

        results = []

        # make copies of the job vars and task so we can add the item to
        # the variables and re-validate the task with the item variable
        # task_vars = self._job_vars.copy()
        task_vars = self._job_vars

        loop_var = 'item'
        label = None
        loop_pause = 0
        if self._task.loop_control:
            # the value may be 'None', so we still need to default it back to 'item'
            loop_var = self._task.loop_control.loop_var or 'item'
            label = self._task.loop_control.label or ('{{' + loop_var + '}}')
            loop_pause = self._task.loop_control.pause or 0

        if loop_var in task_vars:
            display.warning(u"The loop variable '%s' is already in use. "
                            u"You should set the `loop_var` value in the `loop_control` option for the task"
                            u" to something else to avoid variable collisions and unexpected behavior." % loop_var)

        ran_once = False
        items = self._squash_items(items, loop_var, task_vars)
        for item in items:
            task_vars[loop_var] = item

            # pause between loop iterations
            if loop_pause and ran_once:
                time.sleep(loop_pause)
            else:
                ran_once = True

            try:
                tmp_task = self._task.copy(exclude_parent=True, exclude_tasks=True)
                tmp_task._parent = self._task._parent
                tmp_play_context = self._play_context.copy()
            except AnsibleParserError as e:
                results.append(dict(failed=True, msg=to_text(e)))
                continue

            # now we swap the internal task and play context with their copies,
            # execute, and swap them back so we can do the next iteration cleanly
            (self._task, tmp_task) = (tmp_task, self._task)
            (self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)
            res = self._execute(variables=task_vars)
            (self._task, tmp_task) = (tmp_task, self._task)
            (self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)

            # now update the result with the item info, and append the result
            # to the list of results
            res[loop_var] = item
            res['_ansible_item_result'] = True

            if label is not None:
                templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
                res['_ansible_item_label'] = templar.template(label)

            self._rslt_q.put(
                TaskResult(
                    self._host.name,
                    self._task._uuid,
                    res,
                    task_fields=self._task.dump_attrs(),
                ),
                block=False,
            )
            results.append(res)
            del task_vars[loop_var]

        return results

    def _squash_items(self, items, loop_var, variables):
        '''
        Squash items down to a comma-separated list for certain modules which support it
        (typically package management modules).
        '''
        name = None
        try:
            # _task.action could contain templatable strings (via action: and
            # local_action:)  Template it before comparing.  If we don't end up
            # optimizing it here, the templatable string might use template vars
            # that aren't available until later (it could even use vars from the
            # with_items loop) so don't make the templated string permanent yet.
            templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)
            task_action = self._task.action
            if templar._contains_vars(task_action):
                task_action = templar.template(task_action, fail_on_undefined=False)

            if len(items) > 0 and task_action in self.SQUASH_ACTIONS:
                if all(isinstance(o, string_types) for o in items):
                    final_items = []

                    for allowed in ['name', 'pkg', 'package']:
                        name = self._task.args.pop(allowed, None)
                        if name is not None:
                            break

                    # This gets the information to check whether the name field
                    # contains a template that we can squash for
                    template_no_item = template_with_item = None
                    if name:
                        if templar._contains_vars(name):
                            variables[loop_var] = '\0$'
                            template_no_item = templar.template(name, variables, cache=False)
                            variables[loop_var] = '\0@'
                            template_with_item = templar.template(name, variables, cache=False)
                            del variables[loop_var]

                        # Check if the user is doing some operation that doesn't take
                        # name/pkg or the name/pkg field doesn't have any variables
                        # and thus the items can't be squashed
                        if template_no_item != template_with_item:
                            for item in items:
                                variables[loop_var] = item
                                if self._task.evaluate_conditional(templar, variables):
                                    new_item = templar.template(name, cache=False)
                                    final_items.append(new_item)
                            self._task.args['name'] = final_items
                            # Wrap this in a list so that the calling function loop
                            # executes exactly once
                            return [final_items]
                        else:
                            # Restore the name parameter
                            self._task.args['name'] = name
                # elif:
                    # Right now we only optimize single entries.  In the future we
                    # could optimize more types:
                    # * lists can be squashed together
                    # * dicts could squash entries that match in all cases except the
                    #   name or pkg field.
        except:
            # Squashing is an optimization.  If it fails for any reason,
            # simply use the unoptimized list of items.

            # Restore the name parameter
            if name is not None:
                self._task.args['name'] = name
        return items

    def _execute(self, variables=None):
        '''
        The primary workhorse of the executor system, this runs the task
        on the specified host (which may be the delegated_to host) and handles
        the retry/until and block rescue/always execution
        '''

        if variables is None:
            variables = self._job_vars

        templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)

        context_validation_error = None
        try:
            # apply the given task's information to the connection info,
            # which may override some fields already set by the play or
            # the options specified on the command line
            self._play_context = self._play_context.set_task_and_variable_override(task=self._task, variables=variables, templar=templar)

            # fields set from the play/task may be based on variables, so we have to
            # do the same kind of post validation step on it here before we use it.
            self._play_context.post_validate(templar=templar)

            # now that the play context is finalized, if the remote_addr is not set
            # default to using the host's address field as the remote address
            if not self._play_context.remote_addr:
                self._play_context.remote_addr = self._host.address

            # We also add "magic" variables back into the variables dict to make sure
            # a certain subset of variables exist.
            self._play_context.update_vars(variables)

            # FIXME: update connection/shell plugin options
        except AnsibleError as e:
            # save the error, which we'll raise later if we don't end up
            # skipping this task during the conditional evaluation step
            context_validation_error = e

        # Evaluate the conditional (if any) for this task, which we do before running
        # the final task post-validation. We do this before the post validation due to
        # the fact that the conditional may specify that the task be skipped due to a
        # variable not being present which would otherwise cause validation to fail
        try:
            if not self._task.evaluate_conditional(templar, variables):
                display.debug("when evaluation is False, skipping this task")
                return dict(changed=False, skipped=True, skip_reason='Conditional result was False', _ansible_no_log=self._play_context.no_log)
        except AnsibleError:
            # loop error takes precedence
            if self._loop_eval_error is not None:
                raise self._loop_eval_error
            # skip conditional exception in the case of includes as the vars needed might not be available except in the included tasks or due to tags
            if self._task.action not in ['include', 'include_tasks', 'include_role']:
                raise

        # Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task
        if self._loop_eval_error is not None:
            raise self._loop_eval_error

        # if we ran into an error while setting up the PlayContext, raise it now
        if context_validation_error is not None:
            raise context_validation_error

        # if this task is a TaskInclude, we just return now with a success code so the
        # main thread can expand the task list for the given host
        if self._task.action in ('include', 'include_tasks'):
            include_variables = self._task.args.copy()
            include_file = include_variables.pop('_raw_params', None)
            if not include_file:
                return dict(failed=True, msg="No include file was specified to the include")

            include_file = templar.template(include_file)
            return dict(include=include_file, include_variables=include_variables)

        # if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host
        elif self._task.action == 'include_role':
            include_variables = self._task.args.copy()
            return dict(include_role=self._task, include_variables=include_variables)

        # Now we do final validation on the task, which sets all fields to their final values.
        self._task.post_validate(templar=templar)
        if '_variable_params' in self._task.args:
            variable_params = self._task.args.pop('_variable_params')
            if isinstance(variable_params, dict):
                display.deprecated("Using variables for task params is unsafe, especially if the variables come from an external source like facts",
                                   version="2.6")
                variable_params.update(self._task.args)
                self._task.args = variable_params

        # get the connection and the handler for this execution
        if (not self._connection or
                not getattr(self._connection, 'connected', False) or
                self._play_context.remote_addr != self._connection._play_context.remote_addr):
            self._connection = self._get_connection(variables=variables, templar=templar)
            # only template the vars if the connection actually implements set_host_overrides
            # NB: this is expensive, and should be removed once connection-specific vars are being handled by play_context
            sho_impl = getattr(type(self._connection), 'set_host_overrides', None)
            if sho_impl and sho_impl != ConnectionBase.set_host_overrides:
                self._connection.set_host_overrides(self._host, variables, templar)
        else:
            # if connection is reused, its _play_context is no longer valid and needs
            # to be replaced with the one templated above, in case other data changed
            self._connection._play_context = self._play_context

        self._handler = self._get_action_handler(connection=self._connection, templar=templar)

        # And filter out any fields which were set to default(omit), and got the omit token value
        omit_token = variables.get('omit')
        if omit_token is not None:
            self._task.args = dict((i[0], i[1]) for i in iteritems(self._task.args) if i[1] != omit_token)

        # Read some values from the task, so that we can modify them if need be
        if self._task.until:
            retries = self._task.retries
            if retries is None:
                retries = 3
            elif retries <= 0:
                retries = 1
            else:
                retries += 1
        else:
            retries = 1

        delay = self._task.delay
        if delay < 0:
            delay = 1

        # make a copy of the job vars here, in case we need to update them
        # with the registered variable value later on when testing conditions
        vars_copy = variables.copy()

        display.debug("starting attempt loop")
        result = None
        for attempt in range(1, retries + 1):
            display.debug("running the handler")
            try:
                result = self._handler.run(task_vars=variables)
            except AnsibleActionSkip as e:
                return dict(skipped=True, msg=to_text(e))
            except AnsibleActionFail as e:
                return dict(failed=True, msg=to_text(e))
            except AnsibleConnectionFailure as e:
                return dict(unreachable=True, msg=to_text(e))
            display.debug("handler run complete")

            # preserve no log
            result["_ansible_no_log"] = self._play_context.no_log

            # update the local copy of vars with the registered value, if specified,
            # or any facts which may have been generated by the module execution
            if self._task.register:
                vars_copy[self._task.register] = wrap_var(result.copy())

            if self._task.async > 0:
                if self._task.poll > 0 and not result.get('skipped') and not result.get('failed'):
                    result = self._poll_async_result(result=result, templar=templar, task_vars=vars_copy)
                    # FIXME callback 'v2_runner_on_async_poll' here

                # ensure no log is preserved
                result["_ansible_no_log"] = self._play_context.no_log

            # helper methods for use below in evaluating changed/failed_when
            def _evaluate_changed_when_result(result):
                if self._task.changed_when is not None and self._task.changed_when:
                    cond = Conditional(loader=self._loader)
                    cond.when = self._task.changed_when
                    result['changed'] = cond.evaluate_conditional(templar, vars_copy)

            def _evaluate_failed_when_result(result):
                if self._task.failed_when:
                    cond = Conditional(loader=self._loader)
                    cond.when = self._task.failed_when
                    failed_when_result = cond.evaluate_conditional(templar, vars_copy)
                    result['failed_when_result'] = result['failed'] = failed_when_result
                else:
                    failed_when_result = False
                return failed_when_result

            if 'ansible_facts' in result:
                vars_copy.update(result['ansible_facts'])

            # set the failed property if it was missing.
            if 'failed' not in result:
                # rc is here for backwards compatibility and modules that use it instead of 'failed'
                if 'rc' in result and result['rc'] not in [0, "0"]:
                    result['failed'] = True
                else:
                    result['failed'] = False

            # set the changed property if it was missing.
            if 'changed' not in result:
                result['changed'] = False

            # if we didn't skip this task, use the helpers to evaluate the changed/
            # failed_when properties
            if 'skipped' not in result:
                _evaluate_changed_when_result(result)
                _evaluate_failed_when_result(result)

            if retries > 1:
                cond = Conditional(loader=self._loader)
                cond.when = self._task.until
                result['attempts'] = attempt
                if cond.evaluate_conditional(templar, vars_copy):
                    break
                else:
                    # no conditional check, or it failed, so sleep for the specified time
                    if attempt < retries:
                        result['_ansible_retry'] = True
                        result['retries'] = retries
                        display.debug('Retrying task, attempt %d of %d' % (attempt, retries))
                        self._rslt_q.put(TaskResult(self._host.name, self._task._uuid, result, task_fields=self._task.dump_attrs()), block=False)
                        time.sleep(delay)
        else:
            if retries > 1:
                # we ran out of attempts, so mark the result as failed
                result['attempts'] = retries - 1
                result['failed'] = True

        # do the final update of the local variables here, for both registered
        # values and any facts which may have been created
        if self._task.register:
            variables[self._task.register] = wrap_var(result)

        if 'ansible_facts' in result:
            variables.update(result['ansible_facts'])

        # save the notification target in the result, if it was specified, as
        # this task may be running in a loop in which case the notification
        # may be item-specific, ie. "notify: service {{item}}"
        if self._task.notify is not None:
            result['_ansible_notify'] = self._task.notify

        # add the delegated vars to the result, so we can reference them
        # on the results side without having to do any further templating
        # FIXME: we only want a limited set of variables here, so this is currently
        #        hardcoded but should be possibly fixed if we want more or if
        #        there is another source of truth we can use
        delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()).copy()
        if len(delegated_vars) > 0:
            result["_ansible_delegated_vars"] = {'ansible_delegated_host': self._task.delegate_to}
            for k in ('ansible_host', ):
                result["_ansible_delegated_vars"][k] = delegated_vars.get(k)

        # and return
        display.debug("attempt loop complete, returning result")
        return result

    def _poll_async_result(self, result, templar, task_vars=None):
        '''
        Polls for the specified JID to be complete
        '''

        if task_vars is None:
            task_vars = self._job_vars

        async_jid = result.get('ansible_job_id')
        if async_jid is None:
            return dict(failed=True, msg="No job id was returned by the async task")

        # Create a new pseudo-task to run the async_status module, and run
        # that (with a sleep for "poll" seconds between each retry) until the
        # async time limit is exceeded.

        async_task = Task().load(dict(action='async_status jid=%s' % async_jid))

        # FIXME: this is no longer the case, normal takes care of all, see if this can just be generalized
        # Because this is an async task, the action handler is async. However,
        # we need the 'normal' action handler for the status check, so get it
        # now via the action_loader
        normal_handler = self._shared_loader_obj.action_loader.get(
            'normal',
            task=async_task,
            connection=self._connection,
            play_context=self._play_context,
            loader=self._loader,
            templar=templar,
            shared_loader_obj=self._shared_loader_obj,
        )

        time_left = self._task.async
        while time_left > 0:
            time.sleep(self._task.poll)

            try:
                async_result = normal_handler.run(task_vars=task_vars)
                # We do not bail out of the loop in cases where the failure
                # is associated with a parsing error. The async_runner can
                # have issues which result in a half-written/unparseable result
                # file on disk, which manifests to the user as a timeout happening
                # before it's time to timeout.
                if (int(async_result.get('finished', 0)) == 1 or
                        ('failed' in async_result and async_result.get('_ansible_parsed', False)) or
                        'skipped' in async_result):
                    break
            except Exception as e:
                # Connections can raise exceptions during polling (eg, network bounce, reboot); these should be non-fatal.
                # On an exception, call the connection's reset method if it has one
                # (eg, drop/recreate WinRM connection; some reused connections are in a broken state)
                display.vvvv("Exception during async poll, retrying... (%s)" % to_text(e))
                display.debug("Async poll exception was:\n%s" % to_text(traceback.format_exc()))
                try:
                    normal_handler._connection._reset()
                except AttributeError:
                    pass

            time_left -= self._task.poll

        if int(async_result.get('finished', 0)) != 1:
            if async_result.get('_ansible_parsed'):
                return dict(failed=True, msg="async task did not complete within the requested time")
            else:
                return dict(failed=True, msg="async task produced unparseable results", async_result=async_result)
        else:
            return async_result

    def _get_connection(self, variables, templar):
        '''
        Reads the connection property for the host, and returns the
        correct connection object from the list of connection plugins
        '''

        if self._task.delegate_to is not None:
            # since we're delegating, we don't want to use interpreter values
            # which would have been set for the original target host
            for i in list(variables.keys()):
                if isinstance(i, string_types) and i.startswith('ansible_') and i.endswith('_interpreter'):
                    del variables[i]
            # now replace the interpreter values with those that may have come
            # from the delegated-to host
            delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict())
            if isinstance(delegated_vars, dict):
                for i in delegated_vars:
                    if isinstance(i, string_types) and i.startswith("ansible_") and i.endswith("_interpreter"):
                        variables[i] = delegated_vars[i]

        # if using persistent paramiko connections (or the action has set the FORCE_PERSISTENT_CONNECTION attribute to True),
        # then we use the persistent connection plugion. Otherwise load the requested connection plugin
        if C.USE_PERSISTENT_CONNECTIONS or getattr(self, 'FORCE_PERSISTENT_CONNECTION', False):
            conn_type = 'persistent'
        else:
            conn_type = self._play_context.connection

        connection = self._shared_loader_obj.connection_loader.get(conn_type, self._play_context, self._new_stdin)
        if not connection:
            raise AnsibleError("the connection plugin '%s' was not found" % conn_type)

        self._play_context.set_options_from_plugin(connection)

        if self._play_context.accelerate:
            # accelerate is deprecated as of 2.1...
            display.deprecated('Accelerated mode is deprecated. Consider using SSH with ControlPersist and pipelining enabled instead', version='2.6')
            # launch the accelerated daemon here
            ssh_connection = connection
            handler = self._shared_loader_obj.action_loader.get(
                'normal',
                task=self._task,
                connection=ssh_connection,
                play_context=self._play_context,
                loader=self._loader,
                templar=templar,
                shared_loader_obj=self._shared_loader_obj,
            )

            key = key_for_hostname(self._play_context.remote_addr)
            accelerate_args = dict(
                password=base64.b64encode(key.__str__()),
                port=self._play_context.accelerate_port,
                minutes=C.ACCELERATE_DAEMON_TIMEOUT,
                ipv6=self._play_context.accelerate_ipv6,
                debug=self._play_context.verbosity,
            )

            connection = self._shared_loader_obj.connection_loader.get('accelerate', self._play_context, self._new_stdin)
            if not connection:
                raise AnsibleError("the connection plugin '%s' was not found" % conn_type)

            try:
                connection._connect()
            except AnsibleConnectionFailure:
                display.debug('connection failed, fallback to accelerate')
                res = handler._execute_module(module_name='accelerate', module_args=accelerate_args, task_vars=variables, delete_remote_tmp=False)
                display.debug(res)
                connection._connect()

        return connection

    def _get_action_handler(self, connection, templar):
        '''
        Returns the correct action plugin to handle the requestion task action
        '''

        module_prefix = self._task.action.split('_')[0]

        # let action plugin override module, fallback to 'normal' action plugin otherwise
        if self._task.action in self._shared_loader_obj.action_loader:
            handler_name = self._task.action
        elif all((module_prefix in C.NETWORK_GROUP_MODULES, module_prefix in self._shared_loader_obj.action_loader)):
            handler_name = module_prefix
        else:
            handler_name = 'normal'

        handler = self._shared_loader_obj.action_loader.get(
            handler_name,
            task=self._task,
            connection=connection,
            play_context=self._play_context,
            loader=self._loader,
            templar=templar,
            shared_loader_obj=self._shared_loader_obj,
        )

        if not handler:
            raise AnsibleError("the handler '%s' was not found" % handler_name)

        return handler


text:
Taxonomy Filter
===============

The TaxonomyFilter filters by a taxonomy.

+-------------+--------------------------------------------------------------------+
| type        | taxonomy                                                           |
+-------------+--------------------------------------------------------------------+
| required    | - taxonomy_                                                        |
|             | - property_                                                        |
|             | - label_                                                           |
+-------------+--------------------------------------------------------------------+
| option      | - translation_domain_                                              |
|             | - permission_                                                      |
|             | - hidden_                                                          |
|             | - initial_active_                                                  |
|             | - initial_value_                                                   |
|             | - initial_value_method_                                            |
|             | - initial_value_arguments_                                         |
+-------------+--------------------------------------------------------------------+
| class       | `Enhavo\\Bundle\\TaxonomyBundle\\Filter\\TaxonomyFilterType`       |
+-------------+--------------------------------------------------------------------+

Required
--------

taxonomy
~~~~~~~~

**type**: `string`

The slug of the Taxonomy.

.. code-block:: yaml

    columns:
        myFilter:
            type: taxonomy
            operator: article_category

.. include:: /reference/filter/option/property.rst

.. include:: /reference/filter/option/label.rst

Option
------

.. include:: /reference/filter/option/translation_domain.rst

.. include:: /reference/filter/option/permission.rst

.. include:: /reference/filter/option/hidden.rst

.. include:: /reference/filter/option/initial_active.rst

.. include:: /reference/filter/option/initial_value.rst

initial_value_method
~~~~~~~~~~~~~~~~~~~~

**type**: `string|null`

Defines the repository method to use when setting the initial value. Default `findOneByNameAndTaxonomy`.
If multiple results are returned by the method, the first one is used.

.. code-block:: yaml

    columns:
        myFilter:
            initial_value: Foo
            initial_value_method: findOneByBar

initial_value_arguments
~~~~~~~~~~~~~~~~~~~~~~~

**type**: `string|null`

Optional arguments that will be added to the call of the repository method.
Default is an array containing the values of parameters initial_value_ and taxonomy_.

.. code-block:: yaml

    columns:
        myFilter:
            initial_value: Foo
            initial_value_method: findOneByFoo
            initial_value_arguments: { foo: 'bar' }


text:
package io.kaif.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.kaif.flake.FlakeId;
import io.kaif.model.clientapp.ClientAppUserAccessToken;
import io.kaif.model.zone.Zone;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRules;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
public class SwaggerConfiguration {

  private static final String API_VERSION = "1.0.0-alpha";

  @Bean
  public Docket apiDocket() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
        .alternateTypeRules(alternativeTypeRules())
        .useDefaultResponseMessages(false)
        .ignoredParameterTypes(ignoredParameterTypes())
        .groupName("v1")
        .select()
        .apis(RequestHandlerSelectors.basePackage("io.kaif.web.v1"))
        .paths(PathSelectors.any())
        .build();
  }

  private Class<?>[] ignoredParameterTypes() {
    return new Class[] { ClientAppUserAccessToken.class };
  }

  /**
   * convert FlakeId and Zone to String in swagger document
   *
   * @see io.kaif.web.support.WebDataBinderAdvice
   * see json deserializer of FlakeId
   * see json deserializer of Zone
   */
  private AlternateTypeRule[] alternativeTypeRules() {
    return new AlternateTypeRule[] { AlternateTypeRules.newRule(FlakeId.class, String.class),
        AlternateTypeRules.newRule(Zone.class, String.class) };
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder().title("kaif")
        .description("kaif Open API " + API_VERSION)
        .termsOfServiceUrl("https://kaif.io/z/kaif-terms")
        .license("Apache 2.0")
        .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
        .build();
  }
}


text:
import java.awt.Rectangle;

/**
 * Represents the Tullys of Riverrun.
 *
 * @author Tyler Smith
 * @version 1.0
 */
public class Tully extends NorthHouse {
    public Tully(int x, int y, Rectangle bounds) {
        this.x = x;
        this.y = y;
        this.bounds = bounds;
        this.health = 100;
        this.maxAge = 250;
        this.age = 0;
        this.speed = 1;
        this.sigil = this.getSigilFromFile();
    }

    /**
     * Returns the name of the Tully sigil
     *
     * @return String - the name of the Tully sigil
     */
    public String toString() {
        return "trout";
    }

    /**
     * Determines if the House can reproduce with another.
     *
     * @param House - the possible other parent House
     * @return true if they can reproduce, false otherwise
     */
    public boolean canReproduceWithHouse(House otherHouse) {
        if (otherHouse instanceof Stark) {
            return true;
        }
        if (otherHouse instanceof Arryn) {
            return true;
        }
        return false;
    }

    /**
     * Determines if this house can destroy another.
     * @param House - the victim house
     * @return true if the other house can be destroyed, false otherwise
     */
    public boolean canDestroyHouse(House otherHouse) {
        if (otherHouse instanceof Lannister && Math.random() > 0.2) {
            return true;
        }
        return false;
    }
}


text:
from sklearn.feature_extraction.text import CountVectorizer
from numpy.linalg import norm

from sklearn.preprocessing import normalize, scale
from sklearn import preprocessing
import numpy as np
import re, io, json
from string import punctuation

from time import gmtime, strftime
from datetime import datetime

def words(text):
    """An iterator over tokens (words) in text. Replace this with a
    stemmer or other smarter logic.
    """

    for word in text.split():
        # normalize words by lowercasing and dropping non-alpha characters
        normed = re.sub('[^a-z]', '', word.lower())
        if normed:
            yield normed

def buildingHistogram6Bins(keyword1, keyword2, result):
    if keyword1 == 'strongsubj' and keyword2 == 'positive':
        result[0]+=1
    elif keyword1 == 'weaksubj' and keyword2 == 'positive':
        result[1]+=1
    elif keyword1 == 'strongsubj' and keyword2 == 'neutral':
        result[2]+=1
    elif keyword1 == 'weaksubj' and keyword2 == 'neutral':
        result[3]+=1
    elif keyword1 == 'strongsubj' and keyword2 == 'negative':
        result[4]+=1
    elif keyword1 == 'weaksubj' and keyword2 == 'negative':
        result[5]+=1
    elif keyword1 == 'weaksubj' and keyword2 == 'both':
        result[1]+=1
        result[5]+=1
    elif keyword1 == 'strongsubj' and keyword2 == 'both':
        result[0]+=1
        result[4]+=1

def buildingHistogram3Bins(keyword, result):
    if keyword == 'positive':
        result[6]+=1
    elif keyword == 'negative':
        result[7]+=1
    elif keyword == 'negation':
        result[8]+=1

def buildingHistogram2Bins(ps, ns, result):
    result[12]+=float(ps)
    result[13]+=float(ns)

def buildingHistogramDay(date, result):
    date_object = datetime.strptime(date, '%Y-%m-%d')
    day = date_object.strftime("%A")
    if day == 'Sunday' or day == 'Saturday':
        result[10] = 1
    else:
        result[10] = 0

def buildingHistogramVote(votes, result):
    v_result = votes["funny"] + votes["useful"] + votes["cool"]
    result[11] = v_result

def buildingHistogramLength(length, result):
    result [9] = length

def main(inputFile, outputFile):

    filenames = ['data/input/bow/1StarsSamples.json', 'data/input/bow/2StarsSamples.json', 'data/input/bow/3StarsSamples.json', 'data/input/bow/4StarsSamples.json', 'data/input/bow/5StarsSamples.json']

    vectorizer = CountVectorizer(input='filename', ngram_range=(1,3), stop_words='english', strip_accents='unicode', token_pattern=ur'\b\w+\b')

    dtm = vectorizer.fit_transform(filenames).toarray()
    dtm = scale(dtm)
    vocab = np.array(vectorizer.get_feature_names())

    _vectorizer = CountVectorizer(input='content', ngram_range=(1,3), stop_words='english', strip_accents='unicode', token_pattern=ur'\b\w+\b')
    analyze = _vectorizer.build_analyzer()

    with open(inputFile) as fileobject, open("data/dictionary/mydictionary_2bins.json") as dicObject2Bins, open("data/dictionary/mydictionary_3bins.json") as dicObject3Bins, open("data/dictionary/mydictionary_6bins.json") as dicObject6Bins:
        dicData2Bins = json.load(dicObject2Bins)
        dicData3Bins = json.load(dicObject3Bins)
        dicData6Bins = json.load(dicObject6Bins)
        listOfHistogramAndRating = []

        for i, line in enumerate(fileobject):

            print(i)

            if line == '\n':
                break
            data = json.loads(line)
            #Descripton [0-spos, 1-wpos, 2-sneu, 3-wneu, 4-sneg, 5-wneg, 6-pos, 7-neg, 8-negation, 9-len, 10-day, 11-vote, 12-ps, 13-ns]
            result =    [0     , 0     , 0     , 0     , 0     , 0     , 0    , 0    , 0         , 0    , 0     , 0      , 0.0  , 0.0  ]
            length = 0
            text = data["text"]
            for word in words(text):
                length += 1

                for item in dicData2Bins:
                    if word == item["word"]:
                        buildingHistogram2Bins(item["pos"], item["neg"], result)
                for item in dicData3Bins:
                    if word == item["word"]:
                        buildingHistogram3Bins(item["priorpolarity"], result)
                for item in dicData6Bins:
                    if word == item["word"]:
                        buildingHistogram6Bins(item["type"], item["priorpolarity"], result)

            buildingHistogramDay(data["date"], result)

            buildingHistogramVote(data["votes"], result)

            buildingHistogramLength(length, result)

            character_count = len(text)
            uppercase_count = sum(1 for c in text if c.isupper())
            lowercase_count = sum(1 for c in text if c.islower())
            punctuation_count = sum(1 for c in text if c in punctuation)
            alphabetic_count = sum(1 for c in text if c.isalpha())
            numeric_count = sum(1 for c in text if c.isnumeric())

            #Fearures lesection
            final_result = []

            final_result.append(result[0])
            final_result.append(result[1])
            final_result.append(result[2])
            final_result.append(result[3])
            final_result.append(result[4])
            final_result.append(result[5])
            final_result.append(result[6])
            final_result.append(result[7])
            final_result.append(result[8])
            final_result.append(result[9])
            final_result.append(result[10])
            final_result.append(result[11])
            final_result.append(result[12])
            final_result.append(result[13])

            final_result.append(character_count) #14
            final_result.append(uppercase_count) #15
            final_result.append(lowercase_count) #16
            final_result.append(punctuation_count) #17
            final_result.append(alphabetic_count) #18
            final_result.append(numeric_count) #19

            analyzed = analyze(text)
            #Descripton [20-1star, 21-2star, 22-3star, 23-4star, 24-5star]
            resultBOW = [0       , 0       , 0       , 0       , 0       ]

            for item in analyzed:
                feature_index = vectorizer.vocabulary_.get(item)
                if feature_index:
                    item_histogram = dtm[:, feature_index]

                    resultBOW = [x + y for x, y in zip(resultBOW, item_histogram)]

            for item in resultBOW:
                if sum(resultBOW) != 0:
                    item = item*1.0/sum(resultBOW)
                final_result.append(item)

            listOfHistogramAndRating.append({'rating': data["stars"], 'histogram': final_result})
        with io.open(outputFile, 'w', encoding='utf-8') as outfile:
            outfile.write(unicode(json.dumps(listOfHistogramAndRating, ensure_ascii=False)))

    print "FINISHED"

if __name__  == "__main__":

    starttime = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    config = {}
    execfile("params.conf", config)
    #Change input and output file here
    inputFile = 'data/input/' + str(config["dataset_Samples"]) + 'Samples.json'
    outputFile = 'data/output/histogram_' + str(config["dataset_Samples"]) + 'Samples.json'

    main(inputFile, outputFile)

    endtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())

    mailmessage = 'This is a notification email to show that the task is completed\n' + "Start time: " + starttime + " End time: " + endtime + "\n"
    print(mailmessage)


text:
class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def reverseList(self, head):
        last, current = None, head
        while current:
            next = current.next
            current.next = last
            last = current
            current = next
        return last


text:
package cc.mallet.grmm.learning;
/**
 *
 * Created: Aug 23, 2005
 *
 * @author casutton@cs.umass.edu
 * @version $Id: GenericAcrfTui.java,v 1.1 2007/10/22 21:37:43 mccallum Exp $
 */

import bsh.EvalError;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import cc.mallet.grmm.inference.Inferencer;
import cc.mallet.optimize.Optimizer;
import cc.mallet.pipe.*;
import cc.mallet.pipe.iterator.LineGroupIterator;
import cc.mallet.pipe.iterator.PipeInputIterator;
import cc.mallet.types.InstanceList;
import cc.mallet.types.Instance;
import cc.mallet.util.*;

public class GenericAcrfTui {

  private static CommandOption.File modelFile = new CommandOption.File
          (GenericAcrfTui.class, "model-file", "FILENAME", true, null, "Text file describing model structure.", null);

  private static CommandOption.File trainFile = new CommandOption.File
          (GenericAcrfTui.class, "training", "FILENAME", true, null, "File containing training data.", null);

  private static CommandOption.File testFile = new CommandOption.File
          (GenericAcrfTui.class, "testing", "FILENAME", true, null, "File containing testing data.", null);

  private static CommandOption.Integer numLabelsOption = new CommandOption.Integer
  (GenericAcrfTui.class, "num-labels", "INT", true, -1,
          "If supplied, number of labels on each line of input file." +
                  "  Otherwise, the token ---- must separate labels from features.", null);

  private static CommandOption.String inferencerOption = new CommandOption.String
          (GenericAcrfTui.class, "inferencer", "STRING", true, "TRP",
                  "Specification of inferencer.", null);

  private static CommandOption.String maxInferencerOption = new CommandOption.String
          (GenericAcrfTui.class, "max-inferencer", "STRING", true, "TRP.createForMaxProduct()",
                  "Specification of inferencer.", null);

  private static CommandOption.String evalOption = new CommandOption.String
          (GenericAcrfTui.class, "eval", "STRING", true, "LOG",
                  "Evaluator to use.  Java code grokking performed.", null);

  private static CommandOption.Boolean usePiecewiseTraining = new CommandOption.Boolean
            (GenericAcrfTui.class, "piecewise", "true|false", true, false,
                    "Whether to use piecewise training.", null);

  private  static CommandOption.Boolean usePwplTraining = new CommandOption.Boolean
            (GenericAcrfTui.class, "pwpl", "true|false", true, false,
                    "Whether to use pwpl training.", null);

  private  static CommandOption.Boolean usePlTraining = new CommandOption.Boolean
            (GenericAcrfTui.class, "pl", "true|false", true, false,
                    "Whether to use Besag pseudolikelihood.", null);

  static CommandOption.Boolean cacheUnrolledGraph = new CommandOption.Boolean
          (GenericAcrfTui.class, "cache-graphs", "true|false", true, false,
                  "Whether to use memory-intensive caching.", null);

  static CommandOption.Boolean useTokenText = new CommandOption.Boolean
          (GenericAcrfTui.class, "use-token-text", "true|false", true, false,
                  "Set this to true if first feature in every list is should be considered the text of the " +
                          "current token.  This is used for NLP-specific debugging and error analysis.", null);

  static CommandOption.Integer randomSeedOption = new CommandOption.Integer
	(GenericAcrfTui.class, "random-seed", "INTEGER", true, 0,
	 "The random seed for randomly selecting a proportion of the instance list for training", null);

  private static BshInterpreter interpreter = setupInterpreter ();

    private static ACRFTrainer createTrainer ()
    {
      if (usePiecewiseTraining.value) {
        return new PiecewiseACRFTrainer();
      } else if (usePwplTraining.value) {
        return new PwplACRFTrainer();
      } else if (usePlTraining.value) {
        return new PseudolikelihoodACRFTrainer ();
      } else {
        return new DefaultAcrfTrainer ();
      }
    }

  public static void main (String[] args) throws IOException, EvalError
  {
    doProcessOptions (GenericAcrfTui.class, args);
    Timing timing = new Timing ();

    GenericAcrfData2TokenSequence basePipe;
    if (!numLabelsOption.wasInvoked ()) {
      basePipe = new GenericAcrfData2TokenSequence ();
    } else {
      basePipe = new GenericAcrfData2TokenSequence (numLabelsOption.value);
    }

    basePipe.setFeaturesIncludeToken(useTokenText.value);
    basePipe.setIncludeTokenText(useTokenText.value);

    Pipe pipe = new SerialPipes (new Pipe[] {
        basePipe,
        new TokenSequence2FeatureVectorSequence (true, true),
    });

    Iterator<Instance> trainSource = new LineGroupIterator (new FileReader (trainFile.value), Pattern.compile ("^\\s*$"), true);
    Iterator<Instance> testSource;
    if (testFile.wasInvoked ()) {
      testSource = new LineGroupIterator (new FileReader (testFile.value), Pattern.compile ("^\\s*$"), true);
    } else {
      testSource = null;
    }

    InstanceList training = new InstanceList (pipe);
    training.addThruPipe (trainSource);
    InstanceList testing = new InstanceList (pipe);
    testing.addThruPipe (testSource);

    ACRF.Template[] tmpls = parseModelFile (modelFile.value);
    ACRFEvaluator eval = createEvaluator (evalOption.value);

    Inferencer inf = createInferencer (inferencerOption.value);
    Inferencer maxInf = createInferencer (maxInferencerOption.value);

    ACRF acrf = new ACRF (pipe, tmpls);
    acrf.setInferencer (inf);
    acrf.setViterbiInferencer (maxInf);

    ACRFTrainer trainer = createTrainer();
    System.err.println ("ACRF Trainer = "+trainer);
    trainer.train (acrf, training, null, testing, eval, 9999);
    timing.tick ("Training");

    FileUtils.writeGzippedObject (new File ("acrf.ser.gz"), acrf);
    timing.tick ("Serializing");

    System.err.println ("Total time (ms) = " + timing.elapsedTime ());
  }

  private static BshInterpreter setupInterpreter ()
  {
    BshInterpreter interpreter = CommandOption.getInterpreter ();
    try {
      interpreter.eval ("import cc.mallet.base.extract.*");
      interpreter.eval ("import cc.mallet.grmm.inference.*");
      interpreter.eval ("import cc.mallet.grmm.learning.*");
      interpreter.eval ("import cc.mallet.grmm.learning.templates.*");
    } catch (EvalError e) {
      throw new RuntimeException (e);
    }

    return interpreter;
  }

  public static ACRFEvaluator createEvaluator (String spec) throws EvalError
  {
    if (spec.indexOf ('(') >= 0) {
      // assume it's Java code, and don't screw with it.
      return (ACRFEvaluator) interpreter.eval (spec);
    } else {
      LinkedList toks = new LinkedList (Arrays.asList (spec.split ("\\s+")));
      return createEvaluator (toks);
    }
  }

  private static ACRFEvaluator createEvaluator (LinkedList toks)
  {
    String type = (String) toks.removeFirst ();

    if (type.equalsIgnoreCase ("SEGMENT")) {
      int slice = Integer.parseInt ((String) toks.removeFirst ());
      if (toks.size() % 2 != 0)
        throw new RuntimeException ("Error in --eval "+evalOption.value+": Every start tag must have a continue.");
      int numTags = toks.size () / 2;
      String[] startTags = new String [numTags];
      String[] continueTags = new String [numTags];

      for (int i = 0; i < numTags; i++) {
        startTags[i] = (String) toks.removeFirst ();
        continueTags[i] = (String) toks.removeFirst ();
      }

      return new MultiSegmentationEvaluatorACRF (startTags, continueTags, slice);

    } else if (type.equalsIgnoreCase ("LOG")) {
      return new DefaultAcrfTrainer.LogEvaluator ();

    } else if (type.equalsIgnoreCase ("SERIAL")) {
      List evals = new ArrayList ();
      while (!toks.isEmpty ()) {
        evals.add (createEvaluator (toks));
      }
      return new AcrfSerialEvaluator (evals);

    } else {
      throw new RuntimeException ("Error in --eval "+evalOption.value+": illegal evaluator "+type);
    }
  }

  private static Inferencer createInferencer (String spec) throws EvalError
  {
    String cmd;
    if (spec.indexOf ('(') >= 0) {
      // assume it's Java code, and don't screw with it.
      cmd = spec;
    } else {
      cmd = "new "+spec+"()";
    }

    // Return whatever the Java code says to
    Object inf = interpreter.eval (cmd);

    if (inf instanceof Inferencer)
      return (Inferencer) inf;

    else throw new RuntimeException ("Don't know what to do with inferencer "+inf);
  }

  public static void doProcessOptions (Class childClass, String[] args)
  {
    CommandOption.List options = new CommandOption.List ("", new CommandOption[0]);
    options.add (childClass);
    options.process (args);
    options.logOptions (Logger.getLogger (""));
  }

  private static ACRF.Template[] parseModelFile (File mdlFile) throws IOException, EvalError
  {
    BufferedReader in = new BufferedReader (new FileReader (mdlFile));

    List tmpls = new ArrayList ();
    String line = in.readLine ();
    while (line != null) {
      Object tmpl = interpreter.eval (line);
      if (!(tmpl instanceof ACRF.Template)) {
        throw new RuntimeException ("Error in "+mdlFile+" line "+in.toString ()+":\n  Object "+tmpl+" not a template");
      }
      tmpls.add (tmpl);
      line = in.readLine ();
    }

    return (ACRF.Template[]) tmpls.toArray (new ACRF.Template [0]);
  }

}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 283477;
var summary = 'a.lastIndexOf(b, c) should return -1 when there is no match';
var actual = '';
var expect = '';
var status;

enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);

status = summary + ' ' + inSection(1) + " " + '"".lastIndexOf("hello", 0);';
expect = -1;
actual = "".lastIndexOf("hello", 0);
reportCompare(expect, actual, status);

status = summary + ' ' + inSection(2) + " " + ' "".lastIndexOf("hello");';
expect = -1;
actual = "".lastIndexOf("hello");
reportCompare(expect, actual, status);

exitFunc ('test');


text:
(function() {

  var s = document.createElement('script'),
    githubApiUrl = 'https://api.github.com/repos/',
    owner = '<%= jekyllConfig.github_username %>',
    repo = owner + '.github.io';

  s.type = 'text/javascript';
  s.async = true;
  s.src = githubApiUrl + owner + '/' + repo + '?callback=' + owner + '.getGitHubRepoInfo';

  window[ owner ] = window[ owner ] || {};
  window[ owner ].getGitHubRepoInfo = function( response ) {

    var stargazers = response.data.stargazers_count,
      forks = response.data.forks_count;

    document.getElementById('stargazers').innerText = stargazers;
    document.getElementById('forks').innerText = forks;
    document.getElementById('github-repo-info').style.display = 'block';
  };

  document.getElementsByTagName('HEAD')[ 0 ].appendChild( s );
}());


text:
namespace juce
{

struct PhysicalTopologySource::DetectorHolder  : private Timer
{
    DetectorHolder (PhysicalTopologySource& pts)
        : topologySource (pts),
          detector (Detector::getDefaultDetector())
    {
        startTimerHz (30);
    }

    DetectorHolder (PhysicalTopologySource& pts, DeviceDetector& dd)
        : topologySource (pts),
          detector (new Detector (dd))
    {
        startTimerHz (30);
    }

    void timerCallback() override
    {
        if (! topologySource.hasOwnServiceTimer())
            handleTimerTick();
    }

    void handleTimerTick()
    {
        auto blocks = detector->currentTopology.blocks;

        if (blocks.size() == 0)
            return;

        if (nextIndexToTick >= blocks.size())
            nextIndexToTick = 0;

        if (auto* bi = BlockImplementation<Detector>::getFrom (*blocks [nextIndexToTick]))
            bi->handleTimerTick();

        nextIndexToTick = (nextIndexToTick + 1) % blocks.size();
    }

    PhysicalTopologySource& topologySource;
    Detector::Ptr detector;

    int nextIndexToTick {0};
};

} // namespace juce


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Tests\Doctrine\Odm\Extension;

use ApiPlatform\Api\FilterInterface as ApiFilterInterface;
use ApiPlatform\Doctrine\Odm\Extension\FilterExtension;
use ApiPlatform\Doctrine\Odm\Filter\FilterInterface;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Tests\Fixtures\TestBundle\Document\Dummy;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Container\ContainerInterface;

/**
 * @author Alan Poulain <contact@alanpoulain.eu>
 *
 * @group mongodb
 */
class FilterExtensionTest extends TestCase
{
    use ProphecyTrait;

    public function testApplyToCollectionWithValidFilters(): void
    {
        $aggregationBuilderProphecy = $this->prophesize(Builder::class);

        $aggregationBuilder = $aggregationBuilderProphecy->reveal();

        $operation = (new GetCollection())->withFilters(['dummyFilter', 'dummyBadFilter']);

        $mongoDbOdmFilterProphecy = $this->prophesize(FilterInterface::class);
        $mongoDbOdmFilterProphecy->apply($aggregationBuilder, Dummy::class, $operation, ['filters' => []])->shouldBeCalled();

        $ordinaryFilterProphecy = $this->prophesize(ApiFilterInterface::class);

        $filterLocatorProphecy = $this->prophesize(ContainerInterface::class);
        $filterLocatorProphecy->has('dummyFilter')->willReturn(true)->shouldBeCalled();
        $filterLocatorProphecy->has('dummyBadFilter')->willReturn(true)->shouldBeCalled();
        $filterLocatorProphecy->get('dummyFilter')->willReturn($mongoDbOdmFilterProphecy->reveal())->shouldBeCalled();
        $filterLocatorProphecy->get('dummyBadFilter')->willReturn($ordinaryFilterProphecy->reveal())->shouldBeCalled();

        $filterExtensionTest = new FilterExtension($filterLocatorProphecy->reveal());
        $filterExtensionTest->applyToCollection($aggregationBuilder, Dummy::class, $operation);
    }

    public function testApplyToCollectionWithoutFilters(): void
    {
        $filterLocatorProphecy = $this->prophesize(ContainerInterface::class);

        $filterLocatorProphecy->has(Argument::cetera())->willReturn(false);
        $filterLocatorProphecy->get(Argument::cetera())->shouldNotBeCalled();

        $filterExtensionTest = new FilterExtension($filterLocatorProphecy->reveal());
        $filterExtensionTest->applyToCollection($this->prophesize(Builder::class)->reveal(), Dummy::class, (new GetCollection())->withFilters(['dummyFilter', 'dummyBadFilter']));
    }
}


text:
using pingpot.Classes;
using pingpot.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Threading.Tasks;
using SQLite;

namespace pingpot.Controllers
{
    public class PotController : ApiController
    {
        public static bool HasCheckedDB = false;

        private SQLiteConnection db;
        private SQLiteAsyncConnection asyncDB;
        public PotController()
        {
            db = new SQLiteConnection(Constants.DBLocation);
            asyncDB = new SQLiteAsyncConnection(Constants.DBLocation);

            if (!HasCheckedDB)
                CheckDB();
        }

        private async void CheckDB()
        {
            int tableCount = db.ExecuteScalar<int>("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='PotModel'");
            if (tableCount < 1)
            {
                CreateTable();
            }
            HasCheckedDB = true;
        }

        private void CreateTable()
        {
            db.CreateTable<PotModel>();
            db.Insert(new PotModel()
            {
                office = "main",
            });
        }

        // GET api/<controller>
        public async Task<HttpResponseMessage> Get()
        {
            return Request.CreateResponse(HttpStatusCode.OK, await GetCurrentPot());
        }

        private async Task<PotModel> GetCurrentPot()
        {
            return await asyncDB.Table<PotModel>().Where(p => p.office == "main").FirstOrDefaultAsync();
        }

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] PotModel potStatusUpdate, int id)
        {
            potStatusUpdate.Id = id;
            return Request.CreateResponse(HttpStatusCode.OK, await SetPot(potStatusUpdate));
        }

        private async Task<PotModel> SetPot(PotModel potStatusUpdate)
        {
            await asyncDB.UpdateAsync(potStatusUpdate);
            return await GetCurrentPot();
        }

    }

}


text:
Redis Object
============

About
-----

A Python dictionary-like interface to a [Redis](http://redis.io/) database, implementing all methods provided by the
[UserDict](http://docs.python.org/library/userdict.html) mixin.

**caution**: This is intended for an interactive shell environment, not as a library to interface
with your production Redis database. You should probably use [redis-py](https://github.com/andymccurdy/redis-py) for that.

Dependencies
------------

* [redis-py](https://github.com/andymccurdy/redis-py)
* [mock](http://code.google.com/p/mock/) to run the unit tests

Usage
-----

### Connecting to a Redis database

    >>> import redisobj
    >>> rdb = redisobj.RedisDB(host='localhost', port=6379, db=0)

### Dictionary operations

A RedisDB object can be used like an ordinary Python dictionary object.

#### Getting and setting

    >>> rdb["key"] = "value"
    >>> rdb["key"]
    'value'

#### IN-operator

    >>> "key" in rdb
    True

#### Delete key

    >>> del rdb["key"]
    >>> "key" in rdb
    False

#### Keys

    >>> rdb.keys()
    ['key1', 'key2', 'key3']

#### Clear

Be careful, this deletes all keys from the current database.

    >>> rdb.clear()
    >>> rdb.keys()
    []

### Exceptions

#### KeyError

Just like a normal dictionary, a KeyError will be raised when accessing a non-existing key.

    >>> rdb["non-existing-key"]
    KeyError: key 'non-existing-key' does not exist

#### InvalidDataType Exception

The only accepted values are string, integer, list, set or dictionary.

    >>> rdb["key"] = 1.5
    InvalidDataType: value needs to be of type str, int, set, list or dict

The list, set and dict types can only contain string or integer values.

    >>> rdb["key"] = [1,2,3,{"a":"b"}]
    InvalidDataType: lists can only contain values of type str or int

### Data types

#### Strings

    >>> rdb["my_string"] = "this is my string"
    >>> rdb["my_string"]
    'this is my string'

#### Integers

Integers can be set, but will always be returned as strings.

    >>> rdb["my_integer"] = 1
    >>> rdb["my_integer"]
    '1'

#### Lists

Lists can contain integers, but integer values will always be returned as strings.

    >>> rdb["my_list"] = [1,2,'this is a string']
    >>> rdb["my_list"]
    ['1','2','this is a string']

#### Sets

Sets can contain integers, but integer values will always be returned as strings.

    >>> rdb["my_set"] = set([1,2,'this is a string'])
    >>> rdb["my_set"]
    set(['1','2','this is a string'])

#### Hashes (dictionaries)

Hashes (dictionaries) can contain integers, but integer values will always be returned as strings. Keys should
always be strings.

    >>> rdb["my_hash"] = {"a":2,"b":"c"}
    >>> rdb["my_hash"]
    {'a':'2','b':'c'}

### Future Features

Currently, all operations work on the DB level. Future addition could include bound datatypes, where operations on the
values themselves will be translated to redis commands, directly altering the values in the DB.


text:
$p = @{
    Name = "ImportExcel"
    NuGetApiKey = $NuGetApiKey
    LicenseUri = "https://github.com/dfinke/ImportExcel/blob/master/LICENSE.txt"
    Tag = "Excel","EPPlus","Export","Import"
    ReleaseNote = "Now you can read Excel files even if they're open in Excel"
    ProjectUri = "https://github.com/dfinke/ImportExcel"
}

Publish-Module @p


text:
@interface DRIDataControllerHelper : NSObject

+ (NSIndexPath *)handleRowSelectedState:(NSIndexPath *)indexPath richMessage:(DNRichMessage *)richMessage tableView:(UITableView *)tableView selectedMessages:(NSArray *)selectedMessages delegate:(id)delegate dataSource:(DRIDataController *)dataSource originnalIndexPath:(NSIndexPath *)originalIndexPath;

+ (DRITableViewCell *)attemptToSelectNextRow:(NSIndexPath *)indexPath fetchedResultsController:(NSFetchedResultsController *)fetchedResultsController tableView:(UITableView *)tableView;

+ (NSIndexPath *)toggleSelectedCell:(DRITableViewCell *)cell tableView:(UITableView *)tableView fetchedResultsController:(NSFetchedResultsController *)fetchedResultsController dataSource:(DRIDataController *)controller delegate:(id <DRIDataControllerDelegate>)delegate originalIndexPath:(NSIndexPath *)originalIndexPath;

+ (CGFloat)sizeOfTableViewRowWithMessage:(DNRichMessage *)richMessage tableView:(UITableView *)tableView theme:(DRUITheme *)theme;

@end


text:
package implementation.queenproblem;

public class QueenProxy implements IQueenGame {

	private QueenGame proxy=null;
	private IQueenGame source=null;
	private int x,y=-1;

	public QueenProxy(IQueenGame state,int x, int y) {
		if (state==null) throw new IllegalArgumentException("source may never be null");
		if (x<0 || x>state.size()) throw new IllegalArgumentException("x is out of bound");
		if (y<0 || y>state.size()) throw new IllegalArgumentException("y is out of bound");
		this.source=state;
		this.x=x;
		this.y=y;
	}

	private QueenGame getProxy(){
		if (proxy==null){
			proxy=new QueenGame(source);
			proxy.setQueen(x,y);
		}
		return proxy;
	}

	@Override
	public int collisions() {	return getProxy().collisions();	}
	@Override
	public boolean hasQueen(int x, int y) {	return getProxy().hasQueen(x, y);	}
	@Override
	public void initialize() {
		if (proxy==null) proxy=new QueenGame(source.size());
		proxy.initialize();
	}
	@Override
	public boolean isSolved() {	return getProxy().isSolved(); }
	@Override
	public int positionOf(int x) {	return getProxy().positionOf(x);	}
	@Override
 public void random() {
		if (proxy==null) proxy=new QueenGame(source.size());
		proxy.random();
	}
 @Override
	public void randomFull() {
		if (proxy==null) proxy=new QueenGame(source.size());
		proxy.randomFull();
	}
	@Override
	public void setQueen(int x, int y) {	getProxy().setQueen(x, y); }
	@Override
	public int size() {	return source.size(); }
	@Override
	public int[] getGrid() {	return getProxy().getGrid();	}
	@Override
	public int compareTo(IQueenGame o) {	return getProxy().compareTo(o); }
	@Override
	public String toString() {	return getProxy().toString();	}
	@Override
	public int hashCode() {	return getProxy().hashCode(); }
	public boolean equals(QueenGame g) {	return getProxy().equals(g); }
	@Override
	public boolean equals(Object o) {	return getProxy().equals(o);	}

}