text:
import urllib2
import sys
import json
import argparse
import os
import getpass

url = 'http://192.168.220.28/api_jsonrpc.php'
all_value = []

#get username and passwd for cli
def get_user_passwd():
    file_path = os.path.join(os.path.dirname(__file__),'secrets.txt')
    if os.path.exists(file_path):
        f = open(file_path,'r')
        try:
            x = json.load(f)
        except:
            print "continue"
            sys.exit(1)
        finally:
            f.close()
        return x
    else:
        username = raw_input('please input your username:')
        password = getpass.getpass(prompt='please input your password:')
        x = {"username":username,"password":password}
        f = open(file_path,'w')
        try:
            json.dump(x,f)
        except:
            print "user/password error,secrets.txt"
            sys.exit(1)
        finally:
            f.close()
        return x

#get zabbix auth_id
def authenticate(url, username, password):
    values = {'jsonrpc': '2.0',
              'method': 'user.login',
              'params': {
                  'user': username,
                  'password': password
              },
              'id': '0'
              }
    idvalue = requestJason(url,values)
    return idvalue['result']

#get response  for request zabbix_api
def requestJason(url,values):

    data = json.dumps(values)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
    response = urllib2.urlopen(req, data)
    data_get = response.read()
    output = json.loads(data_get)
    try:
        message = output['result']
    except:
        message = output['error']
        print message
        quit()
    return output

#get hostid
def getHosts(url,auth):
    host_id_list = []
    hostname = []
    for i in all_value:
        hostname.append(i['hostname'])
    values = {'jsonrpc': '2.0',
       'method': 'host.get',
       'params': {
           'output': ["hostid","host"],
           'filter': {
               'host': hostname
                 }
           },
          'auth': auth,
              'id': '2'
          }
    output = requestJason(url,values)

    if output.has_key('result') and len(output['result']) == len(hostname) :
        for k in output['result']:
            host_id_list.append(k['hostid'])
            for i in range(0,len(all_value)):
                if all_value[i]['hostname'] == k['host']:
                    all_value[i]['hostid'] = k['hostid']
        return host_id_list
    else:
        print "not fount host,please check"
        sys.exit(1)

#get graphs property
def getGraphs(url, auth, hostid,columns graphtype=0 ,dynamic=0):
    for i in range(0,len(all_value)):
        values = ({'jsonrpc': '2.0',
            "method": "graph.get",
            "params": {
                "selectGraphs": [['graphid'],"name"],
                "output": ["graphid","name"],
                "hostids": all_value[i]["hostid"],
                "filter":{'name': all_value[i]['graphname']},
                "sortfield":"name",
                },
            "auth": auth,
            "id": '3'
            })
        output = requestJason(url,values)
        if len(output['result']) == 0 :
            print "%s not fount %s"%(all_value[i]["hostname"],all_value[i]['graphname'])
            sys.exit(1)
        else:
            all_value[i]['graphid'] = output['result'][0]['graphid']

    graphs = []
    for i in all_value:
        graphs.append(i['graphid'])

    screenid = None
    if is_append:
        old_screenitemids_list = []
        # add graph to screen
        values = ({
            "jsonrpc": "2.0",
            "method": "screen.get",
            "params": {
                "search": {
                    "name": screenname
                },
                "output": "screenid"
            },
            "auth": auth,
            "id": 2
        })
        screenid = requestJason(url, values)["result"][0]["screenid"]

        values = ({
            "jsonrpc": "2.0",
            "method": "screenitem.get",
            "params": {
                "screenids": screenid,
                "output": "extend"
            },
            "auth": auth,
            "id": 2
        })
        for resource in requestJason(url, values)["result"]:
            old_screenitemids_list.append(resource["resourceid"])
        graphs.extend(old_screenitemids_list)
    graph_list = []

    x = 0
    y = 0

    for graph in graphs:
        graph_list.append({
            "resourcetype": graphtype,
            "resourceid": graph,
            "width": "500",
            "height": "100",
            "x": str(x),
            "y": str(y),
            "colspan": "1",
            "rowspan": "1",
            "elements": "0",
            "valign": "0",
            "halign": "0",
            "style": "0",
            "url": "",
            "dynamic": str(dynamic)
        })
        x += 1
        if x == int(columns):
            x = 0
            y += 1

    return (graph_list, screenid)

#create screen
def screenCreate(url, auth, graphids, screen_id):
    hsize = columns
    vsize = len(graphids) / columns + 1

    screen_name = screenname
    # update screen
    if is_append:
        screen_method = "screen.update"
        values = ({"jsonrpc": "2.0",
                  "method": screen_method,
                  "params": {
                      "screenid": screen_id,
                      "hsize": hsize,
                      "vsize": vsize,
                      "screenitems": graphids
                  },
                  "auth": auth,
                  "id": 2
                  })
    else:
        screen_method = "screen.create"
        values = ({"jsonrpc": "2.0",
                  "method": screen_method,
                  "params": {
                      "name": screen_name,
                      "hsize": hsize,
                      "vsize": vsize,
                      "screenitems": graphids
                  },
                  "auth": auth,
                  "id": 2
                  })

    output = requestJason(url,values)
    return output

def operation(all_value,auth,columns):
    user_passwd =  get_user_passwd()
    username = user_passwd['username']
    password = user_passwd['password']
    auth = authenticate(url,auth, username, password)
    hostid = getHosts(url,auth)
    (graph_ids, screen_id) = getGraphs(url, auth, hostid,columns)
    output = screenCreate(url, auth, graph_ids, screen_id)
    print output

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')

    parser.add_argument('-G', dest='graphlist', nargs='+',metavar=('grah name'),
                        help='Graph list:  host1.graph1 host2.graph2 ... ...')
    parser.add_argument('-n', dest='screenname', type=str,
                        help='Screen name in Zabbix.  Put quotes around it if you want spaces in the name.')
    parser.add_argument('-c', dest='columns', type=int,
                        help='number of columns in the screen')
    parser.add_argument('-a', dest='is_append', action="store_true", default=False,
                        help='is append')

    args = parser.parse_args()

    graphlist = args.graphlist
    screenname = args.screenname
    columns = args.columns
    is_append = args.is_append
    for i in args.graphlist:
        tmp = {"hostname":i.split(":")[0],"graphname":i.split(":")[1]}
        all_value.append(tmp)
    if columns is None:
        columns = len(all_value)

    operation(all_value,auth,columns)


text:
package action

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"

	"helm.sh/helm/v3/internal/test"
	"helm.sh/helm/v3/pkg/chart"
	"helm.sh/helm/v3/pkg/chartutil"
	kubefake "helm.sh/helm/v3/pkg/kube/fake"
	"helm.sh/helm/v3/pkg/release"
	"helm.sh/helm/v3/pkg/storage/driver"
	"helm.sh/helm/v3/pkg/time"
)

type nameTemplateTestCase struct {
	tpl              string
	expected         string
	expectedErrorStr string
}

func installAction(t *testing.T) *Install {
	config := actionConfigFixture(t)
	instAction := NewInstall(config)
	instAction.Namespace = "spaced"
	instAction.ReleaseName = "test-install-release"

	return instAction
}

func TestInstallRelease(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}
	is.Equal(res.Name, "test-install-release", "Expected release name.")
	is.Equal(res.Namespace, "spaced")

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.NoError(err)

	is.Len(rel.Hooks, 1)
	is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
	is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
	is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")

	is.NotEqual(len(res.Manifest), 0)
	is.NotEqual(len(rel.Manifest), 0)
	is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
	is.Equal(rel.Info.Description, "Install complete")
}

func TestInstallReleaseWithValues(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	userVals := map[string]interface{}{
		"nestedKey": map[string]interface{}{
			"simpleKey": "simpleValue",
		},
	}
	expectedUserValues := map[string]interface{}{
		"nestedKey": map[string]interface{}{
			"simpleKey": "simpleValue",
		},
	}
	res, err := instAction.Run(buildChart(withSampleValues()), userVals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}
	is.Equal(res.Name, "test-install-release", "Expected release name.")
	is.Equal(res.Namespace, "spaced")

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.NoError(err)

	is.Len(rel.Hooks, 1)
	is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
	is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
	is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")

	is.NotEqual(len(res.Manifest), 0)
	is.NotEqual(len(rel.Manifest), 0)
	is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
	is.Equal("Install complete", rel.Info.Description)
	is.Equal(expectedUserValues, rel.Config)
}

func TestInstallReleaseClientOnly(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ClientOnly = true
	instAction.Run(buildChart(), nil) // disregard output

	is.Equal(instAction.cfg.Capabilities, chartutil.DefaultCapabilities)
	is.Equal(instAction.cfg.KubeClient, &kubefake.PrintingKubeClient{Out: ioutil.Discard})
}

func TestInstallRelease_NoName(t *testing.T) {
	instAction := installAction(t)
	instAction.ReleaseName = ""
	vals := map[string]interface{}{}
	_, err := instAction.Run(buildChart(), vals)
	if err == nil {
		t.Fatal("expected failure when no name is specified")
	}
	assert.Contains(t, err.Error(), "name is required")
}

func TestInstallRelease_WithNotes(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "with-notes"
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(withNotes("note here")), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	is.Equal(res.Name, "with-notes")
	is.Equal(res.Namespace, "spaced")

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.NoError(err)
	is.Len(rel.Hooks, 1)
	is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
	is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
	is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")
	is.NotEqual(len(res.Manifest), 0)
	is.NotEqual(len(rel.Manifest), 0)
	is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
	is.Equal(rel.Info.Description, "Install complete")

	is.Equal(rel.Info.Notes, "note here")
}

func TestInstallRelease_WithNotesRendered(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "with-notes"
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(withNotes("got-{{.Release.Name}}")), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.NoError(err)

	expectedNotes := fmt.Sprintf("got-%s", res.Name)
	is.Equal(expectedNotes, rel.Info.Notes)
	is.Equal(rel.Info.Description, "Install complete")
}

func TestInstallRelease_WithChartAndDependencyParentNotes(t *testing.T) {
	// Regression: Make sure that the child's notes don't override the parent's
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "with-notes"
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(withNotes("parent"), withDependency(withNotes("child"))), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.Equal("with-notes", rel.Name)
	is.NoError(err)
	is.Equal("parent", rel.Info.Notes)
	is.Equal(rel.Info.Description, "Install complete")
}

func TestInstallRelease_WithChartAndDependencyAllNotes(t *testing.T) {
	// Regression: Make sure that the child's notes don't override the parent's
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "with-notes"
	instAction.SubNotes = true
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(withNotes("parent"), withDependency(withNotes("child"))), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	rel, err := instAction.cfg.Releases.Get(res.Name, res.Version)
	is.Equal("with-notes", rel.Name)
	is.NoError(err)
	// test run can return as either 'parent\nchild' or 'child\nparent'
	if !strings.Contains(rel.Info.Notes, "parent") && !strings.Contains(rel.Info.Notes, "child") {
		t.Fatalf("Expected 'parent\nchild' or 'child\nparent', got '%s'", rel.Info.Notes)
	}
	is.Equal(rel.Info.Description, "Install complete")
}

func TestInstallRelease_DryRun(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.DryRun = true
	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(withSampleTemplates()), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	is.Contains(res.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
	is.Contains(res.Manifest, "---\n# Source: hello/templates/goodbye\ngoodbye: world")
	is.Contains(res.Manifest, "hello: Earth")
	is.NotContains(res.Manifest, "hello: {{ template \"_planet\" . }}")
	is.NotContains(res.Manifest, "empty")

	_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
	is.Error(err)
	is.Len(res.Hooks, 1)
	is.True(res.Hooks[0].LastRun.CompletedAt.IsZero(), "expect hook to not be marked as run")
	is.Equal(res.Info.Description, "Dry run complete")
}

// Regression test for #7955: Lookup must not connect to Kubernetes on a dry-run.
func TestInstallRelease_DryRun_Lookup(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.DryRun = true
	vals := map[string]interface{}{}

	mockChart := buildChart(withSampleTemplates())
	mockChart.Templates = append(mockChart.Templates, &chart.File{
		Name: "templates/lookup",
		Data: []byte(`goodbye: {{ lookup "v1" "Namespace" "" "___" }}`),
	})

	res, err := instAction.Run(mockChart, vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	is.Contains(res.Manifest, "goodbye: map[]")
}

func TestInstallReleaseIncorrectTemplate_DryRun(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.DryRun = true
	vals := map[string]interface{}{}
	_, err := instAction.Run(buildChart(withSampleIncludingIncorrectTemplates()), vals)
	expectedErr := "\"hello/templates/incorrect\" at <.Values.bad.doh>: nil pointer evaluating interface {}.doh"
	if err == nil {
		t.Fatalf("Install should fail containing error: %s", expectedErr)
	}
	if err != nil {
		is.Contains(err.Error(), expectedErr)
	}
}

func TestInstallRelease_NoHooks(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.DisableHooks = true
	instAction.ReleaseName = "no-hooks"
	instAction.cfg.Releases.Create(releaseStub())

	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	is.True(res.Hooks[0].LastRun.CompletedAt.IsZero(), "hooks should not run with no-hooks")
}

func TestInstallRelease_FailedHooks(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "failed-hooks"
	failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
	failer.WatchUntilReadyError = fmt.Errorf("Failed watch")
	instAction.cfg.KubeClient = failer

	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(), vals)
	is.Error(err)
	is.Contains(res.Info.Description, "failed post-install")
	is.Equal(release.StatusFailed, res.Info.Status)
}

func TestInstallRelease_ReplaceRelease(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.Replace = true

	rel := releaseStub()
	rel.Info.Status = release.StatusUninstalled
	instAction.cfg.Releases.Create(rel)
	instAction.ReleaseName = rel.Name

	vals := map[string]interface{}{}
	res, err := instAction.Run(buildChart(), vals)
	is.NoError(err)

	// This should have been auto-incremented
	is.Equal(2, res.Version)
	is.Equal(res.Name, rel.Name)

	getres, err := instAction.cfg.Releases.Get(rel.Name, res.Version)
	is.NoError(err)
	is.Equal(getres.Info.Status, release.StatusDeployed)
}

func TestInstallRelease_KubeVersion(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	vals := map[string]interface{}{}
	_, err := instAction.Run(buildChart(withKube(">=0.0.0")), vals)
	is.NoError(err)

	// This should fail for a few hundred years
	instAction.ReleaseName = "should-fail"
	vals = map[string]interface{}{}
	_, err = instAction.Run(buildChart(withKube(">=99.0.0")), vals)
	is.Error(err)
	is.Contains(err.Error(), "chart requires kubeVersion")
}

func TestInstallRelease_Wait(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "come-fail-away"
	failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
	failer.WaitError = fmt.Errorf("I timed out")
	instAction.cfg.KubeClient = failer
	instAction.Wait = true
	vals := map[string]interface{}{}

	res, err := instAction.Run(buildChart(), vals)
	is.Error(err)
	is.Contains(res.Info.Description, "I timed out")
	is.Equal(res.Info.Status, release.StatusFailed)
}

func TestInstallRelease_WaitForJobs(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	instAction.ReleaseName = "come-fail-away"
	failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
	failer.WaitError = fmt.Errorf("I timed out")
	instAction.cfg.KubeClient = failer
	instAction.Wait = true
	instAction.WaitForJobs = true
	vals := map[string]interface{}{}

	res, err := instAction.Run(buildChart(), vals)
	is.Error(err)
	is.Contains(res.Info.Description, "I timed out")
	is.Equal(res.Info.Status, release.StatusFailed)
}

func TestInstallRelease_Atomic(t *testing.T) {
	is := assert.New(t)

	t.Run("atomic uninstall succeeds", func(t *testing.T) {
		instAction := installAction(t)
		instAction.ReleaseName = "come-fail-away"
		failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
		failer.WaitError = fmt.Errorf("I timed out")
		instAction.cfg.KubeClient = failer
		instAction.Atomic = true
		vals := map[string]interface{}{}

		res, err := instAction.Run(buildChart(), vals)
		is.Error(err)
		is.Contains(err.Error(), "I timed out")
		is.Contains(err.Error(), "atomic")

		// Now make sure it isn't in storage any more
		_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
		is.Error(err)
		is.Equal(err, driver.ErrReleaseNotFound)
	})

	t.Run("atomic uninstall fails", func(t *testing.T) {
		instAction := installAction(t)
		instAction.ReleaseName = "come-fail-away-with-me"
		failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
		failer.WaitError = fmt.Errorf("I timed out")
		failer.DeleteError = fmt.Errorf("uninstall fail")
		instAction.cfg.KubeClient = failer
		instAction.Atomic = true
		vals := map[string]interface{}{}

		_, err := instAction.Run(buildChart(), vals)
		is.Error(err)
		is.Contains(err.Error(), "I timed out")
		is.Contains(err.Error(), "uninstall fail")
		is.Contains(err.Error(), "an error occurred while uninstalling the release")
	})
}

func TestNameTemplate(t *testing.T) {
	testCases := []nameTemplateTestCase{
		// Just a straight up nop please
		{
			tpl:              "foobar",
			expected:         "foobar",
			expectedErrorStr: "",
		},
		// Random numbers at the end for fun & profit
		{
			tpl:              "foobar-{{randNumeric 6}}",
			expected:         "foobar-[0-9]{6}$",
			expectedErrorStr: "",
		},
		// Random numbers in the middle for fun & profit
		{
			tpl:              "foobar-{{randNumeric 4}}-baz",
			expected:         "foobar-[0-9]{4}-baz$",
			expectedErrorStr: "",
		},
		// No such function
		{
			tpl:              "foobar-{{randInteger}}",
			expected:         "",
			expectedErrorStr: "function \"randInteger\" not defined",
		},
		// Invalid template
		{
			tpl:              "foobar-{{",
			expected:         "",
			expectedErrorStr: "unexpected unclosed action",
		},
	}

	for _, tc := range testCases {

		n, err := TemplateName(tc.tpl)
		if err != nil {
			if tc.expectedErrorStr == "" {
				t.Errorf("Was not expecting error, but got: %v", err)
				continue
			}
			re, compErr := regexp.Compile(tc.expectedErrorStr)
			if compErr != nil {
				t.Errorf("Expected error string failed to compile: %v", compErr)
				continue
			}
			if !re.MatchString(err.Error()) {
				t.Errorf("Error didn't match for %s expected %s but got %v", tc.tpl, tc.expectedErrorStr, err)
				continue
			}
		}
		if err == nil && tc.expectedErrorStr != "" {
			t.Errorf("Was expecting error %s but didn't get an error back", tc.expectedErrorStr)
		}

		if tc.expected != "" {
			re, err := regexp.Compile(tc.expected)
			if err != nil {
				t.Errorf("Expected string failed to compile: %v", err)
				continue
			}
			if !re.MatchString(n) {
				t.Errorf("Returned name didn't match for %s expected %s but got %s", tc.tpl, tc.expected, n)
			}
		}
	}
}

func TestInstallReleaseOutputDir(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	vals := map[string]interface{}{}

	dir, err := ioutil.TempDir("", "output-dir")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	instAction.OutputDir = dir

	_, err = instAction.Run(buildChart(withSampleTemplates(), withMultipleManifestTemplate()), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	_, err = os.Stat(filepath.Join(dir, "hello/templates/goodbye"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(dir, "hello/templates/hello"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(dir, "hello/templates/with-partials"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(dir, "hello/templates/rbac"))
	is.NoError(err)

	test.AssertGoldenFile(t, filepath.Join(dir, "hello/templates/rbac"), "rbac.txt")

	_, err = os.Stat(filepath.Join(dir, "hello/templates/empty"))
	is.True(os.IsNotExist(err))
}

func TestInstallOutputDirWithReleaseName(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	vals := map[string]interface{}{}

	dir, err := ioutil.TempDir("", "output-dir")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	instAction.OutputDir = dir
	instAction.UseReleaseName = true
	instAction.ReleaseName = "madra"

	newDir := filepath.Join(dir, instAction.ReleaseName)

	_, err = instAction.Run(buildChart(withSampleTemplates(), withMultipleManifestTemplate()), vals)
	if err != nil {
		t.Fatalf("Failed install: %s", err)
	}

	_, err = os.Stat(filepath.Join(newDir, "hello/templates/goodbye"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(newDir, "hello/templates/hello"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(newDir, "hello/templates/with-partials"))
	is.NoError(err)

	_, err = os.Stat(filepath.Join(newDir, "hello/templates/rbac"))
	is.NoError(err)

	test.AssertGoldenFile(t, filepath.Join(newDir, "hello/templates/rbac"), "rbac.txt")

	_, err = os.Stat(filepath.Join(newDir, "hello/templates/empty"))
	is.True(os.IsNotExist(err))
}

func TestNameAndChart(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)
	chartName := "./foo"

	name, chrt, err := instAction.NameAndChart([]string{chartName})
	if err != nil {
		t.Fatal(err)
	}
	is.Equal(instAction.ReleaseName, name)
	is.Equal(chartName, chrt)

	instAction.GenerateName = true
	_, _, err = instAction.NameAndChart([]string{"foo", chartName})
	if err == nil {
		t.Fatal("expected an error")
	}
	is.Equal("cannot set --generate-name and also specify a name", err.Error())

	instAction.GenerateName = false
	instAction.NameTemplate = "{{ . }}"
	_, _, err = instAction.NameAndChart([]string{"foo", chartName})
	if err == nil {
		t.Fatal("expected an error")
	}
	is.Equal("cannot set --name-template and also specify a name", err.Error())

	instAction.NameTemplate = ""
	instAction.ReleaseName = ""
	_, _, err = instAction.NameAndChart([]string{chartName})
	if err == nil {
		t.Fatal("expected an error")
	}
	is.Equal("must either provide a name or specify --generate-name", err.Error())

	instAction.NameTemplate = ""
	instAction.ReleaseName = ""
	_, _, err = instAction.NameAndChart([]string{"foo", chartName, "bar"})
	if err == nil {
		t.Fatal("expected an error")
	}
	is.Equal("expected at most two arguments, unexpected arguments: bar", err.Error())
}

func TestNameAndChartGenerateName(t *testing.T) {
	is := assert.New(t)
	instAction := installAction(t)

	instAction.ReleaseName = ""
	instAction.GenerateName = true

	tests := []struct {
		Name         string
		Chart        string
		ExpectedName string
	}{
		{
			"local filepath",
			"./chart",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
		{
			"dot filepath",
			".",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
		{
			"empty filepath",
			"",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
		{
			"packaged chart",
			"chart.tgz",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
		{
			"packaged chart with .tar.gz extension",
			"chart.tar.gz",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
		{
			"packaged chart with local extension",
			"./chart.tgz",
			fmt.Sprintf("chart-%d", time.Now().Unix()),
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.Name, func(t *testing.T) {
			t.Parallel()

			name, chrt, err := instAction.NameAndChart([]string{tc.Chart})
			if err != nil {
				t.Fatal(err)
			}

			is.Equal(tc.ExpectedName, name)
			is.Equal(tc.Chart, chrt)
		})
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ublu.command;

import ublu.util.ArgArray;
//import ublu.util.DataSink;
//import ublu.util.Tuple;
import com.ibm.as400.access.AS400SecurityException;
import com.ibm.as400.access.ErrorCompletingRequestException;
import com.ibm.as400.access.ObjectDoesNotExistException;
import com.ibm.as400.access.RequestNotSupportedException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import ublu.util.Generics.UserTupleMap;
import ublu.util.Tuple;

/**
 * Command to manipulate Maps
 *
 * @author jwoehr
 */
public class CmdMap extends Command {

    {
        setNameAndDescription("map", "/0? [--,-map ~@map] [-to datasink] [-new | -> ~@tuple | -clear | -add ~@{key} ~@tuple | -~,-push ~@{key} | -.,-get ~@{key} | -drop ~@{key} | -keys | -size]  : create and manipulate maps of tuples");
    }

    private enum OPS {

        NEW, ADD, CLEAR, GET, PUT, PUSH, DROP, KEYS, SIZE
    }

    /**
     * Perform the work of manipulating a doMap.
     *
     * @param argArray the input arg array
     * @return what's left of the arg array
     */
    public ArgArray doMap(ArgArray argArray) {
        OPS op = OPS.NEW;
        UserTupleMap map = null;
        Tuple tuple = null;
        String key = null;
        while (argArray.hasDashCommand()) {
            String dashCommand = argArray.parseDashCommand();
            switch (dashCommand) {
                case "-to":
                    setDataDestfromArgArray(argArray);
                    break;
//                case "-from":
//                    String srcName = argArray.next();
//                    setDataSrc(DataSink.fromSinkName(srcName));
//                    break;
                case "--":
                case "-map":
                    map = argArray.nextTupleOrPop().value(UserTupleMap.class);
                    break;
                case "-new":
                    op = OPS.NEW;
                    break;
                case "-clear":
                    op = OPS.CLEAR;
                    break;
                case "-add":
                    op = OPS.ADD;
                    key = argArray.nextMaybeQuotationTuplePopStringTrim();
                    tuple = argArray.nextTupleOrPop();
                    break;
                case "-drop":
                    op = OPS.DROP;
                    key = argArray.nextMaybeQuotationTuplePopStringTrim();
                    break;
                case "->":
                    op = OPS.PUT;
                    tuple = argArray.nextTupleOrPop();
                    break;
                case "-.":
                case "-get":
                    op = OPS.GET;
                    key = argArray.nextMaybeQuotationTuplePopStringTrim();
                    break;
                case "-~":
                case "-push":
                    op = OPS.PUSH;
                    key = argArray.nextMaybeQuotationTuplePopStringTrim();
                    break;
                case "-keys":
                    op = OPS.KEYS;
                    break;
                case "-size":
                    op = OPS.SIZE;
                    break;
                default:
                    unknownDashCommand(dashCommand);
            }
        }
        if (havingUnknownDashCommand()) {
            setCommandResult(COMMANDRESULT.FAILURE);
        } else if (map == null && op != OPS.NEW) {
            getLogger().log(Level.SEVERE, "No Map provided to --map in {0}", getNameAndDescription());
            setCommandResult(COMMANDRESULT.FAILURE);
        } else {
            switch (op) {
                case SIZE:
                    try {
                        put(map.size());
                    } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
                        getLogger().log(Level.SEVERE, "Error putting size of Map in " + getNameAndDescription(), ex);
                        setCommandResult(COMMANDRESULT.FAILURE);
                    }
                    break;
                case NEW:
                    try {
                        put(new UserTupleMap());
                    } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
                        getLogger().log(Level.SEVERE, "Error putting new Map in " + getNameAndDescription(), ex);
                        setCommandResult(COMMANDRESULT.FAILURE);
                    }
                    break;
                case CLEAR:
                    map.clear();
                case ADD:
                    map.put(key, tuple);
                    break;
                case DROP:
                    map.remove(key);
                    break;
                case GET:
                    try {
                        put(map.get(key));
                    } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
                        getLogger().log(Level.SEVERE, "Error putting tuple with key " + key + " from Map in " + getNameAndDescription(), ex);
                        setCommandResult(COMMANDRESULT.FAILURE);
                    }
                    break;
                case KEYS:
                    try {
                        put(map.keySet());
                    } catch (SQLException | IOException | AS400SecurityException | ErrorCompletingRequestException | InterruptedException | ObjectDoesNotExistException | RequestNotSupportedException ex) {
                        getLogger().log(Level.SEVERE, "Error putting size of Map in " + getNameAndDescription(), ex);
                        setCommandResult(COMMANDRESULT.FAILURE);
                    }
                    break;
                case PUSH:
                    getTupleStack().push(map.get(key));
                    break;
                case PUT:
                    map.put(tuple.getKey().substring(1), tuple); // remove the "@"
                    break;
            }
        }
        return argArray;
    }

    @Override
    public ArgArray cmd(ArgArray args) {
        reinit();
        return doMap(args);
    }

    @Override
    public COMMANDRESULT getResult() {
        return getCommandResult();
    }
}


text:
require "json"

begin
  require "active_support/inflector"
rescue LoadError
  puts "You need to install active support: gem install activesupport"
  exit 1
end

out_dir = nil
if ARGV.length == 1 then
  out_dir = ARGV[0]
  puts "Out dir: #{out_dir}"
else
  puts "No output directory specified"
end

script_path = File.expand_path(File.dirname(__FILE__))

paths = Dir["#{script_path}/../json/keybase1/*.json"]

# Add common first to workaround import ordering, TODO: Fixme
paths_move = ["#{script_path}/../json/keybase1/common.json",
  "#{script_path}/../json/keybase1/prove_common.json",
  "#{script_path}/../json/keybase1/identify_common.json",
  "#{script_path}/../json/keybase1/identify_ui.json",
  "#{script_path}/../json/keybase1/saltpack_ui.json"]
paths_move.reverse.each do |p|
  paths.delete(p)
  paths.unshift(p)
end
# Uses external import, TODO: Fixme
paths.delete("#{script_path}/../json/keybase1/gregor_ui.json")
paths.delete("#{script_path}/../json/keybase1/gregor.json")

defined_types = []
enums = []
aliases = {}

def classname(type, aliases)
  type = aliases[type] if aliases[type]

  case type
  when "int" then "NSNumber"
  when "int64" then "NSNumber"
  when "long" then "NSNumber"
  when "float" then "NSNumber"
  when "double" then "NSNumber"
  when "string" then "NSString"
  when "bytes" then "NSData"
  else
    "KBR#{type}"
  end
end

def objc_for_type(type, enums, aliases, space)
  type = type["type"] if type.kind_of?(Hash) # Subtype (for arrays)
  type = type.find { |t| t != "null" && !t.nil? } if type.kind_of?(Array) # Union

  type = aliases[type] if aliases[type]

  ptr = false
  name, ptr = case type
  when "string" then ["NSString *", true]
  when "int" then ["NSInteger", false]
  when "int64" then ["int64_t", false]
  when "long" then ["int64_t", false]
  when "float" then ["float", false]
  when "double" then ["double", false]
  when "array" then ["NSArray *", true]
  when "map" then ["NSDictionary *", true]
  when "boolean" then ["BOOL", false]
  when "bool" then ["BOOL", false]
  when "bytes" then ["NSData *", true]
  when "null" then ["void", false]
  when nil then ["void", false]
  else
    if type.start_with?("void")
      [type, false]
    elsif enums.include?(type)
      [classname(type, {}), false]
    else
      [classname("#{type} *", {}), true]
    end
  end

  name = "#{name} " if space and !ptr
  name
end

def is_native_type(type)
  is_primitive_type(type) || ["string", "array", "map", "bytes"].include?(type)
end

def is_primitive_type(type)
  type = type.find { |t| t != "null" && !t.nil? } if type.kind_of?(Array) # Union
  ["int", "int64", "long", "float", "double", "boolean", "bool", "null", nil, "Time"].include?(type)
end

# Deprecated
def alias_name(name)
  name
end

def validate_name(name, source)
  case name
  when "self"
    return "selfValue"
  when "default"
    return "defaultValue"
  when "auto"
    return "automatic"
  end

  # Move new to end of name if starts with name, e.g. "newFolders" => "foldersNew"
  if name.start_with?("new")
    return name[3, 1].downcase + name[4..-1] + "New"
  end
  name
end

def default_name_for_type(type)
  type = type["type"] if type.kind_of?(Hash) # Subtype (for arrays)

  case type
  when "string" then "str"
  when "int" then "n"
  when "int64" then "n"
  when "long" then "l"
  when "float" then "f"
  when "double" then "d"
  when "array" then "items"
  when "map" then "dict"
  when "boolean" then "b"
  when "bool" then "b"
  when "binary" then "data"
  when "null" then "void"
  when nil then "void"
  else type.camelize(:lower)
  end
end

def value_for_type(type, name, enums, aliases)
  type = type.find { |t| t != "null" && !t.nil? } if type.kind_of?(Array) # Union
  varname = "params[0][@\"#{name}\"]"

  if type.kind_of?(Hash) # For array, map
    if type["type"] == "array" then
      type_for_array = type["items"]
      type_for_array = aliases[type_for_array] if aliases[type_for_array]
      if is_native_type(type_for_array)
        return "KBRValidateArray(#{varname}, #{classname(type_for_array, aliases)}.class)"
      else
        return "[MTLJSONAdapter modelsOfClass:#{classname(type_for_array, aliases)}.class fromJSONArray:#{varname} error:nil]"
      end
    else
      type_for_map = type["values"]
      type_for_map = aliases[type_for_map] if aliases[type_for_map]
      return "KBRValidateDictionary(#{varname}, #{classname(type_for_map, aliases)}.class)"
    end
  end

  if enums.include?(type)
    return "[#{varname} integerValue]"
  end

  type = aliases[type] if aliases[type]

  case type
  when "int" then "[#{varname} integerValue]"
  when "int64" then "[#{varname} longLongValue]"
  when "long" then "[#{varname} longLongValue]"
  when "float" then "[#{varname} floatValue]"
  when "double" then "[#{varname} doubleValue]"
  when "boolean" then "[#{varname} boolValue]"
  when "bool" then "[#{varname} boolValue]"
  when "string" then varname
  when "array" then varname
  when "map" then varname
  when "bytes" then varname
  else
    "[MTLJSONAdapter modelOfClass:#{classname(type, aliases)}.class fromJSONDictionary:#{varname} error:nil]"
  end
end

def add_methods(header, impl, namespace, protocol, response_type, method, request_params_items, params_str, aliases, enums)
  rpc_method = "#{namespace}.#{protocol}.#{method}"
  dc_method = method.camelize(:lower)
  objc_method = "- (void)#{dc_method}#{params_str.join(" ")}"

  #puts "Method: #{objc_method}"
  header << "#{objc_method};\n"
  impl << "#{objc_method} {"

  callback = if response_type == "null" || response_type.nil? then # No result
    "completion(error);"
  elsif is_primitive_type(response_type) # Primitive type result
    "completion(error, 0);" # TODO
  elsif enums.include?(response_type)
    "completion(error, [retval integerValue]);"
  elsif response_type.kind_of?(Hash) # Array result
    item_type = response_type["items"]
    item_clsname = classname(item_type, aliases)
    "if (error) {
      completion(error, nil);
      return;
    }
    NSArray *results = retval ? [MTLJSONAdapter modelsOfClass:#{item_clsname}.class fromJSONArray:retval error:&error] : nil;
    completion(error, results);"
  else # Dictionary result
    clsname = classname(response_type, aliases)
    "if (error) {
      completion(error, nil);
      return;
    }
    #{clsname} *result = retval ? [MTLJSONAdapter modelOfClass:#{clsname}.class fromJSONDictionary:retval error:&error] : nil;
    completion(error, result);"
  end

  impl << "  NSDictionary *rparams = @{#{request_params_items.join(", ")}};
  [self.client sendRequestWithMethod:@\"#{rpc_method}\" params:rparams sessionId:self.sessionId completion:^(NSError *error, id retval) {
    #{callback}
  }];"

  impl << "}\n"

  return header, impl
end

header = []
impl = []
header_rparams = []
impl_rparams = []
header_records = []
impl_records = []

paths.each do |path|
  file = File.read(path)
  h = JSON.parse(file)

  protocol = h["protocol"]
  namespace = h["namespace"]
  #puts "\nProtocol: #{protocol}"

  h["types"].each do |type|
    if (defined_types.include?(type["name"]))
      #puts "Skipping: #{type["name"]}. Already defined."
      next
    end
    defined_types << type["name"]
    #puts "Type: #{type["name"]}"

    if type["type"] == "enum"
      enum_name = type["name"]
      enums << enum_name
      enum_name_objc = "#{classname(enum_name, aliases)}"
      header_records << "typedef NS_ENUM (NSInteger, #{enum_name_objc}) {"
      type["symbols"].each do |symbol|
        sym, _, sym_val = symbol.rpartition('_')

        raise "Enums must specify value: #{enum_name} #{symbol}" if sym.length == 0
        raise "Enums must specify an integer value: #{enum_name} #{symbol}" if not /\A\d+\z/.match(sym_val)

        header_records << "\t#{enum_name_objc}#{sym.capitalize.camelize} = #{sym_val},"
      end
      header_records << "};\n"
    elsif type["type"] == "fixed"
      aliases[type["name"]] = "bytes"
    elsif type["type"] == "record" and type["typedef"]
      aliases[type["name"]] = type["typedef"]
    elsif type["type"] == "record"
      transformers = []
      header_records << "@interface #{classname(type["name"], aliases)} : KBRObject"
      type["fields"].each do |field|
        name = field["name"]
        name = validate_name(name, type["name"])
        if field["type"].kind_of?(Hash)
          subtype = field["type"]
          if subtype["type"] == "array"

            if is_native_type(subtype["items"])
              header_records << "@property NSArray *#{name}; /*of #{subtype["items"]}*/"
            else
              header_records << "@property NSArray *#{name}; /*of #{classname(subtype["items"], aliases)}*/"
              transformers << "+ (NSValueTransformer *)#{name}JSONTransformer { return [MTLJSONAdapter arrayTransformerWithModelClass:#{classname(subtype["items"], aliases)}.class]; }"
            end
          end
        else
          header_records << "@property #{objc_for_type(field["type"], enums, aliases, true)}#{name};"
        end
      end
      header_records << "@end\n"
      impl_records << "@implementation #{classname(type["name"], aliases)}"
      impl_records += transformers if transformers
      impl_records << "@end\n"
    else
      puts "Undefined type: #{type["type"]}"
    end
  end

  header << "@interface #{classname(protocol.camelize, aliases)}Request : KBRRequest\n"
  impl << "@implementation #{classname(protocol.camelize, aliases)}Request\n"

  h["messages"].each do |method, mparam|
    request_params = mparam["request"].dup
    response_type = mparam["response"]

    request_params.shift if request_params.length > 0 && request_params[0]["name"] == "sessionID"

    response_completion = if response_type == "null" || response_type.nil? then
      "void (^)(NSError *error)"
    else
      "void (^)(NSError *error, #{objc_for_type(response_type, enums, aliases, true)}#{default_name_for_type(response_type)})"
    end

    # Generate with params object
    request_params_items = request_params.map do |p|
      name = validate_name(p["name"], protocol)
      type = p["type"]
      type = aliases[type] if aliases[type]
      if is_primitive_type(type) || enums.include?(type)
        "@\"#{p["name"]}\": @(params.#{alias_name(name)})"
      else
        "@\"#{p["name"]}\": KBRValue(params.#{alias_name(name)})"
      end
    end
    params_str = []
    if mparam["doc"] then
      header << "/*!"
      header << " " + mparam["doc"].gsub(/[\t ]+/, ' ')
      header << " */"
    end
    if request_params.length > 0
      params_str << ":(KBR#{method.camelize}RequestParams *)params"
      params_str << "completion:(#{objc_for_type(response_completion, enums, aliases, false)})completion"
      add_methods(header, impl, namespace, protocol, response_type, method, request_params_items, params_str, aliases, enums)
    else
      params_str << ":(#{objc_for_type(response_completion, enums, aliases, false)})completion"
      add_methods(header, impl, namespace, protocol, response_type, method, request_params_items, params_str, aliases, enums)
    end

    # Generate with full method signature (deprecated)
    if request_params.length > 0
      request_params_items = request_params.map do |p|
        name = validate_name(p["name"], protocol)
        type = p["type"]
        type = aliases[type] if aliases[type]
        if is_primitive_type(type) || enums.include?(type)
          "@\"#{p["name"]}\": @(#{alias_name(name)})"
        else
          "@\"#{p["name"]}\": KBRValue(#{alias_name(name)})"
        end
      end
      request_params << {"name" => "completion", "type" => response_completion}
      params_str = request_params.each_with_index.collect do |param, index|
        name = alias_name(param["name"])
        name = validate_name(name, protocol)
        nameLabel = name
        nameLabel = "With#{name.camelize}" if index == 0
        nameLabel = "" if request_params.length == 1

        "#{nameLabel}:(#{objc_for_type(param["type"], enums, aliases, false)})#{alias_name(name)}"
      end
      add_methods(header, impl, namespace, protocol, response_type, method, request_params_items, params_str, aliases, enums)
    end

    # Request params
    if mparam["request"].length > 0
      header_rparams << "@interface KBR#{method.camelize}RequestParams : KBRRequestParams"
      mparam["request"].each do |param|
        name = validate_name(param["name"], protocol)
        header_rparams << "@property #{objc_for_type(param["type"], enums, aliases, true)}#{name};"
      end
      header_rparams << "@end"

      obj_name = "KBR#{method.camelize}RequestParams"
      impl_rparams << "@implementation #{obj_name}\n"

      impl_rparams << "- (instancetype)initWithParams:(NSArray *)params {"
      impl_rparams << "  if ((self = [super initWithParams:params])) {"
      mparam["request"].each do |param|
        name = validate_name(param["name"], protocol)
        value = value_for_type(param["type"], name, enums, aliases)
        impl_rparams << "    self.#{name} = #{value};"
      end
      impl_rparams << "  }"
      impl_rparams << "  return self;"
      impl_rparams << "}\n"

      # Default values
      impl_rparams << "+ (instancetype)params {"
      impl_rparams << "  #{obj_name} *p = [[self alloc] init];"
      impl_rparams << "  // Add default values"
      mparam["request"].each do |param|
        if param.has_key?("default") then
          impl_rparams << "  p.#{param["name"]} = #{param["default"]};"
        end
      end
      impl_rparams << "  return p;"
      impl_rparams << "}"

      impl_rparams << "@end\n"
    end

  end
  header << "@end\n"
  impl << "@end\n"

end

if !out_dir.nil? then
  File.open("#{out_dir}/KBRPC.h", "w") { |f|
    f.write(<<-EOS
  // This file is autogenerated
  #import "KBRObject.h"
  #import "KBRRequest.h"
  #import "KBRRequestParams.h"

  EOS
  )

    f.write(header_records.join("\n"))
    f.write(header_rparams.join("\n"))
    f.write(header.join("\n"))
  }

  File.open("#{out_dir}/KBRPC.m", "w") { |f|
    f.write(<<-EOS
  // This file is autogenerated
  #import "KBRPC.h"

  EOS
  )

    f.write(impl.join("\n"))
    f.write(impl_rparams.join("\n"))
    f.write(impl_records.join("\n"))
  }
end


text:
from vitrage.common.constants import DatasourceProperties as DSProps
from vitrage.common.constants import GraphAction
from vitrage.common.constants import VertexProperties as VProps
from vitrage.datasources.consistency import CONSISTENCY_DATASOURCE
from vitrage.datasources.resource_transformer_base import \
    ResourceTransformerBase
import vitrage.graph.utils as graph_utils

class ConsistencyTransformer(ResourceTransformerBase):

    # graph actions which need to refer them differently
    GRAPH_ACTION_MAPPING = {
        GraphAction.DELETE_ENTITY: GraphAction.DELETE_ENTITY,
        GraphAction.REMOVE_DELETED_ENTITY: GraphAction.REMOVE_DELETED_ENTITY
    }

    def __init__(self, transformers):
        super(ConsistencyTransformer, self).__init__(transformers)

    def _create_snapshot_entity_vertex(self, entity_event):
        return self._create_vertex(entity_event)

    def _create_update_entity_vertex(self, entity_event):
        return self._create_vertex(entity_event)

    @staticmethod
    def _create_vertex(entity_event):
        metadata = {
            VProps.IS_REAL_VITRAGE_ID:
                entity_event.get(VProps.IS_REAL_VITRAGE_ID, False)
        }

        return graph_utils.create_vertex(
            entity_event[VProps.VITRAGE_ID],
            vitrage_sample_timestamp=entity_event[DSProps.SAMPLE_DATE],
            metadata=metadata
        )

    def _create_entity_key(self, entity_event):
        return None

    def _create_snapshot_neighbors(self, entity_event):
        return None

    def _create_update_neighbors(self, entity_event):
        return None

    def get_vitrage_type(self):
        return CONSISTENCY_DATASOURCE


text:
import { connect } from 'react-redux';
import Helper from '../helpers/GlobalHelpers';
import SocketPlayground from '../components/SocketPlayground';

function mapStateToProps(state) {
  const socketState = state.socketContainerReducer;
  const currentConnection = Helper.getCurrentConnection(socketState);
  return {
    parameters: currentConnection.parameters,
  };
}

export default connect(mapStateToProps)(SocketPlayground);


text:
/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation,
 modification or redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject to these
 terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in
 this original Apple software (the "Apple Software"), to use, reproduce, modify and
 redistribute the Apple Software, with or without modifications, in source and/or binary
 forms; provided that if you redistribute the Apple Software in its entirety and without
 modifications, you must retain this notice and the following text and disclaimers in all
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES,
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#import "ACImageAndTextCell.h"
#define xImagePadding 7.0f

@implementation ACImageAndTextCell
@synthesize image;

- (void) dealloc {
	[image release];
	[super dealloc];
}

- (id) copyWithZone:(NSZone *)zone {
	ACImageAndTextCell *cell = (ACImageAndTextCell *)[super copyWithZone:zone];
	cell->image = [image retain];
	return cell;
}

#pragma mark -

- (NSRect) imageFrameForCellFrame:(NSRect)cellFrame {
	NSRect retRect;

	if (image) {
		retRect.size = [image size];
		retRect.origin.x = cellFrame.origin.x + xImagePadding;
		retRect.origin.y = cellFrame.origin.y
			+ ceilf((cellFrame.size.height - retRect.size.height) * 0.5);
	} else {
		retRect = NSZeroRect;
	}

	return retRect;
}

- (void) editWithFrame:(NSRect)aRect
				inView:(NSView *)controlView
				editor:(NSText *)textObj
			  delegate:(id)anObject
				 event:(NSEvent *)theEvent {
	NSRect textFrame, imageFrame;

	NSDivideRect (aRect, &imageFrame, &textFrame, xImagePadding + [image size].width, NSMinXEdge);
	[super editWithFrame: textFrame
				  inView: controlView
				  editor: textObj
				delegate: anObject
				   event: theEvent];
}

- (void) selectWithFrame:(NSRect)aRect
				  inView:(NSView *)controlView
				  editor:(NSText *)textObj
				delegate:(id)anObject
				   start:(NSInteger)selStart
				  length:(NSInteger)selLength {
	NSRect textFrame, imageFrame;

	NSDivideRect (aRect, &imageFrame, &textFrame, xImagePadding + [image size].width, NSMinXEdge);
	[super selectWithFrame: textFrame
					inView: controlView
					editor:textObj
				  delegate: anObject
					 start: selStart
					length: selLength];
}

- (void) drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
	if (image) {
		NSSize	imageSize = [image size];
		NSRect	imageFrame;

		NSDivideRect(cellFrame, &imageFrame, &cellFrame, xImagePadding + imageSize.width, NSMinXEdge);
		if ([self drawsBackground]) {
			[[self backgroundColor] set];
			NSRectFill(imageFrame);
		}
		imageFrame.origin.x += 3.0;
		//imageFrame.size = imageSize;

		if ([controlView isFlipped]) {
			imageFrame.origin.y += ceilf((cellFrame.size.height + imageSize.height) * 0.5);
		} else {
			imageFrame.origin.y += ceilf((cellFrame.size.height - imageSize.height) * 0.5);
		}

		[image compositeToPoint:imageFrame.origin operation:NSCompositeSourceOver];
	}

	NSAttributedString *string = [self attributedStringValue];
	if (string) {
		NSSize textSize = [string size];
		if (cellFrame.size.height > textSize.height) {
			cellFrame.origin.y += (cellFrame.size.height - textSize.height)/2;
            cellFrame.size.height = textSize.height;
            [super drawWithFrame:cellFrame inView:controlView];
		} else {
			[super drawWithFrame:cellFrame inView:controlView];
		}
	}
}

- (NSSize) cellSize {
	NSSize cellSize = [super cellSize];
	cellSize.width += (image ? [image size].width + xImagePadding : 3.0);
	return cellSize;
}

@end


text:
import { Posts } from '../collections/posts/posts';
import { Meteor } from 'meteor/meteor';

Meteor.publish('posts', () => {
  return Posts.find();
});


text:
;
;//     (c) 2012 Airbnb, Inc.
//
//     polyglot.js may be freely distributed under the terms of the BSD
//     license. For all licensing information, details, and documention:
//     http://airbnb.github.com/polyglot.js
//
//
// Polyglot.js is an I18n helper library written in JavaScript, made to
// work both in the browser and in Node. It provides a simple solution for
// interpolation and pluralization, based off of Airbnb's
// experience adding I18n functionality to its Backbone.js and Node apps.
//
// Polylglot is agnostic to your translation backend. It doesn't perform any
// translation; it simply gives you a way to manage translated phrases from
// your client- or server-side JavaScript application.
//

!function(root) {
  'use strict';

  // ### Polyglot class constructor
  function Polyglot(options) {
    options = options || {};
    this.phrases = {};
    this.extend(options.phrases || {});
    this.currentLocale = options.locale || 'en';
    this.allowMissing = !!options.allowMissing;
    this.warn = options.warn || warn;
  }

  // ### Version
  Polyglot.VERSION = '0.4.2';

  // ### polyglot.locale([locale])
  //
  // Get or set locale. Internally, Polyglot only uses locale for pluralization.
  Polyglot.prototype.locale = function(newLocale) {
    if (newLocale) this.currentLocale = newLocale;
    return this.currentLocale;
  };

  // ### polyglot.extend(phrases)
  //
  // Use `extend` to tell Polyglot how to translate a given key.
  //
  //     polyglot.extend({
  //       "hello": "Hello",
  //       "hello_name": "Hello, %{name}"
  //     });
  //
  // The key can be any string.  Feel free to call `extend` multiple times;
  // it will override any phrases with the same key, but leave existing phrases
  // untouched.
  //
  // It is also possible to pass nested phrase objects, which get flattened
  // into an object with the nested keys concatenated using dot notation.
  //
  //     polyglot.extend({
  //       "nav": {
  //         "hello": "Hello",
  //         "hello_name": "Hello, %{name}",
  //         "sidebar": {
  //           "welcome": "Welcome"
  //         }
  //       }
  //     });
  //
  //     console.log(polyglot.phrases);
  //     // {
  //     //   'nav.hello': 'Hello',
  //     //   'nav.hello_name': 'Hello, %{name}',
  //     //   'nav.sidebar.welcome': 'Welcome'
  //     // }
  //
  // `extend` accepts an optional second argument, `prefix`, which can be used
  // to prefix every key in the phrases object with some string, using dot
  // notation.
  //
  //     polyglot.extend({
  //       "hello": "Hello",
  //       "hello_name": "Hello, %{name}"
  //     }, "nav");
  //
  //     console.log(polyglot.phrases);
  //     // {
  //     //   'nav.hello': 'Hello',
  //     //   'nav.hello_name': 'Hello, %{name}'
  //     // }
  //
  // This feature is used internally to support nested phrase objects.
  Polyglot.prototype.extend = function(morePhrases, prefix) {
    var phrase;

    for (var key in morePhrases) {
      if (morePhrases.hasOwnProperty(key)) {
        phrase = morePhrases[key];
        if (prefix) key = prefix + '.' + key;
        if (typeof phrase === 'object') {
          this.extend(phrase, key);
        } else {
          this.phrases[key] = phrase;
        }
      }
    }
  };

  // ### polyglot.clear()
  //
  // Clears all phrases. Useful for special cases, such as freeing
  // up memory if you have lots of phrases but no longer need to
  // perform any translation. Also used internally by `replace`.
  Polyglot.prototype.clear = function() {
    this.phrases = {};
  };

  // ### polyglot.replace(phrases)
  //
  // Completely replace the existing phrases with a new set of phrases.
  // Normally, just use `extend` to add more phrases, but under certain
  // circumstances, you may want to make sure no old phrases are lying around.
  Polyglot.prototype.replace = function(newPhrases) {
    this.clear();
    this.extend(newPhrases);
  };

  // ### polyglot.t(key, options)
  //
  // The most-used method. Provide a key, and `t` will return the
  // phrase.
  //
  //     polyglot.t("hello");
  //     => "Hello"
  //
  // The phrase value is provided first by a call to `polyglot.extend()` or
  // `polyglot.replace()`.
  //
  // Pass in an object as the second argument to perform interpolation.
  //
  //     polyglot.t("hello_name", {name: "Spike"});
  //     => "Hello, Spike"
  //
  // If you like, you can provide a default value in case the phrase is missing.
  // Use the special option key "_" to specify a default.
  //
  //     polyglot.t("i_like_to_write_in_language", {
  //       _: "I like to write in %{language}.",
  //       language: "JavaScript"
  //     });
  //     => "I like to write in JavaScript."
  //
  Polyglot.prototype.t = function(key, options) {
    var phrase, result;
    options = options == null ? {} : options;
    // allow number as a pluralization shortcut
    if (typeof options === 'number') {
      options = {smart_count: options};
    }
    if (typeof this.phrases[key] === 'string') {
      phrase = this.phrases[key];
    } else if (typeof options._ === 'string') {
      phrase = options._;
    } else if (this.allowMissing) {
      phrase = key;
    } else {
      this.warn('Missing translation for key: "'+key+'"');
      result = key;
    }
    if (typeof phrase === 'string') {
      options = clone(options);
      result = choosePluralForm(phrase, this.currentLocale, options.smart_count);
      result = interpolate(result, options);
    }
    return result;
  };

  // #### Pluralization methods
  // The string that separates the different phrase possibilities.
  var delimeter = '||||';

  // Mapping from pluralization group plural logic.
  var pluralTypes = {
    chinese:   function(n) { return 0; },
    german:    function(n) { return n !== 1 ? 1 : 0; },
    french:    function(n) { return n > 1 ? 1 : 0; },
    russian:   function(n) { return n % 10 === 1 && n % 100 !== 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2; },
    czech:     function(n) { return (n === 1) ? 0 : (n >= 2 && n <= 4) ? 1 : 2; },
    polish:    function(n) { return (n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); },
    icelandic: function(n) { return (n % 10 !== 1 || n % 100 === 11) ? 1 : 0; }
  };

  // Mapping from pluralization group to individual locales.
  var pluralTypeToLanguages = {
    chinese:   ['fa', 'id', 'ja', 'ko', 'lo', 'ms', 'th', 'tr', 'zh'],
    german:    ['da', 'de', 'en', 'es', 'fi', 'el', 'he', 'hu', 'it', 'nl', 'no', 'pt', 'sv'],
    french:    ['fr', 'tl', 'pt-br'],
    russian:   ['hr', 'ru'],
    czech:     ['cs'],
    polish:    ['pl'],
    icelandic: ['is']
  };

  function langToTypeMap(mapping) {
    var type, langs, l, ret = {};
    for (type in mapping) {
      if (mapping.hasOwnProperty(type)) {
        langs = mapping[type];
        for (l in langs) {
          ret[langs[l]] = type;
        }
      }
    }
    return ret;
  }

  // Trim a string.
  function trim(str){
    var trimRe = /^\s+|\s+$/g;
    return str.replace(trimRe, '');
  }

  // Based on a phrase text that contains `n` plural forms separated
  // by `delimeter`, a `locale`, and a `count`, choose the correct
  // plural form, or none if `count` is `null`.
  function choosePluralForm(text, locale, count){
    var ret, texts, chosenText;
    if (count != null && text) {
      texts = text.split(delimeter);
      chosenText = texts[pluralTypeIndex(locale, count)] || texts[0];
      ret = trim(chosenText);
    } else {
      ret = text;
    }
    return ret;
  }

  function pluralTypeName(locale) {
    var langToPluralType = langToTypeMap(pluralTypeToLanguages);
    return langToPluralType[locale] || langToPluralType.en;
  }

  function pluralTypeIndex(locale, count) {
    return pluralTypes[pluralTypeName(locale)](count);
  }

  // ### interpolate
  //
  // Does the dirty work. Creates a `RegExp` object for each
  // interpolation placeholder.
  function interpolate(phrase, options) {
    for (var arg in options) {
      if (arg !== '_' && options.hasOwnProperty(arg)) {
        // We create a new `RegExp` each time instead of using a more-efficient
        // string replace so that the same argument can be replaced multiple times
        // in the same phrase.
        phrase = phrase.replace(new RegExp('%\\{'+arg+'\\}', 'g'), options[arg]);
      }
    }
    return phrase;
  }

  // ### warn
  //
  // Provides a warning in the console if a phrase key is missing.
  function warn(message) {
    root.console && root.console.warn && root.console.warn('WARNING: ' + message);
  }

  // ### clone
  //
  // Clone an object.
  function clone(source) {
    var ret = {};
    for (var prop in source) {
      ret[prop] = source[prop];
    }
    return ret;
  }

  // Export for Node, attach to `window` for browser.
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Polyglot;
  } else {
    root.Polyglot = Polyglot;
  }

}(this);
;//core translations Eng - ES
var i18n = new Polyglot();
i18n.locale(locale);

i18n.extend({
  //English
  "from": "From",
  "to": "To",
  "cmp": "Compare with",
  "date_range": "Date Range",
  "export": "Export to",
});

if (i18n.locale() == "es") i18n.extend({
  //Spanish
  "from": "Desde",
  "to": "Hasta",
   "cmp": "Comparar con",
   "date_range": "Rango de Fechas",
   "export": "Exportar a",
});
;//actual simbolo que se esta comparando
var current_selected_value = "";

//Este modulo es dependiente de, D3,C3,Polyglot
var StockTools = function (raiz, periodos) {
    'use strict';

    var ids = [];
    var self = this;

    function init() {

        var header = d3.select(raiz).append("div")
            .attr("class", "c3-header");

        // Crea el contenedor de los periodos
        var p = header.append("div")
            .attr('class', 'c3-periodos-contenedor')
            .append("ul")
            .attr('class', 'c3-periodos');

        // Crea el contenedor de los intervalos (input para las fechas)
        var intervalos = header.append("div")
            .attr('class', 'c3-intervalos-contenedor')
            .append("ul");

        var li = intervalos.append("li");

        li.append("a").attr('href', '#').text(i18n.t('date_range'));
        var divFechas = li.append('ul').append('li').append('div').attr("class", 'form-intervalos-fechas');

        var inicio = divFechas.append("div").attr('class', 'divFechas');
        inicio.html('' + i18n.t("from") + ':<input type="text" name="inicio" id="inicio" value="' + datos.columns[0][1] + '">');
        inicio.select("input").on("keypress", self.e_input_enter);

        var fin = divFechas.append("div").attr('class', 'divFechas');
        fin.html('' + i18n.t("to") + ':<input type="text" name="fin" id="fin" value="' + datos.columns[0][datos.columns[0].length - 1] + '">');
        fin.select("input").on("keypress", self.e_input_enter);

        var botonActualizar = divFechas.append("div").attr('class', 'btn-Actualizar-contenedor');
        botonActualizar.html('<input id="btn-actualizar" type="button" value="OK">');

        divFechas.append('div').style('clear', 'both');

        // Div contenedor de los botones
        var botones = header.append("div")
            .attr('class', 'c3-botones')
            .append("ul")
            .attr('class', 'c3-botones');

        botonActualizar.select("input").on('click', self.m_update);

        // Botones para comparar
        datos.columns.forEach(function (d, i) {
            if (i > 0) {
                ids.push(datos.columns[i][0]);
            }
        });
        ids[0] = i18n.t("cmp");

        var select = botones.append("select")
            .attr("class", "c3_cmp");

        select.selectAll("opciones")
            .data(ids)
            .enter()
            .append("option")
            .attr('class', 'opciones')
            .attr('data-id', function (d) {
                return d;
            })
            .attr('value', function (d) {
                return d;
            })
            .text(function (d) {
                return d;
            });

        select.on("change", self.e_comparar_click);

        header.append("div")
            .attr('class', 'c3-clear-header')
            .style('clear', 'both');

        // Crea todos los botones de los periodos
        p.selectAll("botones")
            .data(periodos)
            .enter()
            .append("li")
            //.attr("type", "button")
            .attr("class", function (p) {
                return p.seleccionado ? "button selected" : "button";
            })
            .attr("data-value", function (p) {
                return p.cantidad;
            })
            .attr("data-tipo", function (p) {
                return p.tipo;
            })
            .on('click', self.e_click_periodo)
            .append("a")
            .attr("href", "#")
            .attr("class", function (p) {
                return p.seleccionado ? "activo" : "";
            })
            .text(function (d) {
                return d.texto;
            });

        var formatos = [i18n.t("export"), 'png', 'jpeg', 'bmp'];

        var select_export = botones.append("select")
            .attr("class", "c3_export");

        select_export.selectAll("opciones")
            .data(formatos)
            .enter()
            .append("option")
            .attr('class', 'export_options')
            .attr('data-id', function (d) {
                return d;
            })
            .attr('value', function (d) {
                return d;
            })
            .text(function (d) {
                return d;
            });

        select_export.on("change", self.e_exportar_click);

        //Estableciendo la fecha inicial acorde con el periodo seleccionado
        self.m_establecer_fecha_inicial();
    }

    self.m_establecer_fecha_inicial = function () {
        var p = d3.select(".c3-periodos .selected");
        if (p[0][0] != null) {
            var tipo = p.attr('data-tipo');
            var cantidad = p.attr('data-value');
            var fechaInicio = self.m_getFechaInicio(tipo, cantidad);
            document.getElementById("inicio").value = formatDate(fechaInicio);
        }
    }

    //Evento click  en un boton del periodo
    self.e_click_periodo = function () {

        //Si da click en el que tengo activo entonces no hago nada
        var a = d3.select(this).select('a.activo');
        if (a[0][0] != null)
            return;

        //Valor del periodo clickeado
        var cantidad = d3.select(this).attr("data-value");

        //Tipo de periodo
        var tipo = d3.select(this).attr("data-tipo");

        //Ultima fecha de los datos a graficar
        var posLastDate = datos.columns[0].length - 1;
        var fechaFin = parseDate(datos.columns[0][posLastDate]);
        var fechaInicio = self.m_getFechaInicio(tipo, cantidad);

        if (m_intervalo_Correcto(fechaInicio, fechaFin)) {

            //Actualizo las fechas en los campos de texto
            document.getElementById("inicio").value = formatDate(fechaInicio);
            document.getElementById("fin").value = formatDate(fechaFin);

            //Desactivo el periodo que estaba seleccionado y Activo el nuevo
            d3.select('.c3-periodos a.activo').classed("activo", false);
            d3.select(this).select('a').classed("activo", true);

            //Si estamos comparando, enteonces recalcular y graficar cargar los nuevos datos
            if (comparando) {
                var datos_a_cargar = [];

                //esta es los datos de comparacion de la 1ra empresa, que es la que se compara con las demas
                var r1 = self.m_calcular_comparacion(datos.columns[1][0], 1, formatDate(fechaInicio), formatDate(fechaFin));

                var index = document.getElementsByClassName("c3_cmp")[0].selectedIndex;
                var r2 = self.m_calcular_comparacion(current_selected_value, (index + 1), formatDate(fechaInicio), formatDate(fechaFin));
                datos_a_cargar.push(r1);
                datos_a_cargar.push(r2);
                var dominio = [fechaInicio, fechaFin];
                chart.zoom(dominio);
                chart2.zoom(dominio);
                chart3.internal.brush.extent(dominio).update();
                chart.load({columns: datos_a_cargar});
            } else {
                //Actualizo la grafica
                m_updateGrafica(fechaInicio, fechaFin);
            }
        }
        else
            throw new Error("No hay datos para este intervalo");
    }

    //Obtiene la fecha de inicio segun el tipo del periodo y la cantidad que se le pase
    self.m_getFechaInicio = function (tipo, cantidad) {

        //Ultima fecha de los datos a graficar
        var posLastDate = datos.columns[0].length - 1;
        var fechaFin = parseDate(datos.columns[0][posLastDate]);

        var fechaInicio = new Date(fechaFin.getTime());

        switch (tipo) {
            case "dia":
                fechaInicio.setDate(fechaFin.getDate() - cantidad);
                break;
            case "mes":
                fechaInicio.setMonth(fechaFin.getMonth() - cantidad);
                break;
            case "anno":
                fechaInicio.setYear(fechaFin.getFullYear() - cantidad);
                break;
            case "hasta_la_fecha":
                var ano = new Date().getFullYear();

                //1er dia del ano
                var dia_uno = new Date(fechaFin.getFullYear(), 0, 1);
                var pos = bisect(datos.columns[0], dia_uno);
                fechaInicio = parseDate(datos.columns[0][pos]);
                break;
        }
        return fechaInicio;
    }

    self.e_update_click = function () {
        var fechaInicio = parseDate(document.getElementById("inicio").value);
        var fechaFin = parseDate(document.getElementById("fin").value);
        if (m_intervalo_Correcto(fechaInicio, fechaFin)) {

            //Desactivo el periodo que estaba seleccionado y Activo el nuevo
            d3.select('.c3-periodos a.activo').classed("activo", false);
            //d3.select(this).select('a').classed("activo", true);

            if (comparando) {

                var datos_a_cargar = [];

                //esta es los datos de comparacion de la 1ra empresa, que es la que se compara con las demas
                var r1 = self.m_calcular_comparacion(datos.columns[1][0], 1, formatDate(fechaInicio), formatDate(fechaFin));

                var index = document.getElementsByClassName("c3_cmp")[0].selectedIndex;
                var r2 = self.m_calcular_comparacion(current_selected_value, (index + 1), formatDate(fechaInicio), formatDate(fechaFin));
                datos_a_cargar.push(r1);
                datos_a_cargar.push(r2);
                var dominio = [fechaInicio, fechaFin];
                chart.zoom(dominio);
                chart2.zoom(dominio);
                chart3.internal.brush.extent(dominio).update();
                chart.load({columns: datos_a_cargar});
            } else
                m_updateGrafica(fechaInicio, fechaFin);
        }
        else
            throw new Error("No hay datos para este intervalo");
    }

    self.m_update = function () {
        if (self.m_fecha_correcta(document.getElementById("inicio").value) && self.m_fecha_correcta(document.getElementById("fin").value)) {
            self.e_update_click();
        }
    }

    self.e_input_enter = function () {
        if (d3.event.keyCode == 13) {
            self.m_update();
        }
        return false;
    }

    //return la pos donde se encuentra esta fecha en los datos originales
    self.m_buscarFecha = function (fecha) {
        return datos.columns[0].indexOf(fecha);
    }

    self.m_calcular_comparacion = function (empresa, posEmpresa, fechaInicio, fechaFin) {
        var result = [empresa];
        var posStart = self.m_buscarFecha(fechaInicio);
        var posEnd = self.m_buscarFecha(fechaFin);

        var baseValue = +datos.columns[posEmpresa][posStart];
        datos.columns[posEmpresa].forEach(function (d, i) {
            if (i > 0) {
                if (i >= posStart && i <= posEnd) {
                    var currentValue = +d;
                    var t = (currentValue / baseValue) - 1;
                    t = +t.toFixed(2);
                    result.push(t);
                } else {
                    result.push(null);
                }
            }
        });
        return result;
    }

    //Restaura la grafica completamente
    self.m_restaurar_grafica = function () {

        //Si estan comparando
        if (comparando) {
            chart.load({
                columns: [
                    datos.columns[1]
                ],
                unload: [current_selected_value]
            });
        } else {
            alert("no estas comparando");
        }
    }

    //Click en el select para comparar
    self.e_comparar_click = function () {

        var last = "";
        if (current_selected_value != "") {
            last = current_selected_value;
        }

        var empresa = this.options[this.selectedIndex].value;
        //console.info("Seleccionado: " + empresa);
        var fechaInicio = parseDate(document.getElementById("inicio").value);
        var fechaFin = parseDate(document.getElementById("fin").value);

        var datos_a_cargar = [];

        if (m_intervalo_Correcto(fechaInicio, fechaFin)) {

            // Si se selecciona cualquier opcion menos (Seleccione)
            if (this.selectedIndex != 0) {
                comparando = true;
                current_selected_value = empresa;

                //esta es los datos de comparacion de la 1ra empresa, que es la que se compara con las demas
                var r1 = self.m_calcular_comparacion(datos.columns[1][0], 1, formatDate(fechaInicio), formatDate(fechaFin));

                var r2 = self.m_calcular_comparacion(empresa, (this.selectedIndex + 1), formatDate(fechaInicio), formatDate(fechaFin));
                datos_a_cargar.push(r1);
                datos_a_cargar.push(r2);
                if (last != "") {
                    chart.load({
                        columns: datos_a_cargar,
                        unload: [last]
                    });
                } else {
                    chart.load({columns: datos_a_cargar});
                }
            } else {
                self.m_restaurar_grafica(fechaInicio, fechaFin);
                current_selected_value = "";
                comparando = false;
            }
        } else
            throw new Error("Intervalo incorrecto");
    }

    //Click para exportar
    self.e_exportar_click = function () {
        var export_format = this.options[this.selectedIndex].value;

        if(export_format==i18n.t("export"))
            return;
        //arreglando propiedades que no funcionan en canvas
       d3.selectAll('.c3 path').attr('fill','transparent').attr('stroke','#000000');
       d3.selectAll('.tick line').attr('stroke','#000000');
       d3.selectAll('line.c3-xgrid').attr('stroke','#aaaaaa').attr('stroke-dasharray','3 3');
       d3.selectAll('line.c3-ygrid').attr('stroke','#aaaaaa').attr('stroke-dasharray','3 3');
       d3.selectAll('.c3-axis-x .tick text').attr('transform','translate(0,10)');
       d3.selectAll('.extent').attr('fill-opacity','0.1');
       d3.selectAll('.c3-chart').each(function(){
           var str = d3.select(this).attr('clip-path');
           var strquitar = str.substring(4, str.indexOf('#'));
           d3.select(this).attr('clip-path',str.replace(strquitar,''));
       });

        html2canvas(document.getElementById('my-c3-chart'), {
            onrendered: function (canvas) {

                var MIME_TYPE = "image/" + export_format;
                var imgURL = canvas.toDataURL(MIME_TYPE);
                var dlLink = document.createElement('a');
                dlLink.download = "chart." + export_format;
                dlLink.href = imgURL;
                dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

                document.body.appendChild(dlLink);
                console.info(dlLink);
                dlLink.click();
                document.body.removeChild(dlLink);
            }
        });
        //restaurando posicion de los textos
        d3.selectAll('.c3-axis-x .tick text').attr('transform','translate(0,0)');
    };

    //Comprueba que la fecha sea correcta
    self.m_fecha_correcta = function (fecha) {
        return isValidDate(fecha);
        function isValidDate(str) {
            var parms = str.split('-');
            var yyyy = parseInt(parms[0], 10);
            var mm = parseInt(parms[1], 10);
            var dd = parseInt(parms[2], 10);
            var date = new Date(yyyy, mm - 1, dd, 0, 0, 0, 0);
            return mm === (date.getMonth() + 1) && dd === date.getDate() && yyyy === date.getFullYear();
        }
    }

    //Crea los componentes y sus eventos
    init();

};

//Dev true si las fechas estan en el intervalo de los datos
//si no se especifica la fechaFin se entiende que es hasta la ultima fecha de los datos
function m_intervalo_Correcto(fechaInicio, fechaFin) {

    var posLastDate = datos.columns[0].length - 1;
    var inicioDatos = parseDate(datos.columns[0][1]);
    var finDatos = parseDate(datos.columns[0][posLastDate]);
    fechaFin || (fechaFin = finDatos);
    return fechaFin > fechaInicio && fechaInicio >= inicioDatos && fechaFin <= finDatos;
}

//Metodo auxiliar hacer algunas y luego actualizar
function m_aux_Update(obj_stock, fechaInicio, fechaFin) {
    document.getElementById("inicio").value = formatDate(fechaInicio);
    document.getElementById("fin").value = formatDate(fechaFin);
    obj_stock.e_update_click();
}

function m_updateGrafica(fechaInicio, fechaFin) {

    var dominio = [fechaInicio, fechaFin];

    //calculando los tickValues para el rango actual
    var ticks = m_generateTicks(fechaInicio, fechaFin);

    //cambiando los tickValues y dando zoom para el 1er Grafico
    chart.internal.config.axis_x_tick_values = ticks;
    chart.zoom(dominio);

    //cambiando los tickValues y dando zoom para el 2do Grafico
    chart2.internal.config.axis_x_tick_values = ticks;
    chart2.zoom(dominio);

    chart3.internal.brush.extent(dominio).update();
}

function m_generateTicks(fechaInicio, fechaFin) {
    var paso = m_calcularPaso(fechaInicio, fechaFin);
    var cant_ticks_posibles = m_cantTicksPosibles() - 1; // -1 porque el 1ro siempre se pone

    var diferencia = fechaFin - fechaInicio;
    diferencia = diferencia / 86400000;

    var cant_ticks_actual = diferencia / paso;
    cant_ticks_actual = +cant_ticks_actual.toFixed();
    cant_ticks_actual += 1;

    //Recalculando el PASO
    var cant_dias = 1;
    var control = cant_ticks_actual;
    if (cant_ticks_actual > cant_ticks_posibles) { // si no hay espacio para los actuales
        control = cant_ticks_posibles;
        cant_dias = diferencia / cant_ticks_posibles;
        cant_dias = +cant_dias.toFixed();
        paso = cant_dias;
    }

    //console.info(paso, cant_ticks_actual, cant_ticks_posibles, cant_dias);

    var tickss = [];
    var primero = fechaInicio * 1;
    var ultimo = fechaFin * 1;
    var dia = 86400000;
    var iterator = primero;
    tickss.push(primero);
    //while (iterator < ultimo) {
    while (control > 0) {
        iterator = iterator + dia * paso;
        tickss.push(iterator);
        control = control - 1;
    }
    return tickss;
}

//Dev la cant de ticks posibles segun el ancho de la grafica
function m_cantTicksPosibles() {
    var width = +d3.select('#' + chart2.element.id + " svg .c3-zoom-rect").attr("width");
    width = +width.toFixed();

    var dateWidth = 85; // 85 es aproximadamente por exceso el ancho que toma una fecha
    // c3-axis c3-axis-x tener estas clases en cuanta para tomar el tamano de la fecha generico

    var cant_ticks = width / dateWidth;
    return +cant_ticks.toFixed();
}

function m_calcularPaso(fechaInicio, fechaFin) {
    var paso = 1;
    var diferencia = fechaFin - fechaInicio;
    diferencia = diferencia / 86400000;

    if (diferencia < 15)
        paso = 1;
    else if (diferencia > 15 && diferencia < 31)
        paso = 2;
    else if (diferencia > 30 && diferencia <= 120) // mas de 1 mes y menos de 4 meses
        paso = 7;
    else if (diferencia > 120 && diferencia <= 365) // mas de 5 meses hasta 1 ano
        paso = 15;
    else //mas de 1 ano
        paso = 30;
    return paso;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <menu>
        <templates_master>
            <title>Templates Master</title>
            <sort_order>71</sort_order>
            <children>
                <easytabs translate="title" module="easytabs">
                    <title>Easy Tabs</title>
                    <sort_order>540</sort_order>
                    <action>adminhtml/easytabs_index/index</action>
                </easytabs>
            </children>
        </templates_master>
    </menu>

    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <tm_easytabs translate="title" module="easytabs">
                                        <title>Easy Tabs Section</title>
                                    </tm_easytabs>
                                </children>
                            </config>
                        </children>
                    </system>
                    <templates_master>
                        <children>
                            <easytabs module="easytabs">
                                <title>Easy Tabs</title>
                                <sort_order>540</sort_order>
                                <action>adminhtml/easytabs_index/index</action>
                            </easytabs>
                        </children>
                    </templates_master>
                </children>
            </admin>
        </resources>
    </acl>
 </config>