text:
// Versoes
var SOFTWARE_DB_VERSION = 7;
var SOFTWARE_VERSION = 0.1;
var TEST_VERSION = true;

var LOGIN = "LOGIN";
var SYNC = "SYNC";
var SELECTED_CLIENTS = "SELECTED_CLIENTS";
var SELECTED_PRODUCTS = "SELECTED_PRODUCTS";
var SELECTED_MARCA = "SELECTED_MARCA";
var SELECTED_CATEGORY = "SELECTED_CATEGORY";
var CURRENT_USER_ID = "CURRENT_USER_ID";
var CURRENT_USER_NAME = "CURRENT_USER_NAME";
var CURRENT_USER_EMAIL = "CURRENT_USER_EMAIL";
var CURRENT_EMPRESA = "CURRENT_EMPRESA";
var CURRENT_SOFTWARE = "CURRENT_SOFTWARE";
var DATABASE_VERSION = "DATABASE_VERSION";
var DATABASE_FILE = "DATABASE_FILE";
var SYNC_FILE = "SYNC_FILE";
var SESSION_ID = "SESSION_ID";
var SOBRE_PEDIDO = "SOBRE_PEDIDO";

var URL_BASE = "http://marcas.e-catalogos.net";
//var URL_BASE = "http://integracao.net-pedido.com";
var URL_CAMINHO_IMAGENS = "http://marcasedmin.e-catalogos.net/module/edmin/View/fotos/";
//var URL_CAMINHO_IMAGENS = "http://integracaoedmin.net-pedido.com/module/edmin/View/fotos/";

var URL_HORA_DATA = URL_BASE + "/Loja/jsonHoraData/";
var URL_LOGIN = URL_BASE + "/Loja/jsonAcessaRepresentante";
var URL_SYNC = URL_BASE + "/Loja/jsonSincroniza";
var URL_DATAS = URL_BASE + "/Loja/jsonConsultaData_pagamento/";
var URL_PRAZO_MEDIO = URL_BASE + "/Loja/jsonConsultaPrazo_medio/";
var URL_ESTADOS = URL_BASE + "/Loja/jsonConsultaEstados/";
var URL_PRECO_ESTADOS = URL_BASE + "/Loja/jsonConsultaPreco_estado/";
var URL_CATEGORIAS = URL_BASE + "/Loja/jsonConsultaCategoria/";
var URL_PRODUTOS = URL_BASE + "/Loja/jsonConsultaProduto/";
var URL_COR = URL_BASE + "/Loja/jsonConsultaCores/";
var URL_MARCAS = URL_BASE + "/Loja/jsonConsultaMarcas/";
var URL_TAMANHO = URL_BASE + "/Loja/jsonConsultaTamanho/";
var URL_DESCONTO = URL_BASE + "/Loja/jsonConsultaDesconto/";
var URL_DESCONTO_VOLUME = URL_BASE + "/Loja/jsonConsultaDesconto_volume/";
var URL_CLIENTES = URL_BASE + "/Loja/jsonConsultaCliente/";
var URL_GRUPO_CLIENTE = URL_BASE + "/Loja/jsonConsultaGrupo_cliente/";
var URL_REPRESENTANTE = URL_BASE + "/Loja/jsonConsultaRepresentante/";
var URL_REPRESENTANTE_MARCA = URL_BASE + "/Loja/jsonConsultaRepresentanteMarca/";
var URL_REPRESENTANTE_CLIENTE = URL_BASE + "/Loja/jsonConsultaRepresentante_cliente/";
var URL_EMAIL = URL_BASE + "/Loja/jsonConsultaEmail/";
var URL_REFERENCIA_COMERCIAL = URL_BASE + "/Loja/jsonConsultaReferencia_comercial/";
var URL_REFERENCIA_BANCO = URL_BASE + "/Loja/jsonConsultaReferencia_banco/";
var URL_APARENCIA = URL_BASE + "/Loja/jsonConsultaAparencia/";
var URL_CATEGORIAS_MARCA = URL_BASE + "/Loja/jsonConsultaCategoriasMarca/";
var URL_CLIENTE_MARCA = URL_BASE + "/Loja/jsonConsultaClienteMarca/";
var URL_IMAGENS_PRODUTOS = URL_BASE + "/Loja/jsonConsultaImagem_produto/";
var URL_INFORMACAO_PRODUTO = URL_BASE + "/Loja/jsonConsultaInformacao_produto/";
var URL_PERGUNTA = URL_BASE + "/Loja/jsonConsultaPergunta/";
var URL_NOTIFICACAO = URL_BASE + "/Loja/jsonConsultaNotificacao/";
var URL_PEDIDO = URL_BASE + "/Loja/jsonConsultaPedido/";
var URL_CARRINHO_PEDIDO = URL_BASE + "/Loja/jsonConsultaCarrinho_pedido/";
var URL_VIDEO = URL_BASE + "/Loja/jsonConsultaVideo/";

function getSelectedClients() {
	var clientes = Ti.App.Properties.getList(SELECTED_CLIENTS);
	return clientes;
}

function getSelectedProducts() {
	var tmp = Ti.App.Properties.getList(SELECTED_PRODUCTS);
	return tmp;
}

function checkSelectedProduct(id) {
	var products = [];

	var result = "true";

	if (Ti.App.Properties.getList(SELECTED_PRODUCTS)) {
		var products = Ti.App.Properties.getList(SELECTED_PRODUCTS);
	}
	var index = products.indexOf(id);
	if (index >= 0) {
		result = "true";
	} else {
		result = "false";
	}
	return result;
}

function AddSelectedProduct(id) {
	var products = [];
	var algo  = [];
	if (Ti.App.Properties.getList(SELECTED_PRODUCTS)) {
		var products = Ti.App.Properties.getList(SELECTED_PRODUCTS);
	}
	var result = "false";
	if (checkSelectedProduct(id) == "false") {
		products.push(id);
		result = "true";
	} else {
		var index = products.indexOf(id);
		products.splice(index, 1);
		result = "false";
	}
	Ti.App.Properties.setList(SELECTED_PRODUCTS, products);
	return result;
}

function addSelectedClients(cliente) {
	if (Ti.App.Properties.getList(SELECTED_CLIENTS)) {
		var conjunto = Ti.App.Properties.getList(SELECTED_CLIENTS);
		var uso = false;
		var total = 0;

		for (var quantidade = 0; quantidade < conjunto.length; quantidade++) {
			if (conjunto[quantidade] == cliente) {
				uso = true;
			}
			total++;
		}

		if (total == 0) {
			if (Ti.App.Properties.getString(CURRENT_SOFTWARE) != 3) {
				var clientes = [cliente];
				Ti.App.Properties.setList(SELECTED_CLIENTS, clientes);
				return "amarelo";
			} else {
				if (Ti.App.Properties.getString(CURRENT_SOFTWARE) != 2) {
					var clientes = [cliente];
					Ti.App.Properties.setList(SELECTED_CLIENTS, clientes);
					return "vermelho";
				}
			}
		} else {
			if (uso == false) {
				if (Ti.App.Properties.getString(CURRENT_SOFTWARE) != 2) {
					var clientes = Ti.App.Properties.getList(SELECTED_CLIENTS);
					clientes.push(cliente);
					Ti.App.Properties.setList(SELECTED_CLIENTS, clientes);
					return "vermelho";
				}
			}
		}

	} else {
		if (Ti.App.Properties.getString(CURRENT_SOFTWARE) != 3) {
			var clientes = [cliente];
			Ti.App.Properties.setList(SELECTED_CLIENTS, clientes);
			return "amarelo";
		} else {
			if (Ti.App.Properties.getString(CURRENT_SOFTWARE) != 2) {
				var clientes = [cliente];
				Ti.App.Properties.setList(SELECTED_CLIENTS, clientes);
				return "vermelho";
			}
		}
	}
}

function delSelectedClients(cliente) {

	var conjunto = Ti.App.Properties.getList(SELECTED_CLIENTS);
	var posicao = conjunto.indexOf(cliente);
	conjunto.splice(posicao, 1);

	Ti.App.Properties.setList(SELECTED_CLIENTS, conjunto);

}

function redimencionaVitrine(vitrine) {
	var ALTURA_PADRAO = 710;
	var LARGURA_PADRAO = 1260;
	/*
	 var alturaTela = dipUnitsToPixels(Ti.Platform.displayCaps.ydpi);
	 var larguraTela = dipUnitsToPixels(Ti.Platform.displayCaps.xdpi);
	 */

	var alturaTela = 730;
	var larguraTela = 1280;
	if (Ti.Platform.osname != "android") {
		alturaTela = alturaTela - 100;
		larguraTela = larguraTela - 100;
	} else {

		alturaTela -250;

		larguraTela -250;
	}

	var alturaView = Math.round(alturaTela * 0.9);
	var larguraView = Math.round(LARGURA_PADRAO * alturaView / ALTURA_PADRAO);

	if (larguraView < larguraTela) {
		vitrine.width = larguraView;
		vitrine.height = alturaView;
		//alert('largura' + larguraView + ", width: " + v.size.width + ", height: " + v.size.height);
	} else {
		alturaView = Math.round(ALTURA_PADRAO * larguraTela / LARGURA_PADRAO);
		vitrine.width = larguraTela;
		vitrine.height = alturaView;
		//alert('largura' + alturaView + ", width: " + larguraTela + ", height: " + alturaTela);
	}
}

function getImagesFolder() {
	var rootdir;
	if (Ti.Platform.osname == "android") {
		rootdir = Ti.Filesystem.externalStorageDirectory;
	} else {
		rootdir = Ti.Filesystem.applicationDataDirectory;
	}
	return rootdir;
}

function formatCurrency(int) {
	int = int * 100;

	var tmp = int.toFixed(0) + '';
	var neg = false;
	if (tmp.indexOf("-") == 0) {
		neg = true;
		tmp = tmp.replace("-", "");
	}

	if (tmp.length == 1)
		tmp = "0" + tmp;

	tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
	if (tmp.length > 6)
		tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

	if (tmp.length > 9)
		tmp = tmp.replace(/([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g, ".$1.$2,$3");

	if (tmp.length > 12)
		tmp = tmp.replace(/([0-9]{3}).([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g, ".$1.$2.$3,$4");

	if (tmp.indexOf(".") == 0)
		tmp = tmp.replace(".", "");
	if (tmp.indexOf(",") == 0)
		tmp = tmp.replace(",", "0,");

	return ( neg ? 'R$ -' + tmp : "R$ " + tmp);
}

function goTo(location) {
	var load = Alloy.createController(location).getView();
	load.open({
		fullscreen : true,
		navBarHidden : true
	});
}

function getMonth(month) {
	var meses = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"];
	if (month < 1)
		month = 1;
	return meses[month - 1];
}

function getDayOfYear(d) {// d is a Date object
	var yn = d.getFullYear();
	var mn = d.getMonth();
	var dn = d.getDate();
	var d1 = new Date(yn, 0, 1, 12, 0, 0);
	// noon on Jan. 1
	var d2 = new Date(yn, mn, dn, 12, 0, 0);
	// noon on input date
	var ddiff = Math.round((d2 - d1) / 864e5);
	return ddiff + 1;
}

function getWeekOfYear(d) {
	var day = getDayOfYear(d);
	var week = Math.ceil(day / 7);
	return week;
}

function removeAllViews(view) {
	if (view && view.children != undefined) {
		var removeData = [];
		for ( i = view.children.length; i > 0; i--) {
			removeData.push(view.children[i - 1]);
		};

		for ( i = 0; i < removeData.length; i++) {
			view.remove(removeData[i]);
		}
		removeData = null;
	};
}

function resetSession() {
	var text = "";
	var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	for (var i = 0; i < 20; i++)
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	Ti.App.Properties.setString(SESSION_ID, text);
	Ti.App.Properties.getString(SESSION_ID);
}

function checkdecimal(value) {
	var text = '';
	if (value < 10) {
		text = '0' + value;
	} else
		text = value;
	return text;
}


text:
package org.phenopackets.api.model.condition;

import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType;
import org.phenopackets.api.model.ontology.ClassInstance;

/**
 * the degree to which the phenotype or disease is manifest.
 *

 * related to the concept of expressivity, see http://www.ncbi.nlm.nih.gov/books/NBK22090/
 *

 * Note that this is modeled as in instance of a severity class, in which the class is taken
 * from an ontology such as PATO or HPO. Each condition has its own unique severity instance.
 *
 * In humans, all instances of this should be of of type http://purl.obolibrary.org/obo/HP_0012824
 *
 * For other species, the generic http://purl.obolibrary.org/obo/PATO_0000049 can be used
 *
 * @author cjm
 */

@JsonldType("http://purl.obolibrary.org/obo/PATO_0000049")
public class ConditionSeverity extends ClassInstance {

}

redpajama_set_name: RedPajamaGithub


text:
package impl

import (
	"context"
	"os"
	"testing"

	"github.com/gomodule/redigo/redis"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"

	"github.com/goharbor/harbor/src/common"
	common_dao "github.com/goharbor/harbor/src/common/dao"
	"github.com/goharbor/harbor/src/jobservice/common/list"
	"github.com/goharbor/harbor/src/jobservice/common/utils"
	"github.com/goharbor/harbor/src/jobservice/config"
	"github.com/goharbor/harbor/src/jobservice/job"
	"github.com/goharbor/harbor/src/jobservice/tests"
	libCfg "github.com/goharbor/harbor/src/lib/config"
	_ "github.com/goharbor/harbor/src/pkg/config/inmemory"
	_ "github.com/goharbor/harbor/src/pkg/config/rest"
)

// ContextImplTestSuite tests functions of context impl
type ContextImplTestSuite struct {
	suite.Suite

	tracker   job.Tracker
	namespace string
	pool      *redis.Pool
	jobID     string
}

// TestContextImplTestSuite is entry of go test
func TestContextImplTestSuite(t *testing.T) {
	common_dao.PrepareTestForPostgresSQL()
	suite.Run(t, new(ContextImplTestSuite))
}

// SetupSuite prepares test suite
func (suite *ContextImplTestSuite) SetupSuite() {
	config.DefaultConfig.JobLoggerConfigs = []*config.LoggerConfig{
		{
			Name:  "STD_OUTPUT",
			Level: "DEBUG",
		},
		{
			Name:  "FILE",
			Level: "INFO",
			Settings: map[string]interface{}{
				"base_dir": os.TempDir(),
			},
			Sweeper: &config.LogSweeperConfig{
				Duration: 1,
				Settings: map[string]interface{}{
					"work_dir": os.TempDir(),
				},
			},
		},
	}

	suite.namespace = tests.GiveMeTestNamespace()
	suite.pool = tests.GiveMeRedisPool()

	suite.jobID = utils.MakeIdentifier()
	mockStats := &job.Stats{
		Info: &job.StatsInfo{
			JobID:    suite.jobID,
			JobKind:  job.KindGeneric,
			JobName:  job.SampleJob,
			Status:   job.PendingStatus.String(),
			IsUnique: false,
		},
	}

	suite.tracker = job.NewBasicTrackerWithStats(
		context.Background(),
		mockStats,
		suite.namespace,
		suite.pool,
		nil,
		list.New(),
	)

	err := suite.tracker.Save()
	require.NoError(suite.T(), err, "job stats: nil error expected but got %s", err)
}

// SetupSuite clears test suite
func (suite *ContextImplTestSuite) TearDownSuite() {
	conn := suite.pool.Get()
	defer func() {
		_ = conn.Close()
	}()

	_ = tests.ClearAll(suite.namespace, conn)
}

// TestContextImpl tests the context impl
func (suite *ContextImplTestSuite) TestContextImpl() {
	cfgMem, err := libCfg.GetManager(common.InMemoryCfgManager)
	assert.Nil(suite.T(), err)
	cont := context.Background()
	cfgMem.Set(cont, "read_only", "true")
	ctx := NewContext(cont, cfgMem)
	jCtx, err := ctx.Build(suite.tracker)

	require.NoErrorf(suite.T(), err, "build job context: nil error expected but got %s", err)
	v, ok := jCtx.Get("read_only")
	assert.Equal(suite.T(), true, ok)
	assert.Equal(suite.T(), v, v.(bool))

	err = jCtx.Checkin("check in testing")
	assert.NoErrorf(suite.T(), err, "check in: nil error expected but got %s", err)

	l := jCtx.GetLogger()
	assert.NotNil(suite.T(), l, "logger should be not nil")

	_, ok = jCtx.OPCommand()
	assert.Equal(suite.T(), false, ok)
}


text:
package com.asksunny.codegen.java;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.asksunny.codegen.CodeGenConfig;
import com.asksunny.codegen.CodeGenerator;
import com.asksunny.codegen.utils.ParamMapBuilder;
import com.asksunny.codegen.utils.TemplateUtil;
import com.asksunny.schema.Entity;
import com.asksunny.schema.Schema;

public class SpringContextGenerator extends CodeGenerator {

	public void doCodeGen() throws IOException {
		StringBuilder mapperBeans = new StringBuilder();
		List<Entity> entities = schema.getAllEntities();
		for (Entity entity : entities) {
			mapperBeans.append(genSpringMyBatisBeanXml(entity)).append("\n");
		}
		String generated = TemplateUtil.renderTemplate(
				IOUtils.toString(getClass().getResourceAsStream(
						"spring-mybatis-context.xml.tmpl")),
				ParamMapBuilder
						.newBuilder()
						.addMapEntry(
								"MAPPER_PACKAGE_PATH",
								configuration.getMapperPackageName()
										.replaceAll("[\\.]", "/"))
						.addMapEntry("MYBATIS_MAPPERS", mapperBeans.toString())
						.addMapEntry("DOMAIN_PACKAGE_NAME",
								configuration.getDomainPackageName())
						.addMapEntry("REST_PACKAGE_NAME",
								configuration.getRestPackageName()).buildMap());

		String myBatisSpringContext = String.format(
				"%s-spring-mybatis-context.xml",
				configuration.getWebappContext());
		writeCode(new File(configuration.getSpringXmlBaseDir()),
				myBatisSpringContext, generated);

		String uicontext = TemplateUtil.renderTemplate(IOUtils
				.toString(getClass().getResourceAsStream(
						"spring-webui-context.xml.tmpl")), ParamMapBuilder
				.newBuilder().buildMap());
		// System.out.println(uicontext);
		String uiSpringContext = String.format("%s-spring-ui-context.xml",
				configuration.getWebappContext());
		writeCode(new File(configuration.getSpringXmlBaseDir()),
				uiSpringContext, uicontext);

		String bootstrap = TemplateUtil.renderTemplate(
				IOUtils.toString(getClass().getResourceAsStream(
						"spring-jetty-booststrap.xml.tmpl")),
				ParamMapBuilder
						.newBuilder()
						.addMapEntry("WEBAPP_CONTEXT", configuration.getWebappContext())
						.addMapEntry("UI_CONTEXT_XML", uiSpringContext)
						.addMapEntry("MYBATIS_CONTEXT_XML",
								myBatisSpringContext).buildMap());

		String bootstrapSpringContext = String.format(
				"%s-spring-bootstrap-context.xml",
				configuration.getWebappContext());
		writeCode(new File(configuration.getSpringXmlBaseDir()),
				bootstrapSpringContext, bootstrap);

		if (configuration.getAppBootstrapClassName() != null) {
			String bootstrapClass = writeSpringBootstrap();

			File dir = new File(configuration.getJavaBaseDir());
			if (configuration.getAppBootstrapPackage() != null) {
				String fpath = configuration.getAppBootstrapPackage()
						.replaceAll("[\\.]", "/");
				dir = new File(dir, fpath);
			}
			writeCode(
					dir,
					String.format("%s.java",
							configuration.getAppBootstrapClassName()),
					bootstrapClass);
		}

	}

	public String writeSpringBootstrap() throws IOException {

		String bootstrappackage = configuration.getAppBootstrapPackage() == null ? ""
				: String.format("package %s;",
						configuration.getAppBootstrapPackage());
		String boostrapContext = String.format(
				"%s-spring-bootstrap-context.xml",
				configuration.getWebappContext());
		String generated = TemplateUtil.renderTemplate(
				IOUtils.toString(getClass()
						.getResourceAsStream("AppBootstrap.java.tmpl")),
				ParamMapBuilder
						.newBuilder()
						.addMapEntry("BOOTSTRAP_PACKAGE", bootstrappackage)
						.addMapEntry("DOMAIN_PACKAGE",
								configuration.getDomainPackageName())
						.addMapEntry("BOOTSTRAP_CLASSNAME",
								configuration.getAppBootstrapClassName())
						.addMapEntry("BOOTSTRAP_CONTEXT", boostrapContext)
						.buildMap());

		return generated;

	}

	public String genSpringMyBatisBeanXml(Entity entity) throws IOException {
		String generated = TemplateUtil.renderTemplate(
				IOUtils.toString(getClass().getResourceAsStream(
						"spring-mybatis-mapper.xml.tmpl")),
				ParamMapBuilder
						.newBuilder()
						.addMapEntry("MAPPER_PACKAGE",
								configuration.getMapperPackageName())
						.addMapEntry("ENTITY_VAR_NAME",
								entity.getEntityVarName())
						.addMapEntry("ENTITY_NAME",
								entity.getEntityObjectName()).buildMap());
		return generated;
	}

	public SpringContextGenerator(CodeGenConfig configuration, Schema schema) {
		super(configuration, schema);
	}

}


text:
#include "tiledapplication.h"

#include <QFileOpenEvent>

using namespace Tiled;
using namespace Tiled::Internal;

TiledApplication::TiledApplication(int &argc, char **argv) :
#ifdef ZOMBOID
    QtSingleApplication(argc, argv)
#else
    QApplication(argc, argv)
#endif
{
}

bool TiledApplication::event(QEvent *event)
{
    if (event->type() == QEvent::FileOpen) {
        QFileOpenEvent *fileOpenEvent = static_cast<QFileOpenEvent*>(event);
        emit fileOpenRequest(fileOpenEvent->file());
        return true;
    }
    return QApplication::event(event);
}


text:
import chainer.functions as F
import chainer.links as L
from chainer import Variable
from chainer.links import caffe
from chainer import computational_graph as c
from deel.tensor import *
from deel.network import *
import chainer.serializers as cs
import copy

from deel.deel import *
import chainer
import json
import os
import multiprocessing
import threading
import time
import six
import numpy as np
import os.path
from PIL import Image
from six.moves import queue
import pickle
import hashlib
import datetime
import sys
import random

'''
	Network in Network by Chainer
'''
import deel.model.nin

class NetworkInNetwork(ImageNet):
	def __init__(self,modelpath=None,mean='misc/ilsvrc_2012_mean.npy',labels='data/labels.txt',optimizer=None):
		super(NetworkInNetwork,self).__init__('NetworkInNetwork',in_size=227)

		self.func = deel.model.nin.NIN()
		if modelpath is not None:
			cs.load_hdf5("misc/"+modelpath,self.func)

		self.graph_generated=None

		xp = Deel.xp
		#ImageNet.mean_image = pickle.load(open(mean, 'rb'))
		ImageNet.mean_image = np.ndarray((3, 256, 256), dtype=xp.float32)
		ImageNet.mean_image[0] = 104
		ImageNet.mean_image[1] = 117
		ImageNet.mean_image[2] = 123
		ImageNet.in_size = self.func.insize

		self.labels = np.loadtxt(labels, str, delimiter="\t")

		self.t = ChainerTensor(Variable(Deel.xp.asarray([1.0])))

		if Deel.gpu>=0:
			self.func.to_gpu()

		if optimizer is None:
			self.optimizer = optimizers.Adam()
		self.optimizer.setup(self.func)

	def forward(self,x):
		y = self.func.forward(x)
		return y

	def classify(self,x=None):
		if x is None:
			x=Tensor.context

		image = x.value
		self.x_batch = image
		xp = Deel.xp
		x_data = xp.asarray(self.x_batch)

		x = chainer.Variable(x_data, volatile=True)
		score = self.forward(x)

		score = F.softmax(score)

		score = Variable(score.data) #Unchain
		t = ChainerTensor(score)
		t.owner=self
		t.use()
		return t
	def save(self,filename):
		cs.save_hdf5(filename,self.func.copy().to_cpu())

	def backprop(self,t,distill=False):
		x=Tensor.context

		self.optimizer.zero_grads()
		if distill:
			loss = self.func.getLossDistill(x.content,t.content)
			accuracy = 0.0
		else:
			loss,accuracy = self.func.getLoss(x.content,t.content)
			accuracy = accuracy.data

		loss.backward()
		self.optimizer.update()

		if not self.graph_generated:
			#with open('graph.dot', 'w') as o:
			#	o.write(c.build_computational_graph((loss,), False).dump())
			with open('graph.wo_split.dot', 'w') as o:
				o.write(c.build_computational_graph((loss,), True).dump())
			print('generated graph')
			self.graph_generated = True

		return loss.data,accuracy


text:
<?php
header("Access-Control-Allow-Origin: *");
header("location: ".$_GET["url"]);
?>


text:
package com.mapswithme.maps.bookmarks;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import com.mapswithme.maps.R;
import com.mapswithme.maps.auth.Authorizer;
import com.mapswithme.maps.auth.TargetFragmentCallback;
import com.mapswithme.maps.base.Detachable;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;
import com.mapswithme.maps.bookmarks.data.PaymentData;
import com.mapswithme.maps.dialog.AlertDialog;
import com.mapswithme.maps.dialog.ConfirmationDialogFactory;
import com.mapswithme.maps.dialog.ProgressDialogFragment;
import com.mapswithme.maps.purchase.BookmarkPaymentActivity;
import com.mapswithme.maps.purchase.PurchaseUtils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;

class BookmarksDownloadFragmentDelegate implements Authorizer.Callback, BookmarkDownloadCallback,
                                                   TargetFragmentCallback
{
  private final static Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.BILLING);
  private final static String TAG = BookmarksDownloadFragmentDelegate.class.getSimpleName();
  @SuppressWarnings("NullableProblems")
  @NonNull
  private Authorizer mAuthorizer;
  @SuppressWarnings("NullableProblems")
  @NonNull
  private BookmarkDownloadController mDownloadController;
  @NonNull
  private final Fragment mFragment;
  @Nullable
  private Runnable mAuthCompletionRunnable;

  @NonNull
  private final InvalidCategoriesListener mInvalidCategoriesListener;
  @NonNull
  private final Bundle mBundle;

  BookmarksDownloadFragmentDelegate(@NonNull Fragment fragment)
  {
    this(fragment, AuthBundleFactory.guideCatalogue());
  }

  BookmarksDownloadFragmentDelegate(@NonNull Fragment fragment, @NonNull Bundle bundle)
  {
    mFragment = fragment;
    mInvalidCategoriesListener = new InvalidCategoriesListener(fragment);
    mBundle = bundle;
  }

  void onCreate(@Nullable Bundle savedInstanceState)
  {
    mAuthorizer = new Authorizer(mFragment);
    Application application = mFragment.requireActivity().getApplication();
    mDownloadController = new DefaultBookmarkDownloadController(application,
                                                                new CatalogListenerDecorator(mFragment));
    if (savedInstanceState != null)
      mDownloadController.onRestore(savedInstanceState);
  }

  void onStart()
  {
    mAuthorizer.attach(this);
    mDownloadController.attach(this);
    mInvalidCategoriesListener.attach(mFragment);
  }

  void onResume()
  {
    LOGGER.i(TAG, "Check invalid bookmark categories...");
    BookmarkManager.INSTANCE.checkInvalidCategories();
  }

  void onPause()
  {
    // Do nothing.
  }

  void onStop()
  {
    mAuthorizer.detach();
    mDownloadController.detach();
    mInvalidCategoriesListener.detach();
  }

  void onCreateView(@Nullable Bundle savedInstanceState)
  {
    BookmarkManager.INSTANCE.addInvalidCategoriesListener(mInvalidCategoriesListener);
  }

  void onDestroyView()
  {
    BookmarkManager.INSTANCE.removeInvalidCategoriesListener(mInvalidCategoriesListener);
  }

  void onSaveInstanceState(@NonNull Bundle outState)
  {
    mDownloadController.onSave(outState);
  }

  public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
  {
    if (resultCode != Activity.RESULT_OK)
      return;

    switch (requestCode)
    {
      case PurchaseUtils.REQ_CODE_PAY_CONTINUE_SUBSCRIPTION:
        BookmarkManager.INSTANCE.resetInvalidCategories();
        break;
      case PurchaseUtils.REQ_CODE_PAY_BOOKMARK:
        mDownloadController.retryDownloadBookmark();
        break;
    }
  }

  private void showAuthorizationProgress()
  {
    String message = mFragment.getString(R.string.please_wait);
    ProgressDialogFragment dialog = ProgressDialogFragment.newInstance(message, false, true);
    mFragment.requireActivity().getSupportFragmentManager()
             .beginTransaction()
             .add(dialog, dialog.getClass().getCanonicalName())
             .commitAllowingStateLoss();
  }

  private void hideAuthorizationProgress()
  {
    FragmentManager fm = mFragment.requireActivity().getSupportFragmentManager();
    String tag = ProgressDialogFragment.class.getCanonicalName();
    DialogFragment frag = (DialogFragment) fm.findFragmentByTag(tag);
    if (frag != null)
      frag.dismissAllowingStateLoss();
  }

  @Override
  public void onAuthorizationFinish(boolean success)
  {
    hideAuthorizationProgress();
    if (!success)
    {
      Toast.makeText(mFragment.getContext(), R.string.profile_authorization_error,
                     Toast.LENGTH_LONG).show();
      return;
    }

    if (mAuthCompletionRunnable != null)
      mAuthCompletionRunnable.run();
  }

  @Override
  public void onAuthorizationStart()
  {
    showAuthorizationProgress();
  }

  @Override
  public void onSocialAuthenticationCancel(int type)
  {
    // Do nothing by default.
  }

  @Override
  public void onSocialAuthenticationError(int type, @Nullable String error)
  {
    // Do nothing by default.
  }

  @Override
  public void onAuthorizationRequired()
  {
    authorize(this::retryBookmarkDownload);
  }

  @Override
  public void onPaymentRequired(@NonNull PaymentData data)
  {
    BookmarkPaymentActivity.startForResult(mFragment, data, PurchaseUtils.REQ_CODE_PAY_BOOKMARK);
  }

  @Override
  public void onTargetFragmentResult(int resultCode, @Nullable Intent data)
  {
    mAuthorizer.onTargetFragmentResult(resultCode, data);
  }

  @Override
  public boolean isTargetAdded()
  {
    return mFragment.isAdded();
  }

  boolean downloadBookmark(@NonNull String url)
  {
    return mDownloadController.downloadBookmark(url);
  }

  private void retryBookmarkDownload()
  {
    mDownloadController.retryDownloadBookmark();
  }

  void authorize(@NonNull Runnable completionRunnable)
  {
    mAuthCompletionRunnable = completionRunnable;
    mAuthorizer.authorize(mBundle);
  }

  private static class InvalidCategoriesListener implements BookmarkManager.BookmarksInvalidCategoriesListener, Detachable<Fragment>
  {
    @Nullable
    private Fragment mFrag;
    @Nullable
    private Boolean mPendingInvalidCategoriesResult;

    InvalidCategoriesListener(@NonNull Fragment fragment)
    {
      mFrag = fragment;
    }

    @Override
    public void onCheckInvalidCategories(boolean hasInvalidCategories)
    {
      LOGGER.i(TAG, "Has invalid categories: " + hasInvalidCategories);
      if (mFrag == null)
      {
        mPendingInvalidCategoriesResult = hasInvalidCategories;
        return;
      }

      if (!hasInvalidCategories)
        return;

      showInvalidBookmarksDialog();
    }

    private void showInvalidBookmarksDialog()
    {
      if (mFrag == null)
        return;

      AlertDialog dialog = new AlertDialog.Builder()
          .setTitleId(R.string.renewal_screen_title)
          .setMessageId(R.string.renewal_screen_message)
          .setPositiveBtnId(R.string.renewal_screen_button_restore)
          .setNegativeBtnId(R.string.renewal_screen_button_cancel)
          .setReqCode(PurchaseUtils.REQ_CODE_CHECK_INVALID_SUBS_DIALOG)
          .setImageResId(R.drawable.ic_error_red)
          .setFragManagerStrategyType(AlertDialog.FragManagerStrategyType.ACTIVITY_FRAGMENT_MANAGER)
          .setDialogViewStrategyType(AlertDialog.DialogViewStrategyType.CONFIRMATION_DIALOG)
          .setDialogFactory(new ConfirmationDialogFactory())
          .setNegativeBtnTextColor(R.color.rating_horrible)
          .build();

      dialog.setCancelable(false);
      dialog.setTargetFragment(mFrag, PurchaseUtils.REQ_CODE_CHECK_INVALID_SUBS_DIALOG);
      dialog.show(mFrag, PurchaseUtils.DIALOG_TAG_CHECK_INVALID_SUBS);
    }

    @Override
    public void attach(@NonNull Fragment object)
    {
      mFrag = object;
      if (Boolean.TRUE.equals(mPendingInvalidCategoriesResult))
      {
        showInvalidBookmarksDialog();
        mPendingInvalidCategoriesResult = null;
      }
    }

    @Override
    public void detach()
    {
      mFrag = null;
    }
  }
}


text:
package org.intellij.plugins.xpathView.search;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import org.intellij.plugins.xpathView.Config;
import org.intellij.plugins.xpathView.HistoryElement;
import org.intellij.plugins.xpathView.ui.InputExpressionDialog;
import org.intellij.plugins.xpathView.ui.Mode;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class FindByExpressionDialog extends InputExpressionDialog<FindFormPanel> {

    public FindByExpressionDialog(Project parent, Config settings, HistoryElement[] history, Module module) {
        super(parent, settings, history, new FindFormPanel(parent, module, settings.SEARCH_SCOPE));
        setTitle("Find by XPath Expression");
    }

    protected void init() {
        final ToolWindow findWindow = ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.FIND);
        final boolean available = findWindow != null && findWindow.isAvailable();
        final boolean enabled = mySettings.OPEN_NEW_TAB && available;

        myForm.getNewTabCheckbox().setEnabled(available);
        myForm.getNewTabCheckbox().setSelected(enabled);

        myForm.getScopePanel().addPropertyChangeListener("scope", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                updateOkAction();
            }
        });

        myForm.getMatchEachNode().setSelected(mySettings.MATCH_RECURSIVELY);
        myForm.getMatchRootNode().setSelected(!mySettings.MATCH_RECURSIVELY);

        Disposer.register(myDisposable, myForm);
        super.init();
    }

    protected void setModeImpl(Mode mode) {
        myForm.getOptionsPanel().setVisible(mode == Mode.ADVANCED);
        super.setModeImpl(mode);
    }

    protected boolean isOkEnabled() {
        return myForm.getScope().isValid() && super.isOkEnabled();
    }

    protected void doOKAction() {
        if (myForm.getNewTabCheckbox().isEnabled()) {
            mySettings.OPEN_NEW_TAB = myForm.getNewTabCheckbox().isSelected();
        }

        super.doOKAction();
    }

    protected String getPrivateDimensionServiceKey() {
        return "XPathView.FindDialog.DIMENSION_SERVICE_KEY";
    }

    public SearchScope getScope() {
        return myForm.getScopePanel().getSearchScope();
    }

    public boolean isMatchRecursively() {
        return myForm.getMatchEachNode().isSelected();
    }
}


text:
#import <Foundation/NSURLDownload.h>

#import "NSURLAuthenticationChallengeSender-Protocol.h"

@interface NSURLDownload (NSURLAuthenticationChallengeSender) <NSURLAuthenticationChallengeSender>
- (void)cancelAuthenticationChallenge:(id)arg1;
- (void)continueWithoutCredentialForAuthenticationChallenge:(id)arg1;
- (void)useCredential:(id)arg1 forAuthenticationChallenge:(id)arg2;
- (void)cleanupChallenges;
@end


text:
class ProviderPriorityGroupsController < ApplicationController

  before_filter :require_user
  before_filter :load_pool
  before_filter :load_providers, :only => [:new, :create, :edit, :update]
  before_filter :require_privileged_user_for_modify, :except => :index

  def index
    require_privilege(Alberich::Privilege::VIEW, @pool)

    @strategy = ProviderSelection::Base.find_strategy_by_name(params[:name])
    @priority_groups = @pool.provider_priority_groups
  end

  def new
    @priority_group = ProviderPriorityGroup.new
  end

  def create
    @priority_group = ProviderPriorityGroup.new(params[:provider_priority_group])
    @priority_group.pool = @pool

    unless @priority_group.save
      render :new
      return
    end

    if params[:provider_ids].present?
      selected_providers =
        Provider.list_for_user(current_session, current_user, Alberich::Privilege::USE).
          find(params[:provider_ids])
      @priority_group.providers = selected_providers
    end

    if params[:provider_account_ids].present?
      selected_provider_accounts =
        ProviderAccount.list_for_user(current_session, current_user, Alberich::Privilege::USE).
          find(params[:provider_account_ids])
      @priority_group.add_provider_accounts(selected_provider_accounts)
    end

    redirect_to pool_provider_selection_provider_priority_groups_path(@priority_group.pool),
                :notice => _('Priority Group successfully created')
  end

  def edit
    @priority_group = ProviderPriorityGroup.find(params[:id])
  end

  def update
    @priority_group = ProviderPriorityGroup.find(params[:id])

    unless @priority_group.update_attributes!(params[:provider_priority_group])
      render :edit
      return
    end

    if params[:provider_ids].present?
      selected_providers =
        Provider.list_for_user(current_session, current_user, Alberich::Privilege::USE).
          find(params[:provider_ids])
      @priority_group.providers = selected_providers
    end

    @priority_group.provider_accounts.clear
    if params[:provider_account_ids].present?
      selected_provider_accounts =
        ProviderAccount.list_for_user(current_session, current_user, Alberich::Privilege::USE).
          find(params[:provider_account_ids])
      @priority_group.add_provider_accounts(selected_provider_accounts)
    end

    redirect_to pool_provider_selection_provider_priority_groups_path(@priority_group.pool),
                :notice => _('Priority Group successfully updated')
  end

  def destroy
    @pool.provider_priority_groups.find(params[:id]).destroy
    redirect_to :back, :notice => _('Priority Group successfully deleted')
  end

  private

  def load_pool
    @pool = Pool.find(params[:pool_id])
  end

  def load_providers
    @providers = Provider.joins(:provider_accounts => {:pool_families => :pools}).
      where(:pools => {:id => @pool.id}).
        list_for_user(current_session, current_user, Alberich::Privilege::USE).uniq
    @provider_account_ids = ProviderAccount.joins(:pool_families => :pools).
        where(:pools => {:id => @pool.id}).
        list_for_user(current_session, current_user, Alberich::Privilege::USE).
          collect(&:id)
  end

  def require_privileged_user_for_modify
    require_privilege(Alberich::Privilege::MODIFY, @pool)
  end

end


text:
//============================================================================
//ZedGraph Class Library - A Flexible Line Graph/Bar Graph Library in C#
//Copyright © 2004  John Champion
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this library; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//=============================================================================

using System;
using System.Drawing;
using System.Collections.Generic;

namespace ZedGraph
{
	/// <summary>
	/// A collection class containing a list of <see cref="TextObj"/> objects
	/// to be displayed on the graph.
	/// </summary>
	///
	/// <author> John Champion </author>
	/// <version> $Revision: 3.1 $ $Date: 2006-06-24 20:26:44 $ </version>
	[Serializable]
	public class GraphObjList : List<GraphObj>, ICloneable
	{
	#region Constructors
		/// <summary>
		/// Default constructor for the <see cref="GraphObjList"/> collection class
		/// </summary>
		public GraphObjList()
		{
		}

		/// <summary>
		/// The Copy Constructor
		/// </summary>
		/// <param name="rhs">The <see cref="GraphObjList"/> object from which to copy</param>
		public GraphObjList( GraphObjList rhs )
		{
			foreach ( GraphObj item in rhs )
				this.Add( (GraphObj) ((ICloneable)item).Clone() );
		}

		/// <summary>
		/// Implement the <see cref="ICloneable" /> interface in a typesafe manner by just
		/// calling the typed version of <see cref="Clone" />
		/// </summary>
		/// <returns>A deep copy of this object</returns>
		object ICloneable.Clone()
		{
			return this.Clone();
		}

		/// <summary>
		/// Typesafe, deep-copy clone method.
		/// </summary>
		/// <returns>A new, independent copy of this class</returns>
		public GraphObjList Clone()
		{
			return new GraphObjList( this );
		}

	#endregion

	#region Methods
/*
		/// <summary>
		/// Indexer to access the specified <see cref="GraphObj"/> object by its ordinal
		/// position in the list.
		/// </summary>
		/// <param name="index">The ordinal position (zero-based) of the
		/// <see cref="GraphObj"/> object to be accessed.</param>
		/// <value>A <see cref="GraphObj"/> object reference.</value>
		public GraphObj this[ int index ]
		{
			get { return( (GraphObj) List[index] ); }
			set { List[index] = value; }
		}
*/
		/// <summary>
		/// Indexer to access the specified <see cref="GraphObj"/> object by its <see cref="GraphObj.Tag"/>.
		/// Note that the <see cref="GraphObj.Tag"/> must be a <see cref="String"/> type for this method
		/// to work.
		/// </summary>
		/// <param name="tag">The <see cref="String"/> type tag to search for.</param>
		/// <value>A <see cref="GraphObj"/> object reference.</value>
		/// <seealso cref="IndexOfTag"/>
		public GraphObj this[string tag]
		{
			get
			{
				int index = IndexOfTag( tag );
				if ( index >= 0 )
					return( this[index]  );
				else
					return null;
			}
		}
/*
		/// <summary>
		/// Add a <see cref="GraphObj"/> object to the <see cref="GraphObjList"/>
		/// collection at the end of the list.
		/// </summary>
		/// <param name="item">A reference to the <see cref="GraphObj"/> object to
		/// be added</param>
		/// <seealso cref="IList.Add"/>
		public GraphObj Add( GraphObj item )
		{
			List.Add( item );
			return item;
		}

		/// <summary>
		/// Insert a <see cref="GraphObj"/> object into the collection
		/// at the specified zero-based index location.
		/// </summary>
		/// <param name="index">The zero-based index location for insertion.</param>
		/// <param name="item">The <see cref="GraphObj"/> object that is to be
		/// inserted.</param>
		/// <seealso cref="IList.Insert"/>
		public void Insert( int index, GraphObj item )
		{
			List.Insert( index, item );
		}
*/

		/// <summary>
		/// Return the zero-based position index of the
		/// <see cref="GraphObj"/> with the specified <see cref="GraphObj.Tag"/>.
		/// </summary>
		/// <remarks>In order for this method to work, the <see cref="GraphObj.Tag"/>
		/// property must be of type <see cref="String"/>.</remarks>
		/// <param name="tag">The <see cref="String"/> tag that is in the
		/// <see cref="GraphObj.Tag"/> attribute of the item to be found.
		/// </param>
		/// <returns>The zero-based index of the specified <see cref="GraphObj"/>,
		/// or -1 if the <see cref="GraphObj"/> is not in the list</returns>
		public int IndexOfTag( string tag )
		{
			int index = 0;
			foreach ( GraphObj p in this )
			{
				if ( p.Tag is string &&
							String.Compare( (string) p.Tag, tag, true ) == 0 )
					return index;
				index++;
			}

			return -1;
		}

		/// <summary>
		/// Move the position of the object at the specified index
		/// to the new relative position in the list.</summary>
		/// <remarks>For Graphic type objects, this method controls the
		/// Z-Order of the items.  Objects at the beginning of the list
		/// appear in front of objects at the end of the list.</remarks>
		/// <param name="index">The zero-based index of the object
		/// to be moved.</param>
		/// <param name="relativePos">The relative number of positions to move
		/// the object.  A value of -1 will move the
		/// object one position earlier in the list, a value
		/// of 1 will move it one position later.  To move an item to the
		/// beginning of the list, use a large negative value (such as -999).
		/// To move it to the end of the list, use a large positive value.
		/// </param>
		/// <returns>The new position for the object, or -1 if the object
		/// was not found.</returns>
		public int Move( int index, int relativePos )
		{
			if ( index < 0 || index >= Count )
				return -1;

			GraphObj graphObj = this[index];
			this.RemoveAt( index );

			index += relativePos;
			if ( index < 0 )
				index = 0;
			if ( index > Count )
				index = Count;

			Insert( index, graphObj );
			return index;
		}

	#endregion

	#region Render Methods

		/// <summary>
		/// Render text to the specified <see cref="Graphics"/> device
		/// by calling the Draw method of each <see cref="GraphObj"/> object in
		/// the collection.
		/// </summary>
		/// <remarks>This method is normally only called by the Draw method
		/// of the parent <see cref="GraphPane"/> object.
		/// </remarks>
		/// <param name="g">
		/// A graphic device object to be drawn into.  This is normally e.Graphics from the
		/// PaintEventArgs argument to the Paint() method.
		/// </param>
		/// <param name="pane">
		/// A reference to the <see cref="PaneBase"/> object that is the parent or
		/// owner of this object.
		/// </param>
		/// <param name="scaleFactor">
		/// The scaling factor to be used for rendering objects.  This is calculated and
		/// passed down by the parent <see cref="GraphPane"/> object using the
		/// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust
		/// font sizes, etc. according to the actual size of the graph.
		/// </param>
		/// <param name="zOrder">A <see cref="ZOrder"/> enumeration that controls
		/// the placement of this <see cref="GraphObj"/> relative to other
		/// graphic objects.  The order of <see cref="GraphObj"/>'s with the
		/// same <see cref="ZOrder"/> value is control by their order in
		/// this <see cref="GraphObjList"/>.</param>
		public void Draw( Graphics g, PaneBase pane, float scaleFactor,
							ZOrder zOrder )
		{
			// Draw the items in reverse order, so the last items in the
			// list appear behind the first items (consistent with
			// CurveList)
			for ( int i=this.Count-1; i>=0; i-- )
			{
				GraphObj item = this[i];
				if ( item.ZOrder == zOrder && item.IsVisible )
				{
					Region region = null;
					if ( item.IsClippedToChartRect && pane is GraphPane )
					{
						region = g.Clip.Clone();
						g.SetClip( ((GraphPane)pane).Chart._rect );
					}

					item.Draw( g, pane, scaleFactor );

					if ( item.IsClippedToChartRect && pane is GraphPane )
						g.Clip = region;
				}
			}
		}

		/// <summary>
		/// Determine if a mouse point is within any <see cref="GraphObj"/>, and if so,
		/// return the index number of the the <see cref="GraphObj"/>.
		/// </summary>
		/// <param name="mousePt">The screen point, in pixel coordinates.</param>
		/// <param name="pane">
		/// A reference to the <see cref="PaneBase"/> object that is the parent or
		/// owner of this object.
		/// </param>
		/// <param name="g">
		/// A graphic device object to be drawn into.  This is normally e.Graphics from the
		/// PaintEventArgs argument to the Paint() method.
		/// </param>
		/// <param name="scaleFactor">
		/// The scaling factor to be used for rendering objects.  This is calculated and
		/// passed down by the parent <see cref="GraphPane"/> object using the
		/// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust
		/// font sizes, etc. according to the actual size of the graph.
		/// </param>
		/// <param name="index">The index number of the <see cref="TextObj"/>
		///  that is under the mouse point.  The <see cref="TextObj"/> object is
		/// accessible via the <see cref="GraphObjList" /> indexer property.
		/// </param>
		/// <returns>true if the mouse point is within a <see cref="GraphObj"/> bounding
		/// box, false otherwise.</returns>
		/// <seealso cref="GraphPane.FindNearestObject"/>
		public bool FindPoint( PointF mousePt, PaneBase pane, Graphics g, float scaleFactor, out int index )
		{
			index = -1;

			// Search in reverse direction to honor the Z-order
			for ( int i=Count-1; i>=0; i-- )
			{
				if ( this[i].PointInBox( mousePt, pane, g, scaleFactor ) )
				{
					if ( ( index >= 0 && this[i].ZOrder > this[index].ZOrder ) || index < 0 )
						index = i;
				}
			}

			if ( index >= 0 )
				return true;
			else
				return false;
		}

	#endregion
	}
}


text:
#include "SphynxServer.h"

static logging::Channel Logger("SphynxServer");

//-----------------------------------------------------------------------------
// Tools

#ifdef _MSC_VER
#include <nmmintrin.h>
#endif

#ifndef ANDROID
    #define HAS_CRC32_INTRINSIC /* disable if it doesn't compile */
#endif

ALIGNED_TYPE(asio::ip::address_v4::bytes_type, 16) aligned_v4_t;
ALIGNED_TYPE(asio::ip::address_v6::bytes_type, 16) aligned_v6_t;

uint32_t hash_ip_addr(const asio::ip::udp::endpoint& addr)
{
    uint32_t key;

    if (addr.address().is_v4())
    {
        aligned_v4_t v4bytes = addr.address().to_v4().to_bytes();
        key = *(uint32_t*)&v4bytes[0];
#ifdef HAS_CRC32_INTRINSIC
        key = _mm_crc32_u32(addr.port(), key);
#else
        key = (key ^ 61) ^ (key >> 16);
        key = key + (key << 3) + addr.port();
        key = key ^ (key >> 4);
        key = key * 0x27d4eb2d;
        key = key ^ (key >> 15);
#endif
    }
    else
    {
        aligned_v6_t v6bytes = addr.address().to_v6().to_bytes();
        uint32_t* keywords = (uint32_t*)&v6bytes[0];
#ifdef HAS_CRC32_INTRINSIC
        key = _mm_crc32_u32(addr.port(), keywords[0]);
        key = _mm_crc32_u32(key, keywords[1]);
        key = _mm_crc32_u32(key, keywords[2]);
        key = _mm_crc32_u32(key, keywords[3]);
#else
        key = keywords[0] + keywords[1] + keywords[2] + keywords[3];
        key = (key ^ 61) ^ (key >> 16);
        key = key + (key << 3) + addr.port();
        key = key ^ (key >> 4);
        key = key * 0x27d4eb2d;
        key = key ^ (key >> 15);
#endif
    }

    return key;
}

//-----------------------------------------------------------------------------
// ServerWorker

ServerWorker::ServerWorker()
{
    Terminated = false;
}

ServerWorker::~ServerWorker()
{
}

void ServerWorker::AddNewConnection(const std::shared_ptr<Connection>& connection)
{
    ConnectionCount++;

    Locker locker(NewConnectionsLock);
    NewConnections.push_back(connection);
}

void ServerWorker::RemoveConnection(const std::shared_ptr<Connection>& connection)
{
    ConnectionCount--;

    Locker locker(NewConnectionsLock);
    NewConnections.remove(connection);
    Connections.remove(connection);
}

void ServerWorker::Start(std::shared_ptr<asio::io_context>& context, unsigned threadId,
    std::shared_ptr<ServerSettings>& settings)
{
    Context = context;
    ThreadId = threadId;
    Settings = settings;

    Logger.Debug("Thread ", ThreadId, ": Starting");

    Timer = std::make_unique<asio::steady_timer>(*Context);
    PostNextTimer();

    Terminated = false;
    Thread = std::make_unique<std::thread>(&ServerWorker::Loop, this);
}

void ServerWorker::PostNextTimer()
{
    Timer->expires_after(std::chrono::milliseconds(kServerWorkerTimerIntervalMsec));
    Timer->async_wait([this](const asio::error_code& error)
    {
        if (!!error)
            OnTimerError(error);
        else
            OnTimerTick();
    });
}

void ServerWorker::Loop()
{
    SetThreadName("ServerWorker");

    Logger.Info("Thread ", ThreadId, ": Entering loop");

    if (ThreadId < std::thread::hardware_concurrency())
    {
        if (!SetCurrentThreadAffinity(ThreadId))
        {
            Logger.Warning("Thread ", ThreadId, ": Unable to set affinity");
            DEBUG_BREAK;
        }
    }

    while (!Terminated)
        Context->run();

    Logger.Info("Thread ", ThreadId, ": Exiting loop");
}

void ServerWorker::PromoteNewConnections()
{
    std::list<std::shared_ptr<Connection>> newConnections;
    {
        Locker locker(NewConnectionsLock);
        newConnections.splice(newConnections.end(), NewConnections);
    }

    for (auto& connection : newConnections)
        connection->OnWorkerStart();

    Connections.splice(Connections.end(), newConnections);
}

void ServerWorker::OnTimerTick()
{
    u64 nowMsec = GetTimeMsec();

    Logger.Trace("Thread ", ThreadId, ": Tick ", nowMsec);

    PromoteNewConnections();

    Connections.remove_if(
        [nowMsec](std::shared_ptr<Connection>& connection)
    {
        return connection->OnTick(nowMsec);
    });

    PostNextTimer();
}

void ServerWorker::OnTimerError(const asio::error_code& error)
{
    Logger.Warning("Thread ", ThreadId, ": Tick error ", error.message());
}

void ServerWorker::Stop()
{
    Logger.Debug("Thread ", ThreadId, ": Stopping");

    Terminated = true;

    if (Timer)
        Timer->cancel();
    if (Thread)
    {
        try
        {
            Thread->join();
        }
        catch (std::system_error& err)
        {
            Logger.Warning("Exception while joining thread: ", err.what());
        }
    }
    Thread = nullptr;
    Context = nullptr;
    Timer = nullptr;
}

//-----------------------------------------------------------------------------
// ServerWorkers

ServerWorkers::ServerWorkers()
{
}

ServerWorkers::~ServerWorkers()
{
}

void ServerWorkers::Start(std::shared_ptr<asio::io_context>& context, std::shared_ptr<ServerSettings>& settings)
{
    Settings = settings;

    if (settings->WorkerCount <= 0)
    {
        unsigned num_cpus = std::thread::hardware_concurrency();
        if (num_cpus < 1)
            num_cpus = 1;
        settings->WorkerCount = num_cpus;
    }

    Logger.Info("Starting ", Settings->WorkerCount, " workers");

    Context = context;

    Workers.resize(Settings->WorkerCount);
    unsigned threadId = 0;
    for (auto& worker : Workers)
    {
        worker = std::make_shared<ServerWorker>();
        worker->Start(Context, threadId++, Settings);
    }
}

ServerWorker* ServerWorkers::FindLaziestWorker()
{
    int laziestWorker = 0, laziestWorkerCount = Workers[0]->GetConnectionCount();
    for (size_t kWorkerCount = Workers.size(), i = 1; i < kWorkerCount; ++i)
    {
        int count = Workers[i]->GetConnectionCount();
        if (laziestWorkerCount > count)
        {
            laziestWorker = (int)i, laziestWorkerCount = count;
        }
    }
    return Workers[laziestWorker].get();
}

void ServerWorkers::Stop()
{
    Logger.Info("Stopping ", Settings->WorkerCount, " workers");

    u64 t0 = GetTimeMsec();
    for (auto& worker : Workers)
        worker->Stop();
    Workers.clear();
    u64 t1 = GetTimeMsec();

    Logger.Info("Stopped ", Settings->WorkerCount, " workers in ", (t1 - t0) / 1000, " msec");

    Context = nullptr;
}

//-----------------------------------------------------------------------------
// Connection

Connection::Connection()
{
    RPCTimeSyncUDP.CallSender = UDPCallSender;
    RPCHeartbeatTCP.CallSender = TCPCallSender;
    RPCTCPHandshake.CallSender = TCPCallSender;

    Router.Set<C2SHeartbeatT>(C2SHeartbeatID, [this](u16 sentTimeMsec)
    {
        u64 nowMsec = GetTimeMsec();
        u64 sentTimeFullMsec = ReconstructMsec(nowMsec, sentTimeMsec);

        Logger.Debug("Got heartbeat from ", (int)(nowMsec - sentTimeFullMsec));

        // Client is keeping connection alive
    });
}

Connection::~Connection()
{
}

void Connection::Start(std::shared_ptr<asio::io_context>& context, ConnectionInterface* iface)
{
	SphynxPeer::Start(context);

    Interface = iface;
}

void Connection::OnAccept(const std::shared_ptr<asio::ip::udp::socket>& udpSocket, unsigned short port, u32 cookie)
{
    UDPSocket = udpSocket;
    UDPPort = port;
    ConnectionCookie = cookie;
}

void Connection::OnWorkerStart()
{
    Cipher.InitializeEncryption(0, EncryptionRole::Server);

    Logger.Info("Worker starting on connection. Sending TCP handshake");

    RPCTCPHandshake(ConnectionCookie, UDPPort);

    PostNextTCPRead();
}

void Connection::OnUDPHandshake(asio::ip::udp::endpoint& from, std::shared_ptr<asio::ip::udp::socket>& udpSocket)
{
    PeerUDPAddress = from;
	UDPSocket = udpSocket;

	IsFullConnection = true;

    Logger.Info("Connection got UDP handshake from client: Session established!");

    Interface->OnConnect(this);
}

bool Connection::OnTick(u64 nowMsec)
{
    if (nowMsec - LastReceiveLocalMsec > kS2CTimeoutMsec && LastReceiveLocalMsec != 0)
    {
        Logger.Warning("Client timeout: Disconnecting");

        Disconnect();
    }

    if (!IsDisconnected() && IsFullConnection)
        Interface->OnTick(this, nowMsec);

    if (IsDisconnected())
    {
        Logger.Warning("Client is disconnected: Removing from worker list");

        if (IsFullConnection)
            Interface->OnDisconnect(this);

        // FIXME: Call PreMapRemove() here on UDP server
        // FIXME: Call MapRemove() here on UDP server

        return true; // Remove from list
    }

    if (IsFullConnection && nowMsec - LastUDPTimeSyncMsec > static_cast<u64>(S2CUDPTimeSyncIntervalMsec))
    {
        LastUDPTimeSyncMsec = nowMsec;
        Logger.Debug("Sending UDP timesync ", nowMsec);

        u16 bestDelta = static_cast<u16>(WinTimes.ComputeDelta(nowMsec));
        RPCTimeSyncUDP(bestDelta);

        if (FastCount <= kS2CUDPTimeSyncFastCount)
        {
            if (FastCount == kS2CUDPTimeSyncFastCount)
                S2CUDPTimeSyncIntervalMsec = kS2CUDPTimeSyncIntervalSlowMsec;
            ++FastCount;
        }
    }

    if (nowMsec - LastTCPHeartbeatMsec > kS2CTCPHeartbeatIntervalMsec)
    {
        LastTCPHeartbeatMsec = nowMsec;
        Logger.Debug("Sending TCP heartbeat ", nowMsec);

        RPCHeartbeatTCP();
    }

    Flush();

    return false; // Do not remove from list
}

//-----------------------------------------------------------------------------
// UDPServer

UDPServer::UDPServer()
{
}

UDPServer::~UDPServer()
{
}

void UDPServer::Start(std::shared_ptr<asio::io_context>& context, unsigned short port,
    std::shared_ptr<ServerSettings>& settings,
    std::shared_ptr<ServerWorkers>& workers,
    std::shared_ptr<UDPServer>& selfRef)
{
    Context = context;
    Port = port;
    Settings = settings;
    Workers = workers;
    SelfRef = selfRef;

    Logger.Info("UDP ", Port, ": Starting server");

    asio::ip::udp::endpoint UDPEndpoint(asio::ip::udp::v4(), port);
    UDPSocket = std::make_shared<asio::ip::udp::socket>(*Context, UDPEndpoint);

    // Set socket options
    asio::socket_base::send_buffer_size SendBufferSizeOption(kUDPSendBufferSizeBytes);
    UDPSocket->set_option(SendBufferSizeOption);
    asio::socket_base::receive_buffer_size RecvBufferSizeOption(kUDPRecvBufferSizeBytes);
    UDPSocket->set_option(RecvBufferSizeOption);
    asio::socket_base::reuse_address ReuseAddressOption(true);
    UDPSocket->set_option(ReuseAddressOption);

    DontFragment(UDPSocket, true);
    IgnoreUnreachable(UDPSocket, true);

    PreConnectionCipher.InitializeEncryption(0, EncryptionRole::Server);

    PreConnectionRouter.Set<C2SUDPHandshakeT>(C2SUDPHandshakeID, [this](u32 cookie)
    {
        std::shared_ptr<Connection> connection;
        if (PreMapFindRemove(cookie, connection))
        {
            Logger.Info("Got UDP data from the client");

            connection->OnUDPHandshake(FromEndpoint, UDPSocket);

            MapInsert(FromEndpoint, connection);
        }
    });

    PostNextRecvFrom();
}

void UDPServer::OnAccept(const std::shared_ptr<Connection>& connection, u32 cookie)
{
    PreMapInsert(cookie, connection);
}

void UDPServer::HandlePreConnectData(Stream& rawStream)
{
    u8* data = rawStream.GetFront();
    int dataSize = rawStream.GetBufferSize();
    PreConnectionCipher.DecryptUDP(data, data, dataSize);

    Stream stream;
    stream.WrapRead(data, dataSize);

    u16 partialTime;
    if (!stream.Serialize(partialTime))
        return;

    PreConnectionRouter.Call(stream);
}

void UDPServer::OnUDPClose()
{
    Logger.Warning("UDP ", Port, ": Closed");
}

void UDPServer::OnUDPError(const asio::error_code& error)
{
    Logger.Warning("UDP ", Port, ": Socket error: ", error.message());
}

void UDPServer::PostNextRecvFrom()
{
    memset(&UDPReceiveBuffer[0], 0xfe, UDPReceiveBuffer.size());

    UDPSocket->async_receive_from(asio::buffer(UDPReceiveBuffer), FromEndpoint, [this](
        const asio::error_code& error, std::size_t bytes_transferred)
    {
        const u64 nowMsec = GetTimeMsec();

        if (!!error)
            OnUDPError(error);
        else if (bytes_transferred <= 0)
            OnUDPClose();
        else
        {
            Stream stream;
            stream.WrapRead(&UDPReceiveBuffer[0], bytes_transferred);

            Logger.Trace("UDP ", Port, ": Got data len=", stream.GetRemaining());

            std::shared_ptr<Connection> connection;
            if (MapFind(FromEndpoint, connection))
                connection->OnUDPData(nowMsec, stream);
            else
                HandlePreConnectData(stream);

            PostNextRecvFrom();
        }
    });
}

int UDPServer::GetConnectionCount() const
{
    size_t count = 0;
    {
        Locker locker(EstablishedConnectionsMapLock);
        count += EstablishedConnectionsMap.size();
    }
    {
        Locker locker(PreConnectionsMapLock);
        count += PreConnectionsMap.size();
    }
    return static_cast<int>(count);
}

bool UDPServer::MapInsert(asio::ip::udp::endpoint& addr, const std::shared_ptr<Connection>& conn)
{
    Locker locker(EstablishedConnectionsMapLock);

    // Returns true if the value was inserted, false if it existed already
    return EstablishedConnectionsMap.insert(AddressMap::value_type(addr, conn)).second;
}

bool UDPServer::MapRemove(asio::ip::udp::endpoint& addr)
{
    std::shared_ptr<Connection> connection;
    {
        Locker locker(EstablishedConnectionsMapLock);
        auto iter = EstablishedConnectionsMap.find(addr);
        if (iter == EstablishedConnectionsMap.end())
            return false;
        connection = iter->second;
        EstablishedConnectionsMap.erase(iter);
    }
    connection.reset(); // Allow object to go out of scope
    return true;
}

bool UDPServer::MapFind(asio::ip::udp::endpoint& addr, std::shared_ptr<Connection>& conn)
{
    Locker locker(EstablishedConnectionsMapLock);
    auto iter = EstablishedConnectionsMap.find(addr);
    if (iter == EstablishedConnectionsMap.end())
    {
        conn = nullptr;
        return false;
    }
    conn = iter->second;
    return true;
}

void UDPServer::MapClear()
{
    std::vector<std::shared_ptr<Connection>> connections;
    {
        Locker locker(EstablishedConnectionsMapLock);
        connections.reserve(EstablishedConnectionsMap.size());
        for (auto& connection : EstablishedConnectionsMap)
            connections.push_back(connection.second);
        EstablishedConnectionsMap.clear();
    }
    connections.clear(); // Allow objects to go out of scope
}

bool UDPServer::PreMapInsert(u32 cookie, const std::shared_ptr<Connection>& conn)
{
    Locker locker(PreConnectionsMapLock);

    // Returns true if the value was inserted, false if it existed already
    return PreConnectionsMap.insert(CookieMap::value_type(cookie, conn)).second;
}

bool UDPServer::PreMapRemove(u32 cookie)
{
    std::shared_ptr<Connection> connection;
    {
        Locker locker(PreConnectionsMapLock);
        auto iter = PreConnectionsMap.find(cookie);
        if (iter == PreConnectionsMap.end())
            return false;
        connection = iter->second;
        PreConnectionsMap.erase(iter);
    }
    connection.reset(); // Allow object to go out of scope
    return true;
}

bool UDPServer::PreMapFindRemove(u32 cookie, std::shared_ptr<Connection>& conn)
{
    Locker locker(PreConnectionsMapLock);
    auto iter = PreConnectionsMap.find(cookie);
    if (iter == PreConnectionsMap.end())
    {
        conn = nullptr;
        return false;
    }
    conn = iter->second;
    PreConnectionsMap.erase(iter);
    return true;
}

void UDPServer::PreMapClear()
{
    std::vector<std::shared_ptr<Connection>> connections;
    {
        Locker locker(PreConnectionsMapLock);
        connections.reserve(PreConnectionsMap.size());
        for (auto& connection : PreConnectionsMap)
            connections.push_back(connection.second);
        PreConnectionsMap.clear();
    }
    connections.clear(); // Allow objects to go out of scope
}

void UDPServer::Stop()
{
    Logger.Debug("UDP ", Port, ": Stopping");

    MapClear();
    PreMapClear();

    if (UDPSocket)
        UDPSocket->close();
    Context = nullptr;
    Settings = nullptr;
    UDPSocket = nullptr;
    Workers = nullptr;
    SelfRef = nullptr;
}

//-----------------------------------------------------------------------------
// Server

Server::Server()
{
}

Server::~Server()
{
}

void Server::Start(std::shared_ptr<ServerSettings>& settings)
{
    Settings = settings;

    Logger.Info("Starting server on TCP port ", Settings->MainTCPPort, " and UDP ports ", Settings->StartUDPPort, " - ", Settings->StopUDPPort);

    KeyGen.Initialize((u32)GetTimeUsec());

    Context = std::make_shared<asio::io_context>();
    Context->restart();

    Workers = std::make_shared<ServerWorkers>();
    Workers->Start(Context, Settings);

    const int UDPPortCount = static_cast<int>(Settings->StopUDPPort - Settings->StartUDPPort + 1);
    UDPServers.resize(UDPPortCount);
    unsigned short udpPort = Settings->StartUDPPort;
    for (auto& udp : UDPServers)
    {
        udp = std::make_shared<UDPServer>();
        udp->Start(Context, udpPort, Settings, Workers, udp);
        udpPort++;
    }

    asio::ip::tcp::endpoint TCPEndpoint(asio::ip::tcp::v4(), Settings->MainTCPPort);
    TCPAcceptor = std::make_shared<asio::ip::tcp::acceptor>(*Context, TCPEndpoint);

    // Set socket options
    asio::socket_base::send_buffer_size SendBufferSizeOption(kTCPSendBufferSizeBytes);
    TCPAcceptor->set_option(SendBufferSizeOption);
    asio::socket_base::receive_buffer_size RecvBufferSizeOption(kTCPRecvBufferSizeBytes);
    TCPAcceptor->set_option(RecvBufferSizeOption);
    asio::socket_base::linger LingerOption(false, 0);
    TCPAcceptor->set_option(LingerOption);
    asio::socket_base::reuse_address ReuseAddressOption(true);
    TCPAcceptor->set_option(ReuseAddressOption);

    // Set TCP options
    asio::ip::tcp::no_delay NoDelayOption(true);
    TCPAcceptor->set_option(NoDelayOption);

    PostNewAccept();
}

void Server::OnAccept(const std::shared_ptr<Connection>& connection)
{
    auto& addr = connection->PeerTCPAddress;
    Logger.Info("Accepted a TCP connection from ", addr.address().to_string(), " : ", addr.port());

    const u32 cookie = KeyGen.Next();

    UDPServer* udp = FindLaziestUDPServer();
    connection->OnAccept(udp->GetUDPSocket(), udp->GetPort(), cookie);

    udp->OnAccept(connection, cookie);

    Workers->FindLaziestWorker()->AddNewConnection(connection);

    PostNewAccept();
}

UDPServer* Server::FindLaziestUDPServer()
{
    UDPServer* best = UDPServers[0].get();
    int lowestCount = best->GetConnectionCount();

    const int serverCount = static_cast<int>(UDPServers.size());
    for (int i = 1; i < serverCount; ++i)
    {
        UDPServer* server = UDPServers[i].get();
        int count = server->GetConnectionCount();
        if (count < lowestCount)
            best = server;
    }

    return best;
}

void Server::OnAcceptError(const asio::error_code& error)
{
    Logger.Warning("TCP acceptor socket error: ", error.message());
}

void Server::PostNewAccept()
{
    auto connection = std::make_shared<Connection>();
    ConnectionInterface* iface = Settings->Interface->CreateConnection(connection.get());
    connection->Start(Context, iface);

    TCPAcceptor->async_accept(*connection->TCPSocket, connection->PeerTCPAddress, [this, connection](const asio::error_code& error)
    {
        if (!!error)
            OnAcceptError(error);
        else
            OnAccept(connection);
    });
}

void Server::Stop()
{
    Logger.Info("Stopping server");

    if (Context)
        Context->stop();

    if (Workers)
        Workers->Stop();

    for (auto& udp : UDPServers)
        udp->Stop();
    UDPServers.clear();

    if (TCPAcceptor)
        TCPAcceptor->cancel();

    Workers = nullptr;
    TCPAcceptor = nullptr;
    Context = nullptr;
    Settings = nullptr;
}


text:
<!--

Got a question?
===============
The issue list of this repo is exclusively for bug reports and feature requests. For simple questions, please use the following resources:

- Read the docs: https://getuikit.com/docs
- Ask in the Gitter chat room: https://gitter.im/uikit/uikit
- Look for/ask questions on stack overflow: https://stackoverflow.com/questions/ask?tags=getuikit

-->

<!-- BUG REPORT TEMPLATE -->
### UIkit version
<!-- Check if the issue is reproducible with the latest stable version. -->
3.0.0-beta.30

### Browser

### Reproduction Link
<!-- A minimal Codepen that can reproduce the bug. -->
<!-- You could start with this template: http://codepen.io/anon/pen/XMpryM -->

### Steps to reproduce

### What is Expected?

### What is actually happening?


text:
package org.rabix.engine.store.model.scatter.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import org.rabix.bindings.BindingException;
import org.rabix.bindings.model.ScatterMethod;
import org.rabix.bindings.model.dag.DAGLinkPort;
import org.rabix.bindings.model.dag.DAGNode;
import org.rabix.common.helper.InternalSchemaHelper;
import org.rabix.engine.store.model.scatter.PortMapping;
import org.rabix.engine.store.model.scatter.RowMapping;
import org.rabix.engine.store.model.scatter.ScatterStrategy;
import org.rabix.engine.store.model.scatter.ScatterStrategyException;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ScatterCartesianStrategy implements ScatterStrategy {

  @JsonProperty("combinations")
  private LinkedList<Combination> combinations;

  @JsonProperty("values")
  private Map<String, LinkedList<Object>> values;
  @JsonProperty("positions")
  private Map<String, LinkedList<Integer>> positions;
  @JsonProperty("sizePerPort")
  private Map<String, Integer> sizePerPort;

  @JsonProperty("scatterMethod")
  private ScatterMethod scatterMethod;

  @JsonProperty("emptyListDetected")
  private Boolean emptyListDetected;

  @JsonProperty("skipScatter")
  private Boolean skipScatter;

  @JsonCreator
  public ScatterCartesianStrategy(@JsonProperty("combinations") LinkedList<Combination> combinations,
      @JsonProperty("values") Map<String, LinkedList<Object>> values,
      @JsonProperty("positions") Map<String, LinkedList<Integer>> positions,
      @JsonProperty("scatterMethod") ScatterMethod scatterMethod,
      @JsonProperty("sizePerPort") Map<String, Integer> sizePerPort,
      @JsonProperty("emptyListDetected") Boolean emptyListDetected,
      @JsonProperty("skipScatter") Boolean skipScatter) {
    super();
    this.combinations = combinations;
    this.values = values;
    this.positions = positions;
    this.sizePerPort = sizePerPort;
    this.scatterMethod = scatterMethod;
    this.emptyListDetected = emptyListDetected;
    this.skipScatter = skipScatter;
  }

  public ScatterCartesianStrategy(DAGNode dagNode) {
    this.values = new HashMap<>();
    this.positions = new HashMap<>();
    this.combinations = new LinkedList<>();
    this.scatterMethod = dagNode.getScatterMethod();
    this.sizePerPort = new HashMap<>();
    this.emptyListDetected = false;
    this.skipScatter = false;
    initialize(dagNode);
  }

  public ScatterMethod getScatterMethod() {
    return scatterMethod;
  }

  public void initialize(DAGNode dagNode) {
    for (DAGLinkPort port : dagNode.getInputPorts()) {
      if (port.isScatter()) {
        values.put(port.getId(), new LinkedList<Object>());
        positions.put(port.getId(), new LinkedList<Integer>());
      }
    }
  }

  @Override
  public synchronized void enable(String port, Object value, Integer position, Integer sizePerPort) throws ScatterStrategyException {
    LinkedList<Integer> positionList = positions.get(port);
    positionList = expand(positionList, position);
    positionList.set(position - 1, position);
    positions.put(port, positionList);

    LinkedList<Object> valueList = values.get(port);
    valueList = expand(valueList, position);
    valueList.set(position - 1, value);
    values.put(port, valueList);
    this.sizePerPort.put(port, sizePerPort);
  }

  @Override
  @SuppressWarnings("unchecked")
  public List<Object> valueStructure(String jobId, String portId, UUID rootId) {
    if (emptyListDetected) {
      return (List<Object>) generateOutputsForEmptyList();
    }

    Collections.sort(combinations, new Comparator<Combination>() {
      @Override
      public int compare(Combination o1, Combination o2) {
        return o1.indexes.toString().compareTo(o2.indexes.toString());
      }
    });

    if (scatterMethod.equals(ScatterMethod.flat_crossproduct)) {
      LinkedList<Object> result = new LinkedList<>();
      for (Combination combination : combinations) {
        String scatteredJobId = InternalSchemaHelper.scatterId(jobId, combination.position);
        result.addLast(new JobPortPair(scatteredJobId, portId));
      }
      return result;
    }
    if (scatterMethod.equals(ScatterMethod.nested_crossproduct)) {
      LinkedList<Object> result = new LinkedList<>();

      int position = 1;
      LinkedList<Object> subresult = new LinkedList<>();
      for (Combination combination : combinations) {
        if (combination.indexes.get(0) != position) {
          result.addLast(subresult);
          subresult = new LinkedList<>();
          position++;
        }
        String scatteredJobId = InternalSchemaHelper.scatterId(jobId, combination.position);
        subresult.addLast(new JobPortPair(scatteredJobId, portId));
      }
      result.addLast(subresult);
      return result;
    }
    return null;
  }

  private <T> LinkedList<T> expand(LinkedList<T> list, Integer position) {
    if (list == null) {
      list = new LinkedList<>();
    }
    int initialSize = list.size();
    if (initialSize >= position) {
      return list;
    }
    for (int i = 0; i < position - initialSize; i++) {
      list.add(null);
    }
    return list;
  }

  private LinkedList<LinkedList<Integer>> cartesianProduct(LinkedList<LinkedList<Integer>> lists) throws BindingException {
    if (lists.size() < 2) {
      throw new BindingException("Can't have a product of fewer than two lists (got " + lists.size() + ")");
    }
    return cartesianProduct(0, lists);
  }

  private LinkedList<LinkedList<Integer>> cartesianProduct(int index, List<LinkedList<Integer>> lists) {
    LinkedList<LinkedList<Integer>> result = new LinkedList<LinkedList<Integer>>();
    if (index == lists.size()) {
      result.add(new LinkedList<Integer>());
    } else {
      for (Integer obj : lists.get(index)) {
        for (LinkedList<Integer> list : cartesianProduct(index + 1, lists)) {
          list.addFirst(obj);
          result.add(list);
        }
      }
    }
    return result;
  }

  @Override
  public synchronized void commit(List<RowMapping> mappings) {
    for (RowMapping mapping : mappings) {
      for (Combination combination : combinations) {
        if (combination.position == mapping.getIndex()) {
          combination.enabled = true;
        }
      }
    }
  }

  @Override
  public synchronized int enabledCount() {
    int size = 1;
    for (Entry<String, Integer> sizePerPort : this.sizePerPort.entrySet()) {
      size = size * sizePerPort.getValue();
    }
    return size;
  }

  @Override
  public synchronized List<RowMapping> enabled() throws ScatterStrategyException {
    List<RowMapping> result = new LinkedList<>();
    LinkedList<LinkedList<Integer>> mapping = new LinkedList<>();
    for (Entry<String, LinkedList<Integer>> positionEntry : positions.entrySet()) {
      mapping.add(positionEntry.getValue());
    }
    LinkedList<LinkedList<Integer>> newMapping;
    try {
      newMapping = cartesianProduct(mapping);

      for (int i = 0; i < newMapping.size(); i++) {
        LinkedList<Integer> indexes = newMapping.get(i);
        if (!hasNull(indexes)) {
          Combination combination = getCombination(indexes);
          if (combination == null) {
            combination = new Combination(combinations.size() + 1, false, indexes);
            combinations.add(combination);
          }
          if (!combination.enabled) {
            List<PortMapping> portMappings = new LinkedList<>();

            int positionIndex = 1;
            for (Entry<String, LinkedList<Object>> valueEntry : values.entrySet()) {
              String port = valueEntry.getKey();
              int position = combination.indexes.get(positionIndex - 1);
              Object value = valueEntry.getValue().get(position - 1);
              portMappings.add(new PortMapping(port, value));
              positionIndex++;
            }
            result.add(new RowMapping(combination.position, portMappings));
          }
        }
      }
      return result;
    } catch (BindingException e) {
      throw new ScatterStrategyException(e);
    }
  }

  private boolean hasNull(LinkedList<Integer> list) {
    for (Integer value : list) {
      if (value == null) {
        return true;
      }
    }
    return false;
  }

  private Combination getCombination(LinkedList<Integer> indexes) {
    for (Combination combination : combinations) {
      if (combination.indexes.toString().equals(indexes.toString())) {
        return combination;
      }
    }
    return null;
  }

  public static class Combination {
    @JsonProperty("position")
    int position;
    @JsonProperty("enabled")
    boolean enabled;
    @JsonProperty("indexes")
    List<Integer> indexes;

    @JsonCreator
    public Combination(@JsonProperty("position") int position, @JsonProperty("enabled") boolean enabled,
        @JsonProperty("indexes") List<Integer> indexes) {
      this.position = position;
      this.enabled = enabled;
      this.indexes = indexes;
    }

    @Override
    public String toString() {
      return "Combination [position=" + position + ", enabled=" + enabled + ", indexes=" + indexes + "]";
    }

  }

  @Override
  public boolean isBlocking() {
    return ScatterMethod.isBlocking(scatterMethod);
  }

  @Override
  public boolean isHanging() {
    for (String port : values.keySet()) {
      if (values.get(port) == null || (values.get(port) instanceof List<?> && ((List<?>)values.get(port)).isEmpty())) {
        return true;
      }
    }
    return false;
  }

  @Override
  public Object generateOutputsForEmptyList() {
    if (scatterMethod.equals(ScatterMethod.flat_crossproduct)) {
      return new ArrayList<>();
    }

    Integer numberOfEmptyLists = values.values().stream().map(l -> l.size() != 0? l.size() : 1).reduce((x,y) -> x*y).get();
    List<List<?>> result = new ArrayList<>();
    for (int i = 0; i < numberOfEmptyLists; i++) {
      result.add(new ArrayList<>());
    }
    return result;
  }

  @Override
  public void setEmptyListDetected() {
    this.emptyListDetected = true;
  }

  @Override
  public boolean isEmptyListDetected() {
    return emptyListDetected;
  }

  @Override
  public void skipScatter(boolean skipScatter) {
    this.skipScatter = skipScatter;
  }

  @Override
  public boolean skipScatter() {
    return skipScatter;
  }

}


text:
{% extends "/shared/modal-layout.html" %}

{% block HEADERTAGS %}
{{ super() }}

{% endblock %}

{% block BODY %}

Error! Verification link has expired

Sorry, the verification link you are using has expired. Please try to verify your account again.

Would you like to:

Try again

Continue using the site

{% endblock %}


text:
import React from 'react';
import { Router, Route, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { Provider } from 'react-redux';
import { I18nextProvider } from 'react-i18next';

import i18n from './i18n';
import modules from './config/modules';
import reducers from './reducers/';
import configureStore from './store/configureStore';

function getRoute(module) {
	return <Route key={module.path} {...module} />;
}

const store = configureStore()(reducers);

export default (
	<I18nextProvider i18n={i18n()}>
		<Provider store={store}>
			<Router history={syncHistoryWithStore(browserHistory, store)}>
				{modules.map(getRoute)}
			</Router>
		</Provider>
	</I18nextProvider>
);


text:
package org.knowm.xchange.coinbasepro.dto;

import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.coinbasepro.CoinbaseProAdapters;
import org.knowm.xchange.coinbasepro.CoinbaseProExchange;
import org.knowm.xchange.coinbasepro.dto.marketdata.CoinbaseProProduct;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import si.mazi.rescu.serialization.jackson.DefaultJacksonObjectMapperFactory;
import si.mazi.rescu.serialization.jackson.JacksonObjectMapperFactory;

public class CoinbaseProMetadataTest {

  @Test
  public void unmarshalTest() throws IOException {

    JacksonObjectMapperFactory factory = new DefaultJacksonObjectMapperFactory();
    ObjectMapper mapper = factory.createObjectMapper();

    InputStream is =
        getClass().getResourceAsStream("/org/knowm/xchange/coinbasepro/dto/products.json");
    CoinbaseProProduct[] products = mapper.readValue(is, CoinbaseProProduct[].class);
    assertThat(products).hasSize(10);

    ExchangeSpecification specification = new ExchangeSpecification(CoinbaseProExchange.class);
    specification.setShouldLoadRemoteMetaData(false);
    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(specification);
    ExchangeMetaData exchangeMetaData = exchange.getExchangeMetaData();
    exchangeMetaData = CoinbaseProAdapters.adaptToExchangeMetaData(exchangeMetaData, products);
    assertThat(exchangeMetaData.getCurrencyPairs().get(CurrencyPair.ETC_BTC).getPriceScale())
        .isEqualTo(5);
  }
}


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :load_learner

  def index
    topic_num = params[:topic_num]
    rep_num   = params[:rep_num]
    # let it raise ActiveRecord::RecordNotFound if not found; it will become a 404
    Exercise.find_by_path topic_num, rep_num

    send_file 'public/index.html', disposition: 'inline'
  end

  private
  def load_learner
    @learner = Learner.find_by_id(session[:learner_id])
    if @learner.nil?
      @learner              = Learner.new
      @learner.user_agent   = request.user_agent
      @learner.http_referer = request.env['HTTP_REFERER']
      @learner.remote_ip    = request.remote_ip
      unless request.user_agent =~ /(monitis|Googlebot|baiduspider|Exabot|Yahoo! Slurp|DotBot|bingbot|MJ12bot|panscient.com|YandexBot)/
        @learner.save!
        session[:learner_id] = @learner.id
      end
    end
  end
end


text:
package org.xblackcat.sjpu.util.function;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.ToIntBiFunction;

/**
 * Represents a function that accepts two arguments and produces an int-valued
 * result.  This is the {@code int}-producing primitive specialization for
 * {@link BiFunctionEx}.
 *

 *
This is a functional interface
 * whose functional method is {@link #applyAsInt(Object, Object)}.
 *
 * @param <T> the type of the first argument to the function
 * @param  the type of the second argument to the function
 * @param <E> the type of exception could be thrown while performing operation
 * @see BiFunctionEx
 * @since 1.8
 */
@FunctionalInterface
public interface ToIntBiFunctionEx<T, U, E extends Throwable> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    int applyAsInt(T t, U u) throws E;

    default ToIntFunctionEx<T, E> fixRight(U u) {
        return t -> applyAsInt(t, u);
    }

    default ToIntFunctionEx fixLeft(T t) {
        return u -> applyAsInt(t, u);
    }

    default IntSupplierEx<E> fix(T t, U u) {
        return () -> applyAsInt(t, u);
    }

    default ToIntBiFunction<T, U> unchecked(String exceptionText, BiFunction<String, Throwable, ? extends RuntimeException> cover) {
        return unchecked(() -> exceptionText, cover);
    }

    default ToIntBiFunction<T, U> unchecked() {
        return unchecked(CoveringException::new);
    }

    default ToIntBiFunction<T, U> unchecked(BiFunction<String, Throwable, ? extends RuntimeException> cover) {
        return unchecked(Throwable::getMessage, cover);
    }

    default ToIntBiFunction<T, U> unchecked(Supplier<String> text, BiFunction<String, Throwable, ? extends RuntimeException> cover) {
        return unchecked(e -> text.get(), cover);
    }

    default ToIntBiFunction<T, U> unchecked(
            Function<Throwable, String> text,
            BiFunction<String, Throwable, ? extends RuntimeException> cover
    ) {
        return (t, u) -> {
            try {
                return applyAsInt(t, u);
            } catch (Throwable e) {
                throw cover.apply(text.apply(e), e);
            }
        };
    }

}


text:
@interface ShareViewController () <UIActionSheetDelegate>

@end

@implementation ShareViewController

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // set background color of view
        self.view.backgroundColor = [UIColor colorWithRed:1.0 green:.765 blue:.451 alpha:1.0];

        // initialize and setup camera
        _camera = [UIImagePickerController new];
        _camera.delegate = self;
        _showedCamera = NO;

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [_camera setSourceType:UIImagePickerControllerSourceTypeCamera];
            [_camera setCameraDevice:UIImagePickerControllerCameraDeviceRear];
            [_camera setShowsCameraControls:YES];
        }

        // initialize photo saving setting variable
        NSUserDefaults *userSettings = [NSUserDefaults standardUserDefaults];
        _saveToCameraRoll = [[userSettings objectForKey:@"savePhotosToCameraRoll"] boolValue];

        // observe changes in the user's photo saving setting
        [[NSNotificationCenter defaultCenter] addObserver:self
                                              selector:@selector(updatePhotoSettings)
                                              name:NSUserDefaultsDidChangeNotification
                                              object:nil];

        // initialize image viewer
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, statusBarHeight, width, height - tabBarHeight)];
        [_imageView setContentMode:UIViewContentModeScaleAspectFit];
        [self.view addSubview:_imageView];
    }
    return self;
}

- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    _tabBarController.selectedViewController = _mainView;
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // dismiss the camera
    _showedCamera = true;
    [_camera dismissViewControllerAnimated:YES completion:nil];

    // grab the image and display it in the image viewer
    _image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [_imageView setImage:_image];

    // save the image in the camera roll (if user's settings dictate such)
    if (_saveToCameraRoll) {
        UIImageWriteToSavedPhotosAlbum(_image, self, nil, nil);
    }

    // create location string
    NSString *location = [NSString stringWithFormat:@"%@, %@", _city, _state];

    // create date string and remove excess zeroes
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/YYYY"];
    NSString *date = [formatter stringFromDate:[NSDate date]];

    if([[date substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"0"]){
        date = [date substringWithRange:NSMakeRange(1, date.length -1)];
    }
    NSRange indexOfslash = [date rangeOfString:@"/"];
    if([[date substringWithRange:NSMakeRange(indexOfslash.location+1, 1)] isEqualToString:@"0"]) {
        date = [date stringByReplacingCharactersInRange:NSMakeRange(indexOfslash.location+1, 1) withString:@""];
    }

    // save the entry in the database
    [Database saveEntryWithDate:date andLocation:location andImage:_image];
    _collectionView.entries = [Database fetchAllEntries];
    [_collectionView.tableView reloadData];

    // show the share and retake buttons
    [self showShareButton];
    [self showRetakeButton];
}

- (void) updatePhotoSettings
{
    // grab setting from bundle, set the member variable
    NSUserDefaults *userSettings = [NSUserDefaults standardUserDefaults];
    _saveToCameraRoll = [[userSettings objectForKey:@"savePhotosToCameraRoll"] boolValue];
}

- (void) showShareButton
{
    // setup the share button
    _shareButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _tabBarController.tabBar.frame.origin.y - tabBarHeight, width/2, tabBarHeight)];

    _shareButton.backgroundColor = [UIColor colorWithRed:1.0 green:.573 blue:0 alpha:1.0];
    [_shareButton.titleLabel setFont:[UIFont fontWithName:@"Avenir" size:25.0]];

    [_shareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_shareButton setTitle:@"Share" forState:UIControlStateNormal];

    [_shareButton setShowsTouchWhenHighlighted:YES];
    [_shareButton addTarget:self action:@selector(sharePressed) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_shareButton];
}

- (void) sharePressed
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share via" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook", @"Twitter", @"Email", @"Message", nil];

    [actionSheet showFromTabBar:_tabBarController.tabBar];
}

- (void) showRetakeButton
{
    // setup the retake button
    _retakeButton = [[UIButton alloc] initWithFrame:CGRectMake(width/2, _tabBarController.tabBar.frame.origin.y - tabBarHeight, width/2, tabBarHeight)];

    [_retakeButton setBackgroundColor:LIGHT_ORANGE];
    [_retakeButton.titleLabel setFont:[UIFont fontWithName:@"Avenir" size:25.0]];

    [_retakeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_retakeButton setTitle:@"Retake" forState:UIControlStateNormal];

    [_retakeButton setShowsTouchWhenHighlighted:YES];
    [_retakeButton addTarget:self action:@selector(retakePressed) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:_retakeButton];
}

- (void) retakePressed
{
    // clear out image and image viewer, present camera again
    _image = nil;
    [_imageView setImage:nil];
    [self presentViewController:_camera animated:YES completion:^{}];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // indices in this conditional are from [@"Facebook", @"Twitter", @"Email", @"Message", nil]
    if (buttonIndex == 0) { // facebook
        if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
            SLComposeViewController *facebookComposer = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

            [facebookComposer setInitialText:[NSString stringWithFormat:@"Check out this sunset photo I just took in %@, %@! #Splendor", _city, _state]];
            [facebookComposer addImage:_image];

            [self presentViewController:facebookComposer animated:YES completion:nil];
        }
    }
    else if (buttonIndex == 1) { // twitter
        if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
            SLComposeViewController *twitterComposer = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];

            [twitterComposer setInitialText:[NSString stringWithFormat:@"Check out this sunset photo I just took in %@, %@! #Splendor", _city, _state]];
            [twitterComposer addImage:_image];

            [self presentViewController:twitterComposer animated:YES completion:nil];
        }
    }
    else if (buttonIndex == 2) { // email
        MFMailComposeViewController *emailController = [[MFMailComposeViewController alloc] initWithNibName:nil bundle:nil];

        [emailController setMailComposeDelegate:self];
        NSData *imgData = UIImageJPEGRepresentation(_image, .7);

        [emailController addAttachmentData:imgData mimeType:nil fileName:@"image.jpeg"];

        [emailController setMessageBody:[NSString stringWithFormat:@"Hey, check out this sunset photo I just took in %@, %@!", _city, _state] isHTML:NO];

        [emailController setSubject:[NSString stringWithFormat:@"%@, %@ Sunset", _city, _state]];

        [self presentViewController:emailController animated:YES completion:nil];
    }
    else if (buttonIndex == 3) { // message
        MFMessageComposeViewController *messageController = [MFMessageComposeViewController new];

        [messageController setMessageComposeDelegate:self];

        NSData *imgData = UIImageJPEGRepresentation(_image, .7);
        BOOL didAttachImage = [messageController addAttachmentData:imgData typeIdentifier:@"public.data" filename:@"image.jpeg"];
        [messageController setBody:[NSString stringWithFormat:@"Hey, check out this sunset photo I just took in %@, %@!", _city, _state]];

        if (didAttachImage) {
            [self presentViewController:messageController animated:YES completion:nil];
        }
        else {
            UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                   message:@"Failed to attach image"
                                                                  delegate:nil
                                                         cancelButtonTitle:@"OK"
                                                         otherButtonTitles:nil];
            [warningAlert show];
            return;
        }
    }
    else { // cancel
        // do nothing
    }
}

-(void) messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [_tabBarController setSelectedViewController:_mainView];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [_tabBarController setSelectedViewController:_mainView];
}

- (void) viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // show the camera if we haven't already, or if no image is currently present
    if(!_showedCamera || _image == nil){
        [self presentViewController:_camera animated:YES completion:^{}];
    }
}

- (void) viewDidDisappear:(BOOL)animated
{
    // reset view controller when it is closed
    _showedCamera = NO;

    [_imageView setImage:nil];
    _image = nil;

    [_retakeButton removeFromSuperview];
    [_shareButton removeFromSuperview];
}

- (void) didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
.class Lcom/android/internal/widget/ActionBarOverlayLayout$3;
.super Ljava/lang/Object;
.source "ActionBarOverlayLayout.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/widget/ActionBarOverlayLayout;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

# direct methods
.method constructor <init>(Lcom/android/internal/widget/ActionBarOverlayLayout;)V
    .locals 0

    iput-object p1, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 4

    const/4 v3, 0x0

    iget-object v0, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v0}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-wrap0(Lcom/android/internal/widget/ActionBarOverlayLayout;)V

    iget-object v0, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    iget-object v1, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v1}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get1(Lcom/android/internal/widget/ActionBarOverlayLayout;)Lcom/android/internal/widget/ActionBarContainer;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/internal/widget/ActionBarContainer;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    invoke-virtual {v1, v3}, Landroid/view/ViewPropertyAnimator;->translationY(F)Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v2}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get3(Lcom/android/internal/widget/ActionBarOverlayLayout;)Landroid/animation/Animator$AnimatorListener;

    move-result-object v2

    invoke-virtual {v1, v2}, Landroid/view/ViewPropertyAnimator;->setListener(Landroid/animation/Animator$AnimatorListener;)Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    invoke-static {v0, v1}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-set2(Lcom/android/internal/widget/ActionBarOverlayLayout;Landroid/view/ViewPropertyAnimator;)Landroid/view/ViewPropertyAnimator;

    iget-object v0, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v0}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get0(Lcom/android/internal/widget/ActionBarOverlayLayout;)Lcom/android/internal/widget/ActionBarContainer;

    move-result-object v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v0}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get0(Lcom/android/internal/widget/ActionBarOverlayLayout;)Lcom/android/internal/widget/ActionBarContainer;

    move-result-object v0

    invoke-virtual {v0}, Lcom/android/internal/widget/ActionBarContainer;->getVisibility()I

    move-result v0

    const/16 v1, 0x8

    if-eq v0, v1, :cond_0

    iget-object v0, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    iget-object v1, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v1}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get0(Lcom/android/internal/widget/ActionBarOverlayLayout;)Lcom/android/internal/widget/ActionBarContainer;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/internal/widget/ActionBarContainer;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    invoke-virtual {v1, v3}, Landroid/view/ViewPropertyAnimator;->translationY(F)Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/widget/ActionBarOverlayLayout$3;->this$0:Lcom/android/internal/widget/ActionBarOverlayLayout;

    invoke-static {v2}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-get2(Lcom/android/internal/widget/ActionBarOverlayLayout;)Landroid/animation/Animator$AnimatorListener;

    move-result-object v2

    invoke-virtual {v1, v2}, Landroid/view/ViewPropertyAnimator;->setListener(Landroid/animation/Animator$AnimatorListener;)Landroid/view/ViewPropertyAnimator;

    move-result-object v1

    invoke-static {v0, v1}, Lcom/android/internal/widget/ActionBarOverlayLayout;->-set1(Lcom/android/internal/widget/ActionBarOverlayLayout;Landroid/view/ViewPropertyAnimator;)Landroid/view/ViewPropertyAnimator;

    :cond_0
    return-void
.end method