text:
package com.facebook.buck.parser.exceptions;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.UnconfiguredBuildTarget;
import java.nio.file.Path;

/** Thrown when build target definition is missing in corresponding build file */
public class NoSuchBuildTargetException extends BuildTargetException {

  public NoSuchBuildTargetException(BuildTarget target) {
    this(String.format("No such target: '%s'", target));
  }

  public NoSuchBuildTargetException(UnconfiguredBuildTarget target) {
    this(String.format("No such target: '%s'", target));
  }

  private NoSuchBuildTargetException(String message) {
    super(message);
  }

  /** @param buildTarget the failing {@link BuildTarget} */
  public static NoSuchBuildTargetException createForMissingBuildRule(
      UnconfiguredBuildTarget buildTarget, Path buckFilePath) {
    String message =
        String.format(
            "The rule %s could not be found.\nPlease check the spelling and whether it exists in %s.",
            buildTarget.getFullyQualifiedName(), buckFilePath);
    return new NoSuchBuildTargetException(message);
  }

  @Override
  public String getHumanReadableErrorMessage() {
    return getMessage();
  }
}


text:
/**
 * Created by Answer1215 on 8/7/2015.
 */
import axios from 'axios';

function getRepos(username) {
    return axios.get(`https://api.github.com/users/${username}/repos`);
};

function getUserInfo(username) {
    return axios.get(`https://api.github.com/users/${username}`);
}

var helpers = {
    getGithubInfo(username) {
        return axios.all([getRepos(username), getUserInfo(username)])
            .then((arr) => {
                return {
                    repos: arr[0].data,
                    bio: arr[1].data
                }
            });
    }
};

export default helpers;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width" />
		<title>Login</title>

IBM

IBM Worklight

			<form method="post" action="j_security_check">

${errorMessage}

				User name:
				<input type="text" id="j_username" name="j_username" placeholder="User name" />

				Password:
				<input type="password" id="j_password" name="j_password" placeholder="Password" />

				<input type="submit" id="login" name="login" value="Log In" />
			</form>

© 2006, 2012 IBM Corporation. Trademark


text:
<?php

namespace Pitpit\Component\MongoFilesystem\Tests;

use Symfony\Component\Filesystem\Filesystem;
use Pitpit\Component\MongoFilesystem\Finder\Finder;
use Symfony\Component\Finder\Finder as BaseFinder;
use Pitpit\Component\MongoFilesystem\Tests\MongoGridTestHelper;
use Pitpit\Component\MongoFilesystem\SplFileInfo;

class FinderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string
     */
    private $workspace = null;

    /**
     * @var boolean
     */
    protected $legacy;

    protected function getFinder()
    {
        if ($this->legacy) {
            return new BaseFinder();
        } else {
            return new Finder();
        }
    }

    protected function setUp()
    {
        $this->legacy = isset($_SERVER['LEGACY_TESTS']) ? (bool) $_SERVER['LEGACY_TESTS'] : false;
        $this->workspace = sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid();
        $fs = new Filesystem();
        $fs->mkdir($this->workspace.'/bar');
        $fs->touch($this->workspace.'/foo.txt');
        $fs->touch($this->workspace.'/bar/foo.txt');
        $fs->touch($this->workspace.'/bar/.hidden');

        if (!$this->legacy) {
            MongoGridTestHelper::getGridFS()->storeBytes('', array('filename' => $this->workspace, 'type' => 'dir'));
            MongoGridTestHelper::getGridFS()->storeBytes('', array('filename' => $this->workspace.'/bar', 'type' => 'dir'));
            MongoGridTestHelper::getGridFS()->storeFile($this->workspace.'/foo.txt', array('type' => 'file'));
            MongoGridTestHelper::getGridFS()->storeFile($this->workspace.'/bar/foo.txt', array('type' => 'file'));
            MongoGridTestHelper::getGridFS()->storeFile($this->workspace.'/bar/.hidden', array('type' => 'file'));

            $fs->remove($this->workspace);
        }
    }

    protected function tearDown()
    {
        if ($this->legacy) {
            $fs = new Filesystem();
            $fs->remove($this->workspace);
        }
    }

    protected function assertFileIterator($filenames, $iterator)
    {
        $files = array();
        foreach ($iterator as $file) {
            $files[] = $file->getPathname();
        }

        $this->assertEquals($filenames, $files);
    }

    public function testIn()
    {
        $finder = $this->getFinder();
        $finder->in($this->workspace);

        $this->assertFileIterator(array(
            $this->workspace.'/bar',
            $this->workspace.'/bar/foo.txt',
            $this->workspace.'/foo.txt'
        ), $finder->getIterator());
    }

    public function testDepth()
    {
        $finder = $this->getFinder();
        $finder->in($this->workspace)->depth(0);

        $this->assertFileIterator(array(
            $this->workspace.'/bar',
            $this->workspace.'/foo.txt',
        ), $finder->getIterator());

        $finder = $this->getFinder();
        $finder->in($this->workspace)->depth(1);

        $this->assertFileIterator(array(
            $this->workspace.'/bar/foo.txt'
        ), $finder->getIterator());
    }

    public function testignoreDotFiles()
    {
        $finder = $this->getFinder();
        $finder->in($this->workspace)->ignoreDotFiles(true);

        $this->assertFileIterator(array(
            $this->workspace.'/bar',
            $this->workspace.'/bar/foo.txt',
            $this->workspace.'/foo.txt',
        ), $finder->getIterator());
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.hazelcast.spi.impl.NodeEngineImpl (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.hazelcast.spi.impl.NodeEngineImpl

Packages that use NodeEngineImpl

Package
Description

com.hazelcast.cluster

This package contains the cluster functionality.

com.hazelcast.instance

This package contains Hazelcast Instance functionality.

com.hazelcast.spi

Provides interfaces/classes for Hazelcast SPI.

com.hazelcast.spi.impl

Contains implementations for Hazelcast SPI.

com.hazelcast.transaction.impl

Provides implementation for Hazelcast transaction support.

Uses of NodeEngineImpl in com.hazelcast.cluster

Methods in com.hazelcast.cluster that return NodeEngineImpl

Modifier and Type
Method and Description

NodeEngineImpl
ClusterServiceImpl.getNodeEngine()

Uses of NodeEngineImpl in com.hazelcast.instance

Fields in com.hazelcast.instance declared as NodeEngineImpl

Modifier and Type
Field and Description

NodeEngineImpl
Node.nodeEngine

Methods in com.hazelcast.instance that return NodeEngineImpl

Modifier and Type
Method and Description

NodeEngineImpl
Node.getNodeEngine()

Uses of NodeEngineImpl in com.hazelcast.spi

Fields in com.hazelcast.spi declared as NodeEngineImpl

Modifier and Type
Field and Description

protected NodeEngineImpl
InvocationBuilder.nodeEngine

Constructors in com.hazelcast.spi with parameters of type NodeEngineImpl

Constructor and Description

InvocationBuilder(NodeEngineImpl nodeEngine,
                 String serviceName,
                 Operation op,
                 int partitionId,
                 Address target)

Creates an InvocationBuilder

Uses of NodeEngineImpl in com.hazelcast.spi.impl

Constructors in com.hazelcast.spi.impl with parameters of type NodeEngineImpl

Constructor and Description

BasicInvocationBuilder(NodeEngineImpl nodeEngine,
                      String serviceName,
                      Operation op,
                      Address target)

BasicInvocationBuilder(NodeEngineImpl nodeEngine,
                      String serviceName,
                      Operation op,
                      int partitionId)

BasicPartitionInvocation(NodeEngineImpl nodeEngine,
                        String serviceName,
                        Operation op,
                        int partitionId,
                        int replicaIndex,
                        int tryCount,
                        long tryPauseMillis,
                        long callTimeout,
                        Callback<Object> callback,
                        String executorName,
                        boolean resultDeserialized)

BasicTargetInvocation(NodeEngineImpl nodeEngine,
                     String serviceName,
                     Operation op,
                     Address target,
                     int tryCount,
                     long tryPauseMillis,
                     long callTimeout,
                     Callback<Object> callback,
                     String executorName,
                     boolean resultDeserialized)

ExecutionServiceImpl(NodeEngineImpl nodeEngine)

Uses of NodeEngineImpl in com.hazelcast.transaction.impl

Constructors in com.hazelcast.transaction.impl with parameters of type NodeEngineImpl

Constructor and Description

TransactionManagerServiceImpl(NodeEngineImpl nodeEngine)

XAResourceImpl(TransactionManagerServiceImpl transactionManager,
              com.hazelcast.transaction.impl.TransactionContextImpl transactionContext,
              NodeEngineImpl nodeEngine)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
package net.erdfelt.android.apk;

import net.erdfelt.android.apk.xml.Attribute;
import net.erdfelt.android.apk.xml.BinaryXmlListener;

public class BinaryXmlDump implements BinaryXmlListener {
    public void onXmlEntry(String path, String name, Attribute... attrs) {
        System.out.printf("%s -> <%s%n", path, name);
        String indent = path.replaceAll(".", " ");
        for (Attribute attr : attrs) {
            System.out.printf("%s      %s=\"%s\"%n", indent, attr.getName(), attr.getValue());
        }
    }
}


text:
<?php

namespace jubianchi\BehatViewerBundle\Entity;

abstract class Base
{
    public static function initFromArray(array $values = array())
    {
        $instance = new static();

        foreach ($values as $field => $value) {
            $setter = 'set' . ucfirst($field);
            $this->$setter($value);
        }

        return $instance;
    }
}


text:
@interface NSMutableArray (NoCrash)
+ (void)swizzle;
@end


text:
{% extends "admin/base_site.html" %}
{% block content_title %}
Solicitação Bolsa Refeição
{% endblock %}
{% block content %}

Inscrição não permitida nesse horário.

<o>Os horários são:</o>
{% for horario in horarios %}
{% if forloop.first %}{{ horario.hora_inicio }} à {{ horario.hora_fim }}
{% elif forloop.last %}e {{ horario.hora_inicio }} à {{ horario.hora_fim }}
{% else %}, {{ horario.hora_inicio }} à {{ horario.hora_fim }}{% endif %}
{% endfor %}

{% endblock %}


text:
package handler

import (
	"OnlineJudge/models"
	"OnlineJudge/pbgen/api"

	"github.com/jmoiron/sqlx"

	"time"
)

func (this *BasicHandler) ListContests(response *api.ListContestsResponse, req *api.ListContestsRequest) {
	defer PanicHandler(response, this.debug)
	tx := this.dbu.MustBegin()
	defer this.dbu.Rollback()
	ListContests_BuildResponse(
		tx,
		response,
		req,
		false,
		this.debug,
	)
}

func ListContests_BuildResponse(
	tx *sqlx.Tx,
	response *api.ListContestsResponse,
	req *api.ListContestsRequest,
	show_hidden bool,
	debug bool) {

	page, err := models.XQuery_List_Contests_With_Filter(
		tx,
		int(req.GetPerPage()),
		int(req.GetCurrentPage()),
		req.GetOrderBy(),
		req.GetIsDesc(),
		req.GetFilterCtype(),
		req.GetFilterIsPublic(),
		req.GetFilterIsVirtual(),
		nil,
		nil,
	)
	PanicOnError(err)

	// Build response
	lines := []*api.ListContestsResponse_PerLine{}
	for _, contest := range page.Contests {
		// TODO: finish status and access
		line := &api.ListContestsResponse_PerLine{
			ContestId: contest.ContestId,
			Title:     contest.Title,
			StartTime: contest.StartTime.String(),
			EndTime:   contest.EndTime.String(),
			// Status:      "ended",
			// Access:      "public",
			ContestType: contest.ContestType,
		}
		if contest.Password == "" {
			line.Access = "public"
		} else {
			line.Access = "private"
		}
		statusCode := JudgeContestStatus(&contest, time.Now().UTC())
		line.Status = ContestStatusCodeString(statusCode)
		lines = append(lines, line)
	}
	response.Lines = lines
	response.TotalLines = int32(page.TotalLines)
	response.TotalPages = int32(page.TotalPages)
	response.CurrentPage = int32(page.CurrentPage)
}

// -1 in-future, 0 in-progress 1 ended
func JudgeContestStatus(cst *models.Contest, t time.Time) int {
	if t.Before(cst.StartTime) {
		return -1
	}
	if t.After(cst.EndTime) {
		return 1
	}
	return 0
}

func ContestStatusCodeString(c int) string {
	switch c {
	case -1:
		return "in-future"
	case 0:
		return "in-progress"
	case 1:
		return "ended"
	}
	return "unknown"
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link rel="stylesheet" href="../../skin/tigris.css" type="text/css">
<link rel="stylesheet" href="../../skin/mysite.css" type="text/css">
<link rel="stylesheet" href="../../skin/site.css" type="text/css">
<link media="print" rel="stylesheet" href="../../skin/print.css" type="text/css">
<title>Preguntas M Frecuentes (FAQ)</title>

Apache | POI

Home |  | PDF

Apache POI

TOP

Marketing

Casos

Proyecto

Descripción General

POIFS [EN]

HSSF [EN]

HWPF [EN]

HPSF [EN]

POI-Utils [EN]

Descargas

Comunidad

Noticias

Espejos [EN]

Cambios [EN]

Tareas

Contribuya [EN]

Listas de Correo

Visión [EN]

Historia y Futuro

Quiénes Somos

Resoluciones [EN]

Documentación

Javadocs

FAQ

Referencias

Traducciones

Índice

Procedimientos

Alemán (DE)

Español

Japonés (Web)

Coreano(Web)

Código

CVS

Fallos (Bugs) Más Votados

Base de Datos de Fallos

Parches

Resultados de Pruebas Junit

Métricas de Dependencia

<form target="_blank" action="http://www.google.com/search" method="get">

	<input value="poi.apache.org" name="sitesearch" type="hidden"><input size="10" name="q" id="query" type="text"><input name="Search" value="GO" type="submit">

                          Search poi

</form>

Preguntas M Frecuentes (FAQ)

Questions

          or qula lectura de una hoja de cculo simple lleva tanto tiempo?

          ues el "eventmodel" (modelo de evento) de HSSF?

          or quno puedo leer el documento que creutilizando Star Office 5.1?

            or qurecibo una excepci cada vez que intento leer mi hoja de cculo?

            oporta HSSF hojas de cculo protegidas?

            o se sabe si un campo contiene una fecha con HSSF?

            Estoy intentando ver un fichero XLS enviado como flujo (stream) desde un servlet y tengo
            complicaciones. u es el problema?

            Quiero dar formato a una celda (Data format of a cell) de una hoja excel como
            ###,###,###.#### o ###,###,###.0000. s posible hacer esto con POI?

            o ado un borde alrededor de una celda unida (merged)?

            Intentescribir valores en celdas ascomo cambiar el nombre de la hoja Excel
            en mi lengua nativa, pero no pude hacerlo. :(

Answers

1.
          or qula lectura de una hoja de cculo simple lleva tanto tiempo?

          Probablemente hayas habilitado el registro (logging). Dicho registro es
          una herramienta il para la bqueda de errores (debug). Tenerlo habilitado
          reducirel rendimiento en un factor de al menos 100. El registro es il para
          comprender por quPOI no puede leer alg fichero o para el propio desarrollo
          de POI.
          Los errores importantes se lanzan como excepciones, lo cual significa que
          probablemente no necesites el registro (log).

2.
          ues el "eventmodel" (modelo de evento) de HSSF?

 El paquete "eventmodel" de HSSF es un nuevo API para la lectura m eficiente de ficheros
              XML. Requiere mayor conocimiento por parte del usuario, pero reduce el consumo de memoria a
              una dima parte. Estbasado en el modelo de eventos AWT en combinaci con SAX. Si necesita
              acceso de so-lectura a un fichero XML determinado, esta es la mejor manera de hacerlo.

3.
          or quno puedo leer el documento que creutilizando Star Office 5.1?

Star Office 5.1 escribe algunos registros utilizando el viejo estdar BIFF.
              Esto provoca algunos problemas con POI que so soporta BIFF8.

4.
            or qurecibo una excepci cada vez que intento leer mi hoja de cculo?

Es posible que su hoja de cculo contenga alguna caractertica que no est
            soportada actualmente por HSSF. Por ejemplo - hojas de cculo que contengan
            celdas con formato RTF (rich text) no est soportadas actualmente.

5.
            oporta HSSF hojas de cculo protegidas?

Al proteger una hoja de cculo, ta se cifra. No tocaremos el cifrado, porque no
            tenemos el suficiente conocimiento legal y no estamos seguros de las implicaciones que
            conllevar el intentar implementar esto. Si desea intentarlo, es libre de hacerlo y
            de adirlo como un mulo enchufable (plugin). Sin embargo, no lo guardaremos aqu

6.
            o se sabe si un campo contiene una fecha con HSSF?

Excel almacena las fechas como neros. Asla ica manera para determinar
            si una celda estrealmente almacenada como una fecha consiste en mirar su formato.
            Hay un modo de ayuda (helper) en HSSFDateUtil (desde la distribuci 1.7.0-dev)
            que lo comprueba. Gracias a Jason Hoffman por proporcionar la soluci.

case HSSFCell.CELL_TYPE_NUMERIC:
                  double d = cell.getNumericCellValue();
                  // test if a date!
                             if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    // format in form of M/D/YY
                    cal.setTime(HSSFDateUtil.getJavaDate(d));
                    cellText =
                      (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
                    cellText = cal.get(Calendar.MONTH)+1 + "/" +
                               cal.get(Calendar.DAY_OF_MONTH) + "/" +
                               cellText;
                  }

7.
            Estoy intentando ver un fichero XLS enviado como flujo (stream) desde un servlet y tengo
            complicaciones. u es el problema?

            El problema normalmente se manifiesta como un mont de caracteres basura
            en la pantalla. El problema persiste incluso aunque hayas configurado el tipo mime
            correcto.

            La respuesta breve es: no dependas de IE para mostrar un fichero binario.
            Escribe un documento adjunto como es debido si lo envs a trav de un servlet.
            Toda versi de IE tiene diferentes fallos (bugs) en este sentido.

            El problema en la mayor de las versiones de IE reside en que no utiliza el tipo mime
            de la respuesta HTTP para determinar el tipo de fichero; en su lugar utiliza la extensi
            del fichero en la petici. Aspodr adir un .xls a su cadena de petici.
            Por ejemplo: http://yourserver.com/myServelet.xls?param1=xx. Esto se consigue
            filmente a trav del mapeo de URL en cualquier contenedor servlet. A veces una
            petici como
                http://yourserver.com/myServelet?param1=xx&dummy=file.xls
            tambi funciona.

            Para garantizar la correcta apertura del fichero en Excel desde IE, escribe
            tu fichero a un fichero temporal bajo su raiz web desde tu servlet. Env entonces
            una respuesta http al navegador para que haga una redirecci en el lado del cliente
            a tu fichero temporal. (Si haces una redirecci en el lado del servidor utilizando
            RequestDispatcher, tendr que adir .xls a la petici como se ha mendionado m
            arriba)

            Date cuenta de que cuando pides un documento que se abre con un manejador externo,
            IE a veces realiza dos peticiones al servidor web. Asque si tu proceso generador
            es pesado, tiene sentido escribir a un fichero temporal, para que peticiones
            mtiples utilicen el fichero estico.

            Nada de esto pertenece a Excel. El mismo problema ocurre cuando intentas general
            cualquier fichero binario dinicamente a un cliente IE. Por ejemplo, si generas
            ficheros pdf utilizando
                FOP,
                te encontrar con los mismos problemas.

8.
            Quiero dar formato a una celda (Data format of a cell) de una hoja excel como
            ###,###,###.#### o ###,###,###.0000. s posible hacer esto con POI?

                HSSF no soporta todav formatos de datos personalizados, sin embargo,
                deber ser una facilidad razonablemente sencilla de adir y aceptaremos
                gustosos contribuciones en este ea.

                Estos son los formatos incluidos que soporta:

http://jakarta.apache.org/poi/javadocs/javasrc/org/apache/poi/hssf/usermodel/HSSFDataFormat_java.html#HSSFDataFormat

9.
            o ado un borde alrededor de una celda unida (merged)?

            Ade celdas vacs alrededor de donde las celdas hubieran estado normalmente y
            configura los bordes individualmente para cada celda.
            Probablemente mejoraremos HSSF en el futuro para facilitar este proceso.

10.
            Intentescribir valores en celdas ascomo cambiar el nombre de la hoja Excel
            en mi lengua nativa, pero no pude hacerlo. :(

            Por defecto HSSF utiliza valores de celdas y nombres de hoja en unicode comprimido,
            asi que para soportar la localizaci debers utilizar Unicode.
            Para hacerlo debers configurarlo manualmente:

                //
                // para el nombre de la hoja
                //
                HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet s = wb.createSheet();
                wb.setSheetName( 0, "SomeUnicodeName", HSSFWorkbook.ENCODING_UTF_16 );

                //
                // para el valor de la celda
                //
                HSSFRow r = s.createRow( 0 );
                HSSFCell c = r.createCell( (short)0 );
                c.setCellType( HSSFCell.CELL_TYPE_STRING );
                c.setEncoding( HSSFCell.ENCODING_UTF_16 );
                c.setCellValue( "\u0422\u0435\u0441\u0442\u043E\u0432\u0430\u044F" );

            Asegate de que haces la llamada a setEncoding() antes de llamar a setCellValue(),
            si no, lo que le pases no serinterpretado correctamente.

              Copyright © 2002-2007 The Apache Software Foundation. All rights reserved.


text:
require "printaura/version"
require "printaura/product"
require "printaura/image"

module Printaura
  class Config
    def self.API_KEY
      @API_KEY
    end

    def self.API_HASH
      @API_HASH
    end

    def self.API_KEY=(key)
      @API_KEY=key
    end

    def self.API_HASH=(hash)
      @API_HASH=hash
    end
  end
end


text:
module GenSpec
  module Matchers
    class ResultMatcher < GenSpec::Matchers::Base
      attr_reader :filename

      def initialize(filename, &block)
        @filename = filename
        super(&block)
      end

      def generated
        if filename
          path = File.join(destination_root, filename)
          if File.exist?(path)
            match!
            spec_file_contents(path)
          end
        else
          # there was no error, so in the context of
          # "should generate", it most certainly
          # generated.
          match!
          if block
            block.call
          end
        end
      end

      def failure_message
        "Expected to generate #{filename}"
      end

      def negative_failure_message
        "Expected to not generate #{filename}"
      end
    end
  end
end


text:
require 'minitest/autorun'
Bundler.require :default
require 'handlersocket'
require 'yaml'
require 'securerandom'

$conf  = YAML.load_file File.expand_path('../database.yml', __FILE__)
$mysql = Mysql2::Client.new($conf['my'])
$mysql.query "DROP DATABASE IF EXISTS #{$conf['db']}"
$mysql.query "CREATE DATABASE IF NOT EXISTS #{$conf['db']}"
$mysql.query "USE #{$conf['db']}"
$mysql.query 'CREATE TABLE table1 (k VARCHAR(32) PRIMARY KEY, v VARCHAR(32))'
$mysql.query 'CREATE TABLE table2 (k INTEGER PRIMARY KEY, v1 VARCHAR(32) NOT NULL, v2 VARCHAR(32) NOT NULL, v3 VARCHAR(32) NOT NULL)'


text:
package org.cucina.sample.engine.client.app;

/**
 * Provides expression execution functionality.
 *
 * @author $Author: $
 * @version $Revision: $
 */
public interface ExpressionExecutor {
	/**
	 * JAVADOC Method Level Comments
	 *
	 * @param <T>        JAVADOC.
	 * @param context    JAVADOC.
	 * @param expression JAVADOC.
	 * @return JAVADOC.
	 */
	<T> T evaluate(Object context, String expression);

	/**
	 * Set value using expression on context.
	 *
	 * @param context    Object.
	 * @param expression String.
	 * @param value      Object.
	 */
	void set(Object context, String expression, Object value);
}


text:
title: oVirt 3.4.2 Release Notes
category: documentation
authors: dougsland, sandrobonazzola
wiki_category: Documentation
wiki_title: OVirt 3.4.2 Release Notes
wiki_revision_count: 16
wiki_last_updated: 2014-06-11
---

# oVirt 3.4.2 Release Notes

The oVirt Project is pleased to announce the availability of oVirt 3.4.2 release.

oVirt is an open source alternative to VMware vSphere, and provides an awesome KVM management interface for multi-node virtualization.

To find out more about features which were added in previous oVirt releases, check out the [oVirt 3.4.1 release notes](oVirt 3.4.1 release notes), [oVirt 3.4 Release Notes](oVirt 3.4 Release Notes), [oVirt 3.3.5 release notes](oVirt 3.3.5 release notes), [oVirt 3.2 release notes](oVirt 3.2 release notes) and [oVirt 3.1 release notes](oVirt 3.1 release notes). For a general overview of oVirt, read [ the oVirt 3.0 feature guide](oVirt 3.0 Feature Guide) and the [about oVirt](about oVirt) page.

## Install / Upgrade from previous versions

### Fedora / CentOS / RHEL

In order to install it on a clean system, you need to install

`# yum localinstall `[`http://resources.ovirt.org/pub/yum-repo/ovirt-release34.rpm`](http://resources.ovirt.org/pub/yum-repo/ovirt-release34.rpm)

You should read then our [Quick Start Guide](Quick Start Guide)

If you're upgrading from a previous version you should have ovirt-release package already installed on your system.

You can then install ovirt-release34.rpm as in a clean install side-by-side.

If you're upgrading from oVirt 3.4.0 you can now remove ovirt-release package:

      # yum remove ovirt-release
      # yum update "ovirt-engine-setup*"
      # engine-setup

If you're upgrading from 3.3.2 or later, keep ovirt-release rpm in place until the upgrade is completed. See [oVirt 3.4.0 release notes](oVirt 3.4.0 release notes) for upgrading from previous versions.

### oVirt Live

A new oVirt Live ISO is available:

[`http://resources.ovirt.org/pub/ovirt-3.4/iso/ovirt-live-el6-3.4.2.iso`](http://resources.ovirt.org/pub/ovirt-3.4/iso/ovirt-live-el6-3.4.2.iso)

### oVirt Hosted Engine

If you're going to install oVirt as Hosted Engine on a clean system please follow [Hosted_Engine_Howto#Fresh_Install](Hosted_Engine_Howto#Fresh_Install) guide.

If you're upgrading an existing Hosted Engine setup, please follow [Hosted_Engine_Howto#Upgrade_Hosted_Engine](Hosted_Engine_Howto#Upgrade_Hosted_Engine) guide.

## What's New in 3.4.2?

## Known issues

## Bugs fixed

### oVirt Engine

* 'list jobs' shows 'UNKNOWN' for target hosts when VMs are migrating
 - [RHSC] Host does not move to non operational even after glusterd is made down .
 - display the actual CPU allocation of a VM to manage inconsistencies
 - User and System CPU Usage have values higher than 100%
 - [branding] engine-setup says "login into oVirt Engine"
 - [REST-API] Can't set display network if display=false and usages.usage is display
 - [engine] [RO-disk] Direct-LUN connected by Virt-IO-SCSI which is configured to be RO to a VM is writeable
 - Run once vm with attached cd, not attach payload
 - Hot plug causes the breach in quota enforcement
 - Break bond by detaching the network label cannot be done in one step
 - template of thin provision NFS,can't be copied to block data domains
 - [Network Label] Cannot break bond with Network label attached by break bond action
 - Engine should not send defaultRoute in clusterLevel <= 3.3
 - [User Portal] Windows VNC-based VM are opened via RDP by default in User Portal
 - Cannot sysprep Windows VM with different time zone than the one set in VM dialog / System side-tab
 - SuperUser of DataCenter X cannot approve a host under this Data Center
 - [Network labels] Network label rename should be blocked while label is configured on hosts
 - Extending Preallocated Read Only Disk should fail
 - Extending Thin provision Read Only Disk should block with canDoAction
 - NullPointerException raised while perform REST API request api/vms/\*\*\*/applications for VM w/o installed applications
 - New Power Savings Policy Parameters are not in Beta 3 Build
 - Failed to commit custom preview of snapshot
 - Unable to upgrade rhevh - Please select an ISO with major version 6.x
 - Neutron: Failed to install Host neseted_host_1. Failed to execute stage 'Misc configuration': list index out of range.
 - Block IDE disks and VirtIO-SCSI disks when attaching/updating
 - admin@internal can not log in to the Web admin portal if another admin user exists in an external directory
 - rhevm failed to create "rhevm" bridge after add new host
 - ovirt-engine failed to create management network during new host installation
 - [Neutron integration] It's impossible to create network on Neutron from ovirt-engine
 - [RHEVM-RHS] Host status is shown up in RHEVM UI, even when glusterd is stopped
 - [engine] [RO-disk] Disbale read-only VirtIO-SCIS LUN disks in the GUI
 - [engine-webadmin] Cannot create an export domain under local DC
 - A movement operation of raw sparse disk from file to block domain results in Raw preallocated disk, but reports its type wrongly in the webadmin
 - Batch updates might create a database deadlock
 Bugs fixed between RC and GA:

* Run once vm via REST with <pause>true</pause> parameter, save this parameter true also in next runs
 - Tracker: oVirt 3.4.2 release

### oVirt Log Collector

* [engine-log-collector] problem with sos3 on rhel7 as general.all_logs no longer exist

### oVirt Hosted Engine HA

* Could not start ha-agent with exception AttributeError: 'dict' object has no attribute 'engine_status'
 - Hosted engine upgrade from 3.3 to 3.4, ovirt-ha-agent die after three errors

### oVirt Hosted Engine Setup

* hosted-engine setup logs the temporary VM password

### VDSM

### ovirt-node-plugin-vdsm

* engine_page: catch exception from vdscli.connect()
 - engine_page: replace netinfo to xmlrpc
 - engine_page: set password when no address is used
 - spec: remove uneeded sed's
 - engine_page: Display correctly proto for Manage by
 - engine_page: Remove Retrieve Certificate button
 - engine_page: network is required to register tab
 - engine_page: add exception for ENETUNREACH
 - hooks: Adding hooks for ovirt-node-upgrade
 - engine_page: remove dep. from ovirt_config_setup.engine

### oVirt ISO Uploader

* option insecure doesn't work

### oVirt Image Uploader

* option insecure doesn't work


text:
package de.fu_berlin.imp.apiua.groundedtheory.model.dimension;

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

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

import com.bkahlert.nebula.widgets.scale.IScale;
import com.bkahlert.nebula.widgets.scale.OrdinalScale;
import com.bkahlert.nebula.widgets.scale.OrdinalScale.EditType;
import com.bkahlert.nebula.widgets.scale.OrdinalScale.IOrdinalScaleListener;

/**
 * A {@link IDimension} with nominals.
 *
 * @author bkahlert
 *
 */
public class OrdinalDimension implements IDimension {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = Logger
			.getLogger(OrdinalDimension.class);

	private List<String> ordinals;

	public OrdinalDimension(List<String> ordinals) {
		this.ordinals = ordinals != null ? new ArrayList<String>(ordinals)
				: new ArrayList<String>();
	}

	public OrdinalDimension(String... ordinals) {
		this(ordinals != null ? Arrays.asList(ordinals) : null);
	}

	public OrdinalDimension() {
		this(new ArrayList<String>());
	}

	@Override
	public boolean isLegal(String value) {
		return value == null || this.ordinals.contains(value);
	}

	@Override
	public String represent() {
		StringBuilder sb = new StringBuilder("");
		switch (this.ordinals.size()) {
		case 0:
			sb.append("-");
			break;
		case 1:
			sb.append(this.ordinals.get(0));
			break;
		case 2:
			sb.append(this.ordinals.get(0));
			sb.append(", ");
			sb.append(this.ordinals.get(1));
			break;
		case 3:
			sb.append(this.ordinals.get(0));
			sb.append(", ");
			sb.append(this.ordinals.get(1));
			sb.append(", ");
			sb.append(this.ordinals.get(2));
			break;
		default:
			sb.append(this.ordinals.get(0));
			sb.append(" ... ");
			sb.append(this.ordinals.get(this.ordinals.size() - 1));
		}
		return sb.toString();
	}

	@Override
	public Control createEditControl(final Composite parent,
			final IDimensionListener dimensionListener) {
		final OrdinalScale ordinalScale = new OrdinalScale(parent, SWT.NONE,
				EditType.CHANGE_ORDER);
		ordinalScale.setOrdinals(this.ordinals.toArray(new String[0]));
		ordinalScale.setMargin(5);
		ordinalScale.addListener(new IOrdinalScaleListener() {
			@Override
			public void valueChanged(String oldValue, String newValue) {
			}

			@Override
			public void ordinalRenamed(String oldName, String newName) {
				if (dimensionListener != null) {
					OrdinalDimension.this.ordinals = Arrays.asList(ordinalScale
							.getOrdinals());
					dimensionListener.dimensionChanged(OrdinalDimension.this);
				}
			}

			@Override
			public void ordinalRemoved(String ordinal) {
				if (dimensionListener != null) {
					OrdinalDimension.this.ordinals = Arrays.asList(ordinalScale
							.getOrdinals());
					dimensionListener.dimensionChanged(OrdinalDimension.this);
				}
			}

			@Override
			public void ordinalAdded(String newOrdinal) {
				if (dimensionListener != null) {
					OrdinalDimension.this.ordinals = Arrays.asList(ordinalScale
							.getOrdinals());
					dimensionListener.dimensionChanged(OrdinalDimension.this);
				}
			}

			@Override
			public void orderChanged(String[] oldOrdinals, String[] newOrdinals) {
				if (dimensionListener != null) {
					OrdinalDimension.this.ordinals = Arrays.asList(ordinalScale
							.getOrdinals());
					dimensionListener.dimensionChanged(OrdinalDimension.this);
				}
			}
		});
		return ordinalScale;
	}

	@Override
	public Control createValueEditControl(Composite parent,
			final IDimensionValueListener dimensionValueListener) {
		final Combo combo = new Combo(parent, SWT.READ_ONLY);
		combo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (dimensionValueListener != null) {
					dimensionValueListener.dimensionValueChanged(
							OrdinalDimension.this, combo.getText());
				}
			}
		});
		return combo;
	}

	@Override
	public void setValueEditControlValue(Control control, String value) {
		if (!Combo.class.isInstance(control)) {
			throw new RuntimeException(Control.class.getSimpleName()
					+ "'s type is " + control.getClass().getSimpleName()
					+ " instead of " + Combo.class.getSimpleName());
		}
		Combo combo = (Combo) control;
		combo.add(IScale.UNSET_LABEL);
		for (String ordinal : this.ordinals) {
			combo.add(ordinal);
		}
		combo.select(this.ordinals.indexOf(value) + 1);
	}

	@Override
	public String getValueEditControlValue(Control control) {
		if (!Combo.class.isInstance(control)) {
			throw new RuntimeException(Control.class.getSimpleName()
					+ "'s type is " + control.getClass().getSimpleName()
					+ " instead of " + Combo.class.getSimpleName());
		}
		Combo combo = (Combo) control;
		return combo.getText().equals(IScale.UNSET_LABEL) ? null : combo
				.getText();
	}
}


text:
layout: post
title: Vendor Relations
date: 2014-07-31 11:00:05
share: n
category: skills
---


text:
from inspect import getfullargspec
from os import makedirs, path

from docs.utils import title_line
from pyinfra.api.connectors import get_all_connectors

def build_connectors_docs():
    this_dir = path.dirname(path.realpath(__file__))
    docs_dir = path.abspath(path.join(this_dir, "..", "docs"))

    makedirs(path.join(docs_dir, "connectors"), exist_ok=True)

    for connector_name, connector in get_all_connectors().items():
        lines = []

        full_title = "``@{0}`` Connector".format(connector_name)
        lines.append(full_title)
        lines.append(title_line("-", full_title))
        lines.append("")

        if connector.__doc__:
            lines.append(connector.__doc__)

        data_title = "Usage"
        lines.append(data_title)
        lines.append(title_line("~", data_title))
        lines.append("")

        names_argument_key = getfullargspec(connector.make_names_data).args[0]
        if names_argument_key == "_":
            names_argument_key = ""
        else:
            names_argument_key = f"/{names_argument_key}"
        lines.append(
            f"""
.. code:: python

    pyinfra @{connector_name}{names_argument_key} ...
""".strip(),
        )
        lines.append("")

        data_keys = connector.Meta.DataKeys.__dict__

        data_key_lines = []
        for key, description in data_keys.items():
            if key.startswith("_"):
                continue
            data_key_lines.append(f"    {connector.Meta.keys_prefix}_{key}  # {description}")

        if data_key_lines:
            data_title = "Available Data"
            lines.append(data_title)
            lines.append(title_line("~", data_title))
            lines.append("")

            data_key_lines = "\n".join(data_key_lines)
            lines.append(
                f"""
.. code:: python

{data_key_lines}
    """.strip(),
            )
            lines.append("")

        module_filename = path.join(docs_dir, "connectors", f"{connector_name}.rst")
        print("--> Writing {0}".format(module_filename))

        with open(module_filename, "w", encoding="utf-8") as outfile:
            outfile.write("\n".join(lines))

if __name__ == "__main__":
    print("### Building connectors docs")
    build_connectors_docs()


text:
package com.smasher.andora;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.smasher.andora.libpandora.PandoraException;
import com.smasher.andora.libpandora.PandoraSession;
import com.smasher.andora.libpandora.Partner;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import static com.smasher.andora.libpandora.PandoraException.Error.BIRTH_YEAR_INVALID;
import static com.smasher.andora.libpandora.PandoraException.Error.BIRTH_YEAR_TOO_YOUNG;
import static com.smasher.andora.libpandora.PandoraException.Error.INVALID_PASSWORD;
import static com.smasher.andora.libpandora.PandoraException.Error.INVALID_USERNAME;
import static com.smasher.andora.libpandora.PandoraException.Error.ZIP_CODE_INVALID;

/**
 * Log into Pandora
 */
public class LoginActivity extends Activity {
    // Keep track of the login task to ensure we can cancel it if requested.
    private UserLoginTask mAuthTask = null;

    EditText mEmailView;
    EditText mPasswordView;
    EditText mYearView;
    EditText mZipView;
    private Spinner mGenderView;
    private CheckBox mCheckView;

    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;

    private enum LoginType { SIGN_IN, CREATE_ACCOUNT, FORGOT_PASSWORD }
    LoginType loginMode = LoginType.SIGN_IN;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //setTheme(android.R.style.Theme_Holo);
        //setTheme(android.R.style.Theme_Holo_Light);
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this));
        setContentView(R.layout.activity_login);

        Intent intent = getIntent();
        String email = intent.getStringExtra("email");
        String password = intent.getStringExtra("password");

        // Set up the login form.
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(email);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setText(password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mYearView = (EditText) findViewById(R.id.year);
        mZipView = (EditText) findViewById(R.id.zip);

        mGenderView = (Spinner) findViewById(R.id.gender);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.gender_array, android.R.layout.simple_spinner_dropdown_item);
        mGenderView.setAdapter(adapter);

        mCheckView = (CheckBox) findViewById(R.id.optIn);
        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_sign_in:
                showScreen(LoginType.SIGN_IN);
                return true;
            case R.id.action_forgot_password:
                showScreen(LoginType.FORGOT_PASSWORD);
                return true;
            case R.id.action_create_account:
                showScreen(LoginType.CREATE_ACCOUNT);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);
        mYearView.setError(null);
        mZipView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();
        String year = mYearView.getText().toString();
        String zip = mZipView.getText().toString();
        String gender = (mGenderView.getSelectedItemPosition()==0) ? "male" : "female";
        boolean opt = mCheckView.isChecked();

        //View focusView = null;
        boolean cancel = false;
        int iYear = 0;

        if (loginMode == LoginType.CREATE_ACCOUNT) {
            // Check for a valid zip code.
            if (!zip.matches("^\\d{5}([\\-]?\\d{4})?$")) {
                cancel = handleError(ZIP_CODE_INVALID);
            }

            // Check for a valid birth year.
            if (!year.matches("^\\d{4}")) {
                cancel = handleError(BIRTH_YEAR_INVALID);
            } else {
                try {
                    iYear = Integer.parseInt(year);
                    Time time = new Time();
                    time.setToNow();

                    if (iYear<1900)
                        cancel = handleError(BIRTH_YEAR_INVALID);
                    else if (iYear>time.year-13)
                        cancel = handleError(BIRTH_YEAR_TOO_YOUNG);
                } catch (NumberFormatException e) {
                    cancel = handleError(BIRTH_YEAR_INVALID);
                }
            }
        }

        if (loginMode != LoginType.FORGOT_PASSWORD) {
            // Check for a valid password.
            if (password.length() < 5) {
                cancel = handleError(INVALID_PASSWORD);
            }
        }

        // Check for a valid email address.
        if (!email.contains("@") || !email.contains(".") || email.contains(" ")) {
            cancel = handleError(INVALID_USERNAME);
        }

        if (!cancel) {
            // Show a progress spinner, and kick off a background task
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask(loginMode, email, password, iYear, zip, gender, opt);
            mAuthTask.execute();
        }
    }

    private void showScreen(final LoginType type) {
        loginMode = type;

        String str;
        boolean showPassword = false;
        boolean showCreation = false;

        switch (type) {
            case FORGOT_PASSWORD:
                str = getString(R.string.action_forgot_password);
                showPassword = true;
                break;
            case CREATE_ACCOUNT:
                str = getString(R.string.action_create_account);
                showCreation = true;
                break;
            default:
                str = getString(R.string.action_sign_in);
        }

        mPasswordView.setVisibility(showPassword ? View.GONE : View.VISIBLE);
        mYearView.setVisibility(showCreation ? View.VISIBLE : View.GONE);
        mZipView.setVisibility(showCreation ? View.VISIBLE : View.GONE);
        mGenderView.setVisibility(showCreation ? View.VISIBLE : View.GONE);
        mCheckView.setVisibility(showCreation ? View.VISIBLE : View.GONE);
        ((Button)findViewById(R.id.sign_in_button)).setText(str);
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    protected boolean handleError(PandoraException.Error error) {
        switch (error) {
            case INVALID_LOGIN:
                Toast.makeText(LoginActivity.this, getString(R.string.error_login_failure), Toast.LENGTH_LONG).show();
                return true;
            case INVALID_USERNAME:
                mEmailView.setError(getString(R.string.error_invalid_username));
                mEmailView.requestFocus();
                return true;
            case INVALID_PASSWORD:
                mPasswordView.setError(getString(R.string.error_invalid_password));
                mPasswordView.requestFocus();
                return true;
            case ZIP_CODE_INVALID:
                mZipView.setError(getString(R.string.error_zip_code_invalid));
                mZipView.requestFocus();
                return true;
            case BIRTH_YEAR_INVALID:
                mYearView.setError(getString(R.string.error_birth_year_invalid));
                mYearView.requestFocus();
                return true;
            case BIRTH_YEAR_TOO_YOUNG:
                mYearView.setError(getString(R.string.error_birth_year_too_young));
                mYearView.requestFocus();
                return true;
            case USERNAME_ALREADY_EXISTS:
                mEmailView.setError(getString(R.string.error_username_already_exists));
                mEmailView.requestFocus();
                return true;
            default:
                ErrorActivity.errorPopup(this, error);
                return true;
        }
    }

    public static SecretKey generateKey(Context context) {
        //NOTE: this is a sample method that uses your ANDROID_ID to generate the encryption key.
        //the real method will be different in order to make it more difficult for malicious people to decrypt peoples passwords.
        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec keySpec = new PBEKeySpec(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID).toCharArray(), new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, 1000, 256);
            SecretKey key = factory.generateSecret(keySpec);
            return key;
        } catch (NoSuchAlgorithmException e) {
        } catch (InvalidKeySpecException e) {}
        return null;
    }

    public static byte[] generateIV() {
        //generate a random salt to protect against rainbow tables

        SecureRandom secureRandom = new SecureRandom();
        byte[] bytes = new byte[16];
        secureRandom.nextBytes(bytes);
        return bytes;
    }

    public static String encrypt(SecretKey key, byte iv[], String data) {
        try {
            Cipher encryptionCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            encryptionCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), "AES"), new IvParameterSpec(iv));
            byte[] bytes = encryptionCipher.doFinal(data.getBytes());
            return Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(SecretKey key, byte iv[], String data) {
        try {
            Cipher encryptionCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            encryptionCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getEncoded(), "AES"), new IvParameterSpec(iv));
            byte[] bytes = encryptionCipher.doFinal(Base64.decode(data, Base64.DEFAULT));
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        PandoraSession pandora;
        LoginType mode;
        String email, password, zip, gender;
        int year;
        boolean opt;

        boolean premium;
        PandoraException.Error error;

        UserLoginTask(LoginType mode, String email, String password, int year, String zip, String gender, boolean opt) {
            pandora = new PandoraSession();
            this.mode = mode;
            this.email = email;
            this.password = password;
            this.year = year;
            this.zip = zip;
            this.gender = gender;
            this.opt = opt;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                pandora.partnerLogin(Partner.PARTNER_ANDROID);

                switch (mode) {
                    case SIGN_IN: {
                        pandora.userLogin(email, password);
                        premium = pandora.isPremium();
                        if (premium) {
                            Log.d("Andora", "/Login: " + "User supports Pandora One. Upgrading connection.");
                            pandora.partnerLogin(Partner.PARTNER_PANDORA_ONE);
                            pandora.userLogin(email, password);
                        }

                        /* Store the account credentials in the apps private preferences.
                           However, anyone with root access can read this file making it somewhat insecure.
                           Therefore it is stored encrypted to add another layer of security.
                           Note: Someone with enough motivation and skill could still determine the key.
                         */
                        byte salt[] = generateIV();
                        PreferenceManager.getDefaultSharedPreferences(LoginActivity.this).edit()
                        .putString("email", email)
                        .putString("password", encrypt(generateKey(LoginActivity.this), salt, password))
                        .putString("salt", Base64.encodeToString(salt, Base64.DEFAULT))
                        .putBoolean("premium", premium)
                        .commit();

                        return true;
                    }
                    case FORGOT_PASSWORD: {
                        pandora.emailPassword(email);
                        Toast.makeText(LoginActivity.this, "Password emailed to " + email, Toast.LENGTH_LONG).show();
                        return false;
                    }
                    case CREATE_ACCOUNT: {
                        pandora.createUser(email, password, year, zip, gender, opt);
                        return true;
                    }
                }
            } catch (PandoraException e) {
                error = e.getError();
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.putExtra("loggedIn", true);
                startActivity(intent);
                LoginActivity.this.finish(); //kill the login page
            } else {
                handleError(error);
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.communication.jobrouter.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Represents the capacity a job in this channel will consume from a worker. */
@Fluent
public final class ChannelConfiguration {
    /*
     * The amount of capacity that an instance of a job of this channel will
     * consume of the total worker capacity.
     */
    @JsonProperty(value = "capacityCostPerJob", required = true)
    private int capacityCostPerJob;

    /**
     * Get the capacityCostPerJob property: The amount of capacity that an instance of a job of this channel will
     * consume of the total worker capacity.
     *
     * @return the capacityCostPerJob value.
     */
    public int getCapacityCostPerJob() {
        return this.capacityCostPerJob;
    }

    /**
     * Set the capacityCostPerJob property: The amount of capacity that an instance of a job of this channel will
     * consume of the total worker capacity.
     *
     * @param capacityCostPerJob the capacityCostPerJob value to set.
     * @return the ChannelConfiguration object itself.
     */
    public ChannelConfiguration setCapacityCostPerJob(int capacityCostPerJob) {
        this.capacityCostPerJob = capacityCostPerJob;
        return this;
    }
}


text:
import pytest

from tree import preorder

class TestNodeIndexer:
    @pytest.fixture
    def preorder_indexer1(self, tree1):
        return preorder(tree1).indexer()

    def test_index(self, tree1, preorder_indexer1):
        for (index, node) in enumerate(preorder(tree1)):
            assert preorder_indexer1.index(node) is index

    def test_index_does_not_contain(self, tree2, preorder_indexer1):
        with pytest.raises(ValueError):
            preorder_indexer1.index(tree2) is 0

    def test_getitem(self, tree1, preorder_indexer1):
        for (index, node) in enumerate(preorder(tree1)):
            assert preorder_indexer1[index] is node

    def test_getitem_out_of_range(self, tree1, preorder_indexer1):
        with pytest.raises(IndexError):
            preorder_indexer1[len(tree1)]


text:
#include "ignite/odbc/cursor.h"

namespace ignite
{
    namespace odbc
    {
        Cursor::Cursor(int64_t queryId) : queryId(queryId), currentPage(),
            currentPagePos(0), currentRow()
        {
            // No-op.
        }

        Cursor::~Cursor()
        {
            // No-op.
        }

        bool Cursor::Increment()
        {
            if (currentPage.get() && currentPagePos < currentPage->GetSize())
            {
                ++currentPagePos;

                if (currentPagePos == currentPage->GetSize())
                    currentRow.reset();
                else
                {
                    Row *row = currentRow.get();

                    if (row)
                        row->MoveToNext();
                }
                return true;
            }
            return false;
        }

        bool Cursor::NeedDataUpdate() const
        {
            return !currentPage.get() || (!currentPage->IsLast() &&
                currentPagePos == currentPage->GetSize());
        }

        bool Cursor::HasData() const
        {
            return !currentPage.get() || !currentPage->IsLast() ||
                currentPagePos < currentPage->GetSize();
        }

        bool Cursor::IsClosedRemotely() const
        {
            return currentPage.get() && currentPage->IsLast();
        }

        void Cursor::UpdateData(std::auto_ptr<ResultPage>& newPage)
        {
            currentPage = newPage;

            currentPagePos = 0;

            currentRow.reset(new Row(currentPage->GetData()));
        }

        Row* Cursor::GetRow()
        {
            return currentRow.get();
        }
    }
}


text:
package consulo.fileEditor.impl.text;

import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProviderImpl;
import com.intellij.openapi.fileEditor.impl.text.TextEditorState;
import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import consulo.util.dataholder.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.SingleRootFileViewProvider;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.TestOnly;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;

/**
 * @author VISTALL
 * @since 2018-05-10
 * <p>
 * Extracted part from {@link TextEditorProviderImpl}
 */
public abstract class TextEditorProvider implements FileEditorProvider, DumbAware {
  @Nonnull
  public static TextEditorProvider getInstance() {
    return EP_FILE_EDITOR_PROVIDER.findExtension(TextEditorProvider.class);
  }

  @TestOnly
  public static final Key<Boolean> TREAT_AS_SHOWN = Key.create("treat.editor.component.as.shown");

  protected static final Key<TextEditor> TEXT_EDITOR_KEY = Key.create("textEditor");

  @NonNls
  private static final String TYPE_ID = "text-editor";
  @NonNls
  private static final String LINE_ATTR = "line";
  @NonNls
  private static final String COLUMN_ATTR = "column";
  @NonNls
  private static final String LEAN_FORWARD_ATTR = "lean-forward";
  @NonNls
  private static final String SELECTION_START_LINE_ATTR = "selection-start-line";
  @NonNls
  private static final String SELECTION_START_COLUMN_ATTR = "selection-start-column";
  @NonNls
  private static final String SELECTION_END_LINE_ATTR = "selection-end-line";
  @NonNls
  private static final String SELECTION_END_COLUMN_ATTR = "selection-end-column";
  @NonNls
  private static final String RELATIVE_CARET_POSITION_ATTR = "relative-caret-position";
  @NonNls
  private static final String CARET_ELEMENT = "caret";

  @Nonnull
  public abstract TextEditor getTextEditor(@Nonnull Editor editor);

  @Override
  public boolean accept(@Nonnull Project project, @Nonnull VirtualFile file) {
    return isTextFile(file) && !SingleRootFileViewProvider.isTooLargeForContentLoading(file);
  }

  @Override
  @Nonnull
  public FileEditorState readState(@Nonnull Element element, @Nonnull Project project, @Nonnull VirtualFile file) {
    TextEditorState state = new TextEditorState();

    try {
      List<Element> caretElements = element.getChildren(CARET_ELEMENT);
      if (caretElements.isEmpty()) {
        state.CARETS = new TextEditorState.CaretState[]{readCaretInfo(element)};
      }
      else {
        state.CARETS = new TextEditorState.CaretState[caretElements.size()];
        for (int i = 0; i < caretElements.size(); i++) {
          state.CARETS[i] = readCaretInfo(caretElements.get(i));
        }
      }

      String verticalScrollProportion = element.getAttributeValue(RELATIVE_CARET_POSITION_ATTR);
      state.RELATIVE_CARET_POSITION = verticalScrollProportion == null ? 0 : Integer.parseInt(verticalScrollProportion);
    }
    catch (NumberFormatException ignored) {
    }

    return state;
  }

  private static TextEditorState.CaretState readCaretInfo(Element element) {
    TextEditorState.CaretState caretState = new TextEditorState.CaretState();
    caretState.LINE = parseWithDefault(element, LINE_ATTR);
    caretState.COLUMN = parseWithDefault(element, COLUMN_ATTR);
    caretState.LEAN_FORWARD = parseBooleanWithDefault(element, LEAN_FORWARD_ATTR);
    caretState.SELECTION_START_LINE = parseWithDefault(element, SELECTION_START_LINE_ATTR);
    caretState.SELECTION_START_COLUMN = parseWithDefault(element, SELECTION_START_COLUMN_ATTR);
    caretState.SELECTION_END_LINE = parseWithDefault(element, SELECTION_END_LINE_ATTR);
    caretState.SELECTION_END_COLUMN = parseWithDefault(element, SELECTION_END_COLUMN_ATTR);
    return caretState;
  }

  private static int parseWithDefault(Element element, String attributeName) {
    String value = element.getAttributeValue(attributeName);
    return value == null ? 0 : Integer.parseInt(value);
  }

  private static boolean parseBooleanWithDefault(Element element, String attributeName) {
    String value = element.getAttributeValue(attributeName);
    return value != null && Boolean.parseBoolean(value);
  }

  @Override
  public void writeState(@Nonnull FileEditorState _state, @Nonnull Project project, @Nonnull Element element) {
    TextEditorState state = (TextEditorState)_state;

    element.setAttribute(RELATIVE_CARET_POSITION_ATTR, Integer.toString(state.RELATIVE_CARET_POSITION));
    if (state.CARETS != null) {
      for (TextEditorState.CaretState caretState : state.CARETS) {
        Element e = new Element(CARET_ELEMENT);
        e.setAttribute(LINE_ATTR, Integer.toString(caretState.LINE));
        e.setAttribute(COLUMN_ATTR, Integer.toString(caretState.COLUMN));
        e.setAttribute(LEAN_FORWARD_ATTR, Boolean.toString(caretState.LEAN_FORWARD));
        e.setAttribute(SELECTION_START_LINE_ATTR, Integer.toString(caretState.SELECTION_START_LINE));
        e.setAttribute(SELECTION_START_COLUMN_ATTR, Integer.toString(caretState.SELECTION_START_COLUMN));
        e.setAttribute(SELECTION_END_LINE_ATTR, Integer.toString(caretState.SELECTION_END_LINE));
        e.setAttribute(SELECTION_END_COLUMN_ATTR, Integer.toString(caretState.SELECTION_END_COLUMN));
        element.addContent(e);
      }
    }
  }

  @Override
  @Nonnull
  public String getEditorTypeId() {
    return TYPE_ID;
  }

  @Override
  @Nonnull
  public FileEditorPolicy getPolicy() {
    return FileEditorPolicy.NONE;
  }

  @Nullable
  public static Document[] getDocuments(@Nonnull FileEditor editor) {
    if (editor instanceof DocumentsEditor) {
      DocumentsEditor documentsEditor = (DocumentsEditor)editor;
      Document[] documents = documentsEditor.getDocuments();
      return documents.length > 0 ? documents : null;
    }

    if (editor instanceof TextEditor) {
      Document document = ((TextEditor)editor).getEditor().getDocument();
      return new Document[]{document};
    }

    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    for (int i = projects.length - 1; i >= 0; i--) {
      VirtualFile file = FileEditorManagerEx.getInstanceEx(projects[i]).getFile(editor);
      if (file != null) {
        Document document = FileDocumentManager.getInstance().getDocument(file);
        if (document != null) {
          return new Document[]{document};
        }
      }
    }

    return null;
  }

  public static void putTextEditor(Editor editor, TextEditor textEditor) {
    editor.putUserData(TEXT_EDITOR_KEY, textEditor);
  }

  @Nonnull
  public TextEditorState getStateImpl(final Project project, @Nonnull Editor editor, @Nonnull FileEditorStateLevel level) {
    TextEditorState state = new TextEditorState();
    CaretModel caretModel = editor.getCaretModel();
    if (caretModel.supportsMultipleCarets()) {
      List<CaretState> caretsAndSelections = caretModel.getCaretsAndSelections();
      state.CARETS = new TextEditorState.CaretState[caretsAndSelections.size()];
      for (int i = 0; i < caretsAndSelections.size(); i++) {
        CaretState caretState = caretsAndSelections.get(i);
        LogicalPosition caretPosition = caretState.getCaretPosition();
        LogicalPosition selectionStartPosition = caretState.getSelectionStart();
        LogicalPosition selectionEndPosition = caretState.getSelectionEnd();
        state.CARETS[i] = createCaretState(caretPosition, selectionStartPosition, selectionEndPosition);
      }
    }
    else {
      LogicalPosition caretPosition = caretModel.getLogicalPosition();
      LogicalPosition selectionStartPosition = editor.offsetToLogicalPosition(editor.getSelectionModel().getSelectionStart());
      LogicalPosition selectionEndPosition = editor.offsetToLogicalPosition(editor.getSelectionModel().getSelectionEnd());
      state.CARETS = new TextEditorState.CaretState[1];
      state.CARETS[0] = createCaretState(caretPosition, selectionStartPosition, selectionEndPosition);
    }

    // Saving scrolling proportion on UNDO may cause undesirable results of undo action fails to perform since
    // scrolling proportion restored slightly differs from what have been saved.
    state.RELATIVE_CARET_POSITION = level == FileEditorStateLevel.UNDO ? Integer.MAX_VALUE : EditorUtil.calcRelativeCaretPosition(editor);

    return state;
  }

  public static boolean isTextFile(@Nonnull VirtualFile file) {
    if (file.isDirectory() || !file.isValid()) {
      return false;
    }

    final FileType ft = file.getFileType();
    return !ft.isBinary() || BinaryFileTypeDecompilers.INSTANCE.forFileType(ft) != null;
  }

  private static TextEditorState.CaretState createCaretState(LogicalPosition caretPosition, LogicalPosition selectionStartPosition, LogicalPosition selectionEndPosition) {
    TextEditorState.CaretState caretState = new TextEditorState.CaretState();
    caretState.LINE = getLine(caretPosition);
    caretState.COLUMN = getColumn(caretPosition);
    caretState.LEAN_FORWARD = caretPosition != null && caretPosition.leansForward;
    caretState.SELECTION_START_LINE = getLine(selectionStartPosition);
    caretState.SELECTION_START_COLUMN = getColumn(selectionStartPosition);
    caretState.SELECTION_END_LINE = getLine(selectionEndPosition);
    caretState.SELECTION_END_COLUMN = getColumn(selectionEndPosition);
    return caretState;
  }

  private static int getLine(@Nullable LogicalPosition pos) {
    return pos == null ? 0 : pos.line;
  }

  private static int getColumn(@Nullable LogicalPosition pos) {
    return pos == null ? 0 : pos.column;
  }
}


text:
package mll.servlets;

import org.json.JSONArray;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mll.service.BandService;

/**
 * Created by William Guo on 3/30/2017.
 */
public class BandServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  BandService service = null;

  public void init() throws ServletException {
    service = new BandService();
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONArray responseObject = service.getBands(request, response);

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.print(responseObject);
    out.flush();
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }

}


text:
FROM python:2.7
RUN apt-get -y update

ADD . /opt/pi_director/
WORKDIR /opt/pi_director
RUN pip install .
RUN find . -name \*.sqlite -delete
RUN initialize_pi_director_db production.ini
CMD gunicorn --paste /opt/pi_director/production.ini -b :6543 -w 4 -k eventlet


text:
//
//  TBNewRule_goMonthViewController.m
//  TrendBetting
//
//  Created by jiazhen-mac-01 on 2017/9/6.
//  Copyright © 2017年 yxy. All rights reserved.
//

#import "TBNewRule_goMonthViewController.h"
//#import "JHChart.h"
//#import "JHLineChart.h"
//#import "WSLineChartView.h"
#import "Charts-Swift.h"
//#define yxy 5
@interface TBNewRule_goMonthViewController ()<UIScrollViewDelegate,ChartViewDelegate>
{
//    LineChartView*_chartView1;
//    LineChartView*_chartView2;
//    LineChartView*_chartView3;
    NSMutableArray*lineArr;
    NSArray*upperDataArray;//符合规则在均线曲线上的点(结果)
    NSArray*upperProgressArray;//符合规则在均线曲线上的点(过程)
    NSArray*backupperDataArray; //返利的值

    int currentP;
    NSArray*allMonthNameArr;

    NSMutableDictionary*goAllMonthDic;
//    NSInteger addCount; //从上个月带过来的数据
}

@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollview;

@end

@implementation TBNewRule_goMonthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=_titleStr;

    goAllMonthDic = [[NSMutableDictionary alloc]init];
    currentP = [_selectP intValue];

    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithTitle:@"导出" style:UIBarButtonItemStylePlain target:self action:@selector(exportAction)];
    UIBarButtonItem*dataitem=[[UIBarButtonItem alloc]initWithTitle:@"统计结果" style:UIBarButtonItemStylePlain target:self action:@selector(resultDataACtion)];
    self.navigationItem.rightBarButtonItems=@[item,dataitem];

    lineArr = [[NSMutableArray alloc]init];
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];

    if([_titleStr containsString:@"连日结果"]){

        allMonthNameArr=[[Utils sharedInstance] orderArr:[_allmonthDic allKeys] isArc:YES];
        [self getMonthKeyAndValue:currentP];

        UIButton*leftBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2.0-40,40 , 40)];
        [leftBtn setTitle:@"上个月" forState:UIControlStateNormal];
        leftBtn.titleLabel.font=[UIFont systemFontOfSize:12];
        [leftBtn addTarget:self action:@selector(leftBtn) forControlEvents:UIControlEventTouchUpInside];
        [leftBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        float a = SCREEN_WIDTH;
        UIButton*rightBtn=[[UIButton alloc]initWithFrame:CGRectMake(a-50, SCREEN_HEIGHT/2.0-40,40 , 40)];
        [rightBtn setTitle:@"下个月" forState:UIControlStateNormal];
        rightBtn.titleLabel.font=[UIFont systemFontOfSize:12];
        [rightBtn addTarget:self action:@selector(rightBtn) forControlEvents:UIControlEventTouchUpInside];
        [rightBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        [_mainScrollview addSubview:leftBtn];
        [_mainScrollview addSubview:rightBtn];

    } else { //连月结果
        int dateSqrCount = [[defs objectForKey:SAVE_dateSqrCount] intValue];
        [lineArr addObject: [self getKeyAndValue:dateSqrCount  color:UIColor.greenColor p:0]];
        NSString * line1 = [defs objectForKey:SAVE_dateSqrCount_1];
        NSString * line2 = [defs objectForKey:SAVE_dateSqrCount_2];
        if (line1.length>0) {
            [lineArr addObject: [self getKeyAndValue:[line1 intValue]  color:UIColor.greenColor p:0]]; ;
        }
        if (line2.length>0) {
            [lineArr addObject: [self getKeyAndValue:[line2 intValue]  color:UIColor.greenColor p:0]]; ;
        }
        NSArray*resArr = [self getComputerResult:_totalDayValueArr tsqrArr:lineArr p:0];
        upperDataArray = resArr[0];
        backupperDataArray = resArr[1];
        upperProgressArray = resArr[2];
        [self initChartView];
        _mainScrollview.contentSize=CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT*lineArr.count-30);
    }

}
-(void)leftBtn{
    if (currentP>0) {
        currentP--;
        [self getMonthKeyAndValue:currentP];
    } else {
        [self.view makeToast:@"没有更多数据了" duration:3.0f position:CSToastPositionCenter];
    }
}
-(void)rightBtn{
    if (currentP<allMonthNameArr.count-1) {
        currentP++;
        [self getMonthKeyAndValue:currentP];
    } else {
        [self.view makeToast:@"没有更多数据了" duration:3.0f position:CSToastPositionCenter];
    }
}
/*
 获取一个月的连日结果
 */
-(void)getMonthKeyAndValue:(int)p{
    NSString * keyStr = allMonthNameArr[p];
    self.title = [NSString stringWithFormat:@"%@连日结果",keyStr];

    if (goAllMonthDic[keyStr]) {
        NSArray*tepArr = goAllMonthDic[keyStr];
        _totalDayKeyArr = tepArr[0];
        _totalDayValueArr = tepArr[1];
        _totalDayBackMoneyArr = tepArr[2];
    } else {
        NSDictionary*monthdic=_allmonthDic[keyStr];
        NSMutableArray*totalTimeKeyArr=[[NSMutableArray alloc]init];//所有日连此
        NSMutableArray*totalTimeValueArr=[[NSMutableArray alloc]init];//所有日连次结果相加
        NSMutableArray*backtotalTimeValueArr=[[NSMutableArray alloc]init];//所有返利日连次结果相加

        if (p>0) {
            NSString * str = allMonthNameArr[p-1];
            NSArray*tepArr = goAllMonthDic[str];
            [totalTimeKeyArr addObject: [tepArr[0] lastObject]];
            [totalTimeValueArr addObject: [tepArr[1] lastObject]];
            [backtotalTimeValueArr addObject: [tepArr[2] lastObject]];
        }
        NSArray*tepArray=[monthdic allKeys];

        NSArray*dayxArray=[[Utils sharedInstance] orderArr:tepArray isArc:YES];
        for (int i=0; i<dayxArray.count; i++)
        {
            NSDictionary*dic=monthdic[dayxArray[i]];

            //月里的日长连次
            NSMutableArray*xkeyArray=[[NSMutableArray alloc]initWithArray:[dic allKeys]];
            [xkeyArray removeObject:@"daycount"];
            NSArray*xtimeArr=[[Utils sharedInstance] orderArr:xkeyArray isArc:YES];
            for (int k=0; k<xtimeArr.count; k++)
            {
                NSArray*tparray=dic[xtimeArr[k]];
                float a=[tparray[5] floatValue]+[[totalTimeValueArr lastObject] floatValue];
                float b=[tparray[8] floatValue]+[[backtotalTimeValueArr lastObject] floatValue];
                [totalTimeKeyArr addObject:[NSString stringWithFormat:@"%@.%d",dayxArray[i],k+1]];
                [totalTimeValueArr addObject:[[Utils sharedInstance]removeFloatAllZero:[NSString stringWithFormat:@"%0.3f",a]]];
                [backtotalTimeValueArr addObject:[[Utils sharedInstance]removeFloatAllZero:[NSString stringWithFormat:@"%0.3f",b]]];
            }
        }
        _totalDayKeyArr = totalTimeKeyArr;
        _totalDayValueArr = totalTimeValueArr;
        _totalDayBackMoneyArr = backtotalTimeValueArr;
        [goAllMonthDic setObject:@[_totalDayKeyArr,_totalDayValueArr,_totalDayBackMoneyArr] forKey:keyStr];
    }

    ////
    lineArr = [[NSMutableArray alloc]init];
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    //1
    int dateSqrCount = [[defs objectForKey:SAVE_dateDaySqrCount] intValue];
    [lineArr addObject: [self getKeyAndValue:dateSqrCount color:UIColor.greenColor p:p]];
    //2
    NSString * line1 = [defs objectForKey:SAVE_dateDaySqrCount_1];
    if (line1.length>0) {
        [lineArr addObject: [self getKeyAndValue:[line1 intValue] color:UIColor.greenColor p:p]]; ;
    }
    //3
    NSString * line2 = [defs objectForKey:SAVE_dateDaySqrCount_2];
    if (line2.length>0) {
        [lineArr addObject: [self getKeyAndValue:[line2 intValue]  color:UIColor.greenColor p:p]]; ;
    }
    NSArray*resArr = [self getComputerResult:_totalDayValueArr tsqrArr:lineArr p:p];
    upperDataArray = resArr[0]; //在曲线上的点
    backupperDataArray = resArr[1];
    upperProgressArray = resArr[2];
    [self initChartView];
    _mainScrollview.contentSize=CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT*lineArr.count-30);
}
/*
 *获取几日(dateSqrCount)均值 p第几个月
 */
-(NSArray*)getKeyAndValue:(int)dateSqrCount color:(UIColor*)color p:(int)p{

    NSMutableArray * keyArr ;
    NSMutableArray * valueArr ;
    NSMutableArray * totalQKeyArr = [[NSMutableArray alloc]init];
    NSMutableArray * totalQValueArr =[[NSMutableArray alloc]init];
   int addCount = 0;
    if (p>0) {
        NSString * str = allMonthNameArr[p-1];
        NSArray*tepArr = goAllMonthDic[str];
        NSArray*lastKeyArr = tepArr[0];
        NSArray*lastValueArr = tepArr[1];
        NSInteger beginp = lastKeyArr.count-dateSqrCount;
        NSInteger splength = dateSqrCount-1;
        if (beginp<0) {
            beginp = 0;
            splength = lastKeyArr.count-1;
        }
        NSArray*needKeyArr = [lastKeyArr subarrayWithRange:NSMakeRange(beginp,splength)];
        NSArray*needValueArr = [lastValueArr subarrayWithRange:NSMakeRange(beginp, splength)];
        keyArr = [NSMutableArray arrayWithArray:needKeyArr];
        valueArr = [NSMutableArray arrayWithArray:needValueArr];
        addCount = keyArr.count+1;
        [keyArr addObjectsFromArray:_totalDayKeyArr];
        [valueArr addObjectsFromArray:_totalDayValueArr];
    } else {
        keyArr = [NSMutableArray arrayWithArray:_totalDayKeyArr];
        valueArr = [NSMutableArray arrayWithArray:_totalDayValueArr];
    }
    float tvalue = 0;
    for (int i=0; i<keyArr.count; i++) {
        tvalue+=[valueArr[i] floatValue];
        if (i<=dateSqrCount-1) {
            if (i==dateSqrCount-1) {
                [totalQKeyArr addObject:keyArr[i]];
                [totalQValueArr addObject:[[Utils sharedInstance]removeFloatAllZero:[NSString stringWithFormat:@"%0.3f",tvalue/dateSqrCount]]];
            }
        } else {
            tvalue -= [valueArr[i-dateSqrCount] floatValue];
            [totalQKeyArr addObject:keyArr[i]];
            [totalQValueArr addObject:[[Utils sharedInstance]removeFloatAllZero:[NSString stringWithFormat:@"%0.3f",tvalue/dateSqrCount]]];
        }
    }
    return @[totalQKeyArr,totalQValueArr,@(dateSqrCount),color,@(addCount)];
}
/*
 *计算在 均线曲线上的点 和 返利的钱
 */
-(NSArray*)getComputerResult:(NSArray*)lineArr tsqrArr:(NSArray*)tsqrArr p:(int)p{
    NSMutableArray*tresultArr=[[NSMutableArray alloc]init];// 在均线曲线上的点
    NSMutableArray*backtresultArr=[[NSMutableArray alloc]init]; //返利的钱
    NSMutableArray*upResArr = [[NSMutableArray alloc]init]; //记录符合规则均线曲线上的点

    for (int j=0; j<tsqrArr.count; j++) {

        NSArray*sqrArr=tsqrArr[j][1];
        NSInteger sqrCount = [tsqrArr[j][2] intValue]-1;
        int addCount = [tsqrArr[j][4] intValue];
        if (p>0) {
            sqrCount=sqrCount-addCount+1;
        }

        NSMutableArray*resultArr=[[NSMutableArray alloc]init];
        NSMutableArray*backresultArr=[[NSMutableArray alloc]init];
        NSMutableArray*upresultArr=[[NSMutableArray alloc]init];
        for (int y=0; y<lineArr.count; y++) {
            [upresultArr addObject:@""];
        }
        BOOL isgo = NO;

        int beginP;
        for (int i=1; i<sqrArr.count; i++) {
            if (isgo==NO&&[lineArr[i-1+sqrCount] floatValue]<[sqrArr[i-1] floatValue]&&[lineArr[i+sqrCount] floatValue]>[sqrArr[i] floatValue]&&[sqrArr[i-1] floatValue]<[sqrArr[i] floatValue]) {
                isgo = YES;
                beginP = i;

            }
            if (isgo)
            {
                [upresultArr replaceObjectAtIndex:i+sqrCount withObject:lineArr[i+sqrCount]];
            } else {
                [upresultArr replaceObjectAtIndex:i+sqrCount withObject:upresultArr[i+sqrCount-1]];
            }
            if (isgo&&[lineArr[i+sqrCount] floatValue]<[sqrArr[i] floatValue]) {
                isgo=NO;
                float  beginData = [lineArr[beginP+sqrCount] floatValue];
                float endData = [lineArr[i+sqrCount] floatValue];

                float  backbeginData = [_totalDayBackMoneyArr[beginP+sqrCount] floatValue];
                float backendData = [_totalDayBackMoneyArr[i+sqrCount] floatValue];

                [resultArr addObject:[NSString stringWithFormat:@"%0.2f",endData-beginData]];
                [backresultArr addObject:[NSString stringWithFormat:@"%0.2f",backendData-backbeginData]];
            }
        }
        //最大回撤金额  和 比
        NSArray*tep = [self getMaxBackMoneyAndlv:lineArr];
        [resultArr addObjectsFromArray:tep];
        //
        [tresultArr addObject:resultArr];
        [backtresultArr addObject:backresultArr];
        [upResArr addObject:upresultArr];
    }
    return @[tresultArr,backtresultArr,upResArr];
}
/*
 *获取最大回撤金额和回撤金额百分比
 */
-(NSArray*)getMaxBackMoneyAndlv:(NSArray*)lineArr{
    float maxBackMoney = -1111; //最大回撤金额
    float minMoney = 0;
    BOOL isfind =NO;
    for (int i=1; i<lineArr.count-2; i++) {
        if ([lineArr[i-1] floatValue]<[lineArr[i] floatValue]&&[lineArr[i] floatValue]>[lineArr[i+1] floatValue])//中间的最大
        {
            if (maxBackMoney==-1111||maxBackMoney<[lineArr[i] floatValue])
            {
                maxBackMoney=[lineArr[i] floatValue];
                isfind=YES;
            }
        }
        if (isfind&&[lineArr[i-1] floatValue]>[lineArr[i] floatValue]&&[lineArr[i] floatValue]<[lineArr[i+1] floatValue]) {
            isfind=NO;
            minMoney =[lineArr[i] floatValue];
        }
    }
    float a = maxBackMoney - minMoney;
    return @[[NSString stringWithFormat:@"%0.2f",a],
             [NSString stringWithFormat:@"%0.2f",maxBackMoney!=0?a/maxBackMoney:0] //
             ];
}

-(void)initChartView{
    int intx = 0;
    int screenw=SCREEN_WIDTH;
    if ([self.title containsString:@"连日"]) {
        intx = 50;
        screenw=screenw-intx*2;
    }
    for (int k=0; k<lineArr.count; k++) {
        LineChartView*chartView = [[LineChartView alloc]initWithFrame:CGRectMake(intx, SCREEN_HEIGHT*k,screenw, SCREEN_HEIGHT-30)];
        chartView.backgroundColor=TBLineGaryColor;
        chartView.delegate = self;
        chartView.chartDescription.enabled = NO;
        chartView.dragEnabled = YES;
        [chartView setScaleEnabled:YES];
        chartView.pinchZoomEnabled = YES;
        chartView.xAxis.labelPosition = XAxisLabelPositionBottomInside;// X轴的位置

        //
        //
        chartView.xAxis.gridLineDashLengths = @[@5.0, @10.0];

        chartView.drawGridBackgroundEnabled = NO;

        ChartYAxis *leftAxis = chartView.leftAxis;
        [leftAxis removeAllLimitLines];
        leftAxis.gridLineDashLengths = @[@5.f, @5.f];
        leftAxis.drawZeroLineEnabled = NO;
        leftAxis.drawLimitLinesBehindDataEnabled = YES;

        chartView.rightAxis.enabled = NO;
        [self setDta:chartView k:k];
        [chartView animateWithXAxisDuration:2.5];
        [_mainScrollview addSubview:chartView];
    }
}

-(void)setDta:(LineChartView*)chartView k:(int)k{

    //横轴数据
    NSMutableArray *xValues1 = [NSMutableArray array];
    for (int i = 0; i < _totalDayKeyArr.count; i ++) {
        [xValues1 addObject:_totalDayKeyArr[i]];
    }
    //设置横轴数据给chartview
    chartView.xAxis.valueFormatter = [[ChartIndexAxisValueFormatter alloc] initWithValues:xValues1];
    //纵轴数据
    NSMutableArray *yValues1 = [NSMutableArray array];
    for (int i = 0; i <_totalDayValueArr.count; i ++) {
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:[_totalDayValueArr[i] floatValue]];
        [yValues1 addObject:entry];
    }

    NSArray*titArr = [_titleStr componentsSeparatedByString:@"-"];
    //创建LineChartDataSet对象
    LineChartDataSet *set1 = [[LineChartDataSet alloc] initWithValues:yValues1 label:titArr.count>1?titArr[1]:_titleStr];
    set1.drawIconsEnabled = NO;
    //    set1.lineDashLengths = @[@5.f, @2.5f];
    set1.highlightLineDashLengths = @[@5.f, @2.5f];
    [set1 setColor:UIColor.orangeColor];
    [set1 setCircleColor:UIColor.orangeColor];
    set1.lineWidth = 1.0;
    set1.circleRadius = 3.0;
    set1.drawCircleHoleEnabled = NO;
    //    _chartView.scaleYEnabled = NO;//取消Y轴缩放
    set1.valueFont = [UIFont systemFontOfSize:8.f];
    set1.formLineDashLengths = @[@5.f, @2.5f];
    set1.formLineWidth = 1.0;
    set1.formSize = 15.0;
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    [self addOtherSet:dataSets k:k];

    LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    //自定义数据显示格式
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setPositiveFormat:@"#0.00"];

    [data setValueFormatter:[[ChartDefaultValueFormatter alloc]initWithFormatter:formatter]];

    chartView.data = data;

}
-(NSArray*)addOtherSet:(NSMutableArray*)dataSets k:(int)k{
    NSArray*titArr = [_titleStr componentsSeparatedByString:@"-"];
    //yxy 2018 0102 add
    //横轴数据
    NSArray*tempArr =lineArr[k];
    int dateSqrCount =[tempArr[2] intValue]-1;
    int addCount = [tempArr[4] intValue];
    if(currentP>0){
        dateSqrCount = dateSqrCount - addCount+1;
    }
    //纵轴数据
    NSMutableArray *yValues1 = [NSMutableArray array];
    for (int i = 0; i <[tempArr[1] count]; i ++) {
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i+dateSqrCount y:[tempArr[1][i] floatValue]];
        [yValues1 addObject:entry];
    }
    //创建LineChartDataSet对象
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:yValues1 label:[NSString stringWithFormat:@"均线%@%d",titArr.count>1? titArr[1]:_titleStr,k+1]];
    set.drawIconsEnabled = NO;
    //    set2.lineDashLengths = @[@5.f, @2.5f];
    set.highlightLineDashLengths = @[@5.f, @2.5f];
    [set setColor:tempArr[3]];
    [set setCircleColor:tempArr[3]];
    set.lineWidth = 1.0;
    set.circleRadius = 3.0;
    set.drawCircleHoleEnabled = NO;
    set.valueFont = [UIFont systemFontOfSize:8.f];
    set.formLineDashLengths = @[@5.f, @2.5f];
    set.formLineWidth = 1.0;
    set.formSize = 15.0;
    [dataSets addObject:set];

    //纵轴数据
    NSMutableArray *yValues2 = [NSMutableArray array];
    NSArray*progressArr = upperProgressArray[k];
    for (int i = 0; i <progressArr.count; i++) {
        if ([progressArr[i] length]>0) {
            ChartDataEntry * entry = [[ChartDataEntry alloc] initWithX:i y:[progressArr[i] floatValue]];
            [yValues2 addObject:entry];
        }

    }
    //创建LineChartDataSet对象
    LineChartDataSet *set1 = [[LineChartDataSet alloc] initWithValues:yValues2 label:[NSString stringWithFormat:@"统计结果过程%d",k+1]];
    set1.drawIconsEnabled = NO;
    //    set2.lineDashLengths = @[@5.f, @2.5f];
    set1.highlightLineDashLengths = @[@5.f, @2.5f];
    [set1 setColor:[UIColor redColor]];
    [set1 setCircleColor:[UIColor redColor]];
    set1.lineWidth = 1.0;
    set1.circleRadius = 3.0;
    set1.drawCircleHoleEnabled = NO;
    set1.valueFont = [UIFont systemFontOfSize:8.f];
    set1.formLineDashLengths = @[@5.f, @2.5f];
    set1.formLineWidth = 1.0;
    set1.formSize = 15.0;
    [dataSets addObject:set1];

    return dataSets;
}

-(void)resultDataACtion{
    [self performSegueWithIdentifier:@"show_upperVC" sender:@{@"dataArray":upperDataArray,@"backdataArray":backupperDataArray}];
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

    UIViewController*vc=[segue destinationViewController];
    [vc setValuesForKeysWithDictionary:(NSDictionary*)sender];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)exportAction {
    // 创建存放XLS文件数据的数组
    NSMutableArray  *xlsDataMuArr = [[NSMutableArray alloc] init];
    // 第一行内容
    [xlsDataMuArr addObject:@"日期"];
    [xlsDataMuArr addObject:@"结果"];
    // 100行数据
    for (int i = 0; i < _totalDayKeyArr.count; i ++) {
        NSString*dateStr =[NSString stringWithFormat:@"%@日",_totalDayKeyArr[i]];
        dateStr = [dateStr stringByReplacingOccurrencesOfString:@"." withString:@"月"];
        [xlsDataMuArr addObject:dateStr];
        [xlsDataMuArr addObject:_totalDayValueArr[i]];
    }
    // 把数组拼接成字符串,连接符是 \t(功能同键盘上的tab键)
    NSString *fileContent = [xlsDataMuArr componentsJoinedByString:@"\t"];
    // 字符串转换为可变字符串,方便改变某些字符
    NSMutableString *muStr = [fileContent mutableCopy];
    // 新建一个可变数组,存储每行最后一个\t的下标(以便改为\n)
    NSMutableArray *subMuArr = [NSMutableArray array];
    for (int i = 0; i < muStr.length; i ++) {
        NSRange range = [muStr rangeOfString:@"\t" options:NSBackwardsSearch range:NSMakeRange(i, 1)];
        if (range.length == 1) {
            [subMuArr addObject:@(range.location)];
        }
    }
    // 替换末尾\t
    for (NSUInteger i = 0; i < subMuArr.count; i ++) {
#warning  下面的6是列数,根据需求修改
        if ( i > 0 && (i%2 == 0) ) {
            [muStr replaceCharactersInRange:NSMakeRange([[subMuArr objectAtIndex:i-1] intValue], 1) withString:@"\n"];
        }
    }
    // 文件管理器
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    NSData *fileData = [muStr dataUsingEncoding:NSUTF16StringEncoding];
    NSString *path = NSHomeDirectory();
    NSArray*nameArr=[_titleStr componentsSeparatedByString:@"-"];

    NSString*createPath = [NSString stringWithFormat:@"%@/Documents/%@",path,SAVE_EXPORT_FILENAME];
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath])
    {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePath = [createPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xls",nameArr[0]]];
    NSLog(@"文件路径:\n%@",filePath);

    BOOL issuccess = [fileManager createFileAtPath:filePath contents:fileData attributes:nil];
    if(issuccess){
        [self.view makeToast:@"导出成功" duration:3.0f position:CSToastPositionCenter];
    } else {
        [self.view makeToast:@"导出失败" duration:3.0f position:CSToastPositionCenter];
    }
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;

namespace osu.Game.Overlays.Notifications
{
    public interface IHasCompletionTarget
    {
        Action<Notification> CompletionTarget { get; set; }
    }
}


text:
package buildchain

import (
	"fmt"
	"strconv"
	"strings"

	imageapi "github.com/openshift/origin/pkg/image/api"
)

// invalidRepoTagErr is returned when an invalid image repository and tag
// combination has been passed by the user
var invalidRepoTagErr = fmt.Errorf("invalid [imageRepository]:[tag] input")

// parseTag parses the input and returns the repo (namespace+name)
// alongside a tag
func parseTag(input string) (string, string, error) {
	args := strings.Split(input, ":")
	switch len(args) {
	case 1:
		return args[0], imageapi.DefaultImageTag, nil
	case 2:
		if strings.TrimSpace(args[1]) == "" {
			return args[0], imageapi.DefaultImageTag, nil
		}
		return args[0], args[1], nil
	default:
		return "", "", invalidRepoTagErr
	}
}

// join joins a namespace and a name
func join(namespace, name string) string {
	return namespace + "/" + name
}

var invalidRepoErr = fmt.Errorf("cannot split input to name and namespace")

// split accepts an image repository namespace/name string
// and splits it to namespace (first) and name (second)
func split(repo string) (string, string, error) {
	args := strings.Split(repo, "/")
	if len(args) != 2 {
		return "", "", invalidRepoErr
	}
	return args[0], args[1], nil
}

// validDOT replaces hyphens with undescores so to
// keep the DOT parser happy
func validDOT(input string) string {
	// TODO: The only special character the DOT parser
	// accepts is the underscore (_)
	return strings.Replace(input, "-", "_", -1)
}

// setLabel is a helper function for setting labels
// on any graph object
func setLabel(name, namespace string, attrs map[string]string, tag string) {
	if tag != "" {
		name += ":" + tag
	}
	attrs["label"] = fmt.Sprintf("<%s
%s>", name, namespace)
}

// setTag sets tags in nodes as comments
func setTag(tag string, attrs map[string]string) {
	attrs["comment"] = strconv.Quote(tag)
}

// treeSize traverses a tree and returns its size
func treeSize(root *ImageRepo) int {
	if root == nil {
		return 0
	}
	if len(root.Children) == 0 {
		// Leaf node
		return 1
	}

	size := 1
	for _, child := range root.Children {
		size += treeSize(child)
	}

	return size
}


text:
require "active_support"
require "react-rails"

# This library
require "react/rails/benchmark_renderer/version"
require "react/server_rendering/concerns/instrumentation"
require "react/server_rendering/benchmark_renderer"


text:
using FlubuCore.Tasks.Versioning;

namespace FlubuCore.Context.Attributes.BuildProperties
{
    /// <summary>
    ///  Get or sets <see cref="BuildVersion"/> from build properties session.
    /// </summary>
    public class BuildVersionAttribute : BuildPropertyAttribute
    {
        public BuildVersionAttribute()
            : base(BuildProps.BuildVersion)
        {
        }
    }
}