text:
from django.db import models
from common.helpers.collections import omit_falsy

# Create your models here.
class Tag(models.Model):
    tag_name = models.CharField(max_length=100, unique=True)
    display_name = models.CharField(max_length=200)
    caption = models.CharField(max_length=500, blank=True)
    category = models.CharField(max_length=200)
    subcategory = models.CharField(max_length=200, blank=True)
    parent = models.CharField(max_length=100, blank=True)

    def __str__(self):
        prefix = self.category
        if self.subcategory:
            prefix += '->' + self.subcategory
        return prefix + '->' + self.tag_name

    class Meta:
        ordering = ["category", "subcategory", "tag_name"]

    @staticmethod
    def get_by_name(name):
        # TODO: Get from in-memory cache
        tag = Tag.objects.filter(tag_name=name).first()
        if tag is None:
            print("ERROR: Could not find tag", name)
        return tag

    @staticmethod
    def from_field(tag_manager_field):
        field_values = tag_manager_field.all().values()
        tag_count = len(field_values)
        if tag_count > 1:
            return list(map(lambda tag: Tag.get_by_name(tag['slug']), field_values))
        elif tag_count == 1:
            return Tag.get_by_name(field_values[0]['slug'])

    @staticmethod
    def hydrate_to_json(project_id, tag_entries):
        # TODO: Use in-memory cache for tags
        # TODO: Remove project id from this if we don't end up using it
        tags = map(lambda tag_slug: Tag.get_by_name(tag_slug['slug']), tag_entries)
        existing_tags = filter(lambda tag: tag is not None, tags)
        hydrated_tags = list(map(lambda tag: Tag.hydrate_tag_model(tag), existing_tags))
        return hydrated_tags

    @staticmethod
    def hydrate_tag_model(tag):
        return {
            'display_name': tag.display_name,
            'tag_name': tag.tag_name,
            'caption': tag.caption,
            'category': tag.category,
            'subcategory': tag.subcategory,
            'parent': tag.parent}

    @staticmethod
    def merge_tags_field(tags_field, tag_entries):
        """
        Merge tag entries into a tag field
        :param tags_field: model tag field
        :param tag_entries: comma-separated string of tag slugs
        :returns True if any changes were made
        """
        tag_entries = tag_entries or ""
        tag_entry_slugs = set(tag_entries.split(',') if tag_entries else [])
        existing_tag_slugs = set(tags_field.slugs())

        tags_to_add = list(tag_entry_slugs - existing_tag_slugs)
        for tag in tags_to_add:
            if len(tag) > 0:
                tags_field.add(tag)

        tags_to_remove = list(existing_tag_slugs - tag_entry_slugs)
        for tag in tags_to_remove:
            if len(tag) > 0:
                tags_field.remove(tag)
        return len(tags_to_add) > 0 or len(tags_to_remove) > 0

    @staticmethod
    def tags_field_descriptions(tags_field):
        """
        :param tags_field: Tag field to pull tag display names from
        :return: Comma-separated list of tag display names
        """
        valid_tags = omit_falsy(list(tags_field.all().values()))
        tag_strings = []
        if valid_tags:
            for tag_data in valid_tags:
                tag = Tag.get_by_name(tag_data['name'])
                if tag:
                    tag_strings.append(tag.display_name)
        return ",".join(tag_strings)

redpajama_set_name: RedPajamaGithub


text:
title:  "Organize seu projeto open-source no Github"
description: Saiba como organizar seu projeto open-source no Github.
date: 2015-11-17
---

Sabemos que no Github temos milhões de projetos open-source, cada um com seu objetivo e sua necessidade, mas eu sinto uma imensa dificuldade em saber, como eu realmente posso contribuir nesse projeto? Pois muitas vezes essas necessidades não estão documentadas em lugar nenhum, deixando possíveis contribuintes a deriva.
Então, para você que tem um projetinho open-source no Github, aqui vai algumas dicas de como organizar o seu projeto e atrair mais contribuidores.

###README
README? SIM, README! Ter um readme organizado ajuda as pessoas a entender o objetivo do seu projeto, então vale a pena você ter um read me que seja grande mas que demonstre o que você quer com o seu projeto. Ok, beleza, mas o que eu devo ter no meu read me então?

Adicione no seu readme tudo que seja relevante para quem for ajudar não fique perdido, alguns bons tópicos a serem colocados são:

intenção do projeto

tech stack

rodar o projeto local

como contribuir

Exemplos de bons readme para serem vistos:

* [Registro Livre](https://github.com/ThoughtWorksInc/registrolivre)
* [FreeCodeCamp](https://github.com/FreeCodeCamp/FreeCodeCamp)
* [Go](https://github.com/golang/go)

Um ponto que deve ser levado em consideração(pelo menos eu levo), se seu readme está grande demais, talvez seja melhor refatorar e criar uma wiki para seu projeto.

####Badges
Outro recurso importante que pode ser adicionado ao seu projeto são badges de ferramentas que seu projeto usa, por exemplo:

* Ferramentas de CI: [Snap](https://snap-ci.com/),[Travis-CI](https://travis-ci.org/)
* Ferramentas de Analise de código: [Code Climate](https://codeclimate.com),[Coveralls](https://coveralls.io),[David-dm](https://david-dm.org/)
* Listas: [Awesome](https://github.com/sindresorhus/awesome)
* Chat: [Gitter](https://gitter.im)
*

###Wiki
Sim, o Github fornece a possibilidade de criar wiki's para o seu projeto, aonde nessa wiki, é colocada informações relevantes sobre o projeto, por exemplo:

como cada componente funciona

como a arquitetura do projeto foi pensada

qual o padrão de nomenclatura do projeto

contribuidores

Básicamente, tudo que não se encaixou no readme e é relevante para o projeto, vai para a wiki. Na wiki tópicos podem ser divididos por páginas o que torna as informações mais visiveis e organizadas, existe uma sessão no github aonde mostra uma lista com vários projeto que usam a wiki de formas bem legais, você pode encontrar [aqui](https://github.com/showcases/projects-with-great-wikis).

###Issues
 O GitHub também provê de uma sessão de cadastro de issues aonde podem ser adicionados labels customizados para defeitos, estórias, bug's e etc.. O uso do issues é muito importante para um colaborador, pois através dele, o colaborador consegue entender qual é a necessidade do projeto atual do projeto e como ele pode contribuir.

 Mas ainda assim, não basta cadastrar a issue, ela tem que ser descrita e sinalizada de forma que o colaborador entenda qual a intenção da issue. Outra forma de utilizar a sessão de issues, é transformar a lista em um board kanban através de ferramentas como o [Tablero](https://github.com/TWtablero/tablero) e o [Waffle](https://waffle.io/).

  ![Board Issues Pixelated](/assets/images/posts/organize_github/Issues_pixelated.png)

 ![Exemplo kanban online com tablero](/assets/images/posts/organize_github/pixelated_tablero.png)


text:
package com.capone.recordvalidation;

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

import org.junit.Assert;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.capone.processes.CompactDecisionTableKieBaseProvider;
import com.capone.processes.DecisionTableKieBaseProvider;
import com.capone.processes.DslKieBaseProvider;
import com.capone.processes.SparseDecisionTableKieBaseProvider;
import com.capone.recordvalidation.csv.CsvFileReader;
import com.capone.recordvalidation.csv.CsvFileWriter;

/**
 * @author asaran
 *
 */
public class RulesTest {
	private static final Logger LOG = LoggerFactory.getLogger(RulesTest.class);
	private static DecisionTableKieBaseProvider dtableManager = new DecisionTableKieBaseProvider();
	private static DslKieBaseProvider dslManager= new DslKieBaseProvider();
	private static SparseDecisionTableKieBaseProvider dtableSparseManager = new SparseDecisionTableKieBaseProvider();
	private static CompactDecisionTableKieBaseProvider dtableCompactManager = new CompactDecisionTableKieBaseProvider();

	/*@Test
	public void testDecisionTableRules() {
		LOG.info("Testing with decision table");
		testRules(dtableManager.getKieBase(), "DSTWithDRL_ResultFile");
	}

	@Test
	public void testDslRules() {
		LOG.info("Testing with DSL");
		testRules(dslManager.getKieBase(), "DSL_ResultFile");
	}*/

	@Test
	public void testSparseDecisionTableRules() {
		LOG.info("Testing with decision table");
		testRules(dtableSparseManager.getKieBase(), "SparseDT_ResultFile");
	}

	@Test
	public void testCompactDecisionTableRules() {
		LOG.info("Testing with decision table");
		testRules(dtableCompactManager.getKieBase(), "CompactDT_ResultFile");
	}

	private void testRules(KieBase kieBase, String outPutFileName) {
		KieSession session = kieBase.newKieSession();
		String fileName = "dataInput1.csv";
		CsvFileReader myreader = new CsvFileReader();

		List<Record> recordList  = new  ArrayList<Record>();
		recordList = myreader.readCsvFile(fileName);

		LOG.info("Read Data from CSV file:");
		for (Record record : recordList) {
			LOG.info(record.toString());
		}

		for (Record r : recordList) {
			session.insert(r);
		}

		session.fireAllRules();

		LOG.info("After firing all rules:");
		/*for (Record record : recordList) {
			Assert.assertTrue("Every record should have an error, this one doesn't : " + record, record.getMessages().size() > 0);
			LOG.info(record.getMessages().toString());
		}*/

		//fileName = outPutFileName;
		CsvFileWriter.writeCsvFile(outPutFileName, recordList);
	}
}


text:
package commands

import (
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"k8s.io/client-go/tools/clientcmd"
)

// AddNamespaceFlags adds the namespace-related flags:
// * --namespace
// * --all-namespaces
func AddNamespaceFlags(flags *pflag.FlagSet, allowAll bool) {
	flags.StringP(
		"namespace",
		"n",
		"",
		"Specify the namespace to operate in.",
	)

	if allowAll {
		flags.BoolP(
			"all-namespaces",
			"A",
			false,
			"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.",
		)
	}
}

// GetNamespace returns namespace from command specified by flag
func (params *KnParams) GetNamespace(cmd *cobra.Command) (string, error) {
	namespace := cmd.Flag("namespace").Value.String()
	// check value of all-namepaces only if its defined
	if cmd.Flags().Lookup("all-namespaces") != nil {
		all, err := cmd.Flags().GetBool("all-namespaces")
		if err != nil {
			return "", err
		} else if all { // if all-namespaces=True
			// namespace = "" <-- all-namespaces representation
			return "", nil
		}
	}
	// if all-namepaces=False or namespace not given, use default namespace
	if namespace == "" {
		var err error
		namespace, err = params.CurrentNamespace()
		if err != nil {
			if !clientcmd.IsEmptyConfig(err) {
				return "", err
			}
			// If no current namespace is set use "default"
			namespace = "default"
		}
	}
	return namespace, nil
}

// CurrentNamespace returns the current namespace which is either provided as option or picked up from kubeconfig
func (params *KnParams) CurrentNamespace() (string, error) {
	var err error
	if params.fixedCurrentNamespace != "" {
		return params.fixedCurrentNamespace, nil
	}
	if params.ClientConfig == nil {
		params.ClientConfig, err = params.GetClientConfig()
		if err != nil {
			return "", err
		}
	}
	name, _, err := params.ClientConfig.Namespace()
	return name, err
}


text:
namespace scudo {

// A common errno setting logic shared by almost all Scudo C wrappers.
inline void *setErrnoOnNull(void *Ptr) {
  if (UNLIKELY(!Ptr))
    errno = ENOMEM;
  return Ptr;
}

// Checks return true on failure.

// Checks aligned_alloc() parameters, verifies that the alignment is a power of
// two and that the size is a multiple of alignment.
inline bool checkAlignedAllocAlignmentAndSize(uptr Alignment, uptr Size) {
  return Alignment == 0 || !isPowerOfTwo(Alignment) ||
         !isAligned(Size, Alignment);
}

// Checks posix_memalign() parameters, verifies that alignment is a power of two
// and a multiple of sizeof(void *).
inline bool checkPosixMemalignAlignment(uptr Alignment) {
  return Alignment == 0 || !isPowerOfTwo(Alignment) ||
         !isAligned(Alignment, sizeof(void *));
}

// Returns true if calloc(Size, N) overflows on Size*N calculation. Use a
// builtin supported by recent clang & GCC if it exists, otherwise fallback to a
// costly division.
inline bool checkForCallocOverflow(uptr Size, uptr N, uptr *Product) {
#if __has_builtin(__builtin_umull_overflow)
  return __builtin_umull_overflow(Size, N, Product);
#else
  *Product = Size * N;
  if (!Size)
    return false;
  return (*Product / Size) != N;
#endif
}

// Returns true if the size passed to pvalloc overflows when rounded to the next
// multiple of PageSize.
inline bool checkForPvallocOverflow(uptr Size, uptr PageSize) {
  return roundUpTo(Size, PageSize) < Size;
}

} // namespace scudo

#endif // SCUDO_CHECKS_H_


text: module.exports.flavor = "nacho cheese"


text: <caption><col><colgroup><tbody><tfoot><thead><tr>


text:
package io.jitstatic.check;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import io.jitstatic.hosted.InputStreamHolder;

public class RepositoryDataError extends FileData {

	public RepositoryDataError(final FileObjectIdStore fileInfo, final InputStreamHolder inputStreamHolder) {
		super(fileInfo, inputStreamHolder);
		Objects.requireNonNull(inputStreamHolder.exception());
	}

	@Override
	public InputStream getInputStream() throws IOException {
		throw getException();
	}

	public FileObjectIdStore getFileObjectIdStore() {
		return getFileInfo();
	}

	public IOException getException() {
	    return getInputStreamHolder().exception();
	}
}


text:
<?php

namespace Storeman\Test\Cli\Command;

use Storeman\Cli\Command\ShowIndexCommand;
use Storeman\Cli\Command\SynchronizeCommand;
use Storeman\Storeman;
use Storeman\Test\TemporaryPathGeneratorProviderTrait;
use Storeman\Test\TestVault;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Tester\CommandTester;

class ShowIndexCommandTest extends AbstractCommandTest
{
    use TemporaryPathGeneratorProviderTrait;

    public function test()
    {
        $vaultPath = $this->getTemporaryPathGenerator()->getTemporaryDirectory();

        $firstConfig = [
            'identity' => 'Someone',
            'vaults' => [
                [
                    'adapter' => 'local',
                    'settings' => [
                        'path' => $vaultPath,
                    ],
                ],
            ],
        ];

        $testVault = new TestVault();
        $testVault->fwrite(Storeman::CONFIG_FILE_NAME, json_encode($firstConfig));

        $showIndexCommandTester = new CommandTester($this->getCommandWithApplication());
        $syncCommandTester = new CommandTester($this->getCommandWithApplication(new SynchronizeCommand()));

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath()]));
        $this->assertContains('not find any past synchronizations', $showIndexCommandTester->getDisplay());

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath(), 'revision' => 'local']));
        $this->assertContains('Empty', $showIndexCommandTester->getDisplay());

        $testVault->touch('file.ext');
        $testVault->mkdir('some dir');

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath(), 'revision' => 'local']));
        $this->assertContains('file.ext', $showIndexCommandTester->getDisplay());
        $this->assertContains('some dir', $showIndexCommandTester->getDisplay());

        $this->assertEquals(0, $syncCommandTester->execute(['-c' => $testVault->getBasePath()]));

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath()]));
        $this->assertContains('file.ext', $showIndexCommandTester->getDisplay());
        $this->assertContains('some dir', $showIndexCommandTester->getDisplay());

        $testVault->touch('new.ext');

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath()]));
        $this->assertNotContains('new.ext', $showIndexCommandTester->getDisplay());

        $this->assertEquals(0, $showIndexCommandTester->execute(['-c' => $testVault->getBasePath(), 'revision' => 'local']));
        $this->assertContains('file.ext', $showIndexCommandTester->getDisplay());
        $this->assertContains('some dir', $showIndexCommandTester->getDisplay());
        $this->assertContains('new.ext', $showIndexCommandTester->getDisplay());
    }

    protected function getCommand(): Command
    {
        return new ShowIndexCommand();
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DiagramaFlujo;

/**
 *
 * @author javier
 */
public enum TipoNodo {

  CONDITION,
  OPERATION,
  START,
  END;

    private int valor;
  @Override
  public String toString() {

    switch (this) {
      case CONDITION:
        return "condition";
      case OPERATION:
        return "operation";
      case START:
        return "start";
      case END:
        return "end";
      default:

        return null;

    }
  }

  public int toInt() {

    switch (this) {
      case CONDITION:
        return 1;
      case OPERATION:
        return 2;
      case START:
        return 3;
      case END:
        return 4;
      default:
        return 0;

    }
  }

  public int getValor(TipoNodo tp) {
    return tp.toInt();
  }

}


text:
package com.koch.ambeth.ioc.util;

import com.koch.ambeth.util.ParamHolder;

public class InterruptingParamHolder extends ParamHolder<Throwable> {
	protected final Thread mainThread;

	public InterruptingParamHolder(Thread mainThread) {
		this.mainThread = mainThread;
	}

	@Override
	public void setValue(Throwable value) {
		super.setValue(value);

		if (value != null) {
			// necessary to inform the main thread that it should not wait any longer for the latch
			mainThread.interrupt();
		}
	}
}


text:
$: << 'lib'

require 'termios'
require 'roku'

def with_unbuffered_input
  old_attrs = Termios.tcgetattr(STDOUT)

  new_attrs = old_attrs.dup

  new_attrs.lflag &= ~Termios::ECHO
  new_attrs.lflag &= ~Termios::ICANON

  Termios::tcsetattr(STDOUT, Termios::TCSANOW, new_attrs)

  yield
ensure
  Termios::tcsetattr(STDOUT, Termios::TCSANOW, old_attrs)
end

if ARGV[0].nil?
  puts "Found servers:"
  Roku::Server.search.each do |server|
    puts " #{server.url}"
  end
  exit 0
end

roku = Roku::Server.new(ARGV[0])

unless roku.valid?
  puts "That doesn't look like a roku player."
  exit 1
end

require "highline/system_extensions"
include HighLine::SystemExtensions

puts "Ready."
with_unbuffered_input do
  loop do
    press = STDIN.getc

    if press == "\e"
      begin
        Timeout::timeout(0.1) do
          press += STDIN.getc
          press += STDIN.getc
        end
      rescue Timeout::Error
      end
    end

    case press
    when "\e[A"
      roku.up
    when "\e[B"
      roku.down
    when "\e[C"
      roku.right
    when "\e[D"
      roku.left
    when "\n"
      roku.select
    when "\e"
      roku.back
    when " "
      roku.play
    else
      roku.send "letter_#{press}"
    end
  end
end


text:
import os
import itertools
import gridfs
import datetime

from django.utils.datastructures import SortedDict

from django.forms.forms import BaseForm, get_declared_fields, NON_FIELD_ERRORS, pretty_name
from django.forms.widgets import media_property
from django.core.exceptions import FieldError
from django.core.validators import EMPTY_VALUES
from django.forms.util import ErrorList
from django.forms.formsets import BaseFormSet, formset_factory
from django.utils.translation import ugettext_lazy as _
from django.utils.text import capfirst

from mongoengine.fields import ObjectIdField, ListField, ReferenceField, FileField, ImageField
from mongoengine.base import ValidationError
from mongoengine.connection import _get_db

from .field_generator import MongoFormFieldGenerator
from .document_options import DocumentMetaWrapper

def _get_unique_filename(name):
    fs = gridfs.GridFS(_get_db())
    file_root, file_ext = os.path.splitext(name)
    count = itertools.count(1)
    while fs.exists(filename=name):
        # file_ext includes the dot.
        name = os.path.join("%s_%s%s" % (file_root, count.next(), file_ext))
    return name

def construct_instance(form, instance, fields=None, exclude=None, ignore=None):
    """
    Constructs and returns a document instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    """
    cleaned_data = form.cleaned_data
    file_field_list = []

    # check wether object is instantiated
    if isinstance(instance, type):
        instance = instance()

    for f in instance._fields.itervalues():
        if isinstance(f, ObjectIdField):
            continue
        if not f.name in cleaned_data:
            continue
        if fields is not None and f.name not in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if f.primary_key and cleaned_data[f.name] == getattr(instance, f.name):
            continue

        # Defer saving file-type fields until after the other fields, so a
        # callable upload_to can use the values from other fields.
        if isinstance(f, FileField) or isinstance(f, ImageField):
            file_field_list.append(f)
        else:
            setattr(instance, f.name, cleaned_data[f.name])

    for f in file_field_list:
        upload = cleaned_data[f.name]
        if upload is None:
            continue
        field = getattr(instance, f.name)
        try:
            upload.file.seek(0)
            filename = _get_unique_filename(upload.name)
            field.replace(upload, content_type=upload.content_type, filename=filename)
            setattr(instance, f.name, field)
        except AttributeError:
            # file was already uploaded and not changed during edit.
            # upload is already the gridfsproxy object we need.
            upload.get()
            setattr(instance, f.name, upload)

    return instance

def save_instance(form, instance, fields=None, fail_message='saved',
                  commit=True, exclude=None, construct=True):
    """
    Saves bound Form ``form``'s cleaned_data into document instance ``instance``.

    If commit=True, then the changes to ``instance`` will be saved to the
    database. Returns ``instance``.

    If construct=False, assume ``instance`` has already been constructed and
    just needs to be saved.
    """
    instance = construct_instance(form, instance, fields, exclude)
    if form.errors:
        raise ValueError("The %s could not be %s because the data didn't"
                         " validate." % (instance.__class__.__name__,
                                         fail_message))

    if commit and hasattr(instance, 'save'):
        # see BaseDocumentForm._post_clean for an explanation
        if hasattr(form, '_delete_before_save'):
            fields = instance._fields
            new_fields = dict([(n, f) for n, f in fields.iteritems()
                                if not n in form._delete_before_save])
            if hasattr(instance, '_changed_fields'):
                for field in form._delete_before_save:
                    instance._changed_fields.remove(field)
            instance._fields = new_fields
            instance.save()
            instance._fields = fields
        else:
            instance.save()

    return instance

def document_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    """
    data = {}
    for f in instance._fields.itervalues():
        if fields and not f.name in fields:
            continue
        if exclude and f.name in exclude:
            continue
        else:
            data[f.name] = getattr(instance, f.name)
    return data

def fields_for_document(document, fields=None, exclude=None, widgets=None,
                        formfield_callback=None,
                        field_generator=MongoFormFieldGenerator):
    """
    Returns a ``SortedDict`` containing form fields for the given model.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned fields.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned fields, even if they are listed
    in the ``fields`` argument.
    """
    field_list = []
    ignored = []
    if isinstance(field_generator, type):
        field_generator = field_generator()

    sorted_fields = sorted(document._fields.values(),
                           key=lambda field: field.creation_counter)

    for f in sorted_fields:
        if isinstance(f, ObjectIdField):
            continue
        if isinstance(f, ListField) and not (f.field.choices or isinstance(f.field, ReferenceField)):
            continue
        if fields is not None and not f.name in fields:
            continue
        if exclude and f.name in exclude:
            continue
        if widgets and f.name in widgets:
            kwargs = {'widget': widgets[f.name]}
        else:
            kwargs = {}

        if formfield_callback is None:
            form_field = field_generator.generate(f, **kwargs)
        elif not callable(formfield_callback):
            raise TypeError('formfield_callback must be a function or callable')
        else:
            form_field = formfield_callback(f, **kwargs)

        if form_field:
            field_list.append((f.name, form_field))
        else:
            ignored.append(f.name)

    field_dict = SortedDict(field_list)
    if fields:
        field_dict = SortedDict(
            [(f, field_dict.get(f)) for f in fields
                if ((not exclude) or (exclude and f not in exclude)) and (f not in ignored)]
        )
    return field_dict

class DocumentFormOptions(object):
    def __init__(self, options=None):
        self.document = getattr(options, 'document', None)
        self.model = self.document
        # set up the document meta wrapper if document meta is a dict
        if self.document is not None:
            if not hasattr(self.document, '_meta'):
                self.document._meta = {}
            if isinstance(self.document._meta, dict):
                self.document._meta = DocumentMetaWrapper(self.document)
                self.document._admin_opts = self.document._meta
        self.fields = getattr(options, 'fields', None)
        self.exclude = getattr(options, 'exclude', None)
        self.widgets = getattr(options, 'widgets', None)
        self.embedded_field = getattr(options, 'embedded_field_name', None)
        self.formfield_generator = getattr(options, 'formfield_generator', MongoFormFieldGenerator)

class DocumentFormMetaclass(type):
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.pop('formfield_callback', None)
        try:
            parents = [b for b in bases if issubclass(b, DocumentForm) or issubclass(b, EmbeddedDocumentForm)]
        except NameError:
            # We are defining DocumentForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super(DocumentFormMetaclass, cls).__new__(cls, name, bases, attrs)
        if not parents:
            return new_class

        if 'media' not in attrs:
            new_class.media = media_property(new_class)

        opts = new_class._meta = DocumentFormOptions(getattr(new_class, 'Meta', None))
        if opts.document:
            formfield_generator = getattr(opts, 'formfield_generator', MongoFormFieldGenerator)

            # If a model is defined, extract form fields from it.
            fields = fields_for_document(opts.document, opts.fields,
                            opts.exclude, opts.widgets, formfield_callback, formfield_generator)
            # make sure opts.fields doesn't specify an invalid field
            none_document_fields = [k for k, v in fields.iteritems() if not v]
            missing_fields = set(none_document_fields) - \
                             set(declared_fields.keys())
            if missing_fields:
                message = 'Unknown field(s) (%s) specified for %s'
                message = message % (', '.join(missing_fields),
                                     opts.model.__name__)
                raise FieldError(message)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields

        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class

class BaseDocumentForm(BaseForm):
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):

        opts = self._meta

        if instance is None:
            if opts.document is None:
                raise ValueError('DocumentForm has no document class specified.')
            # if we didn't get an instance, instantiate a new one
            self.instance = opts.document
            object_data = {}
        else:
            self.instance = instance
            object_data = document_to_dict(instance, opts.fields, opts.exclude)

        # if initial was provided, it should override the values from instance
        if initial is not None:
            object_data.update(initial)

        # self._validate_unique will be set to True by BaseModelForm.clean().
        # It is False by default so overriding self.clean() and failing to call
        # super will stop validate_unique from being called.
        self._validate_unique = False
        super(BaseDocumentForm, self).__init__(data, files, auto_id, prefix, object_data,
                                            error_class, label_suffix, empty_permitted)

    def _update_errors(self, message_dict):
        for k, v in message_dict.items():
            if k != NON_FIELD_ERRORS:
                self._errors.setdefault(k, self.error_class()).extend(v)
                # Remove the data from the cleaned_data dict since it was invalid
                if k in self.cleaned_data:
                    del self.cleaned_data[k]
        if NON_FIELD_ERRORS in message_dict:
            messages = message_dict[NON_FIELD_ERRORS]
            self._errors.setdefault(NON_FIELD_ERRORS, self.error_class()).extend(messages)

    def _get_validation_exclusions(self):
        """
        For backwards-compatibility, several types of fields need to be
        excluded from model validation. See the following tickets for
        details: #12507, #12521, #12553
        """
        exclude = []
        # Build up a list of fields that should be excluded from model field
        # validation and unique checks.
        for f in self.instance._fields.itervalues():
            field = f.name
            # Exclude fields that aren't on the form. The developer may be
            # adding these values to the model after form validation.
            if field not in self.fields:
                exclude.append(f.name)

            # Don't perform model validation on fields that were defined
            # manually on the form and excluded via the ModelForm's Meta
            # class. See #12901.
            elif self._meta.fields and field not in self._meta.fields:
                exclude.append(f.name)
            elif self._meta.exclude and field in self._meta.exclude:
                exclude.append(f.name)

            # Exclude fields that failed form validation. There's no need for
            # the model fields to validate them as well.
            elif field in self._errors.keys():
                exclude.append(f.name)

            # Exclude empty fields that are not required by the form, if the
            # underlying model field is required. This keeps the model field
            # from raising a required error. Note: don't exclude the field from
            # validaton if the model field allows blanks. If it does, the blank
            # value may be included in a unique check, so cannot be excluded
            # from validation.
            else:
                field_value = self.cleaned_data.get(field, None)
                if not f.required and field_value in EMPTY_VALUES:
                    exclude.append(f.name)
        return exclude

    def clean(self):
        self._validate_unique = True
        return self.cleaned_data

    def validate_unique(self):
        """
        Validates unique constrains on the document.
        unique_with is not checked at the moment.
        """
        errors = []
        exclude = self._get_validation_exclusions()
        for f in self.instance._fields.itervalues():
            if f.unique and f.name not in exclude:
                filter_kwargs = {
                    f.name: getattr(self.instance, f.name)
                }
                qs = self.instance.__class__.objects().filter(**filter_kwargs)
                # Exclude the current object from the query if we are editing an
                # instance (as opposed to creating a new one)
                if self.instance.pk is not None:
                    qs = qs.filter(pk__ne=self.instance.pk)
                if len(qs) > 0:
                    message = _("%(model_name)s with this %(field_label)s already exists.") % {
                                'model_name': unicode(capfirst(self.instance._meta.verbose_name)),
                                'field_label': unicode(pretty_name(f.name))
                    }
                    err_dict = {f.name: [message]}
                    self._update_errors(err_dict)
                    errors.append(err_dict)

        return errors

    def save(self, commit=True):
        """
        Saves this ``form``'s cleaned_data into model instance
        ``self.instance``.

        If commit=True, then the changes to ``instance`` will be saved to the
        database. Returns ``instance``.
        """

        try:
            if self.instance.pk is None:
                fail_message = 'created'
            else:
                fail_message = 'changed'
        except (KeyError, AttributeError):
            fail_message = 'embedded document saved'

        if self.errors:
            raise ValueError("The %s could not be %s because the data didn't"
                             " validate." % (self.instance.__class__.__name__, fail_message))

        if self.instance._created:
            self.instance = construct_instance(self, self.instance, self.fields, self._meta.exclude)

            # Validate uniqueness if needed.
            if self._validate_unique:
                self.validate_unique()

            if commit:
                self.instance.save()
        else:
            update = {}
            for name, data in self.cleaned_data.iteritems():

                try:
                    if isinstance(data, datetime.datetime):
                        data = data.replace(tzinfo=None)
                    if getattr(self.instance, name) != data:
                        update['set__' + name] = data
                        setattr(self.instance, name, data)
                except AttributeError:
                    raise Exception('Model %s has not attr %s but form %s has' \
                                    % (type(self.instance),
                                      name,
                                      type(self)))

            # Validate uniqueness if needed.
            if self._validate_unique:
                self.validate_unique()

            if commit and update:
                self.instance.update(**update)
        return self.instance
    save.alters_data = True

class DocumentForm(BaseDocumentForm):
    __metaclass__ = DocumentFormMetaclass

def documentform_factory(document, form=DocumentForm, fields=None,
                         exclude=None, formfield_callback=None):
    # Build up a list of attributes that the Meta object will have.
    attrs = {'document': document, 'model': document}
    if fields is not None:
        attrs['fields'] = fields
    if exclude is not None:
        attrs['exclude'] = exclude

    # If parent form class already has an inner Meta, the Meta we're
    # creating needs to inherit from the parent's inner meta.
    parent = (object,)
    if hasattr(form, 'Meta'):
        parent = (form.Meta, object)
    Meta = type('Meta', parent, attrs)

    # Give this new form class a reasonable name.
    if isinstance(document, type):
        doc_inst = document()
    else:
        doc_inst = document
    class_name = doc_inst.__class__.__name__ + 'Form'

    # Class attributes for the new form class.
    form_class_attrs = {
        'Meta': Meta,
        'formfield_callback': formfield_callback
    }

    return DocumentFormMetaclass(class_name, (form,), form_class_attrs)

class EmbeddedDocumentForm(BaseDocumentForm):
    __metaclass__ = DocumentFormMetaclass

    def __init__(self, parent_document, *args, **kwargs):
        super(EmbeddedDocumentForm, self).__init__(*args, **kwargs)
        self.parent_document = parent_document
        if self._meta.embedded_field is not None and \
                not hasattr(self.parent_document, self._meta.embedded_field):
            raise FieldError("Parent document must have field %s" % self._meta.embedded_field)

    def save(self, commit=True):
        if self.errors:
            raise ValueError("The %s could not be saved because the data didn't"
                         " validate." % self.instance.__class__.__name__)

        if commit:
            instance = construct_instance(self, self.instance, self.fields, self._meta.exclude)
            l = getattr(self.parent_document, self._meta.embedded_field)
            l.append(instance)
            setattr(self.parent_document, self._meta.embedded_field, l)
            self.parent_document.save()

        return self.instance

class BaseDocumentFormSet(BaseFormSet):
    """
    A ``FormSet`` for editing a queryset and/or adding new objects to it.
    """

    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 queryset=None, **kwargs):
        self.queryset = queryset
        self._queryset = self.queryset
        self.initial = self.construct_initial()
        defaults = {'data': data, 'files': files, 'auto_id': auto_id,
                    'prefix': prefix, 'initial': self.initial}
        defaults.update(kwargs)
        super(BaseDocumentFormSet, self).__init__(**defaults)

    def construct_initial(self):
        initial = []
        try:
            for d in self.get_queryset():
                initial.append(document_to_dict(d))
        except TypeError:
            pass
        return initial

    def initial_form_count(self):
        """Returns the number of forms that are required in this FormSet."""
        if not (self.data or self.files):
            return len(self.get_queryset())
        return super(BaseDocumentFormSet, self).initial_form_count()

    def get_queryset(self):
        return self._queryset

    def save_object(self, form):
        obj = form.save(commit=False)
        return obj

    def save(self, commit=True):
        """
        Saves model instances for every form, adding and changing instances
        as necessary, and returns the list of instances.
        """
        saved = []
        for form in self.forms:
            if not form.has_changed() and not form in self.initial_forms:
                continue
            obj = self.save_object(form)

            if form in self.deleted_forms:
                try:
                    obj.delete()
                except AttributeError:
                    # if it has no delete method it is an
                    # embedded object. We just don't add to the list
                    # and it's gone. Cook huh?
                    continue
            saved.append(obj)
        return saved

    def clean(self):
        self.validate_unique()

    def validate_unique(self):
        errors = []
        for form in self.forms:
            if not hasattr(form, 'cleaned_data'):
                continue
            errors += form.validate_unique()

        if errors:
            raise ValidationError(errors)

    def get_date_error_message(self, date_check):
        return _("Please correct the duplicate data for %(field_name)s "
            "which must be unique for the %(lookup)s in %(date_field)s.") % {
            'field_name': date_check[2],
            'date_field': date_check[3],
            'lookup': unicode(date_check[1]),
        }

    def get_form_error(self):
        return _("Please correct the duplicate values below.")

def documentformset_factory(document, form=DocumentForm, formfield_callback=None,
                         formset=BaseDocumentFormSet,
                         extra=1, can_delete=False, can_order=False,
                         max_num=None, fields=None, exclude=None):
    """
    Returns a FormSet class for the given Django model class.
    """
    form = documentform_factory(document, form=form, fields=fields, exclude=exclude,
                             formfield_callback=formfield_callback)
    FormSet = formset_factory(form, formset, extra=extra, max_num=max_num,
                              can_order=can_order, can_delete=can_delete)
    FormSet.model = document
    FormSet.document = document
    return FormSet

class BaseInlineDocumentFormSet(BaseDocumentFormSet):
    """
    A formset for child objects related to a parent.

    self.instance -> the document containing the inline objects
    """
    def __init__(self, data=None, files=None, instance=None,
                 save_as_new=False, prefix=None, queryset=[], **kwargs):
        self.instance = instance
        self.save_as_new = save_as_new

        super(BaseInlineDocumentFormSet, self).__init__(data, files, prefix=prefix, queryset=queryset, **kwargs)

    def initial_form_count(self):
        if self.save_as_new:
            return 0
        return super(BaseInlineDocumentFormSet, self).initial_form_count()

    #@classmethod
    def get_default_prefix(cls):
        return cls.model.__name__.lower()
    get_default_prefix = classmethod(get_default_prefix)

    def add_fields(self, form, index):
        super(BaseInlineDocumentFormSet, self).add_fields(form, index)

        # Add the generated field to form._meta.fields if it's defined to make
        # sure validation isn't skipped on that field.
        if form._meta.fields:
            if isinstance(form._meta.fields, tuple):
                form._meta.fields = list(form._meta.fields)
            #form._meta.fields.append(self.fk.name)

    def get_unique_error_message(self, unique_check):
        unique_check = [field for field in unique_check if field != self.fk.name]
        return super(BaseInlineDocumentFormSet, self).get_unique_error_message(unique_check)

def inlineformset_factory(document, form=DocumentForm,
                          formset=BaseInlineDocumentFormSet,
                          fields=None, exclude=None,
                          extra=1, can_order=False, can_delete=True, max_num=None,
                          formfield_callback=None):
    """
    Returns an ``InlineFormSet`` for the given kwargs.

    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    """
    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': formset,
        'extra': extra,
        'can_delete': can_delete,
        'can_order': can_order,
        'fields': fields,
        'exclude': exclude,
        'max_num': max_num,
    }
    FormSet = documentformset_factory(document, **kwargs)
    return FormSet

class EmbeddedDocumentFormSet(BaseInlineDocumentFormSet):
    def __init__(self, parent_document=None, data=None, files=None, instance=None,
                 save_as_new=False, prefix=None, queryset=[], **kwargs):
        self.parent_document = parent_document
        super(EmbeddedDocumentFormSet, self).__init__(data, files, instance, save_as_new, prefix, queryset, **kwargs)

    def _construct_form(self, i, **kwargs):
        defaults = {'parent_document': self.parent_document}
        defaults.update(kwargs)
        form = super(BaseDocumentFormSet, self)._construct_form(i, **defaults)
        return form

def embeddedformset_factory(document, parent_document, form=EmbeddedDocumentForm,
                          formset=EmbeddedDocumentFormSet,
                          fields=None, exclude=None,
                          extra=1, can_order=False, can_delete=True, max_num=None,
                          formfield_callback=None):
    """
    Returns an ``InlineFormSet`` for the given kwargs.

    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    """
    kwargs = {
        'form': form,
        'formfield_callback': formfield_callback,
        'formset': formset,
        'extra': extra,
        'can_delete': can_delete,
        'can_order': can_order,
        'fields': fields,
        'exclude': exclude,
        'max_num': max_num,
    }
    FormSet = inlineformset_factory(document, **kwargs)
    FormSet.parent_document = parent_document
    return FormSet


text:
package de.uulm.graphicalpasswords.openmiba;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import de.uulm.graphicalpasswords.R;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MIBALoginActivity extends Activity {

	private String password;

	// amount of booleans of one entry
	// one for each rectangle and one for shift
	public final static int INPUTLENGTH = 9;

	private TableLayout tableLayout;
	// private LinearLayout linlBottom;
	private LinearLayout linlGrid[][];
	private Button btnBack;
	private TextView tvRound;

	private static String LOG_TAG = "LoginActivity";
	private int width;
	private int height;
	private TouchListener touchlistener;

	int[][] colors_off = { { 0x3C000000, 0x3C000000, 0x3C000000, 0x3C000000 },
			{ 0x3C000000, 0x3C000000, 0x3C000000, 0x3C000000 } };

	boolean firsttime = false;
	public int min_rounds = 2;
	public int current_round = 1;
	public int rounds_to_do = 2;

	private boolean longpress = false;

	private ArrayList<Boolean> input = new ArrayList<Boolean>();
	private ImageIndexTable imgidxtable = new ImageIndexTable();

	private Handler handler = new MIBALoginHandler(
			new WeakReference<MIBALoginActivity>(this));

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		// WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.activity_miba_login);

		// Show the Up button in the action bar.
		setupActionBar();

		SharedPreferences sharedPref = PreferenceManager
				.getDefaultSharedPreferences(this);
		rounds_to_do = Integer.parseInt(sharedPref
				.getString("miba_length", "1"));
		min_rounds = rounds_to_do;
		password = sharedPref.getString("miba_pw", "");

		setViews();
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.miba_login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void setViews() {
		tableLayout = (TableLayout) findViewById(R.id.tableLayout);
		btnBack = (Button) findViewById(R.id.miba_btnBack);
		btnBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				back();
			}
		});

		tvRound = (TextView) this.findViewById(R.id.tvRound);
		tvRound.setText(getString(R.string.label_round) + " 1");

		linlGrid = new LinearLayout[2][4];
		linlGrid[0][0] = (LinearLayout) this.findViewById(R.id.square1);
		linlGrid[1][0] = (LinearLayout) this.findViewById(R.id.square2);
		linlGrid[0][1] = (LinearLayout) this.findViewById(R.id.square3);
		linlGrid[1][1] = (LinearLayout) this.findViewById(R.id.square4);
		linlGrid[0][2] = (LinearLayout) this.findViewById(R.id.square5);
		linlGrid[1][2] = (LinearLayout) this.findViewById(R.id.square6);
		linlGrid[0][3] = (LinearLayout) this.findViewById(R.id.square7);
		linlGrid[1][3] = (LinearLayout) this.findViewById(R.id.square8);

		for (int y = 0; y < 4; y++) {
			for (int x = 0; x < 2; x++) {
				linlGrid[x][y].setBackgroundColor(colors_off[x][y]);
			}

		}

		// get width and height from mainpanel
		// can not use display width/height because of notification bar
		ViewTreeObserver vto = tableLayout.getViewTreeObserver();
		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {

				// get values of portrait mode

				Display display = getWindowManager().getDefaultDisplay();

				if (display.getRotation() == Surface.ROTATION_0) {
					width = tableLayout.getWidth();
					height = tableLayout.getHeight();
				} else {
					height = tableLayout.getWidth();
					width = tableLayout.getHeight();
				}

				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.ccp000);
				bmp = Bitmap.createScaledBitmap(bmp, width, height, true);
				Drawable d = new BitmapDrawable(getResources(), bmp);
				bmp = null; // prevent outofmemor
				tableLayout.setBackgroundDrawable(d);

				touchlistener = new TouchListener(linlGrid, width, height,
						handler);
				tableLayout.setOnTouchListener(touchlistener);
				// remove listener again otherwise it gets called twice
				tableLayout.getViewTreeObserver().removeGlobalOnLayoutListener(
						this);
			}
		});
	}

	private void back() {
		// last state
		boolean isshift = touchlistener.getLastState();

		// not two long presses in sequence
		// remove last state and return the state of the last but one state
		boolean vorletztzerisshift = touchlistener.reset();

		// adapt round count
		if (!isshift) { // normal click
			if (current_round > 1)
				current_round--;
			if (vorletztzerisshift) { // back to shift screen
				tvRound.setText(getString(R.string.label_round) + " "
						+ current_round + " -Shift-");
			} else { // decrease round
				tvRound.setText(getString(R.string.label_round) + " "
						+ current_round);
			}

		} else { // shift -> do not decrease round, show current round
			tvRound.setText(getString(R.string.label_round) + " "
					+ current_round);
		}

		if (input.size() >= INPUTLENGTH)
			// input: 8 rectangles + 1 shift enabled flag
			for (int i = 0; i < INPUTLENGTH; i++) {
				input.remove(input.size() - 1);
			}

		// enable last index
		// if user inserts the same gesture -> show same picture again
		imgidxtable.removeLastIndex();

		// ... and show previous background image
		int idx = getImageIndex();
		changeBackground(idx);
	}

	/**
	 * Returns the index of the next background image depending on the previous
	 * user input
	 *
	 * @return
	 */
	public int getImageIndex() {
		if (input.size() < INPUTLENGTH)
			return -1;

		int res = 0;

		for (int i = 0; i < INPUTLENGTH; i++) {
			boolean a = input.get(input.size() - INPUTLENGTH + i); // least
																	// significant
																	// bit
																	// first
			res = res << 1;
			res = res + boolToInt(a);
		}
		res = imgidxtable.getIndex(res);
		Log.i(LOG_TAG, "this entry lead to imageindex " + res);
		return res;
	}

	public void changeBackground(int imageindex) {
		int img = 0;
		if (imageindex == -1) {
			img = R.drawable.ccp000;
		} else
			img = R.drawable.ccp001 + imageindex;

		Bitmap bmp = BitmapFactory.decodeResource(getResources(), img);
		bmp = Bitmap.createScaledBitmap(bmp, width, height, true);

		Drawable d = new BitmapDrawable(getResources(), bmp);
		bmp = null; // prevent outofmemory
		tableLayout.setBackgroundDrawable(d);

	}

	public int boolToInt(boolean b) {
		if (b)
			return 1;
		return 0;
	}

	public void checkIfFinished() {
		if (current_round == min_rounds + 1) {
			tableLayout.setOnClickListener(null);

			DialogFragment dialog;
			if (buildPasswordString().equals(password)) {
				dialog = new ResultOKDialog();
			} else {
				dialog = new WrongResultDialog();
			}
			dialog.show(getFragmentManager(), "result");
		}
	}

	/**
	 * Transforms the user input to a passwordstring. This string may contain
	 * unprintable ASCII Codes.
	 *
	 * @return
	 */
	public String buildPasswordString() {
		String res = "";

		for (int i = 0; i < input.size(); i++) {
			if (input.get(i)) {
				res += "1";
			} else {
				res += "0";
			}

		}
		return res;
	}

	public static class ResultOKDialog extends DialogFragment {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(R.string.msg_pw_correct).setNeutralButton(
					R.string.btn_ok, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
							getActivity().finish();
						}
					});
			return builder.create();
		}
	}

	public static class WrongResultDialog extends DialogFragment {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(R.string.msg_pw_wrong).setNeutralButton(
					R.string.btn_ok, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
							getActivity().finish();
						}
					});
			return builder.create();
		}
	}

	private static class MIBALoginHandler extends Handler {
		MIBALoginActivity activity;

		private MIBALoginHandler(WeakReference<MIBALoginActivity> instance) {
			activity = instance.get();
		}

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case TouchListener.MSG_ROUND_FINISHED: {
				activity.longpress = false;

				boolean[][] active = (boolean[][]) msg.obj;
				for (int y1 = 0; y1 < 4; y1++) {
					for (int x1 = 0; x1 < 2; x1++) {
						if (active[x1][y1] == true) {
							Log.i(LOG_TAG, "Rec x" + x1 + " y" + y1
									+ " is activated");
						}
						activity.input.add(active[x1][y1]);
					}
				}
				activity.input.add(false); // not shifted

				activity.current_round++;
				activity.tvRound.setText(activity
						.getString(R.string.label_round)
						+ " "
						+ activity.current_round);

				// show next image
				int idx = activity.getImageIndex();
				activity.changeBackground(idx);

				activity.checkIfFinished();
				break;
			}
			case TouchListener.MSG_SHIFT_ROUND_FINISHED: {
				Vibrator v = (Vibrator) activity
						.getSystemService(Context.VIBRATOR_SERVICE);

				// 1. Vibrate for 300 milliseconds
				long milliseconds = 300;
				v.vibrate(milliseconds);

				activity.tvRound.setText(activity
						.getString(R.string.label_round)
						+ " "
						+ activity.current_round + " -Shift-");
				activity.longpress = true;

				boolean[][] shifted = (boolean[][]) msg.obj;

				for (int y1 = 0; y1 < 4; y1++) {
					for (int x1 = 0; x1 < 2; x1++) {
						if (shifted[x1][y1] == true) {
							Log.i(LOG_TAG, "Rec x" + x1 + " y" + y1
									+ " was shifted");

						}
						activity.input.add(shifted[x1][y1]);
					}
				}
				activity.input.add(true); // shifted true

				// show next image
				int idx = activity.getImageIndex();
				activity.changeBackground(idx);
				activity.checkIfFinished();
				break;
			}
			}

		}
	}
}


text:
'use strict';

var util = require('util');
var path = require('path');

module.exports = function(grunt) {

  return function globFiles(src, dest, extras) {
    // find the first instance of a wildcard
    // TODO: This isn't robust - it wouldn't properly handle something like "js/test_*.js". But it's good enough for now.
    var globIndex = src.indexOf('*');
    var config = { expand: true };

    if (globIndex === -1) {
      throw new Error("bacon.globFiles() expects src to contain a glob pattern or wildcard");
    }

    config.cwd = src.slice(0, globIndex);
    config.src = src.slice(globIndex);
    config.dest = dest;

    if (extras) {
      // Handle exclusions
      if (extras.exclude) {
        var exclude = extras.exclude;
        if (!util.isArray(exclude)) {
          exclude = [exclude];
        }
        delete extras.exclude;
        config.src = [config.src].concat(exclude.map(function(pattern) {
          return '!' + path.relative(config.cwd, pattern);
        }));
      }

      Object.keys(extras).forEach(function(k) {
        config[k] = extras[k];
      });
    }

    return config;
  };

};


text:
package com.twitter.finagle.http.service

import com.twitter.finagle.http.filter.HttpNackFilter
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.service.{ReqRep, ResponseClass, ResponseClassifier}
import com.twitter.util.{Return, Try}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class HttpResponseClassifierTest extends FunSuite {
  private val req = Request()
  private def rep(code: Status): Try[Response] = Return(Response(code))

  test("ServerErrorsAsFailures") {
    val classifier = HttpResponseClassifier.ServerErrorsAsFailures
    assert("ServerErrorsAsFailures" == classifier.toString)

    assert(ResponseClass.NonRetryableFailure ==
      classifier(ReqRep(req, rep(Status.InternalServerError))))

    assert(!classifier.isDefinedAt(ReqRep(req, rep(Status.Ok))))
    assert(ResponseClass.NonRetryableFailure ==
      classifier.applyOrElse(
        ReqRep(req, rep(Status.InternalServerError)),
        ResponseClassifier.Default)
    )
  }

  test("ServerErrorsAsFailures for nacks") {
    val classifier = HttpResponseClassifier.ServerErrorsAsFailures
    val reply = Response(HttpNackFilter.ResponseStatus)
    reply.headerMap.set(HttpNackFilter.RetryableNackHeader, "true")

    assert(ResponseClass.RetryableFailure == classifier(ReqRep(req, Return(reply))))
  }

  test("apply") {
    val ok500 = HttpResponseClassifier {
      case (_, rep: Response) if rep.statusCode == 500 => ResponseClass.Success
    }
    val badReqs = HttpResponseClassifier {
      case (req: Request, _) if req.containsParam("fail") => ResponseClass.NonRetryableFailure
    }
    val classifier = ok500.orElse(badReqs)

    assert(ResponseClass.Success == classifier(ReqRep(req, rep(Status.fromCode(500)))))
    assert(ResponseClass.NonRetryableFailure ==
      classifier(ReqRep(Request("fail" -> "1"), rep(Status.Ok))))

    assert(!classifier.isDefinedAt(ReqRep(req, rep(Status.Ok))))
    assert(ResponseClass.Success ==
      classifier.applyOrElse(
        ReqRep(req, rep(Status.Ok)),
        ResponseClassifier.Default)
    )
  }

}


text:
<?php
	include_once "db.php";
	$idd = mysql_fetch_array(mysql_query("SELECT id FROM photos ORDER BY id DESC"));
	$id = $idd[0] + 1;

	//error_reporting(0);
for($i=0;$_FILES["upload_file"]["name"][$i]==true;$i++)
{

$fileName = $_FILES["upload_file"]["name"][$i]; // The file name
$fileTmpLoc = $_FILES["upload_file"]["tmp_name"][$i]; // File in the PHP tmp folder
$fileType = @$_FILES["upload_file"]["image/png||image/jpg"][$i];  // The type of file it is
$fileSize = $_FILES["upload_file"]["size"][$i]; // File size in bytes
$fileErrorMsg = $_FILES["upload_file"]["error"][$i]; // 0 = false | 1 = true
$kaboom = explode(".",$_FILES["upload_file"]["name"][$i]); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension

$moveResult= move_uploaded_file($fileTmpLoc, "photos/$fileName");
	mysql_query("INSERT INTO photos VALUES ($id, '$fileName', 3)");
	$id++;

unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
}
header("Location: $_SERVER[HTTP_REFERER]");
?>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: ModelStatistics</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>

OR-Tools
    9.4

Public Member Functions |
List of all members

ModelStatistics

Detailed Description

Definition at line 417 of file flatzinc/model.h.

Public Member Functions

 	ModelStatistics (const Model &model, SolverLogger *logger)

int 	NumVariableOccurrences (Variable *var)

void 	BuildStatistics ()

void 	PrintStatistics () const

Constructor & Destructor Documentation

◆ ModelStatistics()

          ModelStatistics
          (
          const Model &
          model,

          SolverLogger *
          logger

          )

inlineexplicit

Definition at line 419 of file flatzinc/model.h.

Member Function Documentation

◆ BuildStatistics()

          void BuildStatistics
          (
          	)

Definition at line 1134 of file flatzinc/model.cc.

◆ NumVariableOccurrences()

          int NumVariableOccurrences
          (
          Variable *
          var	)

inline

Definition at line 421 of file flatzinc/model.h.

◆ PrintStatistics()

          void PrintStatistics
          (
          	)
           const

Definition at line 1119 of file flatzinc/model.cc.

The documentation for this class was generated from the following files:

flatzinc/model.h

flatzinc/model.cc

operations_research

fz

ModelStatistics

Generated by

     1.9.4


text:
@class DVTOpenQuicklyPattern, IDEOpenQuicklyDataSource, NSArray;

@interface IDEOpenQuicklySimplePathMatchProvider : IDEOpenQuicklyMatchProvider
{
    NSArray *_searchPaths;
    id  _dataSourceMatchObserver;
    DVTOpenQuicklyPattern *_previousPattern;
    IDEOpenQuicklyDataSource *_dataSource;
}

+ (id)keyPathsForValuesAffectingIdle;
@property(retain) IDEOpenQuicklyDataSource *dataSource; // @synthesize dataSource=_dataSource;
@property(retain) DVTOpenQuicklyPattern *previousPattern; // @synthesize previousPattern=_previousPattern;
- (void)contextDidChange;
- (void)finishCalculatingMatches;
- (void)startCalculatingMatches;
- (BOOL)isIdle;
- (id)initWithSearchContext:(id)arg1;

@end


text:
//
//  Main2ViewController.m
//  bell-app
//
//  Created by 中原孟 on 2015/09/05.
//  Copyright (c) 2015年 VCJPCM012. All rights reserved.
//

#import "Main2ViewController.h"
#import "DownLoadSoundZipData.h"
#import "GetAudioSound.h"
#import <AFHTTPRequestOperation.h>

@interface Main2ViewController ()
{
    CGSize screenFrame;
    BOOL isPlay;
}

@end

@implementation Main2ViewController

//- (void)viewDidLoad {
//    [super viewDidLoad];
//
//    screenFrame = self.view.bounds.size;
//    _motionManager = [[CMMotionManager alloc] init];
//    [self setupAccelerometer];
//
//    CGRect rect = CGRectMake(0, 0, screenFrame.width/2, screenFrame.height/2);
//    [self MakeShowUILabels:rect];
//
//    //※※ダウンロード用
//    /*
//    //これをダウンロードボタンおしたときに呼び出す
//    [DownLoadSoundZipData downloadZipData:@"1"]; //引数にサウンドIDを指定
//     */
//}
//
//
//
//
//
//-(void)MakeShowUILabels:(CGRect)rect{
//
//    _xLabel = [[UILabel alloc]initWithFrame:rect];
//    _xLabel.center = CGPointMake(screenFrame.width/2, 100);
//    [self.view addSubview:_xLabel];
//
//    _yLabel = [[UILabel alloc]initWithFrame:rect];
//    _yLabel.center = CGPointMake(screenFrame.width/2, 180);
//    [self.view addSubview:_yLabel];
//
//    _zLabel = [[UILabel alloc]initWithFrame:rect];
//    _zLabel.center = CGPointMake(screenFrame.width/2, 240);
//    [self.view addSubview:_zLabel];
//
//}
//
//
//-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
//
//   isPlay = NO;
//
//}
//
//
//- (void)setupAccelerometer{
//    if (_motionManager.accelerometerAvailable){
//        // センサーの更新間隔の指定
//        _motionManager.accelerometerUpdateInterval = 0.5f;
//
//        // ハンドラを設定
//        CMAccelerometerHandler handler = ^(CMAccelerometerData *data, NSError *error)
//        {
//            // 加速度センサー
//            double xac = data.acceleration.x;
//            double yac = data.acceleration.y;
//            double zac = data.acceleration.z;
//
//
//            //最初のxyzのデフォルト値を取得
//
//
//            // 画面に表示
//            self.xLabel.text = [NSString stringWithFormat:@"x: %f", xac];
//            self.xLabel.font = [UIFont fontWithName:@"Helvetica" size:30];
//            self.yLabel.text = [NSString stringWithFormat:@"y: %f", yac];
//            self.yLabel.font = [UIFont fontWithName:@"Helvetica" size:30];
//            self.zLabel.text = [NSString stringWithFormat:@"z: %f", zac];
//            self.zLabel.font = [UIFont fontWithName:@"Helvetica" size:30];
//
//            //3つあるうちのどの音を出すかを判別する数字を取得(上:1,中:2,下:3)
//            int soundRecognizeNum = [RecognizePhoneWave DecideSoundbyWave:xac Y:yac Z:zac];
//
//            //サウンドIDの取得
//            NSString* soundid = @"1";
//
//            //位置に合わせて出す音を分ける
//            if(isPlay){
//                return;
//
//            }else if (soundRecognizeNum == 1) {
//                isPlay = true;
//
//                [self performSelector:@selector(changeisPlayNO) withObject:nil afterDelay:0.5f];
//
//                NSURL* soundUrl = [GetAudioSound getSoundURL:soundid MP3Num: @"1"];
//                [self playSound:soundUrl];
//
//
//            }else if (soundRecognizeNum == 2) {
//                isPlay = true;
//                [self performSelector:@selector(changeisPlayNO) withObject:nil afterDelay:0.5f];
//
//                NSURL* soundUrl = [GetAudioSound getSoundURL:soundid MP3Num: @"2"];
//                [self playSound:soundUrl];
//
//
//            }else if (soundRecognizeNum == 3) {
//                isPlay = true;
//                [self performSelector:@selector(changeisPlayNO) withObject:nil afterDelay:0.5f];
//
//                NSURL* soundUrl = [GetAudioSound getSoundURL:soundid MP3Num: @"3"];
//                [self playSound:soundUrl];
//            }
//        };
//
//        // 加速度の取得開始
//        [_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:handler];
//    }
//
//}
//
//-(void)changeisPlayNO {
//    isPlay = NO;
//}
//
////音楽演奏用
//-(void)playSound:(NSURL*)soundUrl {
//
//    NSError* error = nil;
//    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:soundUrl error:&error];
//
//    if(error){
//        return;
//    }
//    _audioPlayer.delegate = self;
//    [_audioPlayer play];
//
//    isPlay = YES;
//}
//
//
//
//
//
//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}

@end


text:
module Rhaproxy
  module Config
    module Command
      class Base

        INDT = "    "

        @haproxy_config

        public

        def initialize(haproxy_config)
          @haproxy_config = haproxy_config
        end

        def get(*args)
          throw NotImplementedError
        end

        def set(*args)
          throw NotImplementedError
        end

        def show
          throw NotImplementedError
        end

        def self.print_help
          throw NotImplementedError
        end

        def get_array_attr(group_name, array_struct, attr_name)
          "\n#{group_name}\n" + array_struct.map { |backend|
            INDT + backend.send(attr_name)
          }.join("\n") + "\n"
        end

      end
    end
  end
end


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
	<g:FlowPanel ui:field="topicWrapper" addStyleNames="topicWrapper pageWrapper cursorDefault">
		<g:Image ui:field="topicImg" addStyleNames="identImage"></g:Image>
		<g:FlowPanel ui:field="topicPanel" addStyleNames="topicPanel">
			<g:Image ui:field="topicIcon" addStyleNames="topicIcon"></g:Image>
			<g:FlowPanel ui:field="lblPage" addStyleNames="lblTopic"></g:FlowPanel>
		</g:FlowPanel>
	</g:FlowPanel>
</ui:UiBinder>


text:
namespace firebase {

namespace installations {

/// Installations error codes.
enum Error {
  kErrorNone = 0,
  /// An unknown error occurred.
  kErrorUnknown,
  /// Installations service cannot be accessed.
  kErrorNoAccess,
  /// Some of the parameters of the request were invalid.
  kErrorInvalidConfiguration,
};

namespace internal {
// Implementation specific data for an Installation.
class InstallationsInternal;
}  // namespace internal

/// @brief Installations provides a unique identifier for each app instance and
/// a mechanism to authenticate and authorize actions (for example, sending an
/// FCM message).
///
/// Provides a unique identifier for a Firebase installation.
/// Provides an auth token for a Firebase installation.
/// Provides a API to perform data deletion for a Firebase
/// installation.
class Installations {
 public:
  ~Installations();

  /// @brief Get the App this object is connected to.
  ///
  /// @return App this object is connected to.
  App* app() const { return app_; }

  /// @brief Returns the Installations object for an App creating the
  /// Installations if required.
  ///
  /// @param[in] app The App to create an Installations object from.
  ///
  /// @return Installations object if successful, nullptr otherwise.
  static Installations* GetInstance(App* app);

  /// @brief Returns a stable identifier that uniquely identifies the app
  /// installation.
  ///
  /// @return Unique identifier for the app installation.
  Future<std::string> GetId();

  /// @brief Get the results of the most recent call to @ref GetId.
  Future<std::string> GetIdLastResult();

  /// @brief Call to delete this Firebase app installation from the Firebase
  /// backend.
  Future<void> Delete();

  /// @brief Get the results of the most recent call to @ref Delete.
  Future<void> DeleteLastResult();

  /// @brief Returns a token that authorizes an Entity to perform an action on
  /// behalf of the application identified by installations.
  ///
  /// This is similar to an OAuth2 token except it applies to the
  /// application instance instead of a user.
  ///
  /// For example, to get a token that can be used to send messages to an
  /// application via Firebase Cloud Messaging, set entity to the
  /// sender ID, and set scope to "FCM".
  ///
  /// @param forceRefresh If set true, will always return a new token.
  ///
  /// @return Returns a valid authentication token for the Firebase
  /// installation.
  Future<std::string> GetToken(bool forceRefresh);

  /// @brief Get the results of the most recent call to @ref GetToken.
  Future<std::string> GetTokenLastResult();

 private:
  explicit Installations(App* app);

  static Installations* FindInstallations(App* app);
  // Installations internal initialize.
  bool InitInternal();
  // Clean up Installations instance.
  void DeleteInternal();

  App* app_;
  internal::InstallationsInternal* installations_internal_;
};

}  // namespace installations

}  // namespace firebase

#endif  // FIREBASE_INSTALLATIONS_SRC_INCLUDE_FIREBASE_INSTALLATIONS_H_


text:
"use strict";

var execSync = require('sync-exec')
  , Logger = require('./logger')

require('colors')

/**
 *
 * @param {DockerCLI} dockerCli
 */
var routePaquets = exports.routePaquets = function (dockerCli) {

  if (false === dockerCli.isDockerVMRunning()) {
    Logger.error('Please start boot2docker/docker-machine first ( "boot2docker up" or "docker-machine start default")')
    return false
  }

  var routeExec = execSync('route -n add 172.17.0.0/16 ' + dockerCli.getDockerIp())

  if (routeExec.status !== 0) {
    Logger.error("Cannot add route to docker VM")
    Logger.error(routeExec.stderr)
    return false
  }

  return true
}

exports.setup = function (loopback_ip, dockerCli) {

  var hasDockerExecutable = dockerCli.hasDockerExecutable()

  if (hasDockerExecutable) {

    Logger.info((dockerCli.HAS_BOOT2DOCKER ? 'boot2docker' : 'docker-machine') + ' detected')

    if (!dockerCli.isDockerVMRunning()) {
      Logger.error('Docker VM is not started.');
      Logger.error('Please start it using:');

      if (dockerCli.HAS_BOOT2DOCKER) {
        Logger.error('    boot2docker up\n'.yellow);
      } else {
        Logger.error('    boot2docker start default (or whatever VM name other than "default")\n'.yellow);
      }

      return false
    }

    // add loopback URL
    var loopbackExec = execSync('ifconfig lo0 alias ' + loopback_ip)
    if (loopbackExec.status !== 0) {
      Logger.error('Error while setting up loopback IP');
      Logger.error(loopbackExec.stderr);
      return false
    }

    // route paquets
    routePaquets(dockerCli)

    // if DNS is already setup, returns
    if (dockerCli.isDNSSetup(loopback_ip) === true) {
      return true
    }

    Logger.info("Updating Docker DNS with " + loopback_ip);

    var updateDNSCommand =  '\'sudo touch /var/lib/boot2docker/profile && ' +
                            'echo EXTRA_ARGS=\\"\\$EXTRA_ARGS --dns ' + loopback_ip + ' --dns 8.8.8.8\\" ' +
                            ' | sudo tee -a /var/lib/boot2docker/profile\''

    if(dockerCli.HAS_DOCKER_MACHINE) {
      updateDNSCommand = dockerCli.getRunningVMName() + ' ' + updateDNSCommand
    }

    Logger.info("about to execute: " + updateDNSCommand)

    var updateDNSStatus = dockerCli.proxyDockerCommand('ssh', updateDNSCommand);

    if (updateDNSStatus.status !== 0) {
      return Logger.warn("Error while updating Docker DNS: " + updateDNSStatus.stderr)
    }

    Logger.info("boot2docker DNS updated")
    Logger.info("Restarting Docker VM... please wait...");

    var restartStatus = dockerCli.proxyDockerCommand('restart', dockerCli.getRunningVMName())

    if (restartStatus.status === 0) {
      Logger.info("Docker VM restarted");
    } else {
      Logger.warn('Docker VM may have failed restarting. Try to restart it manualy ' +
        '("boot2docker reset" or "docker-machine restart default")')
    }
  }
}


text:
<!DOCTYPE html>

<title>SystemInfoDeviceCapability_wifiDirect_attribute</title>
<meta charset="utf-8"/>


text:
The output from thresholding an image is binary image whose only have two possibilities for each pixels value. The value is either 0 (black-background) or 1 (white-foreground). Sometimes we represents 1 as 255. This leads to smaller image size and simpler way of analyzing it. Thresholding can be done using some methods as follow.

## Simple Thresholding
Simple thresholding, just as its name, works by following simple formula below.

When a pixel has value which is lower than the predetermined **th** then it will be set to 0. On the contrary, when a pixel has value which is higher than or equal to the predetermined **th** then it will be set as 255. Simple thresholding can be done by using ```cv2.threshold``` function and ```cv2.THRESH_BINARY``` as parameter.

The example code on how to do simple thresholding can be found [here](/08_Image_Processing/Thresholding/simpleThresholding).

## Adaptive Thresholding
Adaptive thresholding, unlike simple thresholding, is a thresholding which has a different value of **th** for each pixels. The value of **th** will be determined by pixel's neighbor. For block size of 3 (or kernel size of 3x3), the formula for determining **th** is as below.

Block size is usually (but not always) an odd number, because it will be easier to determine the center. When a pixel has value which is lower than the calculated **th** then it will be set to 0. On the contrary, when a pixel has value which is higher than or equal to the calculated **th** then it will be set as 255. Adaptive thresholding can be done by using ```cv2.adaptiveThreshold``` function and ```cv2.ADAPTIVE_THRESH_MEAN_C``` as parameter. ```cv2.adaptiveThreshold``` works **only with odd number of block size**.

The example code on how to do adaptive thresholding can be found [here](/08_Image_Processing/Thresholding/adaptiveThresholding).

## Adaptive Gaussian Thresholding
Adaptive Gaussian thresholding works the same way as adaptive thresholding, except that the kernel is Gaussian. Gaussian kernel can be made with equation as below.

Adaptive Gaussian thresholding can be done by using ```cv2.adaptiveThreshold``` function and ```cv2.ADAPTIVE_THRESH_GAUSSIAN_C``` as parameter.

The example code on how to do adaptive Gaussian thresholding can be found [here](/08_Image_Processing/Thresholding/adaptiveGaussianThresholding).


text:
package Model;

import com.lob.model.UsVerifications;

import org.testng.annotations.*;
import org.testng.Assert;

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

import com.lob.model.UsVerificationOrError;

@SuppressWarnings("unchecked")
public class UsVerificationsTest {
    @DataProvider (name = "us-verifications-data-provider")
    public Object[][] usVerificationsDpMethod(){
        List<UsVerificationOrError> addresses = new ArrayList<UsVerificationOrError>();
        UsVerificationOrError usVerObj = new UsVerificationOrError();
        usVerObj.setId("us_ver_fakeId");
        addresses.add(usVerObj);

        return new Object[][] {
            {"addresses", addresses},
            {"errors", true},
            {"errors", false},
        };
    }

    @Test(enabled=true, dataProvider = "us-verifications-data-provider")
    public void usVerificationsTestWithProvidedValue(String prop, Object val) {
        UsVerifications rec = new UsVerifications();

        if (prop == "addresses") {
            List<UsVerificationOrError> castedVal = (ArrayList<UsVerificationOrError>)val;
            rec.setAddresses(castedVal);
            Assert.assertEquals(rec.getAddresses(), castedVal);
        } else {
            Boolean castedVal = (Boolean)val;
            rec.setErrors(castedVal);
            Assert.assertEquals(rec.getErrors(), castedVal);
        }
    }
}


text:
namespace IPTV_Sharp
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.statusBox = new System.Windows.Forms.RichTextBox();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.label3 = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.force_checkbox = new System.Windows.Forms.CheckBox();
            this.uppercase_check = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            //
            // comboBox1
            //
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(66, 6);
            this.comboBox1.Margin = new System.Windows.Forms.Padding(2);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(329, 21);
            this.comboBox1.TabIndex = 0;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(11, 14);
            this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Target:";
            //
            // button1
            //
            this.button1.Enabled = false;
            this.button1.Location = new System.Drawing.Point(401, 6);
            this.button1.Margin = new System.Windows.Forms.Padding(2);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(55, 21);
            this.button1.TabIndex = 3;
            this.button1.Text = "Attack";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.875F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(272, 330);
            this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(184, 13);
            this.label2.TabIndex = 4;
            this.label2.Text = "Developed by @Arm4x and @Delfioh";
            //
            // statusBox
            //
            this.statusBox.Location = new System.Drawing.Point(12, 94);
            this.statusBox.Name = "statusBox";
            this.statusBox.ReadOnly = true;
            this.statusBox.Size = new System.Drawing.Size(443, 233);
            this.statusBox.TabIndex = 5;
            this.statusBox.Text = "";
            //
            // progressBar1
            //
            this.progressBar1.Location = new System.Drawing.Point(66, 36);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(390, 23);
            this.progressBar1.TabIndex = 6;
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(11, 46);
            this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(51, 13);
            this.label3.TabIndex = 7;
            this.label3.Text = "Progress:";
            //
            // timer1
            //
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // force_checkbox
            //
            this.force_checkbox.AutoSize = true;
            this.force_checkbox.Location = new System.Drawing.Point(14, 71);
            this.force_checkbox.Name = "force_checkbox";
            this.force_checkbox.Size = new System.Drawing.Size(82, 17);
            this.force_checkbox.TabIndex = 8;
            this.force_checkbox.Text = "Force Crawl";
            this.force_checkbox.UseVisualStyleBackColor = true;
            //
            // uppercase_check
            //
            this.uppercase_check.AutoSize = true;
            this.uppercase_check.Location = new System.Drawing.Point(115, 71);
            this.uppercase_check.Name = "uppercase_check";
            this.uppercase_check.Size = new System.Drawing.Size(148, 17);
            this.uppercase_check.TabIndex = 9;
            this.uppercase_check.Text = "Try Uppercase First Letter";
            this.uppercase_check.UseVisualStyleBackColor = true;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(468, 352);
            this.Controls.Add(this.uppercase_check);
            this.Controls.Add(this.force_checkbox);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.statusBox);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Margin = new System.Windows.Forms.Padding(2);
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "IPTV#";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.RichTextBox statusBox;
        private System.Windows.Forms.ProgressBar progressBar1;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.CheckBox force_checkbox;
        private System.Windows.Forms.CheckBox uppercase_check;
    }
}


text:
package goraph

import (
	"container/heap"
)

type qItem struct {
	vertex   Vertex
	priority int
	index    int
}

type priorityQueue []*qItem

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority > pq[j].priority
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *priorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*qItem)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *priorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and vertex of an qItem in the queue.
func (pq *priorityQueue) updateQItem(item *qItem, v Vertex, priority int) {
	item.vertex = v
	item.priority = priority
	heap.Fix(pq, item.index)
}


text:
module ImportHelper
  include ::Gitlab::Utils::StrongMemoize

  def has_ci_cd_only_params?
    false
  end

  def sanitize_project_name(name)
    # For personal projects in Bitbucket in the form ~username, we can
    # just drop that leading tilde.
    name.gsub(/\A~+/, '').gsub(/[^\w\-]/, '-')
  end

  def import_project_target(owner, name)
    namespace = current_user.can_create_group? ? owner : current_user.namespace_path
    "#{namespace}/#{name}"
  end

  def provider_project_link_url(provider_url, full_path)
    Gitlab::Utils.append_path(provider_url, full_path)
  end

  def import_will_timeout_message(_ci_cd_only)
    timeout = time_interval_in_words(Gitlab.config.gitlab_shell.git_timeout)
    _('The import will time out after %{timeout}. For repositories that take longer, use a clone/push combination.') % { timeout: timeout }
  end

  def import_svn_message(_ci_cd_only)
    svn_link = link_to _('this document'), help_page_path('user/project/import/svn')
    _('To import an SVN repository, check out %{svn_link}.').html_safe % { svn_link: svn_link }
  end

  def import_in_progress_title
    if @project.forked?
      _('Forking in progress')
    else
      _('Import in progress')
    end
  end

  def import_wait_and_refresh_message
    _('Please wait while we import the repository for you. Refresh at will.')
  end

  def import_github_authorize_message
    _('To import GitHub repositories, you first need to authorize GitLab to access the list of your GitHub repositories:')
  end

  def import_github_personal_access_token_message
    personal_access_token_link = link_to _('Personal Access Token'), 'https://github.com/settings/tokens'

    if github_import_configured?
      _('Alternatively, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the repo scope, so we can display a list of your public and private repositories which are available to import.').html_safe % { personal_access_token_link: personal_access_token_link }
    else
      _('To import GitHub repositories, you can use a %{personal_access_token_link}. When you create your Personal Access Token, you will need to select the repo scope, so we can display a list of your public and private repositories which are available to import.').html_safe % { personal_access_token_link: personal_access_token_link }
    end
  end

  def import_configure_github_admin_message
    github_integration_link = link_to 'GitHub integration', help_page_path('integration/github')

    if current_user.admin?
      _('Note: As an administrator you may like to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.').html_safe % { github_integration_link: github_integration_link }
    else
      _('Note: Consider asking your GitLab administrator to configure %{github_integration_link}, which will allow login via GitHub and allow importing repositories without generating a Personal Access Token.').html_safe % { github_integration_link: github_integration_link }
    end
  end
end


text:
export * from './slides-view.component';
export * from './title-slide';


text:
using System;

class Program
{
    static void Main()
    {
        string expression = Console.ReadLine();

        decimal result = 0;

        decimal currentBracketResult = 0;

        char currentOperator = '+';

        char currentBracketOperator = '+';

        bool inBracket = false;

        foreach (char symbol in expression)
        {
            if (symbol == '(')
            {
                inBracket = true;
                continue;
            }
            if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/')
            {
                currentOperator = symbol;
            }
            if (char.IsDigit(symbol))
            {
                int currentNumber = symbol - '0';
                switch (currentOperator)
                {
                    case '+': result += currentNumber;
                        break;
                    case '-': result -= currentNumber;
                        break;
                    case '*': result *= currentNumber;
                        break;
                    case '/': result /= currentNumber;
                        break;

                    default:
                        break;
                }
            }
        }
       Console.WriteLine("{0:F2}", result);
    }
}


text: module.exports = require("npm:turf-union@1.0.1/index");