text:
package main

import (
	"net/http"
	"os/exec"
	"time"

	"github.com/containous/staert"
	"github.com/docker/libkv"
	"github.com/docker/libkv/store"
	"github.com/docker/libkv/store/consul"
	"github.com/go-check/check"
	"golang.org/x/net/context"

	"errors"
	"github.com/containous/traefik/cluster"
	"github.com/containous/traefik/integration/utils"
	"github.com/containous/traefik/provider"
	checker "github.com/vdemeester/shakers"
	"io/ioutil"
	"os"
	"strings"
	"sync"
)

// Consul test suites (using libcompose)
type ConsulSuite struct {
	BaseSuite
	kv store.Store
}

func (s *ConsulSuite) setupConsul(c *check.C) {
	s.createComposeProject(c, "consul")
	s.composeProject.Start(c)

	consul.Register()
	kv, err := libkv.NewStore(
		store.CONSUL,
		[]string{s.composeProject.Container(c, "consul").NetworkSettings.IPAddress + ":8500"},
		&store.Config{
			ConnectionTimeout: 10 * time.Second,
		},
	)
	if err != nil {
		c.Fatal("Cannot create store consul")
	}
	s.kv = kv

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := kv.Exists("test")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)
}

func (s *ConsulSuite) setupConsulTLS(c *check.C) {
	s.createComposeProject(c, "consul_tls")
	s.composeProject.Start(c)

	consul.Register()
	clientTLS := &provider.ClientTLS{
		CA:                 "resources/tls/ca.cert",
		Cert:               "resources/tls/consul.cert",
		Key:                "resources/tls/consul.key",
		InsecureSkipVerify: true,
	}
	TLSConfig, err := clientTLS.CreateTLSConfig()
	c.Assert(err, checker.IsNil)

	kv, err := libkv.NewStore(
		store.CONSUL,
		[]string{s.composeProject.Container(c, "consul").NetworkSettings.IPAddress + ":8585"},
		&store.Config{
			ConnectionTimeout: 10 * time.Second,
			TLS:               TLSConfig,
		},
	)

	if err != nil {
		c.Fatal("Cannot create store consul")
	}
	s.kv = kv

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := kv.Exists("test")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)
}

func (s *ConsulSuite) TearDownTest(c *check.C) {
	// shutdown and delete compose project
	if s.composeProject != nil {
		s.composeProject.Stop(c)
	}
}

func (s *ConsulSuite) TearDownSuite(c *check.C) {}

func (s *ConsulSuite) TestSimpleConfiguration(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress
	file := s.adaptFile(c, "fixtures/consul/simple.toml", struct{ ConsulHost string }{consulHost})
	defer os.Remove(file)
	cmd := exec.Command(traefikBinary, "--configFile="+file)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	time.Sleep(500 * time.Millisecond)
	resp, err := http.Get("http://127.0.0.1:8000/")

	// Expected a 404 as we did not configure anything
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 404)
}

func (s *ConsulSuite) TestNominalConfiguration(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress
	file := s.adaptFile(c, "fixtures/consul/simple.toml", struct{ ConsulHost string }{consulHost})
	defer os.Remove(file)
	cmd := exec.Command(traefikBinary, "--configFile="+file)
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	whoami1 := s.composeProject.Container(c, "whoami1")
	whoami2 := s.composeProject.Container(c, "whoami2")
	whoami3 := s.composeProject.Container(c, "whoami3")
	whoami4 := s.composeProject.Container(c, "whoami4")

	backend1 := map[string]string{
		"traefik/backends/backend1/circuitbreaker/expression": "NetworkErrorRatio() > 0.5",
		"traefik/backends/backend1/servers/server1/url":       "http://" + whoami1.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server1/weight":    "10",
		"traefik/backends/backend1/servers/server2/url":       "http://" + whoami2.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server2/weight":    "1",
	}
	backend2 := map[string]string{
		"traefik/backends/backend2/loadbalancer/method":    "drr",
		"traefik/backends/backend2/servers/server1/url":    "http://" + whoami3.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server1/weight": "1",
		"traefik/backends/backend2/servers/server2/url":    "http://" + whoami4.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server2/weight": "2",
	}
	frontend1 := map[string]string{
		"traefik/frontends/frontend1/backend":            "backend2",
		"traefik/frontends/frontend1/entrypoints":        "http",
		"traefik/frontends/frontend1/priority":           "1",
		"traefik/frontends/frontend1/routes/test_1/rule": "Host:test.localhost",
	}
	frontend2 := map[string]string{
		"traefik/frontends/frontend2/backend":            "backend1",
		"traefik/frontends/frontend2/entrypoints":        "http",
		"traefik/frontends/frontend2/priority":           "10",
		"traefik/frontends/frontend2/routes/test_2/rule": "Path:/test",
	}
	for key, value := range backend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range backend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := s.kv.Exists("traefik/frontends/frontend2/routes/test_2/rule")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	// wait for traefik
	err = utils.TryRequest("http://127.0.0.1:8081/api/providers", 60*time.Second, func(res *http.Response) error {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		if !strings.Contains(string(body), "Path:/test") {
			return errors.New("Incorrect traefik config")
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	client := &http.Client{}
	req, err := http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "test.localhost"
	response, err := client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(response.StatusCode, checker.Equals, 200)

	body, err := ioutil.ReadAll(response.Body)
	c.Assert(err, checker.IsNil)
	if !strings.Contains(string(body), whoami3.NetworkSettings.IPAddress) &&
		!strings.Contains(string(body), whoami4.NetworkSettings.IPAddress) {
		c.Fail()
	}

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/test", nil)
	c.Assert(err, checker.IsNil)
	response, err = client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(response.StatusCode, checker.Equals, 200)

	body, err = ioutil.ReadAll(response.Body)
	c.Assert(err, checker.IsNil)
	if !strings.Contains(string(body), whoami1.NetworkSettings.IPAddress) &&
		!strings.Contains(string(body), whoami2.NetworkSettings.IPAddress) {
		c.Fail()
	}

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/test2", nil)
	resp, err := client.Do(req)
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 404)

	req, err = http.NewRequest("GET", "http://127.0.0.1:8000/", nil)
	req.Host = "test2.localhost"
	resp, err = client.Do(req)
	c.Assert(err, checker.IsNil)
	c.Assert(resp.StatusCode, checker.Equals, 404)
}

func (s *ConsulSuite) TestGlobalConfiguration(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress
	err := s.kv.Put("traefik/entrypoints/http/address", []byte(":8001"), nil)
	c.Assert(err, checker.IsNil)

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := s.kv.Exists("traefik/entrypoints/http/address")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	// start traefik
	cmd := exec.Command(traefikBinary, "--configFile=fixtures/simple_web.toml", "--consul", "--consul.endpoint="+consulHost+":8500")
	// cmd.Stdout = os.Stdout
	// cmd.Stderr = os.Stderr

	err = cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	whoami1 := s.composeProject.Container(c, "whoami1")
	whoami2 := s.composeProject.Container(c, "whoami2")
	whoami3 := s.composeProject.Container(c, "whoami3")
	whoami4 := s.composeProject.Container(c, "whoami4")

	backend1 := map[string]string{
		"traefik/backends/backend1/circuitbreaker/expression": "NetworkErrorRatio() > 0.5",
		"traefik/backends/backend1/servers/server1/url":       "http://" + whoami1.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server1/weight":    "10",
		"traefik/backends/backend1/servers/server2/url":       "http://" + whoami2.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend1/servers/server2/weight":    "1",
	}
	backend2 := map[string]string{
		"traefik/backends/backend2/loadbalancer/method":    "drr",
		"traefik/backends/backend2/servers/server1/url":    "http://" + whoami3.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server1/weight": "1",
		"traefik/backends/backend2/servers/server2/url":    "http://" + whoami4.NetworkSettings.IPAddress + ":80",
		"traefik/backends/backend2/servers/server2/weight": "2",
	}
	frontend1 := map[string]string{
		"traefik/frontends/frontend1/backend":            "backend2",
		"traefik/frontends/frontend1/entrypoints":        "http",
		"traefik/frontends/frontend1/priority":           "1",
		"traefik/frontends/frontend1/routes/test_1/rule": "Host:test.localhost",
	}
	frontend2 := map[string]string{
		"traefik/frontends/frontend2/backend":            "backend1",
		"traefik/frontends/frontend2/entrypoints":        "http",
		"traefik/frontends/frontend2/priority":           "10",
		"traefik/frontends/frontend2/routes/test_2/rule": "Path:/test",
	}
	for key, value := range backend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range backend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend1 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}
	for key, value := range frontend2 {
		err := s.kv.Put(key, []byte(value), nil)
		c.Assert(err, checker.IsNil)
	}

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := s.kv.Exists("traefik/frontends/frontend2/routes/test_2/rule")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	// wait for traefik
	err = utils.TryRequest("http://127.0.0.1:8080/api/providers", 60*time.Second, func(res *http.Response) error {
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		if !strings.Contains(string(body), "Path:/test") {
			return errors.New("Incorrect traefik config")
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	//check
	client := &http.Client{}
	req, err := http.NewRequest("GET", "http://127.0.0.1:8001/", nil)
	c.Assert(err, checker.IsNil)
	req.Host = "test.localhost"
	response, err := client.Do(req)

	c.Assert(err, checker.IsNil)
	c.Assert(response.StatusCode, checker.Equals, 200)
}

func (s *ConsulSuite) skipTestGlobalConfigurationWithClientTLS(c *check.C) {
	c.Skip("wait for relative path issue in the composefile")
	s.setupConsulTLS(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress

	err := s.kv.Put("traefik/web/address", []byte(":8081"), nil)
	c.Assert(err, checker.IsNil)

	// wait for consul
	err = utils.Try(60*time.Second, func() error {
		_, err := s.kv.Exists("traefik/web/address")
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

	// start traefik
	cmd := exec.Command(traefikBinary, "--configFile=fixtures/simple_web.toml",
		"--consul", "--consul.endpoint="+consulHost+":8585",
		"--consul.tls.ca=resources/tls/ca.cert",
		"--consul.tls.cert=resources/tls/consul.cert",
		"--consul.tls.key=resources/tls/consul.key",
		"--consul.tls.insecureskipverify")
	// cmd.Stdout = os.Stdout
	// cmd.Stderr = os.Stderr

	err = cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	// wait for traefik
	err = utils.TryRequest("http://127.0.0.1:8081/api/providers", 60*time.Second, func(res *http.Response) error {
		_, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		return nil
	})
	c.Assert(err, checker.IsNil)

}
func (s *ConsulSuite) TestCommandStoreConfig(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress

	cmd := exec.Command(traefikBinary, "storeconfig", "--configFile=fixtures/simple_web.toml", "--consul.endpoint="+consulHost+":8500")
	err := cmd.Start()
	c.Assert(err, checker.IsNil)

	// wait for traefik finish without error
	cmd.Wait()

	//CHECK
	checkmap := map[string]string{
		"/traefik/loglevel":                 "DEBUG",
		"/traefik/defaultentrypoints/0":     "http",
		"/traefik/entrypoints/http/address": ":8000",
		"/traefik/web/address":              ":8080",
		"/traefik/consul/endpoint":          (consulHost + ":8500"),
	}

	for key, value := range checkmap {
		var p *store.KVPair
		err = utils.Try(60*time.Second, func() error {
			p, err = s.kv.Get(key)
			if err != nil {
				return err
			}
			return nil
		})
		c.Assert(err, checker.IsNil)

		c.Assert(string(p.Value), checker.Equals, value)

	}
}

type TestStruct struct {
	String string
	Int    int
}

func (s *ConsulSuite) TestDatastore(c *check.C) {
	s.setupConsul(c)
	consulHost := s.composeProject.Container(c, "consul").NetworkSettings.IPAddress
	kvSource, err := staert.NewKvSource(store.CONSUL, []string{consulHost + ":8500"}, &store.Config{
		ConnectionTimeout: 10 * time.Second,
	}, "traefik")
	c.Assert(err, checker.IsNil)

	ctx := context.Background()
	datastore1, err := cluster.NewDataStore(*kvSource, ctx, &TestStruct{}, nil)
	c.Assert(err, checker.IsNil)
	datastore2, err := cluster.NewDataStore(*kvSource, ctx, &TestStruct{}, nil)
	c.Assert(err, checker.IsNil)

	setter1, _, err := datastore1.Begin()
	c.Assert(err, checker.IsNil)
	err = setter1.Commit(&TestStruct{
		String: "foo",
		Int:    1,
	})
	c.Assert(err, checker.IsNil)
	time.Sleep(2 * time.Second)
	test1 := datastore1.Get().(*TestStruct)
	c.Assert(test1.String, checker.Equals, "foo")

	test2 := datastore2.Get().(*TestStruct)
	c.Assert(test2.String, checker.Equals, "foo")

	setter2, _, err := datastore2.Begin()
	c.Assert(err, checker.IsNil)
	err = setter2.Commit(&TestStruct{
		String: "bar",
		Int:    2,
	})
	c.Assert(err, checker.IsNil)
	time.Sleep(2 * time.Second)
	test1 = datastore1.Get().(*TestStruct)
	c.Assert(test1.String, checker.Equals, "bar")

	test2 = datastore2.Get().(*TestStruct)
	c.Assert(test2.String, checker.Equals, "bar")

	wg := &sync.WaitGroup{}
	wg.Add(4)
	go func() {
		for i := 0; i < 100; i++ {
			setter1, _, err := datastore1.Begin()
			c.Assert(err, checker.IsNil)
			err = setter1.Commit(&TestStruct{
				String: "datastore1",
				Int:    i,
			})
			c.Assert(err, checker.IsNil)
		}
		wg.Done()
	}()
	go func() {
		for i := 0; i < 100; i++ {
			setter2, _, err := datastore2.Begin()
			c.Assert(err, checker.IsNil)
			err = setter2.Commit(&TestStruct{
				String: "datastore2",
				Int:    i,
			})
			c.Assert(err, checker.IsNil)
		}
		wg.Done()
	}()
	go func() {
		for i := 0; i < 100; i++ {
			test1 := datastore1.Get().(*TestStruct)
			c.Assert(test1, checker.NotNil)
		}
		wg.Done()
	}()
	go func() {
		for i := 0; i < 100; i++ {
			test2 := datastore2.Get().(*TestStruct)
			c.Assert(test2, checker.NotNil)
		}
		wg.Done()
	}()
	wg.Wait()
}


text:
using Cirrious.CrossCore;
using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.WindowsStore.Platform;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

namespace Paragon.Container
{
    public class Setup : MvxStoreSetup
    {
        public Setup(Frame rootFrame)
            : base(rootFrame)
        {
        }

        protected override void InitializeIoC()
        {
            base.InitializeIoC();

            Common.FileDownloader fileDownloader = new Common.FileDownloader();
            fileDownloader.SetRequestHeader("user-agent", string.Format("Windows Store Container app/v{0}", Utils.GetPackageVersion()));

            Mvx.RegisterSingleton<Common.IFileAccessorFactory>(new Common.FileAccessorFactory());
            Mvx.RegisterSingleton<Common.IResourcesProvider>(new Common.ResourcesProvider());
            Mvx.RegisterSingleton<Common.IUIDispatcher>(new Common.UIDispatcher());
            Mvx.RegisterSingleton<Common.IFileDownloader>(fileDownloader);
            Mvx.RegisterSingleton<Common.IInAppService>(new Common.TestInAppService());
            Mvx.RegisterSingleton<Common.ISettingsManager>(new Common.SettingsManager());
            Mvx.RegisterSingleton<Common.IShortcutManager>(new Common.ShortcutManager());
            Mvx.RegisterSingleton<Common.IDeviceInformation>(new Common.DeviceInformation());
            Mvx.RegisterSingleton<Common.IHttpClient>(new Common.HttpClient());
            Mvx.RegisterSingleton<Core.IItemsController>(new ItemsController());
            Mvx.RegisterSingleton<Core.IUserInteraction>(new UserInteraction());
            Mvx.RegisterSingleton<Core.IAppStylesService>(new AppStylesService());
            Mvx.RegisterSingleton<Dictionary.ISoundPlayer>(new SoundPlayer());
            Mvx.RegisterType<Common.ITimer, Common.Timer>();
        }

        protected override IMvxApplication CreateApp()
        {
            return new Core.App();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
    Made with  by Tolva

    </> on Github


text:
package ph.hatch.ddd.oe.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
public @interface OverrideName {

    String name() default "";

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phlegmacium cumatile var. robustum M.M. Moser

### Remarks
null


text:
package org.openestate.io.is24_xml.xml;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class Adapter11
    extends XmlAdapter<String, String>
{

    public String unmarshal(String value) {
        return (org.openestate.io.is24_xml.Is24XmlUtils.parseText200(value));
    }

    public String marshal(String value) {
        return (org.openestate.io.is24_xml.Is24XmlUtils.printText200(value));
    }

}


text:
FROM java:openjdk-8-jdk

# config, mainjar, logs and data folders respectively
RUN mkdir /etc/sonicd/; mkdir /usr/local/sonicd; mkdir /var/log/sonicd; mkdir /var/lib/sonicd;
RUN chmod 0775 /etc/sonicd; chmod 0775 /usr/local/sonicd; chmod 0775 /var/log/sonicd/; chmod 0775 /var/lib/sonicd

ENV configfolder /etc/sonicd/
ENV lib /var/lib/sonicd/*
ENV mainclass build.unstable.sonicd.Sonicd
ENV mainjar /usr/local/sonicd/sonicd-assembly.jar
ENV cp $configfolder:$mainjar:$lib
#ENV javaoptions=''

ADD server/target/scala-2.11/sonicd-assembly.jar /usr/local/sonicd/

CMD java -cp $cp $mainclass


text:
package org.robolectric.shadows;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.util.SQLite;

import java.sql.ResultSet;
import java.sql.SQLException;

@Implements(value = SQLiteStatement.class, inheritImplementationMethods = true)
public class ShadowSQLiteStatement extends ShadowSQLiteProgram {
  String mSql;

  public void init(SQLiteDatabase db, String sql) {
    super.init(db, sql);
    mSql = sql;
  }

  @Implementation
  public void execute() {
    if (!mDatabase.isOpen()) {
      throw new IllegalStateException("database " + mDatabase.getPath() + " already closed");
    }
    try {
      actualDBstatement.execute();
    } catch (SQLException e) {
      throw new SQLiteException(e.getMessage(), e);
    }
  }

  @Implementation
  public long executeInsert() {
    try {
      actualDBstatement.executeUpdate();
      return SQLite.fetchGeneratedKey(actualDBstatement.getGeneratedKeys());
    } catch (SQLException e) {
      throw new SQLiteException(e.getMessage(), e);
    }
  }

  @Implementation
  public int executeUpdateDelete() {
    try {
      return actualDBstatement.executeUpdate();
    } catch (SQLException e) {
      throw new SQLiteException(e.getMessage(), e);
    }
  }

  @Implementation
  public long simpleQueryForLong() {
    ResultSet rs;
    try {
      rs = actualDBstatement.executeQuery();
      rs.next();
      return rs.getLong(1);
    } catch (SQLException e) {
       handleException(e);
       throw new SQLiteException(e.getMessage(), e);
    }
  }

  @Implementation
  public String simpleQueryForString() {
    ResultSet rs;
    try {
      rs = actualDBstatement.executeQuery();
      rs.next();
      return rs.getString(1);
    } catch (SQLException e) {
      handleException(e);
      throw new SQLiteException(e.getMessage(), e);
    }
  }

  @Implementation
  public void close() {
    try {
      actualDBstatement.close();
    } catch (SQLException e) {
      throw new SQLiteException(e.getMessage(), e);
    }
  }

  private void handleException(SQLException e)  {
    if (e.getMessage().contains("No data is available")) {
      //if the query returns zero rows
      throw new SQLiteDoneException("No data is available");
    } else if (e.getMessage().contains("ResultSet closed")) {
      //if the query returns zero rows (SQLiteMap)
      throw new SQLiteDoneException("ResultSet closed,(probably, no data available)");
    }
  }
}


text:
package com.pabhinav;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @author pabhinav
 */
@Controller
public class FileUploadController {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    @RequestMapping(method = RequestMethod.GET, value = "/upload")
    public String provideUploadInfo(Model model){

        File rootApplication = new File(Application.ROOT);
        List<String> fileNames = Arrays.asList(rootApplication.list());
        model.addAttribute("files", fileNames);

        return "uploadForm";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file")MultipartFile multipartFile, RedirectAttributes redirectAttributes){
        if (name.contains("/") || name.contains("\\") ) {
            redirectAttributes.addFlashAttribute("message", "Folder separators '/' or '\' not allowed");
            return "redirect:upload";
        }
        if(name.isEmpty()){
            redirectAttributes.addFlashAttribute("message", "File name is empty, name your uploaded file");
            return "redirect:upload";
        }
        if(!multipartFile.isEmpty()){
            try{
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(Application.ROOT+ "/"+ name)));
                FileCopyUtils.copy(multipartFile.getInputStream(), stream);
                stream.close();
                redirectAttributes.addFlashAttribute("SuccessMessage", "You Successfully upload " + name + " !");
            } catch (Exception e){
                redirectAttributes.addFlashAttribute("message", "You failed to upload " + name + " => " + e.getMessage());
            }
        } else{
            redirectAttributes.addFlashAttribute("message" , "You Failed to upload " + name + " because the file was empty");
        }
        return "redirect:upload";
    }
}


text:
class Gatk < Formula
  desc "Genome Analysis Toolkit: Variant Discovery in High-Throughput Sequencing"
  homepage "https://software.broadinstitute.org/gatk/"
  url "https://github.com/broadgsa/gatk-protected/archive/3.6.tar.gz"
  sha256 "f2f1311136e06189b0f44a35a3c92fa700ddcbf3d6c4760517ec7bbe08eafce0"
  head "https://github.com/broadgsa/gatk-protected.git"
  # doi "10.1101/gr.107524.110"
  # tag "bioinformatics"

  bottle :disable, "See https://github.com/Homebrew/homebrew-science/pull/4428"

  depends_on :java
  depends_on "maven" => :build

  def install
    # Fix error on Circle CI.
    # Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher
    ENV.delete "M2_HOME"

    system "mvn", "package", "-Dmaven.repo.local=${PWD}/repo"
    java = share/"java"
    mkdir_p java
    cp "target/GenomeAnalysisTK.jar", java
    bin.write_jar_script java/"GenomeAnalysisTK.jar", "gatk"
    prefix.install_metafiles
  end

  def caveats; <<-EOS.undent
    GATK Official Release Repository: contains the core MIT-licensed GATK
    framework, plus "protected" tools restricted to non-commercial use only
    EOS
  end

  test do
    assert_match "usage", shell_output("#{bin}/gatk --help 2>&1", 0)
  end
end


text:
module Para
  module Admin
    module PaginationHelper
      def page_entries(resources)
        page_entries_info(resources) + per_page_select
      end

      private

      def per_page_select
        options = [25, 50, 100, 250, 500, 1000]

        params = (Rack::Utils.parse_query(request.env['QUERY_STRING']).symbolize_keys rescue {})
        params.delete(:page)
        count_with_url = options.each_with_object({}) do |count, hash|
          query = params.merge(:per_page => count)
          url  = request.env['PATH_INFO'] + (query.empty? ? '' : "?#{query.to_query}")

          hash[count] = url
        end

        current_per_page = params[:per_page] || Kaminari.config.default_per_page

        render partial: 'para/admin/resources/per_page_select', locals: {
          count_with_url: count_with_url,
          current_per_page: current_per_page
        }
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

use ApiPlatform\Core\Bridge\Symfony\Bundle\ApiPlatformBundle;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\User;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\TestBundle;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use FOS\UserBundle\FOSUserBundle;
use Nelmio\ApiDocBundle\NelmioApiDocBundle;
use Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Firewall\ContextListener;

/**
 * AppKernel for tests.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class AppKernel extends Kernel
{
    use MicroKernelTrait;

    public function registerBundles(): array
    {
        $bundles = [
            new FrameworkBundle(),
            new TwigBundle(),
            new DoctrineBundle(),
            new SensioFrameworkExtraBundle(),
            new ApiPlatformBundle(),
            new SecurityBundle(),
            new FOSUserBundle(),
            new TestBundle(),
        ];

        if ($_SERVER['LEGACY'] ?? true) {
            $bundles[] = new NelmioApiDocBundle();
        }

        return $bundles;
    }

    protected function configureRoutes(RouteCollectionBuilder $routes)
    {
        $routes->import('config/routing.yml');

        if ($_SERVER['LEGACY'] ?? true) {
            $routes->import('@NelmioApiDocBundle/Resources/config/routing.yml', '/nelmioapidoc');
        }
    }

    protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
    {
        $environment = $this->getEnvironment();
        $c->setParameter('kernel.project_dir', __DIR__);

        // patch for behat not supporting %env(APP_ENV)% in older versions
        if (($appEnv = $_SERVER['APP_ENV'] ?? 'test') && $appEnv !== $environment) {
            $environment = $appEnv;
        }

        $loader->load("{$this->getRootDir()}/config/config_{$environment}.yml");

        $securityConfig = [
            'encoders' => [
                User::class => 'bcrypt',
                // Don't use plaintext in production!
                UserInterface::class => 'plaintext',
            ],
            'providers' => [
                'chain_provider' => [
                    'chain' => [
                        'providers' => ['in_memory', 'fos_userbundle'],
                    ],
                ],
                'in_memory' => [
                    'memory' => [
                        'users' => [
                            'dunglas' => ['password' => 'kevin', 'roles' => 'ROLE_USER'],
                            'admin' => ['password' => 'kitten', 'roles' => 'ROLE_ADMIN'],
                        ],
                    ],
                ],
                'fos_userbundle' => ['id' => 'fos_user.user_provider.username_email'],
            ],
            'firewalls' => [
                'dev' => [
                    'pattern' => '^/(_(profiler|wdt|error)|css|images|js)/',
                    'security' => false,
                ],
                'default' => [
                    'provider' => 'chain_provider',
                    'http_basic' => null,
                    'anonymous' => null,
                ],
            ],
            'access_control' => [
                ['path' => '^/', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY'],
            ],
        ];

        if (method_exists(ContextListener::class, 'setLogoutOnUserChange')) {
            $securityConfig['firewalls']['default']['logout_on_user_change'] = true;
        }
        $c->loadFromExtension('security', $securityConfig);

        if ($_SERVER['LEGACY'] ?? true) {
            $c->loadFromExtension('nelmio_api_doc', [
                'sandbox' => [
                    'accept_type' => 'application/json',
                    'body_format' => [
                        'formats' => ['json'],
                        'default_format' => 'json',
                    ],
                    'request_format' => [
                        'formats' => ['json' => 'application/json'],
                    ],
                ],
            ]);
            $c->loadFromExtension('api_platform', ['enable_nelmio_api_doc' => true]);
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>noData</title>
</head>
<body>
<script>
  // error: Uncaught TypeError: Failed to execute 'createTextNode' on 'Document': 1 argument required, but only 0 present.
  var textNode = document.createTextNode();
</script>
</body>
</html>


text:
FactoryGirl.define do
  factory :meaning do
    self.def { Faker::Lorem.sentence }
    self.example { Faker::Lorem.sentence }
    entry

    factory :wordnet_meaning do
      wordnet_import true
    end
  end
end


text:
@extends('layouts.default')

{{-- Web site Title --}}
@section('title')
@parent
Create Group
@stop

{{-- Content --}}
@section('content')

        <form method="POST" action="{{ route('sentinel.groups.store') }}" accept-charset="UTF-8">

Create New Group

has('name')) ? 'has-error' : '' }}">
                <input class="form-control" placeholder="Name" name="name" type="text"  value="{{ Input::old('email') }}">
                {{ ($errors->has('name') ? $errors->first('name') : '') }}

            Permissions

                <?php $defaultPermissions = config('sentinel.default_permissions', []); ?>
                @foreach ($defaultPermissions as $permission)

                        <input name="permissions[{{ $permission }}]" value="1" type="checkbox"
                        @if (Input::old('permissions[' . $permission .']'))
                           checked
                        @endif
                        > {{ ucwords($permission) }}

                @endforeach

            <input name="_token" value="{{ csrf_token() }}" type="hidden">
            <input class="btn btn-primary" value="Create New Group" type="submit">

        </form>

@stop


text:
package org.spongepowered.api.boss;

import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.Identifiable;

/**
 * Represents a boss bar.
 */
public interface BossBar extends Identifiable {

    /**
     * Gets the name of this boss bar.
     *
     * @return The boss bar name
     */
    Text getName();

    /**
     * Sets the name of this boss bar.
     *
     * @param name The boss bar name
     * @return This boss bar
     */
    BossBar setName(Text name);

    /**
     * Gets the percent.
     *
     * @return The percent
     */
    float getPercent();

    /**
     * Sets the percent.
     *
     *
The percent must be between {@code 0.0} and {@code 1.0}.

     *
     * @param percent The percent
     * @return This boss bar
     */
    BossBar setPercent(float percent);

    /**
     * Gets the color.
     *
     * @return The color of the boss bar
     */
    BossBarColor getColor();

    /**
     * Sets the color.
     *
     * @param color The color of the boss bar
     * @return This boss bar
     */
    BossBar setColor(BossBarColor color);

    /**
     * Gets the overlay.
     *
     * @return The overlay
     */
    BossBarOverlay getOverlay();

    /**
     * Sets the overlay.
     *
     * @param overlay The overlay
     * @return This boss bar
     */
    BossBar setOverlay(BossBarOverlay overlay);

    /**
     * If the sky should darken.
     *
     * @return If the sky should darken
     */
    boolean shouldDarkenSky();

    /**
     * Sets if the sky should darken.
     *
     * @param darkenSky If the sky should darken
     * @return This boss bar
     */
    BossBar setDarkenSky(boolean darkenSky);

    /**
     * If the end boss music should be played.
     *
     * @return If the end boss music should be played
     */
    boolean shouldPlayEndBossMusic();

    /**
     * Sets if the end boss music should be played.
     *
     * @param playEndBossMusic If the end boss music should be played
     * @return This boss bar
     */
    BossBar setPlayEndBossMusic(boolean playEndBossMusic);

    /**
     * If fog should be created.
     *
     * @return If fog should be created
     */
    boolean shouldCreateFog();

    /**
     * Sets if fog should be created.
     *
     * @param createFog If fog should be created
     * @return This boss bar
     */
    BossBar setCreateFog(boolean createFog);

}


text:
#import "TCTVRagePlugin.h"
#import "TVRageController.h"

@implementation TCTVRagePlugin

TCUUID(@"90FAD8EB-FE51-48E3-9783-5BBE81CEFBAC")

-(void)handleInsertedObject:(TCExtendableObject *)object{
	if([object isKindOfClass:[TCTVShow class]]){
		[[TVRageController sharedController] beginLoadOperation:TCTVRageGetEpisodesOperation
												 withInfoObject:object
													   delegate:self];
	}
}

@end


text:
import numpy as np
import pymoskito as pm

import matplotlib as mpl
import matplotlib.patches
import matplotlib.transforms

from . import settings as st

try:
    import vtk

    class TwoPendulumVisualizer(pm.VtkVisualizer):

        def __init__(self, renderer):
            pm.VtkVisualizer.__init__(self, renderer)

            # -------- add the beam ----
            # geometry
            self.beam = vtk.vtkCubeSource()
            self.beam.SetXLength(st.beam_length)
            self.beam.SetYLength(st.beam_height)
            self.beam.SetZLength(st.beam_depth)

            # mapper
            self.beam_Mapper = vtk.vtkPolyDataMapper()
            self.beam_Mapper.SetInputConnection(self.beam.GetOutputPort())

            # actor
            self.beam_Actor = vtk.vtkLODActor()
            self.beam_Actor.SetMapper(self.beam_Mapper)
            self.beam_Actor.SetPosition(0, -(st.cart_height / 2
                                             + st.beam_height / 2), 0)

            # make it look nice
            self.beam_Prop = self.beam_Actor.GetProperty()
            # RAL 9007, grey-aluminium
            self.beam_Prop.SetColor(142 / 255, 142 / 255, 139 / 255)

            self.ren.AddActor(self.beam_Actor)

            # -------- add cart ----
            # geometry
            self.cart = vtk.vtkCubeSource()
            self.cart.SetXLength(st.cart_length)
            self.cart.SetYLength(st.cart_height)
            self.cart.SetZLength(st.cart_depth)

            # mapper
            self.cart_Mapper = vtk.vtkPolyDataMapper()
            self.cart_Mapper.SetInputConnection(self.cart.GetOutputPort())

            # actor
            self.cart_Actor = vtk.vtkLODActor()
            self.cart_Actor.SetPosition(0, 0, 0)
            self.cart_Actor.RotateWXYZ(0, 1, 0, 0)
            self.cart_Actor.SetMapper(self.cart_Mapper)

            # make it look nice
            self.cart_Prop = self.cart_Actor.GetProperty()
            # RAL 7011, iron-grey
            self.cart_Prop.SetColor(64 / 255, 74 / 255, 84 / 255)

            self.ren.AddActor(self.cart_Actor)
            # save pose
            self.cart_pose = [np.array([0, 0, 0]), np.eye(3)]

            # -------- add axis ----
            # geometry
            self.axis = vtk.vtkCylinderSource()
            self.axis.SetHeight(st.axis_height)
            self.axis.SetRadius(st.axis_radius)
            self.axis.SetResolution(100)

            # mapper
            self.axis_Mapper = vtk.vtkPolyDataMapper()
            self.axis_Mapper.SetInputConnection(self.axis.GetOutputPort())

            # actor
            self.axis_Actor = vtk.vtkLODActor()
            self.axis_Actor.SetPosition(0, 0, st.cart_depth/2
                                        + st.axis_height/2)
            self.axis_Actor.RotateWXYZ(90, 1, 0, 0)
            self.axis_Actor.SetMapper(self.axis_Mapper)

            # make it look nice
            self.axis_Prop = self.axis_Actor.GetProperty()
            # RAL 7011, iron-grey
            self.axis_Prop.SetColor(64 / 255, 74 / 255, 84 / 255)

            self.ren.AddActor(self.axis_Actor)
            # save pose
            self.axis_pose = [np.array([0,
                                        0,
                                        st.cart_depth/2 + st.axis_height/2]),
                              pm.rotation_matrix_xyz("x", 90, "deg")]

            # -------- add short pendulum ----
            # add short pendulum shaft
            # geometry
            self.short_pendulum_shaft = vtk.vtkCylinderSource()
            self.short_pendulum_shaft.SetHeight(st.pendulum_shaft_height)
            self.short_pendulum_shaft.SetRadius(st.pendulum_shaft_radius)
            self.short_pendulum_shaft.SetResolution(100)

            # mapper
            self.short_pendulum_shaft_Mapper = vtk.vtkPolyDataMapper()
            self.short_pendulum_shaft_Mapper.SetInputConnection(
                self.short_pendulum_shaft.GetOutputPort())

            # actor
            self.short_pendulum_shaft_Actor = vtk.vtkLODActor()
            self.short_pendulum_shaft_Actor.SetPosition(
                0,
                0,
                st.cart_depth/2
                + st.axis_height
                + st.pendulum_shaft_height/2)
            self.short_pendulum_shaft_Actor.RotateWXYZ(90, 1, 0, 0)
            self.short_pendulum_shaft_Actor.SetMapper(
                self.short_pendulum_shaft_Mapper)

            # make it look nice
            self.short_pendulum_shaft_Prop = \
                self.short_pendulum_shaft_Actor.GetProperty()
            # RAL 9007, grey-aluminium, a little bit darker
            self.short_pendulum_shaft_Prop.SetColor(122 / 255,
                                                    122 / 255,
                                                    119 / 255)

            self.ren.AddActor(self.short_pendulum_shaft_Actor)
            # save pose
            self.short_pendulum_shaft_pose = [
                np.array([0,
                          0,
                          st.cart_depth/2
                          + st.axis_height
                          + st.pendulum_shaft_height/2]),
                pm.rotation_matrix_xyz("x", 90, "deg")]

            # add short pendulum
            # geometry
            self.short_pendulum = vtk.vtkCylinderSource()
            self.short_pendulum.SetHeight(st.short_pendulum_height)
            self.short_pendulum.SetRadius(st.short_pendulum_radius)
            self.short_pendulum.SetResolution(100)

            # mapper
            self.short_pendulum_Mapper = vtk.vtkPolyDataMapper()
            self.short_pendulum_Mapper.SetInputConnection(
                self.short_pendulum.GetOutputPort())

            # actor
            self.short_pendulum_Actor = vtk.vtkLODActor()
            self.short_pendulum_Actor.SetPosition(0,
                                                  st.short_pendulum_height/2,
                                                  st.cart_depth/2
                                                  + st.axis_height
                                                  + st.pendulum_shaft_height/2)
            self.short_pendulum_Actor.RotateWXYZ(0, 1, 0, 0)
            self.short_pendulum_Actor.SetMapper(self.short_pendulum_Mapper)

            # make it look nice
            self.short_pendulum_Prop = self.short_pendulum_Actor.GetProperty()
            # RAL 9007, grey-aluminium, a little bit darker
            self.short_pendulum_Prop.SetColor(122 / 255, 122 / 255, 119 / 255)

            self.ren.AddActor(self.short_pendulum_Actor)
            self.short_pendulum_pose = [
                np.array([0,
                          st.short_pendulum_height/2,
                          st.cart_depth/2
                          + st.axis_height
                          + st.pendulum_shaft_height/2]),
                np.eye(3)]

            # add short pendulum weight
            # geometry
            self.short_pendulum_weight = vtk.vtkCylinderSource()
            self.short_pendulum_weight.SetHeight(st.pendulum_weight_height)
            self.short_pendulum_weight.SetRadius(st.pendulum_weight_radius)
            self.short_pendulum_weight.SetResolution(100)

            # mapper
            self.short_pendulum_weight_Mapper = vtk.vtkPolyDataMapper()
            self.short_pendulum_weight_Mapper.SetInputConnection(
                self.short_pendulum_weight.GetOutputPort())

            # actor
            self.short_pendulum_weight_Actor = vtk.vtkLODActor()
            self.short_pendulum_weight_Actor.SetPosition(
                0,
                (st.short_pendulum_height + st.pendulum_weight_height/2),
                st.cart_depth/2 + st.axis_height + st.pendulum_shaft_height/2)
            self.short_pendulum_weight_Actor.RotateWXYZ(0, 1, 0, 0)
            self.short_pendulum_weight_Actor.SetMapper(
                self.short_pendulum_weight_Mapper)

            # make it look nice
            self.short_pendulum_weight_Prop \
                = self.short_pendulum_weight_Actor.GetProperty()
            # RAL 9006, white-aluminium
            self.short_pendulum_weight_Prop.SetColor(162 / 255,
                                                     166 / 255,
                                                     164 / 255)

            self.ren.AddActor(self.short_pendulum_weight_Actor)
            self.short_pendulum_weight_pose = [
                np.array([0,
                          (st.short_pendulum_height
                           + st.pendulum_weight_height/2),
                          st.cart_depth/2
                          + st.axis_height
                          + st.pendulum_shaft_height/2]),
                np.eye(3)
            ]

            # -------- add long pendulum ----
            # add long pendulum shaft
            # geometry
            self.long_pendulum_shaft = vtk.vtkCylinderSource()
            self.long_pendulum_shaft.SetHeight(st.pendulum_shaft_height)
            self.long_pendulum_shaft.SetRadius(st.pendulum_shaft_radius)
            self.long_pendulum_shaft.SetResolution(100)

            # mapper
            self.long_pendulum_shaft_Mapper = vtk.vtkPolyDataMapper()
            self.long_pendulum_shaft_Mapper.SetInputConnection(
                self.long_pendulum_shaft.GetOutputPort())

            # actor
            self.long_pendulum_shaft_Actor = vtk.vtkLODActor()
            self.long_pendulum_shaft_Actor.SetPosition(
                0,
                0,
                st.cart_depth/2
                + st.axis_height
                + st.pendulum_shaft_height
                + st.pendulum_shaft_height/2)
            self.long_pendulum_shaft_Actor.RotateWXYZ(90, 1, 0, 0)
            self.long_pendulum_shaft_Actor.SetMapper(
                self.long_pendulum_shaft_Mapper)

            # make it look nice
            self.long_pendulum_shaft_Prop =\
                self.long_pendulum_shaft_Actor.GetProperty()
            # RAL 9007, grey-aluminium
            self.long_pendulum_shaft_Prop.SetColor(142 / 255,
                                                   142 / 255,
                                                   139 / 255)

            self.ren.AddActor(self.long_pendulum_shaft_Actor)
            # save pose
            self.long_pendulum_shaft_pose = [
                np.array([0,
                          0,
                          st.cart_depth/2
                          + st.axis_height
                          + st.pendulum_shaft_height
                          + st.pendulum_shaft_height/2]),
                pm.rotation_matrix_xyz("x", 90, "deg")]

            # add long pendulum
            # geometry
            self.long_pendulum = vtk.vtkCylinderSource()
            self.long_pendulum.SetHeight(st.long_pendulum_height)
            self.long_pendulum.SetRadius(st.long_pendulum_radius)
            self.long_pendulum.SetResolution(100)

            # mapper
            self.long_pendulum_Mapper = vtk.vtkPolyDataMapper()
            self.long_pendulum_Mapper.SetInputConnection(
                self.long_pendulum.GetOutputPort())

            # actor
            self.long_pendulum_Actor = vtk.vtkLODActor()
            self.long_pendulum_Actor.SetPosition(0,
                                                 st.long_pendulum_height/2,
                                                 st.cart_depth/2
                                                 + st.axis_height
                                                 + st.pendulum_shaft_height
                                                 + st.pendulum_shaft_height/2)
            self.long_pendulum_Actor.RotateWXYZ(0, 1, 0, 0)
            self.long_pendulum_Actor.SetMapper(self.long_pendulum_Mapper)

            # make it look nice
            self.long_pendulum_Prop = self.long_pendulum_Actor.GetProperty()
            # RAL 9007, grey-aluminium
            self.long_pendulum_Prop.SetColor(142 / 255, 142 / 255, 139 / 255)

            self.ren.AddActor(self.long_pendulum_Actor)
            self.long_pendulum_pose = [np.array([0,
                                                 st.long_pendulum_height/2,
                                                 st.cart_depth/2
                                                 + st.axis_height
                                                 + st.pendulum_shaft_height
                                                 + st.pendulum_shaft_height/2]),
                                       np.eye(3)]

            # add long pendulum weight
            # geometry
            self.long_pendulum_weight = vtk.vtkCylinderSource()
            self.long_pendulum_weight.SetHeight(st.pendulum_weight_height)
            self.long_pendulum_weight.SetRadius(st.pendulum_weight_radius)
            self.long_pendulum_weight.SetResolution(100)

            # mapper
            self.long_pendulum_weight_Mapper = vtk.vtkPolyDataMapper()
            self.long_pendulum_weight_Mapper.SetInputConnection(
                self.long_pendulum_weight.GetOutputPort())

            # actor
            self.long_pendulum_weight_Actor = vtk.vtkLODActor()
            self.long_pendulum_weight_Actor.SetPosition(
                0,
                st.long_pendulum_height + st.pendulum_weight_height/2,
                st.cart_depth/2
                + st.axis_height
                + st.pendulum_shaft_height
                + st.pendulum_shaft_height/2)
            self.long_pendulum_weight_Actor.RotateWXYZ(0, 1, 0, 0)
            self.long_pendulum_weight_Actor.SetMapper(
                self.long_pendulum_weight_Mapper)

            # make it look nice
            self.long_pendulum_weight_Prop \
                = self.long_pendulum_weight_Actor.GetProperty()
            # RAL 9006, white-aluminium
            self.long_pendulum_weight_Prop.SetColor(162 / 255,
                                                    166 / 255,
                                                    164 / 255)

            self.ren.AddActor(self.long_pendulum_weight_Actor)
            self.long_pendulum_weight_pose = [
                np.array([0,
                          st.long_pendulum_height + st.pendulum_weight_height/2,
                          st.cart_depth/2
                          + st.axis_height
                          + st.pendulum_shaft_height
                          + st.pendulum_shaft_height/2]),
                np.eye(3)]

            # add background
            self.ren.GradientBackgroundOn()
            self.ren.SetBackground(228 / 255, 232 / 255, 213 / 255)
            self.ren.SetBackground2(38 / 255, 139 / 255, 210 / 255)

            # get everybody into the frame
            self.ren.ResetCamera()
            self.ren.GetActiveCamera().Zoom(1.45)
            self.ren.GetActiveCamera().SetFocalPoint(0, 0, 0)

            # save this view
            self.save_camera_pose()

        def calc_positions(self, x):
            """
            Calculate stationary vectors and rot. matrices for bodies
            """
            positions_dict = {}

            # cart
            t_cart = np.array([x[0], 0, 0]) + self.cart_pose[0]
            r_cart = np.eye(3) @ self.cart_pose[1]
            positions_dict.update({"cart": [self.cart_Actor, t_cart, r_cart]})

            # axis
            t_axis = np.array([x[0], 0, 0]) + self.axis_pose[0]
            r_axis = np.eye(3) @ self.axis_pose[1]
            positions_dict.update({"axis": [self.axis_Actor, t_axis, r_axis]})

            # short_pendulum_shaft
            t_short_pendulum_shaft = (np.array([x[0], 0, 0])
                                      + self.short_pendulum_shaft_pose[0])
            r_short_pendulum_shaft = pm.rotation_matrix_xyz(
                "z", x[4], "rad") @ self.short_pendulum_shaft_pose[1]
            positions_dict.update({"short_pendulum_shaft": [
                self.short_pendulum_shaft_Actor,
                t_short_pendulum_shaft,
                r_short_pendulum_shaft]})
            # short_pendulum
            t_short_pendulum = (np.array([x[0], 0, 0])
                                + pm.rotation_matrix_xyz(
                "z", x[4], "rad") @ self.short_pendulum_pose[0])

            r_short_pendulum = pm.rotation_matrix_xyz(
                "z", x[4], "rad") @ self.short_pendulum_pose[1]
            positions_dict.update({"short_pendulum": [self.short_pendulum_Actor,
                                                      t_short_pendulum,
                                                      r_short_pendulum]})

            # short_pendulum_weight
            t_short_pendulum_weight = (np.array([x[0], 0, 0])
                                       + pm.rotation_matrix_xyz(
                "z", x[4], "rad") @ self.short_pendulum_weight_pose[0])
            r_short_pendulum_weight = pm.rotation_matrix_xyz(
                "z", x[4], "rad") @ self.short_pendulum_weight_pose[1]
            positions_dict.update({"short_pendulum_weight": [
                self.short_pendulum_weight_Actor,
                t_short_pendulum_weight,
                r_short_pendulum_weight]})

            # long_pendulum_shaft
            t_long_pendulum_shaft = (np.array([x[0], 0, 0])
                                     + self.long_pendulum_shaft_pose[0])
            r_long_pendulum_shaft = pm.rotation_matrix_xyz(
                "z", x[2], "rad") @ self.long_pendulum_shaft_pose[1]
            positions_dict.update({"long_pendulum_shaft": [
                self.long_pendulum_shaft_Actor,
                t_long_pendulum_shaft,
                r_long_pendulum_shaft]})

            # long_pendulum
            t_long_pendulum = (np.array([x[0], 0, 0])
                               + pm.rotation_matrix_xyz(
                "z", x[2], "rad") @ self.long_pendulum_pose[0])
            r_long_pendulum = pm.rotation_matrix_xyz(
                "z", x[2], "rad") @ self.long_pendulum_pose[1]
            positions_dict.update({"long_pendulum": [self.long_pendulum_Actor,
                                                     t_long_pendulum,
                                                     r_long_pendulum]})

            # long_pendulum_weight
            t_long_pendulum_weight = (np.array([x[0], 0, 0])
                                      + pm.rotation_matrix_xyz(
                "z", x[2], "rad") @ self.long_pendulum_weight_pose[0])
            r_long_pendulum_weight = pm.rotation_matrix_xyz(
                "z", x[2], "rad") @ self.long_pendulum_weight_pose[1]
            positions_dict.update({"long_pendulum_weight": [
                self.long_pendulum_weight_Actor,
                t_long_pendulum_weight,
                r_long_pendulum_weight]})

            return positions_dict

        @staticmethod
        def set_body_state(pos_dict):

            for x in pos_dict.values():
                poke = vtk.vtkMatrix4x4()
                actor = x[0]
                t = x[1]
                r = x[2]
                for i in range(3):
                    for n in range(3):
                        poke.SetElement(i, n, r[i, n])
                    poke.SetElement(i, 3, t[i])

                actor.PokeMatrix(poke)

        def update_scene(self, x):
            """
            update the body states
            """
            self.set_body_state(self.calc_positions(x))

    pm.register_visualizer(TwoPendulumVisualizer)

except ImportError as e:
    vtk = None
    print("BallTube Visualizer:")
    print(e)
    print("VTK Visualization not available.")

class MplTwoPendulumVisualizer(pm.MplVisualizer):

    def __init__(self, q_widget, q_layout):
        pm.MplVisualizer.__init__(self, q_widget, q_layout)
        self.axes.set_xlim(st.x_min_plot, st.x_max_plot)
        self.axes.set_ylim(st.y_min_plot, st.y_max_plot)
        self.axes.set_aspect("equal")

        self.beam = mpl.patches.Rectangle(xy=[-st.beam_length/2,
                                              -(st.beam_height
                                                + st.cart_height/2)],
                                          width=st.beam_length,
                                          height=st.beam_height,
                                          color="lightgrey")

        self.cart = mpl.patches.Rectangle(xy=[-st.cart_length/2,
                                              -st.cart_height/2],
                                          width=st.cart_length,
                                          height=st.cart_height,
                                          color="dimgrey")

        self.pendulum_shaft = mpl.patches.Circle(
            xy=[0, 0],
            radius=st.pendulum_shaft_radius,
            color="lightgrey",
            zorder=3)

        t = mpl.transforms.Affine2D().rotate_deg(180) + self.axes.transData
        self.short_pendulum = mpl.patches.Rectangle(
            xy=[-st.short_pendulum_radius, 0],
            width=2*st.short_pendulum_radius,
            height=st.short_pendulum_height,
            color="#E87B14",  # TUD CD HKS 07_K
            zorder=2,
            transform=t)
        self.short_pendulum_weight = mpl.patches.Rectangle(
            xy=[-st.pendulum_weight_radius, st.short_pendulum_height],
            width=2*st.pendulum_weight_radius,
            height=st.pendulum_weight_height,
            color="#E87B14",  # TUD CD HKS 07_K
            zorder=2,
            transform=t)
        self.long_pendulum = mpl.patches.Rectangle(
            xy=[-st.long_pendulum_radius, 0],
            width=2*st.long_pendulum_radius,
            height=st.long_pendulum_height,
            color="#0059A3",  # TUD CD HKS 44_K
            zorder=1,
            transform=t)
        self.long_pendulum_weight = mpl.patches.Rectangle(
            xy=[-st.pendulum_weight_radius, st.long_pendulum_height],
            width=2*st.pendulum_weight_radius,
            height=st.pendulum_weight_height,
            color="#0059A3",  # TUD CD HKS 44_K
            zorder=1,
            transform=t)

        self.axes.add_patch(self.beam)
        self.axes.add_patch(self.cart)
        self.axes.add_patch(self.pendulum_shaft)
        self.axes.add_patch(self.short_pendulum)
        self.axes.add_patch(self.short_pendulum_weight)
        self.axes.add_patch(self.long_pendulum)
        self.axes.add_patch(self.long_pendulum_weight)

    def update_scene(self, x):
        x0 = x[0]
        phi1 = np.rad2deg(x[2])
        phi2 = np.rad2deg(x[4])

        # cart and shaft
        self.cart.set_x(-st.cart_length/2 + x0)
        self.pendulum_shaft.center = [x0, 0]

        t_phi1 = (mpl.transforms.Affine2D().rotate_deg_around(x0, 0, phi1)
                  + self.axes.transData)
        t_phi2 = (mpl.transforms.Affine2D().rotate_deg_around(x0, 0, phi2)
                  + self.axes.transData)

        # long pendulum
        self.long_pendulum.set_xy([-st.long_pendulum_radius + x0, 0])
        self.long_pendulum.set_transform(t_phi1)
        self.long_pendulum_weight.set_xy([-st.pendulum_weight_radius
                                          + x0, st.long_pendulum_height])
        self.long_pendulum_weight.set_transform(t_phi1)

        # short pendulum
        self.short_pendulum.set_xy(np.array([-st.short_pendulum_radius, 0])
                                   + np.array([x0, 0]))
        self.short_pendulum.set_transform(t_phi2)
        self.short_pendulum_weight.set_xy([-st.pendulum_weight_radius + x0,
                                           st.short_pendulum_height])

        self.short_pendulum_weight.set_transform(t_phi2)
        self.canvas.draw()

pm.register_visualizer(MplTwoPendulumVisualizer)


text:
package org.jabref.gui.externalfiles;

import java.nio.file.Files;
import java.nio.file.Path;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class GitIgnoreFileFilterTest {

    @Test
    public void checkSimpleGitIgnore(@TempDir Path dir) throws Exception {
        Files.writeString(dir.resolve(".gitignore"), """
                *.png
                """);
        GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
        assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
    }

    @Test
    public void checkSimpleGitIgnoreWithAllowing(@TempDir Path dir) throws Exception {
        Files.writeString(dir.resolve(".gitignore"), """
                !*.png
                """);
        GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
        assertTrue(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
    }

    @Test
    public void checkSimpleGitIgnoreWithOverwritingDefs(@TempDir Path dir) throws Exception {
        Files.writeString(dir.resolve(".gitignore"), """
                !*.png
                *.png
                """);
        GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
        assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
    }

    @Test
    public void checkDirectoryGitIgnore(@TempDir Path dir) throws Exception {
        Files.writeString(dir.resolve(".gitignore"), """
                **/*.png
                """);
        GitIgnoreFileFilter gitIgnoreFileFilter = new GitIgnoreFileFilter(dir);
        assertFalse(gitIgnoreFileFilter.accept(dir.resolve("test.png")));
    }
}


text:
from __future__ import absolute_import

import os
import sys
import json

from todo.commands.toggle import ToggleCommand
from todo.utils.menu import show_options
from todo.utils.styles import Fore, Style

class RemoveCommand(ToggleCommand):
    def get_subtitle(self):
        """Returns the subtitle of the menu"""
        return 'Remove items'

    def handle_click(self, todos, item_index):
        """Returns the todo list without the todo of the given index"""
        todos_removed = todos.copy()
        todos_removed.pop(item_index)
        return todos_removed

    def handle_search(self, todos, item):
        """Returns the todo list without the given item"""
        todos_removed = todos.copy()
        todos_removed.remove(item)
        return todos_removed

Remove = RemoveCommand()


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

    <title>EurekaJ</title>
    <link rel="stylesheet" href="js/css/master.css" type="text/css" charset="utf-8">
    <meta name="author" content="Joachim Haagen Skeie">


text:
layout: post
title: Digital Ocean
slug: digitalocean
source: https://cloud.digitalocean.com/
---

<img src="/screenshots/digitalocean.png" alt="Digital Ocean">


text:
package org.usfirst.frc5902.robot.subsystems;

import com.ctre.CANTalon;
import com.ctre.CANTalon.FeedbackDevice;
import com.ctre.CANTalon.FeedbackDeviceStatus;

import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 */

public class encoderDev extends Subsystem implements edu.wpi.first.wpilibj.CANSpeedController.ControlMode{

    // Put methods for controlling this subsystem
    // here. Call these from Commands.
	public int pulseWidthPos;
	public int pulseWidthRiseToFallUs;
	public int pulseWidthRiseToRiseUs;
	public int pulseWidthVelocity;
	public int wireClippersEncoderValue;
	private int internalEncoderValue;
	public FeedbackDeviceStatus sensorstatus;
	public boolean sensorPluggedIn;
	public CANTalon leftDriveEncoder;
    public encoderDev(CANTalon _tal) {
    	leftDriveEncoder=_tal;
	}
	@Override
	protected void initDefaultCommand() {
		internalEncoderValue = leftDriveEncoder.getPulseWidthPosition();
	}
	public void run() {
		this.pulseWidthPos = internalEncoderValue - leftDriveEncoder.getPulseWidthPosition();
    	this.pulseWidthRiseToFallUs = leftDriveEncoder.getPulseWidthRiseToFallUs();
    	this.pulseWidthRiseToRiseUs = leftDriveEncoder.getPulseWidthRiseToRiseUs();
    	this.pulseWidthVelocity = leftDriveEncoder.getPulseWidthVelocity();
    	this.sensorstatus = leftDriveEncoder.isSensorPresent(FeedbackDevice.CtreMagEncoder_Absolute);
    	this.sensorPluggedIn = (FeedbackDeviceStatus.FeedbackStatusPresent == sensorstatus);

	}
	@Override
	public String name() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public boolean isPID() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public int getValue() {
		// TODO Auto-generated method stub
		return 0;
	}

	public int reset() {
		// TODO Auto-generated method stub
		internalEncoderValue = leftDriveEncoder.getPulseWidthPosition();
		return 0;
	}
	public void zero() {
		// TODO Auto-generated method stub
		internalEncoderValue = 0;
	}
}


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 org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad.Builder (HBase 0.98.7-hadoop2 API)</title>
<meta name="date" content="2014-10-08">
<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
org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad.Builder

Packages that use ClusterStatusProtos.RegionLoad.Builder

Package
Description

org.apache.hadoop.hbase.protobuf.generated

Uses of ClusterStatusProtos.RegionLoad.Builder in org.apache.hadoop.hbase.protobuf.generated

Methods in org.apache.hadoop.hbase.protobuf.generated that return ClusterStatusProtos.RegionLoad.Builder

Modifier and Type
Method and Description

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.addRegionLoadsBuilder()

repeated .RegionLoad region_loads = 5;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.addRegionLoadsBuilder(int index)

repeated .RegionLoad region_loads = 5;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clear()

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearCompleteSequenceId()

optional uint64 complete_sequence_id = 15;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearCurrentCompactedKVs()

optional uint64 current_compacted_KVs = 11;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearMemstoreSizeMB()

optional uint32 memstore_size_MB = 6;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearReadRequestsCount()

optional uint64 read_requests_count = 8;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearRegionSpecifier()

required .RegionSpecifier region_specifier = 1;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearRootIndexSizeKB()

optional uint32 root_index_size_KB = 12;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearStorefileIndexSizeMB()

optional uint32 storefile_index_size_MB = 7;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearStorefiles()

optional uint32 storefiles = 3;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearStorefileSizeMB()

optional uint32 storefile_size_MB = 5;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearStores()

optional uint32 stores = 2;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearStoreUncompressedSizeMB()

optional uint32 store_uncompressed_size_MB = 4;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearTotalCompactingKVs()

optional uint64 total_compacting_KVs = 10;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearTotalStaticBloomSizeKB()

optional uint32 total_static_bloom_size_KB = 14;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearTotalStaticIndexSizeKB()

optional uint32 total_static_index_size_KB = 13;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clearWriteRequestsCount()

optional uint64 write_requests_count = 9;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.clone()

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.getRegionLoadsBuilder(int index)

repeated .RegionLoad region_loads = 5;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.mergeFrom(ClusterStatusProtos.RegionLoad other)

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.mergeFrom(com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.mergeFrom(com.google.protobuf.Message other)

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.mergeRegionSpecifier(HBaseProtos.RegionSpecifier value)

required .RegionSpecifier region_specifier = 1;

static ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.newBuilder()

static ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.newBuilder(ClusterStatusProtos.RegionLoad prototype)

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.newBuilderForType()

protected ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent)

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setCompleteSequenceId(long value)

optional uint64 complete_sequence_id = 15;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setCurrentCompactedKVs(long value)

optional uint64 current_compacted_KVs = 11;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setMemstoreSizeMB(int value)

optional uint32 memstore_size_MB = 6;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setReadRequestsCount(long value)

optional uint64 read_requests_count = 8;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setRegionSpecifier(HBaseProtos.RegionSpecifier.Builder builderForValue)

required .RegionSpecifier region_specifier = 1;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setRegionSpecifier(HBaseProtos.RegionSpecifier value)

required .RegionSpecifier region_specifier = 1;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setRootIndexSizeKB(int value)

optional uint32 root_index_size_KB = 12;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setStorefileIndexSizeMB(int value)

optional uint32 storefile_index_size_MB = 7;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setStorefiles(int value)

optional uint32 storefiles = 3;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setStorefileSizeMB(int value)

optional uint32 storefile_size_MB = 5;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setStores(int value)

optional uint32 stores = 2;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setStoreUncompressedSizeMB(int value)

optional uint32 store_uncompressed_size_MB = 4;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setTotalCompactingKVs(long value)

optional uint64 total_compacting_KVs = 10;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setTotalStaticBloomSizeKB(int value)

optional uint32 total_static_bloom_size_KB = 14;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setTotalStaticIndexSizeKB(int value)

optional uint32 total_static_index_size_KB = 13;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.Builder.setWriteRequestsCount(long value)

optional uint64 write_requests_count = 9;

ClusterStatusProtos.RegionLoad.Builder
ClusterStatusProtos.RegionLoad.toBuilder()

Methods in org.apache.hadoop.hbase.protobuf.generated that return types with arguments of type ClusterStatusProtos.RegionLoad.Builder

Modifier and Type
Method and Description

List<ClusterStatusProtos.RegionLoad.Builder>
ClusterStatusProtos.ServerLoad.Builder.getRegionLoadsBuilderList()

repeated .RegionLoad region_loads = 5;

Methods in org.apache.hadoop.hbase.protobuf.generated with parameters of type ClusterStatusProtos.RegionLoad.Builder

Modifier and Type
Method and Description

ClusterStatusProtos.ServerLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.addRegionLoads(ClusterStatusProtos.RegionLoad.Builder builderForValue)

repeated .RegionLoad region_loads = 5;

ClusterStatusProtos.ServerLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.addRegionLoads(int index,
              ClusterStatusProtos.RegionLoad.Builder builderForValue)

repeated .RegionLoad region_loads = 5;

ClusterStatusProtos.ServerLoad.Builder
ClusterStatusProtos.ServerLoad.Builder.setRegionLoads(int index,
              ClusterStatusProtos.RegionLoad.Builder builderForValue)

repeated .RegionLoad region_loads = 5;

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 The Apache Software Foundation. All rights reserved.


text:
layout: post
title: "tfx"
date: 2021-03-22
excerpt: "tfx(tensorflow extended)ついて"
tags: ["gcp", "automl", "image"]
config: true
comments: false
sort_key: "2021-03-22"
update_dates: ["2021-03-22"]
---

# tfx(tensorflow extended)ついて
 - tensorflow用のパイプライン
 - kubeflow pipelinesのほうが整理されているように見える

## 各ステップの名前
 1. data analysis
 2. data trasnformation
 3. data validation
 4. trainer
 5. model evaluation
 6. serving


text:
/*
 * metadata_lookup.h
 *
 *      Author: zephyr
 *      Get the metadata by table name.
 *
 *      catalogTableExists() checks if the given table exists
 *      getAttributes() gets all the attribute names of the given table
 *      Don't worry about the connection establishment. It will automatically connect to oracle server
 *      if not created.
 *      But you should call databaseConnectionClose() at the end of the whole program.
 *      Note that it need only be called once because it frees the list of attributes and all resources allocated
 *      for OCI connection.
 */

#ifndef METADATA_LOOKUP_H_
#define METADATA_LOOKUP_H_

#include "model/list/list.h"
#include "model/node/nodetype.h"
#include "model/expression/expression.h"
#include "model/set/hashmap.h"
#include "model/set/set.h"
#include "model/relation/relation.h"
#include "model/query_block/query_block.h"
#include "mem_manager/mem_mgr.h"

/* types of supported plugins */
NEW_ENUM_WITH_TO_STRING(MetadataLookupPluginType,
    METADATA_LOOKUP_PLUGIN_ORACLE,
    METADATA_LOOKUP_PLUGIN_POSTGRES,
    METADATA_LOOKUP_PLUGIN_SQLITE,
    METADATA_LOOKUP_PLUGIN_MONETDB,
    METADATA_LOOKUP_PLUGIN_EXTERNAL
);

/* catalog cache */
typedef struct CatalogCache
{
    HashMap *tableAttrs;        // hashmap tablename -> attribute names
    HashMap *tableAttrDefs;     // hashmap tablename -> attribute definitions
    HashMap *viewAttrs;         // hashmap viewname -> attribute names
    HashMap *viewDefs;          // hashmap viewname -> view definition SQL query
    Set *tableNames;            // set of existing table names
    Set *viewNames;             // set of existing view names
    Set *aggFuncNames;          // names of aggregate functions
    Set *winFuncNames;          // names of window functions
    void *cacheHook;            // used to store
//    void (*cleanAddCache) (CatalogCache *cache); // function to clean up additional cache
} CatalogCache;

/* plugin definition */
typedef struct MetadataLookupPlugin
{
    MetadataLookupPluginType type;

    /* functional interface */

    /* init and shutdown plugin and connection */
    boolean (*isInitialized) (void);
    int (*initMetadataLookupPlugin) (void);
    int (*databaseConnectionOpen) (void);
    int (*databaseConnectionClose) (void);
    int (*shutdownMetadataLookupPlugin) (void);
    char * (*connectionDescription) (void);

    /* catalog lookup */
    boolean (*catalogTableExists) (char * tableName);
    boolean (*catalogViewExists) (char * viewName);
    boolean (*checkPostive) (char *tableName, char *colName);
    Constant * (*trasnferRawData) (char *data, char *dataType);
    HashMap * (*getMinAndMax) (char *tableName, char *colName);
//TODO	Constant *(*getMinAndMaxForDT) (DataType t);
    int (*getRowNum) (char *tableName);

    List * (*getAttributes) (char *tableName);
    List * (*getAttributeNames) (char *tableName);
    Node * (*getAttributeDefaultVal) (char *schema, char *tableName, char *attrName);

    boolean (*isAgg) (char *functionName);
    boolean (*isWindowFunction) (char *functionName);
    DataType (*getFuncReturnType) (char *fName, List *argTypes, boolean *funcExists);
    DataType (*getOpReturnType) (char *oName, List *argTypes, boolean *funcExists);
    DataType (*sqlTypeToDT) (char *sqlType);
    char * (*dataTypeToSQL) (DataType dt);

    char * (*getTableDefinition) (char *tableName);
    char * (*getViewDefinition) (char *viewName);
    List * (*getKeyInformation) (char *tableName);
    /* audit log access */
    void (*getTransactionSQLAndSCNs) (char *xid, List **scns, List **sqls,
            List **sqlBinds, IsolationLevel *iso, Constant *commitScn);
    gprom_long_t (*getCommitScn) (char *tableName, gprom_long_t maxScn, char *xid);

    /* execution */
    Node * (*executeAsTransactionAndGetXID) (List *statements, IsolationLevel isoLevel);
    Relation * (*executeQuery) (char *query);       // returns a list of stringlist (tuples)
    void (*executeQueryIgnoreResult) (char *query);
    int (*getCostEstimation)(char *query);

    /* cache for catalog information */
    CatalogCache *cache;
    MemContext *metadataLookupContext;

} MetadataLookupPlugin;

#define INVALID_SCN -1

/* store active plugin */
extern MetadataLookupPlugin *activePlugin;
extern List *availablePlugins;

/* plugin handling methods */
extern int initMetadataLookupPlugins (void);
extern int shutdownMetadataLookupPlugins (void);
extern void chooseMetadataLookupPluginFromString (char *plug);
extern void chooseMetadataLookupPlugin (MetadataLookupPluginType plugin);
extern void setMetadataLookupPlugin (MetadataLookupPlugin *p);

/* generic methods */
extern int initMetadataLookupPlugin (void);
extern int shutdownMetadataLookupPlugin (void);
extern int databaseConnectionOpen (void);
extern int databaseConnectionClose(void);
extern boolean isInitialized (void);
extern char *getConnectionDescription (void);

extern boolean catalogTableExists (char * tableName);
extern boolean catalogViewExists (char * viewName);
extern List *getAttributes (char *tableName);
extern List *getAttributeNames (char *tableName);
extern Node *getAttributeDefaultVal (char *schema, char *tableName, char *attrName);
extern List *getAttributeDataTypes (char *tableName);
extern boolean isAgg(char *functionName);
extern boolean isWindowFunction(char *functionName);
extern DataType getFuncReturnType (char *fName, List *argTypes, boolean *funcExists);
extern DataType getOpReturnType (char *oName, List *argTypes, boolean *opExists);
extern DataType backendSQLTypeToDT (char *sqlType);
extern char * backendDatatypeToSQL (DataType dt);
extern char *getTableDefinition(char *tableName);
extern char *getViewDefinition(char *viewName);
extern List *getKeyInformation (char *tableName);

extern void getTransactionSQLAndSCNs (char *xid, List **scns, List **sqls,
        List **sqlBinds, IsolationLevel *iso, Constant *commitScn);
extern Relation *executeQuery (char *sql);
extern void executeQueryIgnoreResult (char *sql);
extern gprom_long_t getCommitScn (char *tableName, gprom_long_t maxScn, char *xid);
extern Node *executeAsTransactionAndGetXID (List *statements, IsolationLevel isoLevel);
extern int getCostEstimation(char *query);

/* helper functions for createing the cache */
extern CatalogCache *createCache(void);

//extern boolean isPostive(char *tableName, char *colName);
extern Constant *transferRawData(char *data, char *dataType);
extern HashMap *getMinAndMax(char *tableName, char *colName);
extern int getRowNum(char* tableName);

#endif /* METADATA_LOOKUP_H_ */


text:
html{
    height: 100%;
}
body {
    height: 100%;
    /* Move down content, because of the 50px fixed navbar height */
    padding-top: 50px;
    font-family: 'Roboto Condensed', sans-serif;
    font-size:15px;
}
a {
    color: #7d65a3;
}
a:active, a:hover {
    color: #645082;
}
.btn-primary {
    background-color: #7d65a3;
    border-color: #705a92;
}
.btn-primary:hover,
.btn-primary:active,
.btn-primary:focus,
.btn-primary:active:focus {
    background-color: #705a92;
    border-color: #645082;
}
.wrap {
    min-height: 100%;
    height: auto;
    margin: 0 auto -60px;
    padding: 0 0 60px;
}

.footer {
    height: 60px;
    background-color: #f5f5f5;
    border-top: 1px solid #ddd;
    padding-top: 20px;
}

/* -- Top navigation --------------------------- */
/* Hide default border to remove 1px line */
.navbar-fixed-top {
    border: 0;
}
/* -- Custom inverse navbar -------------------- */
.navbar-inverse {
    background-color: #7d65a3;
    border-color: #705a92;
}
.navbar-inverse .navbar-brand {
    color: #eef7ff;
}
.navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus {
    color: #ffffff;
}
.navbar-inverse .navbar-text {
    color: #eef7ff;
}
.navbar-inverse .navbar-nav > li > a {
    color: #eef7ff;
}
.navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus {
    color: #ffffff;
}
.navbar-inverse .navbar-nav > li > .dropdown-menu {
    background-color: #7d65a3;
}
.navbar-inverse .navbar-nav > li > .dropdown-menu > li > a {
    color: #eef7ff !important;
}
.navbar-inverse .navbar-nav > li > .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav > li > .dropdown-menu > li > a:focus {
    color: #ffffff;
    background-color: #705a92;
}
.navbar-inverse .navbar-nav > li > .dropdown-menu > li > .divider {
    background-color: #7d65a3;
}
.navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus {
    color: #ffffff;
    background-color: #705a92;
}
.navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus {
    color: #ffffff;
    background-color: #705a92;
}
.navbar-inverse .navbar-toggle {
    border-color: #705a92;
}
.navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus {
    background-color: #705a92;
}
.navbar-inverse .navbar-toggle .icon-bar {
    background-color: #eef7ff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
    border-color: #7d65a3;
}
.navbar-inverse .navbar-link {
    color: #eef7ff;
}
.navbar-inverse .navbar-link:hover {
    color: #ffffff;
}
.navbar-inverse .profile {
    text-align: center;
    margin-top: 6px;
    color: #FFFFFF;
}
.navbar-inverse .profile .role {
    font-size: 16px;
}
.navbar-inverse .profile .name {
    font-size: 16px;
}
.navbar-inverse .profile .email {
    color: #D1CBDB;
    padding-left:6px;
    padding-right:6px;
}
.navbar-inverse .glyphicon {
    margin-right: 10px;
    vertical-align: middle;
    top: -1px !important;
}
.navbar-inverse .dropdown-menu{
    border: 1px solid #645082;
    border-top: 1px solid #7d65a3;
    min-width: 180px;
}
.navbar-inverse .divider {
    background-color: #9783b5 !important;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
    color: #ffffff;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
    color: #ffffff;
    background-color: #705a92;
}
/* A litle more space for the navbar from browser border */
@media (min-width: 768px) {
    .navbar-right {
        margin-right: 15px;
    }
}
/* -------------------- Custom inverse navbar -- */

.nav .badge {
    font-family: Arial, sans-serif;
    font-size: 11px;
    margin-left: 4px;
    background-color: #F06222;
}
/* --------------------------- Top navigation -- */

/* -- Sidebar container ------------------------ */
/* Hide for mobile, show for bigger screens */
.sidebar {
    display: none;
}
@media (min-width: 768px) {
    .sidebar {
        position: fixed;
        top: 50px;
        bottom: 0;
        left: 0;
        z-index: 1000;
        display: block;
        padding: 20px 16px;
        overflow-x: hidden;
        overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
        background-color: #f5f5f5;
        border-right: 1px solid #DDD;
    }
}
/* ------------------------ Sidebar container -- */

/* -- Main container --------------------------- */
.main {
    padding: 15px;
}
@media (min-width: 768px) {
    .main {
        padding: 20px 30px;
    }
}
/* --------------------------- Main container -- */

/* -- Gridview (sorting icons, links etc) ------ */
a.asc:after, a.desc:after {
    position: relative;
    top: 1px;
    display: inline-block;
    font-family: 'Glyphicons Halflings';
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    padding-left: 5px;
}
a.asc:after {
    content: /*"\e113"*/ "\e151";
}
a.desc:after {
    content: /*"\e114"*/ "\e152";
}
.sort-numerical a.asc:after {
    content: "\e153";
}
.sort-numerical a.desc:after {
    content: "\e154";
}
.sort-ordinal a.asc:after {
    content: "\e155";
}
.sort-ordinal a.desc:after {
    content: "\e156";
}

.grid-view td {
    white-space: nowrap;
}
.grid-view .filters input,
.grid-view .filters select {
    min-width: 50px;
}
.grid-view .column_buttons {
    width:70px;
}
.hint-block {
    display: block;
    margin-top: 5px;
    color: #999;
}
.error-summary {
    color: #a94442;
    background: #fdf7f7;
    border-left: 3px solid #eed3d7;
    padding: 10px 20px;
    margin: 0 0 15px 0;
}
.grid-view .column_id {
    width: 60px;
    text-align: center;
}
.grid-view .column_buttons {
    width:70px;
}
.grid-view .filters td {
    padding:2px;
}
.grid-view .filters td input, .grid-view .filters td select{
    padding:6px;
}
.grid-view .pagination {
    margin: 0;
}
/* --------- Gridview (sorting icons, links etc) -- */

.allpages_title {
    margin: 0 0 8px 0;
}
.allpages_buttons {
    margin: 4px 0 8px 0;
}
.radio_list label {
    margin-right: 16px;
    cursor: pointer;
}

/* -- Panels ----------------------------------- */
.panel_dashboard_header {
    font-size: 24px;
}
.panel-body {
    min-height: 120px;
}
.panel_dashboard_icon {
    font-size: 40px;
    float: left;
    margin-right: 14px;
    color: #CCCCCC;
}
@media (max-width:767px) {
    .panel-body {
        min-height: inherit;
    }
}
@media (min-width:1200px) {
    .panel-body {
        min-height: inherit;
    }
}
@media (min-width:992px){
    .panel_dashboard_icon {
        font-size: 60px;
    }
}
/* ----------------------------------- Panels -- */

/*
@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
*/


text:
package mx.bigdata.sat.cfdi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
import mx.bigdata.sat.cfdi.v32.schema.ObjectFactory;
import mx.bigdata.sat.cfdi.v32.schema.Comprobante;
import mx.bigdata.sat.common.ComprobanteBase;
import mx.bigdata.sat.common.NamespacePrefixMapperImpl;
import mx.bigdata.sat.common.SatCharacterEscapeHandler;
import mx.bigdata.sat.common.URIResolverImpl;

import mx.bigdata.sat.security.KeyLoaderEnumeration;
import mx.bigdata.sat.security.factory.KeyLoaderFactory;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.ErrorHandler;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public final class CFDv32 implements CFDI {

  private static final String XSLT = "/xslt/cadenaoriginal_3_2.xslt";

  private static final String[] XSD = new String[] {
      "/xsd/v32/cfdv32.xsd",
      "/xsd/v3/TimbreFiscalDigital.xsd",
      "/xsd/common/TuristaPasajeroExtranjero/TuristaPasajeroExtranjero.xsd",
      "/xsd/common/detallista/detallista.xsd",
      "/xsd/common/divisas/divisas.xsd",
      "/xsd/common/donat/donat11.xsd",
      "/xsd/common/ecb/ecb.xsd",
      "/xsd/common/ecc/ecc.xsd",
      "/xsd/common/iedu/iedu.xsd",
      "/xsd/common/implocal/implocal.xsd",
      "/xsd/common/leyendasFisc/leyendasFisc.xsd",
      "/xsd/common/pfic/pfic.xsd",
      "/xsd/common/psgcfdsp/psgcfdsp.xsd",
      "/xsd/common/psgecfd/psgecfd.xsd",
      "/xsd/common/terceros/terceros11.xsd",
      "/xsd/common/ventavehiculos/ventavehiculos.xsd",
      "/xsd/common/nomina/nomina11.xsd",
      "/xsd/common/nomina12/nomina12.xsd"
  };

  private static final String XML_HEADER =
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

  private static final String BASE_CONTEXT = "mx.bigdata.sat.cfdi.v32.schema";

  private final static Joiner JOINER = Joiner.on(':');

  private final JAXBContext context;

  public static final ImmutableMap<String, String> PREFIXES =
    ImmutableMap.of("http://www.w3.org/2001/XMLSchema-instance","xsi",
                    "http://www.sat.gob.mx/cfd/3", "cfdi",
                    "http://www.sat.gob.mx/TimbreFiscalDigital", "tfd");

  private final Map<String, String> localPrefixes = Maps.newHashMap(PREFIXES);

  private TransformerFactory tf;

  final Comprobante document;

  public CFDv32(InputStream in, String... contexts) throws Exception {
    this.context = getContext(contexts);
    this.document = load(in);
  }

  public CFDv32(Comprobante comprobante, String... contexts) throws Exception {
    this.context = getContext(contexts);
    this.document = copy(comprobante);
  }

  public void addNamespace(String uri, String prefix) {
    localPrefixes.put(uri, prefix);
  }

  public void setTransformerFactory(TransformerFactory tf) {
    this.tf = tf;
    tf.setURIResolver(new URIResolverImpl());
  }

  public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    cert.checkValidity();
    String signature = getSignature(key);
    document.setSello(signature);
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    BigInteger bi = cert.getSerialNumber();
    document.setNoCertificado(new String(bi.toByteArray()));
  }

  public Comprobante sellarComprobante(PrivateKey key, X509Certificate cert)
    throws Exception {
    sellar(key, cert);
    return doGetComprobante();
  }

  public void validar() throws Exception {
    validar(null);
  }

  public void validar(ErrorHandler handler) throws Exception {
    SchemaFactory sf =
      SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Source[] schemas = new Source[XSD.length];
    for (int i = 0; i < XSD.length; i++) {
      schemas[i] = new StreamSource(getClass().getResourceAsStream(XSD[i]));
    }
    Schema schema = sf.newSchema(schemas);
    Validator validator = schema.newValidator();
    if (handler != null) {
      validator.setErrorHandler(handler);
    }
    validator.validate(new JAXBSource(context, document));
  }

  public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();

    //String cadenaOriginal = new String(bytes, "UTF8");
    //System.out.println("Cadena Original: " + cadenaOriginal);

    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
      throw new Exception("Invalid signature");
    }
  }

  public void guardar(OutputStream out) throws Exception {
    Marshaller m = context.createMarshaller();
    m.setProperty(CharacterEscapeHandler.class.getName(),  new SatCharacterEscapeHandler());
    m.setProperty(Marshaller.JAXB_ENCODING, "ASCII");
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                  new NamespacePrefixMapperImpl(localPrefixes));
    m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                  "http://www.sat.gob.mx/cfd/3  "
                  + "http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd");
    byte[] xmlHeaderBytes = XML_HEADER.getBytes("UTF8");
    out.write(xmlHeaderBytes);
    m.marshal(document, out);
  }

  public String getCadenaOriginal() throws Exception {
    byte[] bytes = getOriginalBytes();
    return new String(bytes, "UTF8");
  }

  public static Comprobante newComprobante(InputStream in) throws Exception {
    return load(in);
  }

  byte[] getOriginalBytes() throws Exception {
    JAXBSource in = new JAXBSource(context, document);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
      factory = TransformerFactory.newInstance();
      factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory
      .newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(in, out);
    return baos.toByteArray();
  }

  String getSignature(PrivateKey key) throws Exception {
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    sig.update(bytes);
    byte[] signed = sig.sign();
    Base64 b64 = new Base64(-1);
    return b64.encodeToString(signed);
  }

  public ComprobanteBase getComprobante() throws Exception {
    return new CFDv32ComprobanteBase(doGetComprobante());
  }

  Comprobante doGetComprobante() throws Exception {
    return copy(document);
  }

  // Defensive deep-copy
  private Comprobante copy(Comprobante comprobante) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = context.createMarshaller();
    m.marshal(comprobante, doc);
    Unmarshaller u = context.createUnmarshaller();
    return (Comprobante) u.unmarshal(doc);
  }

  public static final class CFDv32ComprobanteBase implements ComprobanteBase {

    private final Comprobante document;

    public CFDv32ComprobanteBase(Comprobante document) {
      this.document = document;
    }

    public boolean hasComplemento() {
      return document.getComplemento() != null;
    }

    public List<Object> getComplementoGetAny() {
      return document.getComplemento().getAny();
    }

    public String getSello() {
      return document.getSello();
    }

    public void setComplemento(Element element) {
      ObjectFactory of = new ObjectFactory();
      Comprobante.Complemento comp = of.createComprobanteComplemento();
      List<Object> list = comp.getAny();
      list.add(element);
      document.setComplemento(comp);
    }

    public Object getComprobante() {
      return document;
    }
  }

  private static JAXBContext getContext(String[] contexts) throws Exception {
    List<String> ctx = Lists.asList(BASE_CONTEXT, contexts);
    return JAXBContext.newInstance(JOINER.join(ctx));
  }

  private static Comprobante load(InputStream source, String... contexts)
    throws Exception {
    JAXBContext context = getContext(contexts);
    try {
      Unmarshaller u = context.createUnmarshaller();
      return (Comprobante) u.unmarshal(source);
    } finally {
      source.close();
    }
  }

  static void dump(String title, byte[] bytes, PrintStream out) {
    out.printf("%s: ", title);
    for (byte b : bytes) {
      out.printf("%02x ", b & 0xff);
    }
    out.println();
  }
}


text:
#ifndef CORE_DATA_RENDER_VNODE_VNODE_ON_EVENT_LISTENER_H_
#define CORE_DATA_RENDER_VNODE_VNODE_ON_EVENT_LISTENER_H_

#include "core/data_render/vnode/vnode.h"

namespace weex {
namespace core {
namespace data_render {

class VNodeOnEventListener : public VNode::OnEventListener {
  void OnEvent(VNode *node, const std::string &event,
               const std::string &json_args, const std::string dom_changes,
               const VNode::Params &params);
};

}  // namespace data_render
}  // namespace core
}  // namespace weex

#endif  // CORE_DATA_RENDER_VNODE_VNODE_ON_EVENT_LISTENER_H_