text:
package alexa.skills;

import com.amazon.speech.speechlet.*;
import grails.config.Config;
import org.grails.core.AbstractGrailsClass;
import org.grails.core.AbstractInjectableGrailsClass;

import java.util.HashMap;
import java.util.Map;

/**
 * Grails artifact class which represents a Quartz job.
 *
 * @author Micha?? K??ujszo
 * @author Marcel Overdijk
 * @author Sergey Nebolsin (nebolsin@gmail.com)
 * @since 0.1
 */
public class DefaultGrailsSpeechletClass extends AbstractInjectableGrailsClass implements GrailsSpeechletClass {

    public DefaultGrailsSpeechletClass(Class c) {
        super(c, SpeechletArtefactHandler.TYPE);
    }
  /*  public class DefaultGrailsSpeechletClass extends AbstractInjectableGrailsClass implements GrailsGuardClass {
        public DefaultGrailsGuardClass(Class c) {
            super(c, GuardArtefactHandler.TYPE);
        }
    }*/
   /* public static final String SPEECHLET = "Speechlet";

    public DefaultGrailsSpeechletClass(Class clazz) {
        super(clazz, SPEECHLET);

    }

    public void setConfiguration(Config co) {
            getMetaClass().invokeMethod(getReferenceInstance(), "SetConfiguration", new Object[]{});
    }

    public void onSessionStarted(SessionStartedRequest request, Session session) throws SpeechletException {

            getMetaClass().invokeMethod(getReferenceInstance(), "onSessionStarted", new Object[]{});
    }

    public SpeechletResponse onLaunch(LaunchRequest request, Session session) throws SpeechletException {
           getMetaClass().invokeMethod(getReferenceInstance(), "onLaunch", new Object[]{});
           return null;
    }

    public SpeechletResponse onIntent(IntentRequest request, Session session) throws SpeechletException {
        getMetaClass().invokeMethod(getReferenceInstance(), "onIntent", new Object[]{});
        return null;
    }

    public void onSessionEnded(SessionEndedRequest request, Session session) throws SpeechletException {
        getMetaClass().invokeMethod(getReferenceInstance(), "onSessionEnded", new Object[]{});

    }

    public SpeechletResponse getWelcomeResponse() {
        return null;
    }

    public SpeechletResponse getHelpResponse() {
        return null;
    }

    public SpeechletResponse createLinkCard(Session session) {
        return null;
    }

*/

}


text:
#include <aws/eks/model/ListAddonsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::EKS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListAddonsResult::ListAddonsResult()
{
}

ListAddonsResult::ListAddonsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListAddonsResult& ListAddonsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("addons"))
  {
    Aws::Utils::Array<JsonView> addonsJsonList = jsonValue.GetArray("addons");
    for(unsigned addonsIndex = 0; addonsIndex < addonsJsonList.GetLength(); ++addonsIndex)
    {
      m_addons.push_back(addonsJsonList[addonsIndex].AsString());
    }
  }

  if(jsonValue.ValueExists("nextToken"))
  {
    m_nextToken = jsonValue.GetString("nextToken");

  }

  return *this;
}

redpajama_set_name: RedPajamaGithub


text:
package msgraph

import "context"

// IdentityContainerRequestBuilder is request builder for IdentityContainer
type IdentityContainerRequestBuilder struct{ BaseRequestBuilder }

// Request returns IdentityContainerRequest
func (b *IdentityContainerRequestBuilder) Request() *IdentityContainerRequest {
	return &IdentityContainerRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// IdentityContainerRequest is request for IdentityContainer
type IdentityContainerRequest struct{ BaseRequest }

// Get performs GET request for IdentityContainer
func (r *IdentityContainerRequest) Get(ctx context.Context) (resObj *IdentityContainer, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for IdentityContainer
func (r *IdentityContainerRequest) Update(ctx context.Context, reqObj *IdentityContainer) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for IdentityContainer
func (r *IdentityContainerRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}

// IdentityGovernanceRequestBuilder is request builder for IdentityGovernance
type IdentityGovernanceRequestBuilder struct{ BaseRequestBuilder }

// Request returns IdentityGovernanceRequest
func (b *IdentityGovernanceRequestBuilder) Request() *IdentityGovernanceRequest {
	return &IdentityGovernanceRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// IdentityGovernanceRequest is request for IdentityGovernance
type IdentityGovernanceRequest struct{ BaseRequest }

// Get performs GET request for IdentityGovernance
func (r *IdentityGovernanceRequest) Get(ctx context.Context) (resObj *IdentityGovernance, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for IdentityGovernance
func (r *IdentityGovernanceRequest) Update(ctx context.Context, reqObj *IdentityGovernance) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for IdentityGovernance
func (r *IdentityGovernanceRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}

// IdentityProviderRequestBuilder is request builder for IdentityProvider
type IdentityProviderRequestBuilder struct{ BaseRequestBuilder }

// Request returns IdentityProviderRequest
func (b *IdentityProviderRequestBuilder) Request() *IdentityProviderRequest {
	return &IdentityProviderRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// IdentityProviderRequest is request for IdentityProvider
type IdentityProviderRequest struct{ BaseRequest }

// Get performs GET request for IdentityProvider
func (r *IdentityProviderRequest) Get(ctx context.Context) (resObj *IdentityProvider, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for IdentityProvider
func (r *IdentityProviderRequest) Update(ctx context.Context, reqObj *IdentityProvider) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for IdentityProvider
func (r *IdentityProviderRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}

// IdentityRiskEventRequestBuilder is request builder for IdentityRiskEvent
type IdentityRiskEventRequestBuilder struct{ BaseRequestBuilder }

// Request returns IdentityRiskEventRequest
func (b *IdentityRiskEventRequestBuilder) Request() *IdentityRiskEventRequest {
	return &IdentityRiskEventRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// IdentityRiskEventRequest is request for IdentityRiskEvent
type IdentityRiskEventRequest struct{ BaseRequest }

// Get performs GET request for IdentityRiskEvent
func (r *IdentityRiskEventRequest) Get(ctx context.Context) (resObj *IdentityRiskEvent, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for IdentityRiskEvent
func (r *IdentityRiskEventRequest) Update(ctx context.Context, reqObj *IdentityRiskEvent) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for IdentityRiskEvent
func (r *IdentityRiskEventRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}

// IdentityUserFlowRequestBuilder is request builder for IdentityUserFlow
type IdentityUserFlowRequestBuilder struct{ BaseRequestBuilder }

// Request returns IdentityUserFlowRequest
func (b *IdentityUserFlowRequestBuilder) Request() *IdentityUserFlowRequest {
	return &IdentityUserFlowRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// IdentityUserFlowRequest is request for IdentityUserFlow
type IdentityUserFlowRequest struct{ BaseRequest }

// Get performs GET request for IdentityUserFlow
func (r *IdentityUserFlowRequest) Get(ctx context.Context) (resObj *IdentityUserFlow, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for IdentityUserFlow
func (r *IdentityUserFlowRequest) Update(ctx context.Context, reqObj *IdentityUserFlow) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for IdentityUserFlow
func (r *IdentityUserFlowRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}


text:
symbols = {'ahead of': '↑', 'behind': '↓', 'staged':'♦', 'changed':'‣', 'untracked':'…', 'clean':'⚡', 'unmerged':'≠', 'sha1':':'}

from subprocess import Popen, PIPE

output,error = Popen(['git','status'], stdout=PIPE, stderr=PIPE).communicate()

if error:
	import sys
	sys.exit(0)
lines = output.splitlines()

import re
behead_re = re.compile(r"^# Your branch is (ahead of|behind) '(.*)' by (\d+) commit")
diverge_re = re.compile(r"^# and have (\d+) and (\d+) different")

status = ''
staged = re.compile(r'^# Changes to be committed:$', re.MULTILINE)
changed = re.compile(r'^# Changed but not updated:$', re.MULTILINE)
untracked = re.compile(r'^# Untracked files:$', re.MULTILINE)
unmerged = re.compile(r'^# Unmerged paths:$', re.MULTILINE)

def execute(*command):
	out, err = Popen(stdout=PIPE, stderr=PIPE, *command).communicate()
	if not err:
		nb = len(out.splitlines())
	else:
		nb = '?'
	return nb

if staged.search(output):
	nb = execute(['git','diff','--staged','--name-only','--diff-filter=ACDMRT'])
	status += '%s%s' % (symbols['staged'], nb)
if unmerged.search(output):
	nb = execute(['git','diff', '--staged','--name-only', '--diff-filter=U'])
	status += '%s%s' % (symbols['unmerged'], nb)
if changed.search(output):
	nb = execute(['git','diff','--name-only', '--diff-filter=ACDMRT'])
	status += '%s%s' % (symbols['changed'], nb)
if untracked.search(output):
## 		nb = len(Popen(['git','ls-files','--others','--exclude-standard'],stdout=PIPE).communicate()[0].splitlines())
## 		status += "%s" % (symbols['untracked']*(nb//3 + 1), )
	status += symbols['untracked']
if status == '':
	status = symbols['clean']

remote = ''

bline = lines[0]
if bline.find('Not currently on any branch') != -1:
	branch = symbols['sha1']+ Popen(['git','rev-parse','--short','HEAD'], stdout=PIPE).communicate()[0][:-1]
else:
	branch = bline.split(' ')[3]
	bstatusline = lines[1]
	match = behead_re.match(bstatusline)
	if match:
		remote = symbols[match.groups()[0]]
		remote += match.groups()[2]
	elif lines[2:]:
		div_match = diverge_re.match(lines[2])
	 	if div_match:
			remote = "{behind}{1}{ahead of}{0}".format(*div_match.groups(), **symbols)

print '\n'.join([branch,remote,status])


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

<title>C-Index</title>
<meta name="date" content="2017-05-29">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

B C G I M N P R S U

C

CliCommands - Class in njensen.configurations

All the available groups of commands.

CliCommands() - Constructor for class njensen.configurations.CliCommands

Configurations - Class in njensen.configurations

Configure the app with these variables

Configurations() - Constructor for class njensen.configurations.Configurations

B C G I M N P R S U

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
namespace Rainbow
{
	struct Image
	{
		enum class Format
		{
			UNKNOWN,
			ATITC,  // Adreno
			ETC1,   // OpenGL ES standard
			PVRTC,  // iOS, OMAP43xx, PowerVR
			S3TC,   // Desktops, Tegra
			PNG
		};

		/// Creates an Image struct from image data.
		///
		/// Supports
		/// - iOS: PVRTC and whatever UIImage devours.
		/// - Other: PNG.
		///
		/// Limitations
		/// - PNG: Non-transparent grayscale is assumed to be PNG8, i.e. it's not supported.
		/// - PVRTC: PVR3 only, square, power of 2, no mipmaps, pre-multiplied alpha.
		static Image decode(const DataMap &);
		static void release(const Image &);

		Format format;
		unsigned int width;
		unsigned int height;
		unsigned int depth;
		unsigned int channels;
		size_t size;
		void *data;

		Image()
		    : format(Format::UNKNOWN), width(0), height(0), depth(0),
		      channels(0), size(0), data(nullptr) { }
	};
}

#include "Graphics/OpenGL.h"
#if defined(RAINBOW_OS_IOS)
#	include "Graphics/Decoders/UIKit.h"
#else
#	include "Graphics/Decoders/PNG.h"
#endif
#ifdef GL_IMG_texture_compression_pvrtc
#	include "Graphics/Decoders/PVRTC.h"
#endif  // GL_IMG_texture_compression_pvrtc

namespace Rainbow
{
	Image Image::decode(const DataMap &data)
	{
	#ifdef USE_PVRTC
		if (PVRTC::check(data))
			return PVRTC::decode(data);
	#endif  // USE_PVRTC

	#ifdef USE_PNG
		if (PNG::check(data))
			return PNG::decode(data);
	#endif  // USE_PNG

	#ifdef USE_UIKIT
		return UIKit::decode(data);
	#else
		return Image();
	#endif
	}

	void Image::release(const Image &image)
	{
		switch (image.format)
		{
			case Format::PVRTC:
				break;
			case Format::PNG:
			default:
				delete[] static_cast<unsigned char*>(image.data);
				break;
		}
	}
}

#endif


text:
/******************************************************************************
 * Licensed under Apache License Version 2.0 - see LICENSE
 *****************************************************************************/

#include "applyfunc.h"
#include <structmember.h>
#include "docs_reduce.h"
#include "helper.h"

PyDoc_STRVAR(
    applyfunc_prop_func_doc,
    "(callable) The function used (readonly).\n"
    "\n"
    ".. versionadded:: 0.6");

PyDoc_STRVAR(
    applyfunc_prop_current_doc,
    "(any type) The current value for the function (readonly).\n"
    "\n"
    ".. versionadded:: 0.6");

PyDoc_STRVAR(
    applyfunc_doc,
    "applyfunc(func, initial)\n"
    "--\n\n"
    "Successively apply `func` on `value`.\n"
    "\n"
    "Parameters\n"
    "----------\n"
    "func : callable\n"
    "    The function to apply. The `value` is given as first argument to the \n"
    "    `func`, no other arguments will be passed during the function call.\n"
    "\n"
    "initial : any type\n"
    "    The `initial` `value` for the function.\n"
    "\n"
    "Returns\n"
    "-------\n"
    "results : generator\n"
    "    The result of the successively applied `func`.\n"
    "\n"
    "Examples\n"
    "--------\n"
    "The first element is the initial `value` and the next elements are\n"
    "the result of ``func(value)``, then ``func(func(value))``, ...::\n"
    "\n"
    "    >>> from iteration_utilities import applyfunc, getitem\n"
    "    >>> import math\n"
    "    >>> list(getitem(applyfunc(math.sqrt, 10), stop=4))\n"
    "    [3.1622776601683795, 1.7782794100389228, 1.333521432163324, 1.1547819846894583]\n"
    "\n"
    ".. warning::\n"
    "    This will return an infinitely long generator so do **not** try to do\n"
    "    something like ``list(applyfunc())``!\n");

static PyObject *
applyfunc_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
    static char *kwlist[] = {"func", "initial", NULL};
    PyIUObject_Applyfunc *self;
    PyObject *func;
    PyObject *initial;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO:applyfunc", kwlist,
                                     &func, &initial)) {
        return NULL;
    }
    self = (PyIUObject_Applyfunc *)type->tp_alloc(type, 0);
    if (self == NULL) {
        return NULL;
    }
    Py_INCREF(func);
    self->func = func;
    Py_INCREF(initial);
    self->value = initial;
    return (PyObject *)self;
}

static void
applyfunc_dealloc(PyIUObject_Applyfunc *self) {
    PyObject_GC_UnTrack(self);
    Py_XDECREF(self->func);
    Py_XDECREF(self->value);
    Py_TYPE(self)->tp_free(self);
}

static int
applyfunc_traverse(PyIUObject_Applyfunc *self, visitproc visit, void *arg) {
    Py_VISIT(self->func);
    Py_VISIT(self->value);
    return 0;
}

static int
applyfunc_clear(PyIUObject_Applyfunc *self) {
    Py_CLEAR(self->func);
    Py_CLEAR(self->value);
    return 0;
}

static PyObject *
applyfunc_next(PyIUObject_Applyfunc *self) {
    PyObject *newval;

    /* Call the function with the current value as argument.  */
    newval = PyIU_CallWithOneArgument(self->func, self->value);
    if (newval == NULL) {
        return NULL;
    }

    /* Save the new value and also return it. */
    Py_INCREF(newval);
    Py_SETREF(self->value, newval);
    return newval;
}

static PyObject *
applyfunc_reduce(PyIUObject_Applyfunc *self, PyObject *Py_UNUSED(args)) {
    return Py_BuildValue("O(OO)",
                         Py_TYPE(self),
                         self->func,
                         self->value);
}

static PyMethodDef applyfunc_methods[] = {
    {
        "__reduce__",                  /* ml_name */
        (PyCFunction)applyfunc_reduce, /* ml_meth */
        METH_NOARGS,                   /* ml_flags */
        PYIU_reduce_doc                /* ml_doc */
    },
    {NULL, NULL} /* sentinel */
};

static PyMemberDef applyfunc_memberlist[] = {
    {
        "func",                               /* name */
        T_OBJECT,                             /* type */
        offsetof(PyIUObject_Applyfunc, func), /* offset */
        READONLY,                             /* flags */
        applyfunc_prop_func_doc               /* doc */
    },
    {
        "current",                             /* name */
        T_OBJECT,                              /* type */
        offsetof(PyIUObject_Applyfunc, value), /* offset */
        READONLY,                              /* flags */
        applyfunc_prop_current_doc             /* doc */
    },
    {NULL} /* sentinel */
};

PyTypeObject PyIUType_Applyfunc = {
    PyVarObject_HEAD_INIT(NULL, 0)(const char *) "iteration_utilities.applyfunc", /* tp_name */
    (Py_ssize_t)sizeof(PyIUObject_Applyfunc),                                     /* tp_basicsize */
    (Py_ssize_t)0,                                                                /* tp_itemsize */
    /* methods */
    (destructor)applyfunc_dealloc,         /* tp_dealloc */
    (printfunc)0,                          /* tp_print */
    (getattrfunc)0,                        /* tp_getattr */
    (setattrfunc)0,                        /* tp_setattr */
    0,                                     /* tp_reserved */
    (reprfunc)0,                           /* tp_repr */
    (PyNumberMethods *)0,                  /* tp_as_number */
    (PySequenceMethods *)0,                /* tp_as_sequence */
    (PyMappingMethods *)0,                 /* tp_as_mapping */
    (hashfunc)0,                           /* tp_hash */
    (ternaryfunc)0,                        /* tp_call */
    (reprfunc)0,                           /* tp_str */
    (getattrofunc)PyObject_GenericGetAttr, /* tp_getattro */
    (setattrofunc)0,                       /* tp_setattro */
    (PyBufferProcs *)0,                    /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
        Py_TPFLAGS_BASETYPE,          /* tp_flags */
    (const char *)applyfunc_doc,      /* tp_doc */
    (traverseproc)applyfunc_traverse, /* tp_traverse */
    (inquiry)applyfunc_clear,         /* tp_clear */
    (richcmpfunc)0,                   /* tp_richcompare */
    (Py_ssize_t)0,                    /* tp_weaklistoffset */
    (getiterfunc)PyObject_SelfIter,   /* tp_iter */
    (iternextfunc)applyfunc_next,     /* tp_iternext */
    applyfunc_methods,                /* tp_methods */
    applyfunc_memberlist,             /* tp_members */
    0,                                /* tp_getset */
    0,                                /* tp_base */
    0,                                /* tp_dict */
    (descrgetfunc)0,                  /* tp_descr_get */
    (descrsetfunc)0,                  /* tp_descr_set */
    (Py_ssize_t)0,                    /* tp_dictoffset */
    (initproc)0,                      /* tp_init */
    (allocfunc)0,                     /* tp_alloc */
    (newfunc)applyfunc_new,           /* tp_new */
    (freefunc)PyObject_GC_Del,        /* tp_free */
};


text:
package com.intellij.json.editor.smartEnter;

import com.intellij.json.psi.JsonArray;
import com.intellij.json.psi.JsonFile;
import com.intellij.json.psi.JsonProperty;
import com.intellij.json.psi.JsonValue;
import com.intellij.lang.SmartEnterProcessorWithFixers;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

import java.util.List;

import static com.intellij.json.JsonElementTypes.COLON;
import static com.intellij.json.JsonElementTypes.COMMA;

/**
 * This processor allows
 *

 *
Insert colon after key inside object property

 *
Insert comma after array element or object property

 *

 *
 * @author Mikhail Golubev
 */
public class JsonSmartEnterProcessor extends SmartEnterProcessorWithFixers {
  public static final Logger LOG = Logger.getInstance(JsonSmartEnterProcessor.class);

  private boolean myShouldAddNewline = false;

  public JsonSmartEnterProcessor() {
    addFixers(new JsonObjectPropertyFixer(), new JsonArrayElementFixer());
    addEnterProcessors(new JsonEnterProcessor());
  }

  @Override
  protected void collectAdditionalElements(@NotNull PsiElement element, @NotNull List<PsiElement> result) {
    // include all parents as well
    PsiElement parent = element.getParent();
    while (parent != null && !(parent instanceof JsonFile)) {
      result.add(parent);
      parent = parent.getParent();
    }
  }

  private static boolean terminatedOnCurrentLine(@NotNull Editor editor, @NotNull PsiElement element) {
    final Document document = editor.getDocument();
    final int caretOffset = editor.getCaretModel().getCurrentCaret().getOffset();
    final int elementEndOffset = element.getTextRange().getEndOffset();
    if (document.getLineNumber(elementEndOffset) != document.getLineNumber(caretOffset)) {
      return false;
    }
    // Skip empty PsiError elements if comma is missing
    PsiElement nextLeaf = PsiTreeUtil.nextLeaf(element, true);
    return nextLeaf == null || (nextLeaf instanceof PsiWhiteSpace && nextLeaf.getText().contains("\n"));
  }

  private static boolean isFollowedByTerminal(@NotNull PsiElement element, IElementType type) {
    final PsiElement nextLeaf = PsiTreeUtil.nextVisibleLeaf(element);
    return nextLeaf != null && nextLeaf.getNode().getElementType() == type;
  }

  private static class JsonArrayElementFixer extends SmartEnterProcessorWithFixers.Fixer<JsonSmartEnterProcessor> {
    @Override
    public void apply(@NotNull Editor editor, @NotNull JsonSmartEnterProcessor processor, @NotNull PsiElement element)
      throws IncorrectOperationException {
      if (element instanceof JsonValue && element.getParent() instanceof JsonArray) {
        final JsonValue arrayElement = (JsonValue)element;
        if (terminatedOnCurrentLine(editor, arrayElement) && !isFollowedByTerminal(element, COMMA)) {
          editor.getDocument().insertString(arrayElement.getTextRange().getEndOffset(), ",");
          processor.myShouldAddNewline = true;
        }
      }
    }
  }

  private class JsonObjectPropertyFixer extends SmartEnterProcessorWithFixers.Fixer<JsonSmartEnterProcessor> {
    @Override
    public void apply(@NotNull Editor editor, @NotNull JsonSmartEnterProcessor processor, @NotNull PsiElement element)
      throws IncorrectOperationException {
      if (element instanceof JsonProperty) {
        final JsonValue propertyValue = ((JsonProperty)element).getValue();
        if (propertyValue != null) {
          if (terminatedOnCurrentLine(editor, propertyValue) && !isFollowedByTerminal(propertyValue, COMMA)) {
            editor.getDocument().insertString(propertyValue.getTextRange().getEndOffset(), ",");
            processor.myShouldAddNewline = true;
          }
        }
        else {
          final JsonValue propertyKey = ((JsonProperty)element).getNameElement();
          final int keyEndOffset = propertyKey.getTextRange().getEndOffset();
          //processor.myFirstErrorOffset = keyEndOffset;
          if (terminatedOnCurrentLine(editor, propertyKey) && !isFollowedByTerminal(propertyKey, COLON)) {
            processor.myFirstErrorOffset = keyEndOffset + 2;
            editor.getDocument().insertString(keyEndOffset, ": ");
          }
        }
      }
    }
  }

  private class JsonEnterProcessor extends SmartEnterProcessorWithFixers.FixEnterProcessor {
    @Override
    public boolean doEnter(PsiElement atCaret, PsiFile file, @NotNull Editor editor, boolean modified) {
      if (myShouldAddNewline) {
        try {
          plainEnter(editor);
        }
        finally {
          myShouldAddNewline = false;
        }
      }
      return true;
    }
  }
}


text:
"""
Handles making HTTP requests to the REST API and converting the results into a usable format
"""

import urllib.parse
import urllib.request
import urllib.error
import json
import zlib

import cassiopeia.type.api.exception
import cassiopeia.type.api.rates

api_versions = {
    "champion": "v1.2",
    "currentgame": "v1.0",
    "featuredgames": "v1.0",
    "game": "v1.3",
    "league": "v2.5",
    "staticdata": "v1.2",
    "status": "v1.0",
    "match": "v2.2",
    "matchlist": "v2.2",
    "stats": "v1.3",
    "summoner": "v1.4",
    "team": "v2.4"
}

api_key = ""
tournament_api_key = ""
region = ""
print_calls = False
rate_limiter = None
tournament_rate_limiter = None

def get(request, params={}, static=False, include_base=True, tournament=False):
    """Makes a rate-limited HTTP request to the Riot API and returns the result

    request         str               the request string
    params          dict<str, any>    the parameters to send with the request (default {})
    static          bool              whether this is a call to a static (non-rate-limited) API
    include_base    bool              whether to prepend https://{server}.api.pvp.net/api/lol/{region}/ to the request

    return          dict              the JSON response from the Riot API as a dict
    """
    if (not tournament and not api_key) or (tournament and not tournament_api_key):
        raise cassiopeia.type.api.exception.CassiopeiaException("API Key must be set before the API can be queried.")
    if not region:
        raise cassiopeia.type.api.exception.CassiopeiaException("Region must be set before the API can be queried.")

    # Set server and rgn
    server = "global" if static else region
    rgn = ("static-data/{region}" if static else "{region}").format(region=region)

    # Encode params
    params["api_key"] = tournament_api_key if tournament else api_key
    encoded_params = urllib.parse.urlencode(params)

    # Build and execute request
    if include_base:
        url = "https://{server}.api.pvp.net/api/lol/{region}/{request}?{params}".format(server=server, region=rgn, request=request, params=encoded_params)
    else:
        url = "{request}?{params}".format(request=request, params=encoded_params)

    limiter = tournament_rate_limiter if tournament else rate_limiter
    try:
        content = limiter.call(execute_request, url) if limiter else execute_request(url)
        return json.loads(content)
    except urllib.error.HTTPError as e:
        # Reset rate limiter and retry on 429 (rate limit exceeded)
        if e.code == 429 and limiter:
            retry_after = 1
            if e.headers["Retry-After"]:
                retry_after += int(e.headers["Retry-After"])

            limiter.reset_in(retry_after)
            return get(request, params, static, include_base, tournament)
        else:
            raise cassiopeia.type.api.exception.APIError("Server returned error {code} on call: {url}".format(code=e.code, url=url), e.code)

def execute_request(url, method="GET", payload=""):
    """Executes an HTTP request and returns the result in a string

    url        str    the full URL to send a request to
    method     str    the HTTP method to use
    payload    str    the json payload to send if appropriate for HTTP method

    return     str    the content returned by the server
    """
    if print_calls:
        print(url)

    response = None
    try:
        if payload:
            payload = payload.encode("UTF-8")
            request = urllib.request.Request(url, method=method, payload=payload)
        else:
            request = urllib.request.Request(url, method=method)
        request.add_header("Accept-Encoding", "gzip")
        response = urllib.request.urlopen(request)
        content = response.read()
        content = zlib.decompress(content, zlib.MAX_WBITS | 16).decode(encoding="UTF-8")
        return content
    finally:
        if response:
            response.close()


text:
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarExample" aria-controls="navbarExample" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        KÇMS YAPI

               {% assign navigation_pages = site.html_pages | sort: 'navigation_weight' %}
               {% for p in site.pages %}
                 {% if p.navigation_weight %}

                    {{ p.title}}

                 {% endif %}
                {% endfor %}


text:
package examples;

import java.util.List;
import java.util.Map;
import me.legrange.mikrotik.MikrotikApiException;

/**
 * Example 2: A command that returns results. Print all interfaces
 *
 * @author gideon
 */
public class SimpleCommandWithResults extends Example {

    public static void main(String... args) throws Exception {
        SimpleCommandWithResults ex = new SimpleCommandWithResults();
        ex.connect();
        ex.test();
        ex.disconnect();
    }

    private void test() throws MikrotikApiException {
        List<Map<String, String>> results =  con.execute("/interface/print");
        for (Map<String, String> result : results) {
            System.out.println(result);
        }
    }
}


text:
.class public Lcom/android/internal/policy/impl/MzCustomCircleButton;
.super Landroid/widget/TextView;
.source "MzCustomCircleButton.java"

# instance fields
.field private mCircleCenterX:F

.field private mCircleCenterY:F

.field private mCoverAlpha:I

.field private mCoverPaint:Landroid/graphics/Paint;

.field private mCustomColor:I

.field private mPaint:Landroid/graphics/Paint;

.field mPressAnimtor:Landroid/animation/ObjectAnimator;

.field private mPressed:Z

.field private mRadius:F

.field private mText:Ljava/lang/String;

.field private mTextHeight:F

.field private mTextPaint:Landroid/graphics/Paint;

.field private mTextWidth:F

# direct methods
.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
    .locals 5
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "attrs"    # Landroid/util/AttributeSet;

    .prologue
    const/4 v4, 0x1

    const/4 v3, 0x0

    .line 46
    invoke-direct {p0, p1, p2}, Landroid/widget/TextView;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    .line 37
    iput v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCustomColor:I

    .line 39
    iput-boolean v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressed:Z

    .line 43
    iput v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    .line 49
    new-instance v0, Landroid/graphics/Paint;

    invoke-direct {v0}, Landroid/graphics/Paint;-><init>()V

    iput-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPaint:Landroid/graphics/Paint;

    .line 50
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, v4}, Landroid/graphics/Paint;->setAntiAlias(Z)V

    .line 51
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPaint:Landroid/graphics/Paint;

    iget v1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCustomColor:I

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setColor(I)V

    .line 53
    new-instance v0, Landroid/graphics/Paint;

    invoke-direct {v0}, Landroid/graphics/Paint;-><init>()V

    iput-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    .line 54
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, v4}, Landroid/graphics/Paint;->setAntiAlias(Z)V

    .line 55
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    const/high16 v1, -0x1000000

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setColor(I)V

    .line 56
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    invoke-virtual {v0, v3}, Landroid/graphics/Paint;->setAlpha(I)V

    .line 65
    const-string v0, "coveralpha"

    const/4 v1, 0x2

    new-array v1, v1, [F

    iget v2, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    int-to-float v2, v2

    aput v2, v1, v3

    const/4 v2, 0x0

    aput v2, v1, v4

    invoke-static {p0, v0, v1}, Landroid/animation/ObjectAnimator;->ofFloat(Ljava/lang/Object;Ljava/lang/String;[F)Landroid/animation/ObjectAnimator;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    .line 67
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    const-wide/16 v2, 0x1a0

    invoke-virtual {v0, v2, v3}, Landroid/animation/ObjectAnimator;->setDuration(J)Landroid/animation/ObjectAnimator;

    .line 68
    return-void
.end method

.method private inCircleArea(Landroid/view/MotionEvent;)Z
    .locals 10
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    const-wide/high16 v8, 0x4000000000000000L    # 2.0

    .line 133
    const/4 v0, 0x1

    .line 134
    .local v0, "result":Z
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getX()F

    move-result v1

    .line 135
    .local v1, "x":F
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getY()F

    move-result v2

    .line 136
    .local v2, "y":F
    iget v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterY:F

    sub-float/2addr v3, v2

    float-to-double v4, v3

    invoke-static {v4, v5, v8, v9}, Ljava/lang/Math;->pow(DD)D

    move-result-wide v4

    iget v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterY:F

    sub-float/2addr v3, v2

    float-to-double v6, v3

    invoke-static {v6, v7, v8, v9}, Ljava/lang/Math;->pow(DD)D

    move-result-wide v6

    add-double/2addr v4, v6

    invoke-static {v4, v5}, Ljava/lang/Math;->sqrt(D)D

    move-result-wide v4

    iget v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mRadius:F

    float-to-double v6, v3

    cmpg-double v3, v4, v6

    if-gtz v3, :cond_0

    const/4 v3, 0x1

    :goto_0
    return v3

    :cond_0
    const/4 v3, 0x0

    goto :goto_0
.end method

# virtual methods
.method public getCoverAlpha()I
    .locals 1

    .prologue
    .line 164
    iget v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    return v0
.end method

.method protected onDraw(Landroid/graphics/Canvas;)V
    .locals 4
    .param p1, "canvas"    # Landroid/graphics/Canvas;

    .prologue
    .line 86
    iget v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterX:F

    iget v1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterY:F

    iget v2, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mRadius:F

    iget-object v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPaint:Landroid/graphics/Paint;

    invoke-virtual {p1, v0, v1, v2, v3}, Landroid/graphics/Canvas;->drawCircle(FFFLandroid/graphics/Paint;)V

    .line 93
    iget v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    if-ltz v0, :cond_0

    iget v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    const/16 v1, 0xff

    if-gt v0, v1, :cond_0

    .line 94
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    iget v1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setAlpha(I)V

    .line 95
    iget v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterX:F

    iget v1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterY:F

    iget v2, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mRadius:F

    iget-object v3, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverPaint:Landroid/graphics/Paint;

    invoke-virtual {p1, v0, v1, v2, v3}, Landroid/graphics/Canvas;->drawCircle(FFFLandroid/graphics/Paint;)V

    .line 98
    :cond_0
    invoke-super {p0, p1}, Landroid/widget/TextView;->onDraw(Landroid/graphics/Canvas;)V

    .line 99
    return-void
.end method

.method protected onLayout(ZIIII)V
    .locals 1
    .param p1, "changed"    # Z
    .param p2, "left"    # I
    .param p3, "top"    # I
    .param p4, "right"    # I
    .param p5, "bottom"    # I

    .prologue
    .line 104
    sub-int v0, p4, p2

    div-int/lit8 v0, v0, 0x2

    int-to-float v0, v0

    iput v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterX:F

    iput v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mRadius:F

    .line 105
    sub-int v0, p5, p3

    div-int/lit8 v0, v0, 0x2

    int-to-float v0, v0

    iput v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCircleCenterY:F

    .line 106
    return-void
.end method

.method public onTouchEvent(Landroid/view/MotionEvent;)Z
    .locals 3
    .param p1, "event"    # Landroid/view/MotionEvent;

    .prologue
    const/4 v0, 0x1

    const/4 v1, 0x0

    .line 111
    invoke-super {p0, p1}, Landroid/widget/TextView;->onTouchEvent(Landroid/view/MotionEvent;)Z

    .line 112
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getAction()I

    move-result v2

    packed-switch v2, :pswitch_data_0

    :cond_0
    :goto_0
    :pswitch_0
    move v0, v1

    .line 126
    :goto_1
    return v0

    .line 114
    :pswitch_1
    invoke-direct {p0, p1}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->inCircleArea(Landroid/view/MotionEvent;)Z

    move-result v2

    if-eqz v2, :cond_0

    .line 115
    invoke-virtual {p0, v0}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->setStatePressed(Z)V

    goto :goto_1

    .line 121
    :pswitch_2
    invoke-virtual {p0, v1}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->setStatePressed(Z)V

    goto :goto_0

    .line 112
    :pswitch_data_0
    .packed-switch 0x0
        :pswitch_1
        :pswitch_2
        :pswitch_0
        :pswitch_2
    .end packed-switch
.end method

.method public setCoverAlpha(I)V
    .locals 0
    .param p1, "alpha"    # I

    .prologue
    .line 159
    iput p1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    .line 160
    invoke-virtual {p0}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->postInvalidate()V

    .line 161
    return-void
.end method

.method public setCustomColor(I)V
    .locals 2
    .param p1, "color"    # I

    .prologue
    .line 71
    iput p1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCustomColor:I

    .line 72
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPaint:Landroid/graphics/Paint;

    iget v1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCustomColor:I

    invoke-virtual {v0, v1}, Landroid/graphics/Paint;->setColor(I)V

    .line 73
    invoke-virtual {p0}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->postInvalidate()V

    .line 74
    return-void
.end method

.method public setStatePressed(Z)V
    .locals 4
    .param p1, "pressed"    # Z

    .prologue
    const/4 v3, 0x0

    .line 141
    iget-boolean v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressed:Z

    if-eq p1, v0, :cond_1

    .line 142
    iput-boolean p1, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressed:Z

    .line 143
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    invoke-virtual {v0}, Landroid/animation/ObjectAnimator;->isRunning()Z

    move-result v0

    if-eqz v0, :cond_0

    .line 144
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    invoke-virtual {v0}, Landroid/animation/ObjectAnimator;->cancel()V

    .line 146
    :cond_0
    if-eqz p1, :cond_2

    .line 147
    const/16 v0, 0x66

    invoke-virtual {p0, v0}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->setCoverAlpha(I)V

    .line 148
    invoke-virtual {p0}, Lcom/android/internal/policy/impl/MzCustomCircleButton;->postInvalidate()V

    .line 156
    :cond_1
    :goto_0
    return-void

    .line 150
    :cond_2
    const-string v0, "coverAlpha"

    const/4 v1, 0x2

    new-array v1, v1, [I

    iget v2, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mCoverAlpha:I

    aput v2, v1, v3

    const/4 v2, 0x1

    aput v3, v1, v2

    invoke-static {p0, v0, v1}, Landroid/animation/ObjectAnimator;->ofInt(Ljava/lang/Object;Ljava/lang/String;[I)Landroid/animation/ObjectAnimator;

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    .line 152
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    const-wide/16 v2, 0x1a0

    invoke-virtual {v0, v2, v3}, Landroid/animation/ObjectAnimator;->setDuration(J)Landroid/animation/ObjectAnimator;

    .line 153
    iget-object v0, p0, Lcom/android/internal/policy/impl/MzCustomCircleButton;->mPressAnimtor:Landroid/animation/ObjectAnimator;

    invoke-virtual {v0}, Landroid/animation/ObjectAnimator;->start()V

    goto :goto_0
.end method


text:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm

# ## Weighted GLM: Poisson response data
#
# ### Load data
#
# In this example, we'll use the affair dataset using a handful of
# exogenous variables to predict the extra-marital affair rate.
#
# Weights will be generated to show that `freq_weights` are equivalent to
# repeating records of data. On the other hand, `var_weights` is equivalent
# to aggregating data.

print(sm.datasets.fair.NOTE)

# Load the data into a pandas dataframe.

data = sm.datasets.fair.load_pandas().data

#  The dependent (endogenous) variable is ``affairs``

data.describe()

data[:3]

# In the following we will work mostly with Poisson. While using decimal
# affairs works, we convert them to integers to have a count distribution.

data["affairs"] = np.ceil(data["affairs"])
data[:3]

(data["affairs"] == 0).mean()

np.bincount(data["affairs"].astype(int))

# ## Condensing and Aggregating observations
#
# We have 6366 observations in our original dataset. When we consider only
# some selected variables, then we have fewer unique observations. In the
# following we combine observations in two ways, first we combine
# observations that have values for all variables identical, and secondly we
# combine observations that have the same explanatory variables.

# ### Dataset with unique observations
#
# We use pandas's groupby to combine identical observations and create a
# new variable `freq` that count how many observation have the values in the
# corresponding row.

data2 = data.copy()
data2['const'] = 1
dc = data2['affairs rate_marriage age yrs_married const'.split()].groupby(
    'affairs rate_marriage age yrs_married'.split()).count()
dc.reset_index(inplace=True)
dc.rename(columns={'const': 'freq'}, inplace=True)
print(dc.shape)
dc.head()

# ### Dataset with unique explanatory variables (exog)
#
# For the next dataset we combine observations that have the same values
# of the explanatory variables. However, because the response variable can
# differ among combined observations, we compute the mean and the sum of the
# response variable for all combined observations.
#
# We use again pandas ``groupby`` to combine observations and to create
# the new variables. We also flatten the ``MultiIndex`` into a simple index.

gr = data['affairs rate_marriage age yrs_married'.split()].groupby(
    'rate_marriage age yrs_married'.split())
df_a = gr.agg(['mean', 'sum', 'count'])

def merge_tuple(tpl):
    if isinstance(tpl, tuple) and len(tpl) > 1:
        return "_".join(map(str, tpl))
    else:
        return tpl

df_a.columns = df_a.columns.map(merge_tuple)
df_a.reset_index(inplace=True)
print(df_a.shape)
df_a.head()

# After combining observations with have a dataframe `dc` with 467 unique
# observations, and a dataframe `df_a` with 130 observations with unique
# values of the explanatory variables.

print('number of rows: \noriginal, with unique observations, with unique exog')
data.shape[0], dc.shape[0], df_a.shape[0]

# ## Analysis
#
# In the following, we compare the GLM-Poisson results of the original
# data with models of the combined observations where the multiplicity or
# aggregation is given by weights or exposure.
#
#
# ### original data

glm = smf.glm(
    'affairs ~ rate_marriage + age + yrs_married',
    data=data,
    family=sm.families.Poisson())
res_o = glm.fit()
print(res_o.summary())

res_o.pearson_chi2 / res_o.df_resid

# ### condensed data (unique observations with frequencies)
#
# Combining identical observations and using frequency weights to take
# into account the multiplicity of observations produces exactly the same
# results. Some results attribute will differ when we want to have
# information about the observation and not about the aggregate of all
# identical observations. For example, residuals do not take
# ``freq_weights`` into account.

glm = smf.glm(
    'affairs ~ rate_marriage + age + yrs_married',
    data=dc,
    family=sm.families.Poisson(),
    freq_weights=np.asarray(dc['freq']))
res_f = glm.fit()
print(res_f.summary())

res_f.pearson_chi2 / res_f.df_resid

# ### condensed using ``var_weights`` instead of ``freq_weights``
#
# Next, we compare ``var_weights`` to ``freq_weights``. It is a common
# practice to incorporate ``var_weights`` when the endogenous variable
# reflects averages and not identical observations.
# I do not see a theoretical reason why it produces the same results (in
# general).
#
# This produces the same results but ``df_resid``  differs the
# ``freq_weights`` example because ``var_weights`` do not change the number
# of effective observations.
#

glm = smf.glm(
    'affairs ~ rate_marriage + age + yrs_married',
    data=dc,
    family=sm.families.Poisson(),
    var_weights=np.asarray(dc['freq']))
res_fv = glm.fit()
print(res_fv.summary())

# Dispersion computed from the results is incorrect because of wrong
# ``df_resid``.
# It is correct if we use the original ``df_resid``.

res_fv.pearson_chi2 / res_fv.df_resid, res_f.pearson_chi2 / res_f.df_resid

# ### aggregated or averaged data (unique values of explanatory variables)
#
# For these cases we combine observations that have the same values of the
# explanatory variables. The corresponding response variable is either a sum
# or an average.
#
# #### using ``exposure``
#
# If our dependent variable is the sum of the responses of all combined
# observations, then under the Poisson assumption the distribution remains
# the same but we have varying `exposure` given by the number of individuals
# that are represented by one aggregated observation.
#
# The parameter estimates and covariance of parameters are the same with
# the original data, but log-likelihood, deviance and Pearson chi-squared
# differ

glm = smf.glm(
    'affairs_sum ~ rate_marriage + age + yrs_married',
    data=df_a,
    family=sm.families.Poisson(),
    exposure=np.asarray(df_a['affairs_count']))
res_e = glm.fit()
print(res_e.summary())

res_e.pearson_chi2 / res_e.df_resid

# #### using var_weights
#
# We can also use the mean of all combined values of the dependent
# variable. In this case the variance will be related to the inverse of the
# total exposure reflected by one combined observation.

glm = smf.glm(
    'affairs_mean ~ rate_marriage + age + yrs_married',
    data=df_a,
    family=sm.families.Poisson(),
    var_weights=np.asarray(df_a['affairs_count']))
res_a = glm.fit()
print(res_a.summary())

# ### Comparison
#
# We saw in the summary prints above that ``params`` and ``cov_params``
# with associated Wald inference agree across versions. We summarize this in
# the following comparing individual results attributes across versions.
#
# Parameter estimates `params`, standard errors of the parameters `bse`
# and `pvalues` of the parameters for the tests that the parameters are
# zeros all agree. However, the likelihood and goodness-of-fit statistics,
# `llf`, `deviance` and `pearson_chi2` only partially agree. Specifically,
# the aggregated version do not agree with the results using the original
# data.
#
# **Warning**: The behavior of `llf`, `deviance` and `pearson_chi2` might
# still change in future versions.
#
# Both the sum and average of the response variable for unique values of
# the explanatory variables have a proper likelihood interpretation.
# However, this interpretation is not reflected in these three statistics.
# Computationally this might be due to missing adjustments when aggregated
# data is used. However, theoretically we can think in these cases,
# especially for `var_weights` of the misspecified case when likelihood
# analysis is inappropriate and the results should be interpreted as quasi-
# likelihood estimates. There is an ambiguity in the definition of
# ``var_weights`` because they can be used for averages with correctly
# specified likelihood as well as for variance adjustments in the quasi-
# likelihood case. We are currently not trying to match the likelihood
# specification. However, in the next section we show that likelihood ratio
# type tests still produce the same result for all aggregation versions when
# we assume that the underlying model is correctly specified.

results_all = [res_o, res_f, res_e, res_a]
names = 'res_o res_f res_e res_a'.split()

pd.concat([r.params for r in results_all], axis=1, keys=names)

pd.concat([r.bse for r in results_all], axis=1, keys=names)

pd.concat([r.pvalues for r in results_all], axis=1, keys=names)

pd.DataFrame(
    np.column_stack(
        [[r.llf, r.deviance, r.pearson_chi2] for r in results_all]),
    columns=names,
    index=['llf', 'deviance', 'pearson chi2'])

# ### Likelihood Ratio type tests
#
# We saw above that likelihood and related statistics do not agree between
# the aggregated and original, individual data. We illustrate in the
# following that likelihood ratio test and difference in deviance agree
# across versions, however Pearson chi-squared does not.
#
# As before: This is not sufficiently clear yet and could change.
#
# As a test case we drop the `age` variable and compute the likelihood
# ratio type statistics as difference between reduced or constrained and
# full or unconstrained model.

# #### original observations and frequency weights

glm = smf.glm(
    'affairs ~ rate_marriage + yrs_married',
    data=data,
    family=sm.families.Poisson())
res_o2 = glm.fit()
#print(res_f2.summary())
res_o2.pearson_chi2 - res_o.pearson_chi2, res_o2.deviance - res_o.deviance, res_o2.llf - res_o.llf

glm = smf.glm(
    'affairs ~ rate_marriage + yrs_married',
    data=dc,
    family=sm.families.Poisson(),
    freq_weights=np.asarray(dc['freq']))
res_f2 = glm.fit()
#print(res_f2.summary())
res_f2.pearson_chi2 - res_f.pearson_chi2, res_f2.deviance - res_f.deviance, res_f2.llf - res_f.llf

# #### aggregated data: ``exposure`` and ``var_weights``
#
# Note: LR test agrees with original observations, ``pearson_chi2``
# differs and has the wrong sign.

glm = smf.glm(
    'affairs_sum ~ rate_marriage + yrs_married',
    data=df_a,
    family=sm.families.Poisson(),
    exposure=np.asarray(df_a['affairs_count']))
res_e2 = glm.fit()
res_e2.pearson_chi2 - res_e.pearson_chi2, res_e2.deviance - res_e.deviance, res_e2.llf - res_e.llf

glm = smf.glm(
    'affairs_mean ~ rate_marriage + yrs_married',
    data=df_a,
    family=sm.families.Poisson(),
    var_weights=np.asarray(df_a['affairs_count']))
res_a2 = glm.fit()
res_a2.pearson_chi2 - res_a.pearson_chi2, res_a2.deviance - res_a.deviance, res_a2.llf - res_a.llf

# ### Investigating Pearson chi-square statistic
#
# First, we do some sanity checks that there are no basic bugs in the
# computation of `pearson_chi2` and `resid_pearson`.

res_e2.pearson_chi2, res_e.pearson_chi2, (res_e2.resid_pearson
                                          **2).sum(), (res_e.resid_pearson
                                                       **2).sum()

res_e._results.resid_response.mean(), res_e.model.family.variance(
    res_e.mu)[:5], res_e.mu[:5]

(res_e._results.resid_response**2 / res_e.model.family.variance(
    res_e.mu)).sum()

res_e2._results.resid_response.mean(), res_e2.model.family.variance(
    res_e2.mu)[:5], res_e2.mu[:5]

(res_e2._results.resid_response**2 / res_e2.model.family.variance(
    res_e2.mu)).sum()

(res_e2._results.resid_response**2).sum(), (res_e._results.resid_response
                                            **2).sum()

# One possible reason for the incorrect sign is that we are subtracting
# quadratic terms that are divided by different denominators. In some
# related cases, the recommendation in the literature is to use a common
# denominator. We can compare pearson chi-squared statistic using the same
# variance assumption in the full and reduced model.
#
# In this case we obtain the same pearson chi2 scaled difference between
# reduced and full model across all versions. (Issue
# [#3616](https://github.com/statsmodels/statsmodels/issues/3616) is
# intended to track this further.)

((res_e2._results.resid_response**2 - res_e._results.resid_response**2) /
 res_e2.model.family.variance(res_e2.mu)).sum()

((res_a2._results.resid_response**2 - res_a._results.resid_response**2) /
 res_a2.model.family.variance(res_a2.mu) * res_a2.model.var_weights).sum()

((res_f2._results.resid_response**2 - res_f._results.resid_response**2) /
 res_f2.model.family.variance(res_f2.mu) * res_f2.model.freq_weights).sum()

((res_o2._results.resid_response**2 - res_o._results.resid_response**2) /
 res_o2.model.family.variance(res_o2.mu)).sum()

# ## Remainder
#
# The remainder of the notebook just contains some additional checks and
# can be ignored.

np.exp(res_e2.model.exposure)[:5], np.asarray(df_a['affairs_count'])[:5]

res_e2.resid_pearson.sum() - res_e.resid_pearson.sum()

res_e2.mu[:5]

res_a2.pearson_chi2, res_a.pearson_chi2, res_a2.resid_pearson.sum(
), res_a.resid_pearson.sum()

((res_a2._results.resid_response**2) / res_a2.model.family.variance(res_a2.mu)
 * res_a2.model.var_weights).sum()

((res_a._results.resid_response**2) / res_a.model.family.variance(res_a.mu) *
 res_a.model.var_weights).sum()

((res_a._results.resid_response**2) / res_a.model.family.variance(res_a2.mu) *
 res_a.model.var_weights).sum()

res_e.model.endog[:5], res_e2.model.endog[:5]

res_a.model.endog[:5], res_a2.model.endog[:5]

res_a2.model.endog[:5] * np.exp(res_e2.model.exposure)[:5]

res_a2.model.endog[:5] * res_a2.model.var_weights[:5]

from scipy import stats
stats.chi2.sf(27.19530754604785, 1), stats.chi2.sf(29.083798806764687, 1)

res_o.pvalues

print(res_e2.summary())
print(res_e.summary())

print(res_f2.summary())
print(res_f.summary())


text:
package io.sundr.codegen.model;

import java.util.Collections;
import java.util.List;

public class Source {

    private final List<TypeDef> types;

    public Source() {
        this(Collections.EMPTY_LIST);
    }

    public Source(List<TypeDef> types) {
        this.types = types;
    }

    public List<TypeDef> getTypes() {
        return types;
    }
}


text:
using AuxidyCinema.DTOs;
using AuxidyCinema.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AuxidyCinema.Controllers.API
{
    public class GenreController : ApiController
    {
        private ApplicationDbContext _context;
        public GenreController()
        {
            _context = new ApplicationDbContext();
        }
        //get /API/Genre
        [HttpGet]
        public IHttpActionResult GetGernes(string query = null)
        {
            IQueryable<Genre> GenreQuery = _context.Genres;
            if (!String.IsNullOrWhiteSpace(query))
            {
                GenreQuery = GenreQuery.Where(x => x.genreName.Contains(query));
            }
            var GenreDTO = GenreQuery.ToList().Select(AutoMapper.Mapper.Map<Genre, GenreDTO>);
            return Ok(GenreDTO);
        }
        [HttpGet]
        public IHttpActionResult GetGenres(int ID)
        {
            var Genre = _context.Genres.SingleOrDefault(x => x.genreID == ID);
            if (Genre == null)
            {
                NotFound();
            }
            return Ok(AutoMapper.Mapper.Map<Genre, GenreDTO>(Genre));
        }
        [HttpPost]
        public IHttpActionResult CreateGenre(GenreDTO GenrerDTO)
        {
            if (!ModelState.IsValid)
            {
                BadRequest();
            }
            var Genre = AutoMapper.Mapper.Map<GenreDTO, Genre>(GenrerDTO);
            _context.Genres.Add(Genre);
            _context.SaveChanges();
            GenrerDTO.genreID = Genre.genreID;
            return Created(new Uri(Request.RequestUri + "/" + Genre.genreID), GenrerDTO);
        }
        [HttpPut]
        public void UpdateCustomer(int id, GenreDTO genreDTO)
        {

            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            var GenreinDB = _context.Genres.SingleOrDefault(c => c.genreID == id);

            if (GenreinDB == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);

            }
            AutoMapper.Mapper.Map(genreDTO, GenreinDB);
            _context.SaveChanges();
        }
        [HttpDelete]
        public void DeleteCustomer(int Id)
        {
            var GenreinDB = _context.Genres.SingleOrDefault(x => x.genreID == Id);

            if (GenreinDB == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _context.Genres.Remove(GenreinDB);
            _context.SaveChanges();
        }
    }
}


text:
import mock

from touchdown.tests.fixtures.aws import BucketFixture
from touchdown.tests.stubs.aws import StreamingDistributionStubber

from . import aws

CALLER_REFERENCE = "e0324ac4-e30d-4cde-9b29-173863ac0861"

EXAMPLE_DISTRIBUTION_CONFIG = {
    "Aliases": {"Items": ["www.example.com"], "Quantity": 1},
    "CallerReference": CALLER_REFERENCE,
    "Comment": "www.example.com",
    "TrustedSigners": {"Enabled": False, "Quantity": 0},
    "Enabled": True,
    "Logging": {"Enabled": False, "Bucket": "", "Prefix": ""},
    "S3Origin": {
        "DomainName": "my-test-bucket.s3.amazonaws.com",
        "OriginAccessIdentity": "",
    },
    "PriceClass": "PriceClass_100",
}

class TestStreamingDistributionCreation(aws.StubberTestCase):
    def test_create_streaming_distribution(self):
        goal = self.create_goal("apply")

        uuid4 = self.fixtures.enter_context(mock.patch("uuid.uuid4"))
        uuid4.return_value = CALLER_REFERENCE

        bucket = self.fixtures.enter_context(BucketFixture(goal, self.aws))

        streaming_distribution = self.fixtures.enter_context(
            StreamingDistributionStubber(
                goal.get_service(
                    self.aws.add_streaming_distribution(
                        name="www.example.com", bucket=bucket.bucket
                    ),
                    "apply",
                )
            )
        )
        streaming_distribution.add_list_streaming_distributions_empty_response()

        streaming_distribution.add_create_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG
        )

        streaming_distribution.add_list_streaming_distributions_one_response(
            EXAMPLE_DISTRIBUTION_CONFIG, status="InProgress"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="InProgress"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        streaming_distribution.add_list_streaming_distributions_one_response(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        goal.execute()

    def test_create_streaming_distribution_idempotent(self):
        goal = self.create_goal("apply")

        uuid4 = self.fixtures.enter_context(mock.patch("uuid.uuid4"))
        uuid4.return_value = CALLER_REFERENCE

        bucket = self.fixtures.enter_context(BucketFixture(goal, self.aws))

        streaming_distribution = self.fixtures.enter_context(
            StreamingDistributionStubber(
                goal.get_service(
                    self.aws.add_streaming_distribution(
                        name="www.example.com", bucket=bucket.bucket
                    ),
                    "apply",
                )
            )
        )

        streaming_distribution.add_list_streaming_distributions_one_response(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        self.assertEqual(len(list(goal.plan())), 0)
        self.assertEqual(len(goal.get_changes(streaming_distribution.resource)), 0)

class TestStreamingDistributionDeletion(aws.StubberTestCase):
    def test_delete_streaming_distribution(self):
        goal = self.create_goal("destroy")

        uuid4 = self.fixtures.enter_context(mock.patch("uuid.uuid4"))
        uuid4.return_value = CALLER_REFERENCE

        bucket = self.fixtures.enter_context(BucketFixture(goal, self.aws))

        streaming_distribution = self.fixtures.enter_context(
            StreamingDistributionStubber(
                goal.get_service(
                    self.aws.add_streaming_distribution(
                        name="www.example.com", bucket=bucket.bucket
                    ),
                    "destroy",
                )
            )
        )

        # Find the existing streaming_distribution
        streaming_distribution.add_list_streaming_distributions_one_response(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        # You have to disable the streaming_distribution before you can delete it
        streaming_distribution.add_update_streaming_distribution(
            streaming_distribution.disable(EXAMPLE_DISTRIBUTION_CONFIG)
        )

        # Wait for the change to be replicated to all edges
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="InProgress"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="InProgress"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        # Refresh metadata after a wait
        streaming_distribution.add_list_streaming_distributions_one_response(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )
        streaming_distribution.add_get_streaming_distribution(
            EXAMPLE_DISTRIBUTION_CONFIG, status="Deployed"
        )

        # Actually delete it
        streaming_distribution.add_delete_streaming_distribution()

        goal.execute()

    def test_delete_streaming_distribution_idempotent(self):
        goal = self.create_goal("destroy")

        streaming_distribution = self.fixtures.enter_context(
            StreamingDistributionStubber(
                goal.get_service(
                    self.aws.add_streaming_distribution(name="www.example.com"),
                    "destroy",
                )
            )
        )

        streaming_distribution.add_list_streaming_distributions_empty_response()

        self.assertEqual(len(list(goal.plan())), 0)
        self.assertEqual(len(goal.get_changes(streaming_distribution.resource)), 0)


text:
#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include <mitkLog.h>
#include <mitkNumericTypes.h>
#include <itkMultiThreader.h>
#include <itksys/SystemTools.hxx>
#include <mitkStandardFileLocations.h>

/** Documentation
 *
 * @brief this class provides an accessible BackendCout to determine whether this backend was
 * used to process a message or not.
 * It is needed for the disable / enable backend test.
 */
class TestBackendCout : public mbilog::BackendCout
{
public:
  TestBackendCout()
  {
    m_Called = false;
    mbilog::BackendCout();
  }

  void ProcessMessage(const mbilog::LogMessage &l)
  {
    m_Called = true;
    mbilog::BackendCout::ProcessMessage(l);
  }

  bool WasCalled()
{
  return m_Called;
}

private:

  bool m_Called;
};
/** Documentation
  *
  * @brief Objects of this class can start an internal thread by calling the Start() method.
  *        The thread is then logging messages until the method Stop() is called. The class
  *        can be used to test if logging is thread-save by using multiple objects and let
  *        them log simuntanously.
  */
class mitkTestLoggingThread : public itk::Object
{
public:

mitkClassMacro(mitkTestLoggingThread,itk::Object);
mitkNewMacro1Param(mitkTestLoggingThread,itk::MultiThreader::Pointer);

int NumberOfMessages;

protected:

mitkTestLoggingThread(itk::MultiThreader::Pointer MultiThreader)
  {
  ThreadID = -1;
  NumberOfMessages = 0;
  m_MultiThreader = MultiThreader;
  }

bool LoggingRunning;

int ThreadID;

itk::MultiThreader::Pointer m_MultiThreader;

void LogMessages()
  {

  while(LoggingRunning)
    {
    MITK_INFO << "Test info stream in thread" << ThreadID << "\n even with newlines";
    MITK_WARN << "Test warning stream in thread " << ThreadID <<". "
              << "Even with a very long text, even without meaning or implied meaning or content, just a long sentence to see whether something has problems with long sentences or output in files or into windows or commandlines or whatever.";
    MITK_DEBUG << "Test debugging stream in thread " << ThreadID;
    MITK_ERROR << "Test error stream in thread " << ThreadID;
    MITK_FATAL << "Test fatal stream in thread " << ThreadID;

    NumberOfMessages += 5;
    }
  }

static ITK_THREAD_RETURN_TYPE ThreadStartTracking(void* pInfoStruct)
  {
  /* extract this pointer from Thread Info structure */
  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (struct itk::MultiThreader::ThreadInfoStruct*)pInfoStruct;
  if (pInfo == NULL)
  {
    return ITK_THREAD_RETURN_VALUE;
  }
  if (pInfo->UserData == NULL)
  {
    return ITK_THREAD_RETURN_VALUE;
  }
  mitkTestLoggingThread *thisthread = (mitkTestLoggingThread*)pInfo->UserData;

  if (thisthread != NULL)
    thisthread->LogMessages();

  return ITK_THREAD_RETURN_VALUE;
  }

public:

int Start()
  {
  LoggingRunning = true;
  this->ThreadID = m_MultiThreader->SpawnThread(this->ThreadStartTracking, this);
  return ThreadID;
  }

void Stop()
  {
  LoggingRunning = false;
  }

};

/** Documentation
 *
 *  @brief This class holds static test methods to sturcture the test of the mitk logging mechanism.
 */
class mitkLogTestClass
{

public:

static void TestSimpleLog()
    {
    bool testSucceded = true;
    try
      {
      MITK_INFO << "Test info stream.";
      MITK_WARN << "Test warning stream.";
      MITK_DEBUG << "Test debugging stream."; //only activated if cmake variable is on!
                                              //so no worries if you see no output for this line
      MITK_ERROR << "Test error stream.";
      MITK_FATAL << "Test fatal stream.";
      }
    catch(mitk::Exception e)
      {
      testSucceded = false;
      }
    MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging streams.");
    }

static void TestObjectInfoLogging()
    {
    bool testSucceded = true;
    try
      {
      int i = 123;
      float f = .32234;
      double d = 123123;
      std::string testString = "testString";
      std::stringstream testStringStream;
      testStringStream << "test" << "String" << "Stream";
      mitk::Point3D testMitkPoint;
      testMitkPoint.Fill(2);

      MITK_INFO << i;
      MITK_INFO << f;
      MITK_INFO << d;
      MITK_INFO << testString;
      MITK_INFO << testStringStream.str();
      MITK_INFO << testMitkPoint;
      }
    catch(mitk::Exception e)
      {
      testSucceded = false;
      }
    MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging of object information.");
    }

static void TestThreadSaveLog(bool toFile)
    {
    bool testSucceded = true;

    try
      {
        if (toFile)
        {
          std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testthreadlog.log";
          itksys::SystemTools::RemoveFile(filename.c_str()); // remove old file, we do not want to append to large files
          mitk::LoggingBackend::SetLogFile(filename.c_str());
        }

        unsigned int numberOfThreads = 20;
        unsigned int threadRuntimeInMilliseconds = 2000;

        std::vector<unsigned int> threadIDs;
        std::vector<mitkTestLoggingThread::Pointer> threads;

        itk::MultiThreader::Pointer multiThreader = itk::MultiThreader::New();
        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)
        {
          //initialize threads...
          mitkTestLoggingThread::Pointer newThread = mitkTestLoggingThread::New(multiThreader);
          threads.push_back(newThread);
          std::cout << "Created " << threadIdx << ". thread." << std::endl;
        }

        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)
        {
          //start them
          std::cout << "Start " << threadIdx << ". thread." << std::endl;
          threadIDs.push_back( threads[threadIdx]->Start() );
          std::cout << threadIdx << ". thread has ID " << threadIDs[threadIdx] << std::endl;
        }

        //wait for some time (milliseconds)
        itksys::SystemTools::Delay( threadRuntimeInMilliseconds );

        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)
        {
          //stop them
          std::cout << "Stop " << threadIdx << ". thread." << std::endl;
          threads[threadIdx]->Stop();
        }

        for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx)
        {
          //Wait for all threads to end
          multiThreader->TerminateThread(threadIDs[threadIdx]);
          std::cout << "Terminated " << threadIdx << ". thread (" << threads[threadIdx]->NumberOfMessages << " messages)." << std::endl;
        }

      }
    catch(std::exception e)
      {
        MITK_ERROR << "exception during 'TestThreadSaveLog': "<<e.what();
        testSucceded = false;
      }
    catch(...)
      {
        MITK_ERROR << "unknown exception during 'TestThreadSaveLog'";
        testSucceded = false;
      }

    //if no error occured until now, everything is ok
    MITK_TEST_CONDITION_REQUIRED(testSucceded,"Test logging in different threads.");
    }

static void TestLoggingToFile()
    {
    std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testlog.log";
    mitk::LoggingBackend::SetLogFile(filename.c_str());
    MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile();
    MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(filename.c_str()),"Testing if log file exists.");
    //TODO delete log file?
    }

static void TestAddAndRemoveBackends()
    {
    mbilog::BackendCout myBackend = mbilog::BackendCout();
    mbilog::RegisterBackend(&myBackend);
    MITK_INFO << "Test logging";
    mbilog::UnregisterBackend(&myBackend);

    //if no error occured until now, everything is ok
    MITK_TEST_CONDITION_REQUIRED(true,"Test add/remove logging backend.");
    }

static void  TestDefaultBackend()
    {
    //not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added to mbilog utility one may add this test.
    }

static void TestEnableDisableBackends()
{
  TestBackendCout myCoutBackend = TestBackendCout();
  mbilog::RegisterBackend(&myCoutBackend);

  mbilog::DisableBackends(mbilog::Console);
  MITK_INFO << "There should be no output!";
  bool success = !myCoutBackend.WasCalled();

  mbilog::EnableBackends(mbilog::Console);
  MITK_INFO << "Now there should be an output.";
  success &= myCoutBackend.WasCalled();

  mbilog::UnregisterBackend(&myCoutBackend);
  MITK_TEST_CONDITION_REQUIRED(success, "Test disable / enable logging backends.")
}

};

int mitkLogTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("Log")

  MITK_TEST_OUTPUT(<<"TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!")

  mitkLogTestClass::TestSimpleLog();
  mitkLogTestClass::TestObjectInfoLogging();

  mitkLogTestClass::TestLoggingToFile();
  mitkLogTestClass::TestAddAndRemoveBackends();
  mitkLogTestClass::TestThreadSaveLog( false ); // false = to console
  mitkLogTestClass::TestThreadSaveLog( true );  // true = to file
  mitkLogTestClass::TestEnableDisableBackends();
  // TODO actually test file somehow?

  // always end with this!
  MITK_TEST_END()
}