text:
namespace supersonic {

class HashJoinTest : public testing::TestWithParam<KeyUniqueness> {
 public:
  void SetUp() {
    builder_1_.AddRow(1, "a");
    builder_2_.AddRow(2, "b");

    builder_12345_.
        AddRow(1, "a").
        AddRow(2, "b").
        AddRow(3, "c").
        AddRow(4, "d").
        AddRow(5, "e");

    builder_654321_.
        AddRow(6, "f").
        AddRow(5, "e").
        AddRow(4, "d").
        AddRow(3, "c").
        AddRow(2, "b").
        AddRow(1, "a");

    builder_2b2b2c_.
        AddRow(2, "b").
        AddRow(2, "b").
        AddRow(2, "c");

    builder_1a1b2a2b_.
        AddRow(1, "a").
        AddRow(1, "b").
        AddRow(2, "a").
        AddRow(2, "b");

    builder_1a1NNaNN_.
        AddRow(1, "a").
        AddRow(1, __).
        AddRow(__, "a").
        AddRow(__, __);

    builder_2b2b2c_x2_output_
        .AddRow(2, "b", 2, "b")
        .AddRow(2, "b", 2, "b")
        .AddRow(2, "b", 2, "c")
        .AddRow(2, "b", 2, "b")
        .AddRow(2, "b", 2, "b")
        .AddRow(2, "b", 2, "c")
        .AddRow(2, "c", 2, "b")
        .AddRow(2, "c", 2, "b")
        .AddRow(2, "c", 2, "c");

    const KeyUniqueness* param = &GetParam();
    if (param != NULL) {
      // Parametrized in TEST_Ps.
      rhs_key_uniqueness_ = *param;
    } else {
      // Const in TEST_Fs
      rhs_key_uniqueness_ = NOT_UNIQUE;
    }
  }

  Operation* CreateOperation(
      JoinType join_type,
      const SingleSourceProjector* lhs_key_selector,
      const SingleSourceProjector* rhs_key_selector,
      const MultiSourceProjector* result_projector,
      Operation* lhs, Operation* rhs) {
    return new HashJoinOperation(
        join_type,
        lhs_key_selector, rhs_key_selector, result_projector,
        rhs_key_uniqueness_,
        lhs, rhs);
  }

  const CompoundSingleSourceProjector* column_0_selector() {
    CompoundSingleSourceProjector* selector =
        new CompoundSingleSourceProjector();
    selector->add(ProjectAttributeAt(0));
    return selector;
  }

  const CompoundSingleSourceProjector* column_01_selector() {
    CompoundSingleSourceProjector* selector =
        new CompoundSingleSourceProjector();
    selector->add(ProjectAttributeAt(0));
    selector->add(ProjectAttributeAt(1));
    return selector;
  }

  const CompoundMultiSourceProjector* all_columns_projector() {
    CompoundMultiSourceProjector* projector =
        new CompoundMultiSourceProjector();
    projector->add(0, ProjectAllAttributes("L."));
    projector->add(1, ProjectAllAttributes("R."));
    return projector;
  }

  TestDataBuilder<INT64, STRING>
    builder_1_, builder_2_,
    builder_12345_, builder_654321_,
    builder_2b2b2c_, builder_1a1b2a2b_, builder_1a1NNaNN_;

  TestDataBuilder<INT64, STRING, INT64, STRING> builder_2b2b2c_x2_output_;

  KeyUniqueness rhs_key_uniqueness_;

 private:
};

INSTANTIATE_TEST_CASE_P(rhs_key_uniqueness,
                        HashJoinTest,
                        testing::Values(UNIQUE, NOT_UNIQUE));

TEST_P(HashJoinTest, _1_InnerJoin_1) {
  OperationTest test;
  test.AddInput(builder_1_.Build());
  test.AddInput(builder_1_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .Build());
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _1_LeftOuterJoin_1) {
  OperationTest test;
  test.AddInput(builder_1_.Build());
  test.AddInput(builder_1_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .Build());
  test.Execute(CreateOperation(LEFT_OUTER, column_0_selector(),
                               column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _1_InnerJoin_2) {
  OperationTest test;
  test.AddInput(builder_1_.Build());
  test.AddInput(builder_2_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .Build());
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _1_LeftOuterJoin_2) {
  OperationTest test;
  test.AddInput(builder_1_.Build());
  test.AddInput(builder_2_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", __, __)
                         .Build());
  test.Execute(CreateOperation(LEFT_OUTER, column_0_selector(),
                               column_0_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _12345_InnerJoin_654321) {
  OperationTest test;
  test.AddInput(builder_12345_.Build());
  test.AddInput(builder_654321_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .AddRow(2, "b", 2, "b")
                         .AddRow(3, "c", 3, "c")
                         .AddRow(4, "d", 4, "d")
                         .AddRow(5, "e", 5, "e")
                         .Build());
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _654321_InnerJoin_12345) {
  OperationTest test;
  test.AddInput(builder_654321_.Build());
  test.AddInput(builder_12345_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(5, "e", 5, "e")
                         .AddRow(4, "d", 4, "d")
                         .AddRow(3, "c", 3, "c")
                         .AddRow(2, "b", 2, "b")
                         .AddRow(1, "a", 1, "a")
                         .Build());
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

// TODO(user): Add more tests for left join.
TEST_P(HashJoinTest, _654321_LeftOuterJoin_12345) {
  OperationTest test;
  test.AddInput(builder_654321_.Build());
  test.AddInput(builder_12345_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(6, "f", __, __)
                         .AddRow(5, "e", 5, "e")
                         .AddRow(4, "d", 4, "d")
                         .AddRow(3, "c", 3, "c")
                         .AddRow(2, "b", 2, "b")
                         .AddRow(1, "a", 1, "a")
                         .Build());
  test.Execute(CreateOperation(LEFT_OUTER, column_0_selector(),
                               column_0_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, _12345_InnerJoin_2b2b2c) {
  OperationTest test;
  test.AddInput(builder_12345_.Build());
  test.AddInput(builder_2b2b2c_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(2, "b", 2, "b")
                         .AddRow(2, "b", 2, "b")
                         .AddRow(2, "b", 2, "c")
                         .Build());
  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, _12345_LeftOuterJoin_2b2b2c) {
  OperationTest test;
  test.AddInput(builder_12345_.Build());
  test.AddInput(builder_2b2b2c_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", __, __)
                         .AddRow(2, "b", 2, "b")
                         .AddRow(2, "b", 2, "b")
                         .AddRow(2, "b", 2, "c")
                         .AddRow(3, "c", __, __)
                         .AddRow(4, "d", __, __)
                         .AddRow(5, "e", __, __)
                         .Build());
  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);
  test.Execute(CreateOperation(LEFT_OUTER, column_0_selector(),
                               column_0_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, _2b2b2c_InnerJoin_2b2b2c) {
  OperationTest test;
  test.AddInput(builder_2b2b2c_.Build());
  test.AddInput(builder_2b2b2c_.Build());
  test.SetExpectedResult(builder_2b2b2c_x2_output_.Build());
  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, _2b2b2c_InnerJoin_2b2b2cWithSpyTransform) {
  Operation* lhs = builder_2b2b2c_.Build();
  Operation* rhs = builder_2b2b2c_.Build();

  scoped_ptr<Cursor> expected_result(builder_2b2b2c_x2_output_.BuildCursor());

  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);

  scoped_ptr<Operation> hash_join_operation(
      CreateOperation(INNER, column_0_selector(), column_0_selector(),
                      all_columns_projector(),
                      lhs, rhs));

  scoped_ptr<Cursor> hash_join(
      SucceedOrDie(hash_join_operation->CreateCursor()));

  scoped_ptr<CursorTransformerWithSimpleHistory> spy_transformer(
      PrintingSpyTransformer());
  hash_join->ApplyToChildren(spy_transformer.get());
  hash_join.reset(spy_transformer->Transform(hash_join.release()));

  EXPECT_CURSORS_EQUAL(expected_result.release(), hash_join.release());
}

TEST_P(HashJoinTest, _1a1b2a2b_InnerJoin_1a1b2a2b) {
  OperationTest test;
  test.AddInput(builder_1a1b2a2b_.Build());
  test.AddInput(builder_1a1b2a2b_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .AddRow(1, "b", 1, "b")
                         .AddRow(2, "a", 2, "a")
                         .AddRow(2, "b", 2, "b")
                         .Build());
  test.Execute(CreateOperation(INNER, column_01_selector(),
                               column_01_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, _12345_InnerJoin_5k_Rows) {
  // The input data is prepared in such a way that each lhs row matches more
  // than Cursor::kDefaultRowCount rhs rows. This way splitting and piecewise
  // returning of big results in fixed-size windows is exercised, both in the
  // inner cursor (returned from LookupIndex) and in HashJoinCursor.
  TestDataBuilder<INT64, STRING> builder_5k_rows_;
  for (int i = 0; i < 1100; i++) {
    builder_5k_rows_.
        AddRow(1, "a").
        AddRow(2, "b").
        AddRow(3, "c").
        AddRow(4, "d").
        AddRow(5, "e");
    }

  OperationTest test;
  test.AddInput(builder_12345_.Build());
  test.AddInput(builder_5k_rows_.Build());
  test.SetInputViewSizes(2000);
  test.SetResultViewSizes(2000);

  TestDataBuilder<INT64, STRING, INT64, STRING> expected_output_builder;
  char buf[2] = {0, 0};
  for (int i = 1; i <= 5; i++) {
    buf[0] = 'a' + i - 1;
    for (int j_unused = 0; j_unused < 1100; j_unused++)
      expected_output_builder.AddRow(i, buf, i, buf);
  }
  test.SetExpectedResult(expected_output_builder.Build());
  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);
  test.Execute(CreateOperation(INNER, column_0_selector(), column_0_selector(),
                               all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _1a1NNaNN_InnerJoin_1a1NNaNN) {
  OperationTest test;
  test.AddInput(builder_1a1NNaNN_.Build());
  test.AddInput(builder_1a1NNaNN_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .Build());
  test.Execute(CreateOperation(INNER, column_01_selector(),
                               column_01_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_P(HashJoinTest, _1a1NNaNN_LeftOuterJoin_1a1NNaNN) {
  OperationTest test;
  test.AddInput(builder_1a1NNaNN_.Build());
  test.AddInput(builder_1a1NNaNN_.Build());
  test.SetExpectedResult(TestDataBuilder<INT64, STRING, INT64, STRING>()
                         .AddRow(1, "a", 1, "a")
                         .AddRow(1, __, __, __)
                         .AddRow(__, "a", __, __)
                         .AddRow(__, __, __, __)
                         .Build());
  test.Execute(CreateOperation(LEFT_OUTER, column_01_selector(),
                               column_01_selector(), all_columns_projector(),
                               test.input_at(0), test.input_at(1)));
}

TEST_F(HashJoinTest, HashJoinShallowCopiesStrings) {
  const int kSize = 100;
  TestDataBuilder<STRING> builder;
  for (int i = 0; i < kSize; i++) {
    builder.AddRow("supersonic");
  }
  OperationTest test;
  test.AddInput(builder.Build());
  test.AddInput(builder.Build());
  test.SetInputViewSizes(25);
  test.SetResultViewSizes(25);
  TestDataBuilder<STRING, STRING> expected_output_builder;
  for (int i = 0; i < kSize * kSize; i++) {
    expected_output_builder.AddRow("supersonic", "supersonic");
  }
  test.SetExpectedResult(expected_output_builder.Build());
  ASSERT_EQ(NOT_UNIQUE, rhs_key_uniqueness_);
  Operation* operation = CreateOperation(INNER, column_0_selector(),
                                         column_0_selector(),
                                         all_columns_projector(),
                                         test.input_at(0), test.input_at(1));
  // The limit should be big enough for the index, but not enough for (kSize *
  // kSize) copies of the string "supersonic".
  MemoryLimit memory_limit(9 * kSize * kSize);
  operation->SetBufferAllocator(&memory_limit, false);
  test.Execute(operation);
}

TEST_F(HashJoinTest, TransformTest) {
  Operation* lhs = builder_2b2b2c_.Build();
  Operation* rhs = builder_2b2b2c_.Build();

  scoped_ptr<Operation> hash_join_operation(
      CreateOperation(INNER, column_0_selector(), column_0_selector(),
                      all_columns_projector(),
                      lhs, rhs));

  scoped_ptr<Cursor> hash_join(
      SucceedOrDie(hash_join_operation->CreateCursor()));

  scoped_ptr<CursorTransformerWithSimpleHistory> spy_transformer(
      PrintingSpyTransformer());
  hash_join->ApplyToChildren(spy_transformer.get());

  EXPECT_EQ(2, spy_transformer->GetHistoryLength());
}

}  // namespace supersonic


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>AlphaControl: Examples</title>
  <link rel="stylesheet" type="text/css" href="/examples/base.css"/>

AlphaControl: Examples

UI

Notification

Window

Alert

Picker

Autocompleter

Sortable

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace UniSharp\LaravelFilemanager\Controllers;

use Illuminate\Support\Facades\Storage;
use UniSharp\LaravelFilemanager\Events\FileIsMoving;
use UniSharp\LaravelFilemanager\Events\FileWasMoving;
use UniSharp\LaravelFilemanager\Events\FolderIsMoving;
use UniSharp\LaravelFilemanager\Events\FolderWasMoving;

class ItemsController extends LfmController
{
    /**
     * Get the images to load for a selected folder.
     *
     * @return mixed
     */
    public function getItems()
    {
        $currentPage = self::getCurrentPageFromRequest();

        $perPage = $this->helper->getPaginationPerPage();
        $items = array_merge($this->lfm->folders(), $this->lfm->files());

        return [
            'items' => array_map(function ($item) {
                return $item->fill()->attributes;
            }, array_slice($items, ($currentPage - 1) * $perPage, $perPage)),
            'paginator' => [
                'current_page' => $currentPage,
                'total' => count($items),
                'per_page' => $perPage,
            ],
            'display' => $this->helper->getDisplayMode(),
            'working_dir' => $this->lfm->path('working_dir'),
        ];
    }

    public function move()
    {
        $items = request('items');
        $folder_types = array_filter(['user', 'share'], function ($type) {
            return $this->helper->allowFolderType($type);
        });
        return view('laravel-filemanager::move')
            ->with([
                'root_folders' => array_map(function ($type) use ($folder_types) {
                    $path = $this->lfm->dir($this->helper->getRootFolder($type));

                    return (object) [
                        'name' => trans('laravel-filemanager::lfm.title-' . $type),
                        'url' => $path->path('working_dir'),
                        'children' => $path->folders(),
                        'has_next' => ! ($type == end($folder_types)),
                    ];
                }, $folder_types),
            ])
            ->with('items', $items);
    }

    public function domove()
    {
        $target = $this->helper->input('goToFolder');
        $items = $this->helper->input('items');

        foreach ($items as $item) {
            $old_file = $this->lfm->pretty($item);
            $is_directory = $old_file->isDirectory();

            $file = $this->lfm->setName($item);

            if (!Storage::disk($this->helper->config('disk'))->exists($file->path('storage'))) {
                abort(404);
            }

            $old_path = $old_file->path();

            if ($old_file->hasThumb()) {
                $new_file = $this->lfm->setName($item)->thumb()->dir($target);
                if ($is_directory) {
                    event(new FolderIsMoving($old_file->path(), $new_file->path()));
                } else {
                    event(new FileIsMoving($old_file->path(), $new_file->path()));
                }
                $this->lfm->setName($item)->thumb()->move($new_file);
            }
            $new_file = $this->lfm->setName($item)->dir($target);
            $this->lfm->setName($item)->move($new_file);
            if ($is_directory) {
                event(new FolderWasMoving($old_path, $new_file->path()));
            } else {
                event(new FileWasMoving($old_path, $new_file->path()));
            }
        };

        return parent::$success_response;
    }

    private static function getCurrentPageFromRequest()
    {
        $currentPage = (int) request()->get('page', 1);
        $currentPage = $currentPage < 1 ? 1 : $currentPage;

        return $currentPage;
    }
}


text:
class UpcomingWeddingsController{
    constructor(StatsService){
        'ngInject';

        this.stats = StatsService;
        //
    }

    $onInit(){
        this.getUpcomingWeddings();
    }

    getUpcomingWeddings() {
        this.stats.all('upcomingWeddings').get('').then((response) => {
            this.weddings = response.data.weddings;
        });
    }
}

export const UpcomingWeddingsComponent = {
    templateUrl: './views/app/components/upcoming-weddings/upcoming-weddings.component.html',
    controller: UpcomingWeddingsController,
    controllerAs: 'vm',
    bindings: {}
}


text:
package phases

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	"k8s.io/kubernetes/cmd/kubeadm/app/cmd/phases/workflow"
	kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
	"k8s.io/kubernetes/cmd/kubeadm/app/features"
	"k8s.io/kubernetes/cmd/kubeadm/app/phases/controlplane"
	auditutil "k8s.io/kubernetes/cmd/kubeadm/app/util/audit"
	"k8s.io/kubernetes/pkg/util/normalizer"
)

var (
	controlPlaneExample = normalizer.Examples(`
		# Generates all static Pod manifest files for control plane components,
		# functionally equivalent to what is generated by kubeadm init.
		kubeadm init phase control-plane

		# Generates all static Pod manifest files using options read from a configuration file.
		kubeadm init phase control-plane --config config.yaml
		`)

	controlPlanePhaseProperties = map[string]struct {
		name  string
		short string
	}{
		kubeadmconstants.KubeAPIServer: {
			name:  "apiserver",
			short: getPhaseDescription(kubeadmconstants.KubeAPIServer),
		},
		kubeadmconstants.KubeControllerManager: {
			name:  "controller-manager",
			short: getPhaseDescription(kubeadmconstants.KubeControllerManager),
		},
		kubeadmconstants.KubeScheduler: {
			name:  "scheduler",
			short: getPhaseDescription(kubeadmconstants.KubeScheduler),
		},
	}
)

type controlPlaneData interface {
	Cfg() *kubeadmapi.InitConfiguration
	KubeConfigDir() string
	ManifestDir() string
}

func getPhaseDescription(component string) string {
	return fmt.Sprintf("Generates the %s static Pod manifest", component)
}

// NewControlPlanePhase creates a kubeadm workflow phase that implements bootstrapping the control plane.
func NewControlPlanePhase() workflow.Phase {
	phase := workflow.Phase{
		Name:    "control-plane",
		Short:   "Generates all static Pod manifest files necessary to establish the control plane",
		Example: controlPlaneExample,
		Phases: []workflow.Phase{
			newControlPlaneSubPhase(kubeadmconstants.KubeAPIServer),
			newControlPlaneSubPhase(kubeadmconstants.KubeControllerManager),
			newControlPlaneSubPhase(kubeadmconstants.KubeScheduler),
		},
		Run: runControlPlanePhase,
	}
	return phase
}

func newControlPlaneSubPhase(component string) workflow.Phase {
	phase := workflow.Phase{
		Name:  controlPlanePhaseProperties[component].name,
		Short: controlPlanePhaseProperties[component].short,
		Run:   runControlPlaneSubPhase(component),
	}
	return phase
}

func runControlPlanePhase(c workflow.RunData) error {
	data, ok := c.(controlPlaneData)
	if !ok {
		return errors.New("control-plane phase invoked with an invalid data struct")
	}

	fmt.Printf("[control-plane] Using manifest folder %q\n", data.ManifestDir())
	return nil
}

func runControlPlaneSubPhase(component string) func(c workflow.RunData) error {
	return func(c workflow.RunData) error {
		data, ok := c.(controlPlaneData)
		if !ok {
			return errors.New("control-plane phase invoked with an invalid data struct")
		}
		cfg := data.Cfg()

		// special case to handle audit policy for the API server
		if component == kubeadmconstants.KubeAPIServer && features.Enabled(cfg.FeatureGates, features.Auditing) {
			// Setup the AuditPolicy (either it was passed in and exists or it wasn't passed in and generate a default policy)
			if cfg.AuditPolicyConfiguration.Path != "" {
				// TODO(chuckha) ensure passed in audit policy is valid so users don't have to find the error in the api server log.
				if _, err := os.Stat(cfg.AuditPolicyConfiguration.Path); err != nil {
					return fmt.Errorf("error getting file info for audit policy file %q [%v]", cfg.AuditPolicyConfiguration.Path, err)
				}
			} else {
				cfg.AuditPolicyConfiguration.Path = filepath.Join(data.KubeConfigDir(), kubeadmconstants.AuditPolicyDir, kubeadmconstants.AuditPolicyFile)
				if err := auditutil.CreateDefaultAuditLogPolicy(cfg.AuditPolicyConfiguration.Path); err != nil {
					return fmt.Errorf("error creating default audit policy %q [%v]", cfg.AuditPolicyConfiguration.Path, err)
				}
			}
		}

		fmt.Printf("[control-plane] creating static Pod manifest for %q\n", component)
		if err := controlplane.CreateStaticPodFiles(data.ManifestDir(), cfg, component); err != nil {
			return err
		}
		return nil
	}
}


text:
* Added concordance analysis at strain level.

### 2015/11

* JU312 reassigned to JU311 isotype. Was previously given its own isotype based on inadequite coverage.
* Added 29 new isotypes


text:
Lava.define(
'Lava.widget.DocPage',
/**
 * This file is not the best example of what you can write with Lava framework, sorry for that.
 * When I have more time - I will rewrite it.
 * Author.
 */
{

	Extends: 'Lava.widget.Standard',
	name: 'page',

	_properties: {
		is_loading: false,
		// Data for navigation trees
		/** @type {Lava.system.Enumerable} */
		api_tree: null,
		firestorm_api_tree: null,
		reference_nav_tree: null,
		tutorials_nav_tree: null
	},

	_role_handlers: {
		nav_tabs: '_handleNavTabs'
	},

	_modifiers: {
		render_link: '_renderLink'
	},

	// DOM element with default promotional text
	_promo_text_element: null,
	_tabs_widget: null, // registered via role
	_color_animation: null,
	_scroll_animation: null,
	_current_scroll_target_attribute: null,
	_hashchange_listener: null,
	_active_tab_changed_listener: null,

	_items_by_name_hashes: {api: {}, reference: {}, tutorials: {}}, // used to find items from navigation trees by hash
	// tab_name => item, that is currently loaded into the tab (tutorial, reference, or class/object)
	_tab_items: {},
	// widget, which renders the active tab item. needs refactoring.
	_tab_content_widgets: {},
	// the name of tab, which is owner of the widget with current content
	_active_tab_name: 'reference',
	// where to scroll after request success
	_request_scroll_target: "",
	// parsed location for current request
	_request_location_data: null,
	_request: null,

	ALLOWED_HASH_KEYS: ["tab", "member", "event", "config", "property"], // "tab" is handled separately
	TAB_NAMES: ['tutorials', 'reference', 'api'],
	PAGE_TYPE_TO_TAB_MAP: {
		tutorial: 'tutorials',
		reference: 'reference',
		object: 'api',
		"class": 'api'
	},
	// directories for page content files for each page type
	JSON_DIRS: {
		object: '/www/api/',
		'class': '/www/api/',
		reference: '/www/reference/',
		tutorial: '/www/tutorials/'
	},
	BASE_PAGE_PATH: "/www/doc.html",
	EXT_PAGE_PATH: "/www/doc/",

	init: function(config, widget, parent_view, template, properties) {

		this._color_animation = new Lava.animation.Standard({
			duration: 1500,
			transition: function(x) {
				return (x < 0.5) ? Lava.transitions.inOutCubic(x*2) : Lava.transitions.inOutCubic(1 - (x - 0.5)*2);
			},
			animators: [
				{type: 'Color', from: [255, 255, 255], to: [255, 128, 128], property: 'background-color'}
			]
		}, null);

		this._properties.api_tree = Examples.makeLive(api_tree_source);
		this._prepareTree(this._items_by_name_hashes.api, this._properties.api_tree, 'api', null);
		this._properties.firestorm_api_tree = Examples.makeLive(firestorm_api_tree_source);
		this._prepareTree(this._items_by_name_hashes.api, this._properties.firestorm_api_tree, 'api', null);
		this._properties.reference_nav_tree = Examples.makeLive(reference_nav_tree_source);
		this._prepareTree(this._items_by_name_hashes.reference, this._properties.reference_nav_tree, 'reference', null);
		this._properties.tutorials_nav_tree = Examples.makeLive(tutorials_nav_tree_source);
		this._prepareTree(this._items_by_name_hashes.tutorials, this._properties.tutorials_nav_tree, 'tutorials', null);

		this._tab_content_widgets.api = Lava.createWidget('ClassContent');
		this._items_by_name_hashes.api['Widgets'] = new Lava.mixin.Properties({
			type: 'object', name: 'Widgets', title: 'Widgets', tab_name: 'api', parent: null, file_path: this.JSON_DIRS["object"] + 'Widgets.js'
		});
		this._items_by_name_hashes.api['Support'] = new Lava.mixin.Properties({
			type: 'object', name: 'Support', title: 'Support', tab_name: 'api', parent: null, file_path: this.JSON_DIRS["object"] + 'Support.js'
		});

		this.Standard$init(config, widget, parent_view, template, properties);

		this._hashchange_listener = Lava.Core.addGlobalHandler('hashchange', this._onHashChange, this);
		Lava.Core.addGlobalHandler("popstate", this._onPopState, this);
		Lava.Core.addGlobalHandler("click", this._onPageClick, this);

	},

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// main logic

	injectIntoExistingElement: function(element) {

		this.Standard$injectIntoExistingElement(element);

		// load initial item
		var hash_segments,
			location_hash = window.location.hash,
			location_path = window.location.pathname;

		if (typeof(page_json) != "undefined") {
			var path_data = this._parseLocationPath(location_path);
			if (path_data.item) {
				this._initItem(page_json, path_data.item);
			}
		}

		if (location_hash && location_path == this.BASE_PAGE_PATH) { // select tab on root
			hash_segments = location_hash.substr(1).split("=");

			if (hash_segments.length != 2 || hash_segments[0] != "tab") {
				this._tryRedirect(location_hash);
				return;
			}

			if (hash_segments[0] == "tab" && this.TAB_NAMES.indexOf(hash_segments[1]) != -1) {
				this._active_tab_name = hash_segments[1];
			}
		}

		if (location_path != this.BASE_PAGE_PATH) { // not on root
			this._loadItemByLocation(location_path, location_hash);
		}

	},

	_loadItem: function(item) {

		var self = this;
		this.set('is_loading', true);

		this._request = new SafeRequest({
			url: item.get("file_path"),
			method: 'GET',
			onSuccess: function(text) {
				self._onRequestSuccess(text, item);
			},
			onFailure: function() {
				self._onRequestFailure(item);
			}
		});

		this._request.send();
		Lava.refreshViews();

	},

	_onRequestSuccess: function(text, item) {

		this.set('is_loading', false);
		this._request = null;

		var page_json = eval('(' + text.substr("var page_json = ".length) + ')');
		this._initItem(page_json, item);
		this._showItem(item);

		this._scrollToTarget(this._request_scroll_target);

		Lava.suspendListener(this._hashchange_listener);
		this._setLocation(this._request_location_data.pathname, this._request_location_data.hash);
		Lava.resumeListener(this._hashchange_listener);

	},

	_onRequestFailure: function(item) {

		this.set('is_loading', false);
		this._request = null;
		Lava.refreshViews();

	},

	// try redirect from old URL scheme, when everything was in hashes
	_tryRedirect: function(location_hash) {

		var pairs = location_hash.substr(1).split(";"),
			pair,
			i = 0,
			count = pairs.length,
			item_href = null,
			item_hash = "";

		for (; i < count; i++) {
			pair = pairs[i].split("=");
			if (pair.length == 2) {
				if (
					(pair[0] in this.PAGE_TYPE_TO_TAB_MAP)
					&& (pair[1] in this._items_by_name_hashes[this.PAGE_TYPE_TO_TAB_MAP[pair[0]]])
				) {
					item_href = this._renderLink(pair[0], pair[1]);
				}
				if (this.ALLOWED_HASH_KEYS.indexOf(pair[0]) != -1) {
					item_hash = "#" + pair[0] + "=" + pair[1];
				}
			}
		}

		if (item_href) {
			window.location.href = item_href + item_hash;
		} else {
			window.alert("Invalid URL");
		}

	},

	_onPopState: function(event_name, event_object) {

		this._loadItemByLocation(window.location.pathname, window.location.hash);

	},

	_onPageClick: function(event_name, event_object) {

		var target = event_object.target,
			href;

		if (target && Firestorm.Element.getTagName(target) == "a") {

			href = Firestorm.Element.getProperty(target, "href");

			if (
				href
				&& href != "#"
				&& (href[0] == "#" || this._startsWith(href, this.BASE_PAGE_PATH) || this._startsWith(href, this.EXT_PAGE_PATH))
			) {

				if (this._startsWith(href, this.BASE_PAGE_PATH + "#tab=")) {

					this._doHashAction(href.substr(href.indexOf("#")));

				} else if (href[0] == "#") {

					this._doHashAction(href);

				} else if (this._request == null) {

					if (href.indexOf("#") == -1) {
						this._loadItemByLocation(href, "");
					} else {
						this._loadItemByLocation(href.substr(0, href.indexOf("#")), href.substr(href.indexOf("#")));
					}
				}

				event_object.preventDefault();

			}

		}

	},

	_loadItemByLocation: function(location_path, location_hash) {

		var path_data = this._parseLocationPath(location_path),
			hash_data = this._parseLocationHash(location_hash);

		path_data.pathname = location_path;
		path_data.hash = location_hash;

		if (path_data.is_invalid) {

			window.alert('Invalid URL');

		} else {

			var item = path_data['item'];

			if (item) {

				if (item.get('is_loaded')) {

					this._showItem(item);
					hash_data.scroll_target && this._scrollToTarget(hash_data.scroll_target);
					this._setLocation(location_path, location_hash);

				} else {

					this._request_scroll_target = hash_data.scroll_target;
					this._request_location_data = path_data;
					this._loadItem(item);

				}

			}

		}

	},

	_parseLocationPath: function(pathname) {

		var path_segments,
			tab_name,
			item_name,
			name_group,
			result = {
				item: null,
				is_invalid: false
			};

		if (this._startsWith(pathname, this.EXT_PAGE_PATH)) {
			path_segments = pathname.substr(this.EXT_PAGE_PATH.length).split("/");
			if (
				path_segments.length != 2
				|| !(path_segments[0] in this.PAGE_TYPE_TO_TAB_MAP)
			) {
				result.is_invalid = true;
			} else {
				tab_name = this.PAGE_TYPE_TO_TAB_MAP[path_segments[0]];
				name_group = this._items_by_name_hashes[tab_name];
				item_name = path_segments[1].substr(0, path_segments[1].length - ".html".length);
				if (!name_group || !name_group[item_name]) {
					result.is_invalid = true;
				} else {
					result['item'] = name_group[item_name];
				}
			}
		}

		return result;

	},

	_parseLocationHash: function(hash_string) {

		var hash_segments,
			result = {
				scroll_target: null,
				tab: null,
				is_invalid: false
			};

		if (hash_string) {
			hash_segments = hash_string.substr(1).split('=');
			if (
				hash_segments.length != 2
				|| this.ALLOWED_HASH_KEYS.indexOf(hash_segments[0]) == -1
				|| (hash_segments[0] == 'tab' && this.TAB_NAMES.indexOf(hash_segments[1]) != -1)
			) {
				result.is_invalid = true;
			} else if (hash_segments[0] == 'tab') {
				result['tab'] = hash_segments[1];
			} else {
				result['scroll_target'] = hash_segments[0] + ':' + hash_segments[1];
			}
		}

		return result;

	},

	_showItem: function(item) {

		var content_area = Lava.view_manager.getViewById('content_area').getContainer().getDOMElement(),
			item_tab = item.get('tab_name'),
			is_item_changed = (this._tab_items[item_tab] != item),
			is_tab_changed = (this._active_tab_name != item_tab),
			active_content_widget = this._tab_content_widgets[this._active_tab_name],
			tab_content_widget = this._tab_content_widgets[item_tab];

		this._hidePromoText();
		this._setSelectedTab(item_tab);
		if (is_tab_changed || (is_item_changed && item_tab != 'api')) {
			if (active_content_widget && active_content_widget.isInDOM()) active_content_widget.remove();
		}

		if (is_item_changed) {

			if (item_tab == 'api') {
				tab_content_widget.clearMetaStorage();
				tab_content_widget.set('descriptor', item);
				tab_content_widget.set('extended_descriptor', item.get('extended_descriptor'));
			} else {
				tab_content_widget && tab_content_widget.destroy();
				tab_content_widget = new Lava.widget.Standard(item.get('widget_config'));
				this._tab_content_widgets[item_tab] = tab_content_widget;
			}

			if (this._tab_items[item_tab]) {
				this._tab_items[item_tab].set('is_selected', false);
			}
			this._tab_items[item_tab] = item;
			if (item_tab == "api") {
				this._collapseTree(this._properties.api_tree);
			}
			this._expandNodeParents(item);
			item.set('is_selected', true);

		}

		if (is_item_changed || is_tab_changed) {
			if (tab_content_widget && !tab_content_widget.isInDOM()) tab_content_widget.inject(content_area, 'Top');
			if (!tab_content_widget) this._showPromoText();
		}
		Lava.refreshViews();

	},

	_doHashAction: function(hash) {

		var segments = hash.substr(1).split("=");

		if (hash) {

			if (
				segments.length != 2
				|| this.ALLOWED_HASH_KEYS.indexOf(segments[0]) == -1
				|| (segments[0] == "tab" && this.TAB_NAMES.indexOf(segments[1]) == -1)
			) {

				//window.alert("Invalid URL");

			} else if (this._request == null) {

				if (segments[0] == "tab") {

					this._switchTab(segments[1]);

				} else {

					this._scrollToTarget(segments[0] + ':' + segments[1]);

				}

			}

		}

	},

	_onHashChange: function(event_name, event) {

		this._doHashAction(window.location.hash);

	},

	_setLocation: function(path, hash) {
		try {
			if (window.location.pathname != path || window.location.hash != hash) {
				window.history.pushState({}, "", path + hash);
			}
		} catch (e) {}
	},

	// end
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// supporting

	_initItem: function(page_json, short_descriptor) {

		var type = short_descriptor.get('type'),
			extended_descriptor,
			events,
			support_objects,
			i = 0,
			count;

		short_descriptor.set('is_loaded', true);

		if (type == 'class' || type == 'object') {

			extended_descriptor = page_json;
			events = extended_descriptor.events;
			support_objects = extended_descriptor.support_objects;

			if (extended_descriptor.method_chain) this._initItemChain(extended_descriptor.method_chain);
			//if (extended_descriptor.member_chain) this._initItemChain(extended_descriptor.member_chain);

			if (events) {
				for (i = 0, count = events.length; i < count; i++) {
					events[i].guid = Lava.guid++;
					events[i] = new Lava.mixin.Properties(events[i]);
				}
			}

			if (support_objects) {
				for (i = 0, count = support_objects.length; i < count; i++) {
					if (support_objects[i].method_chain) this._initItemChain(support_objects[i].method_chain);
				}
			}

			short_descriptor.set('extended_descriptor', extended_descriptor);

		} else if (type == 'reference' || type == 'tutorial') {

			short_descriptor.set('widget_config', page_json);

		} else {

			Lava.t('unknown item type: ' + type);

		}

	},

	_scrollToTarget: function(scroll_target_attribute) {

		var self = this,
			content_area,
			scroll_target;

		if (scroll_target_attribute /*&& this._current_scroll_target_attribute != scroll_target_attribute*/) {

			// @todo
			//this._current_scroll_target_attribute = scroll_target_attribute;
			window.setTimeout(function(){

				content_area = Lava.view_manager.getViewById('content_area').getContainer().getDOMElement();
				scroll_target = Firestorm.Element.selectElements(content_area, '*[data-scroll-name=' + scroll_target_attribute + ']')[0];
				if (scroll_target) {

					if (this._scroll_animation) {
						this._scroll_animation.stop();
					}

					this._scroll_animation = new Fx.Scroll(window, {duration: 1000}); // @todo MooTools dependency
					this._scroll_animation.addEvent('complete', function(){
						self._color_animation.finish(); // finish with the old target
						self._color_animation.setTarget(scroll_target);
						self._color_animation.start();
						self._scroll_animation = null;
					});
					this._scroll_animation.toElementCenter(scroll_target);

				}

			}, 0);

		} else {

			window.scrollTo(0,0);

		}

	},

	_handleNavTabs: function(tabs_widget) {

		this._tabs_widget = tabs_widget;
		this._switchTab(this._active_tab_name);
		this._active_tab_changed_listener = tabs_widget.onPropertyChanged('active_tab', this._onTabSelected, this);

	},

	_switchTab: function(tab_name) {

		if (this._tabs_widget) {
			var tab = this._tabs_widget.getTabObjects()[this.TAB_NAMES.indexOf(tab_name)];
			tab.set('is_active', true);
		}

	},

	// select tab in the tree without touching the content area
	_setSelectedTab: function(tab_name) {

		if (this._tabs_widget) {
			Lava.suspendListener(this._active_tab_changed_listener);
			this._switchTab(tab_name);
			Lava.resumeListener(this._active_tab_changed_listener);
		}
		this._active_tab_name = tab_name;

	},

	_onTabSelected: function(tabs_widget) {

		var new_tab_name = tabs_widget.get('active_tab').get('name'),
			new_tab_widget = this._tab_content_widgets[new_tab_name],
			current_active_widget = this._tab_content_widgets[this._active_tab_name],
			item = this._tab_items[new_tab_name];

		if (this._request == null && new_tab_name != this._active_tab_name) {

			if (item) {
				this._hidePromoText();
				this._setLocation(this._renderLink(item.get("type"), item.get("name")), "");
			} else {
				this._setLocation(this.BASE_PAGE_PATH + "#tab=" + new_tab_name, "");
			}
			current_active_widget && current_active_widget.isInDOM() && current_active_widget.remove();
			new_tab_widget && !new_tab_widget.isInDOM() && new_tab_widget.inject(
				Lava.view_manager.getViewById('content_area').getContainer().getDOMElement(),
				'Top'
			);
			if (!item) this._showPromoText();
			this._active_tab_name = new_tab_name;

		}

	},

	// end
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// utility

	_startsWith: function(string, prefix) {
		return string.substr(0, prefix.length) == prefix;
	},

	// modifier
	_renderLink: function(type, name, hash) {

		return this.EXT_PAGE_PATH + type + "/" + name + ".html" + (hash ? ("#" + hash) : "");

	},

	/**
	 * Set "parent" and "tab_name" for each record in the tree
	 * Store items into `hash` as `hash[item_name] => item`
	 */
	_prepareTree: function(hash, collection, tab_name, parent) {

		var children,
			self = this;

		collection.each(function(record) {
			record.set('parent', parent);
			record.set('tab_name', tab_name);
			if (record.get('type') != 'folder') {
				hash[record.get('name')] = record;
				record.set("file_path", self.JSON_DIRS[record.get('type')] + record.get('name') + '.js');
			}
			children = record.get('children');
			if (children) {
				self._prepareTree(hash, children, tab_name, record);
			}
		})

	},

	_initItemChain: function(chain) {

		var group_count = chain.length,
			group_index = 0,
			descriptors,
			i,
			count;

		for (; group_index < group_count; group_index++) {
			descriptors = chain[group_index].descriptors;
			for (i = 0, count = descriptors.length; i < count; i++) {
				descriptors[i].guid = Lava.guid++;
				descriptors[i] = new Lava.mixin.Properties(descriptors[i]);
			}
		}

	},

	_hidePromoText: function() {
		if (!this._promo_text_element) {
			this._promo_text_element = Firestorm.getElementById('default_text');
		}
		this._promo_text_element && Firestorm.Element.remove(this._promo_text_element);
	},

	_showPromoText: function() {
		this._promo_text_element && Firestorm.Element.insertElementBefore(
			Lava.view_manager.getViewById('content_area').getContainer().getDOMElement(),
			this._promo_text_element
		);
	},

	_collapseTree: function(nodes) {

		var self = this;
		nodes.each(function(node) {
			if (node.get("children")) {
				self._collapseTree(node.get("children"));
				node.set("is_expanded", false);
			}
		})

	},

	_expandNodeParents: function(node) {
		var parent = node.get('parent');
		while (parent) {
			parent.set('is_expanded', true);
			parent = parent.get('parent');
		}
	}

	// end
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

});


text:
namespace Microsoft.DocAsCode.DataContracts.ManagedReference
{
    using System;

    using Microsoft.DocAsCode.DataContracts.Common;

    using Newtonsoft.Json;
    using YamlDotNet.Serialization;

    [Serializable]
    public class AdditionalNotes
    {
        [JsonProperty("caller")]
        [YamlMember(Alias = "caller")]
        [MarkdownContent]
        public string Caller { get; set; }

        [JsonProperty("implementer")]
        [YamlMember(Alias = "implementer")]
        [MarkdownContent]
        public string Implementer { get; set; }

        [JsonProperty("inheritor")]
        [YamlMember(Alias = "inheritor")]
        [MarkdownContent]
        public string Inheritor { get; set; }
    }
}


text:
#ifndef _CONFIG_READER_H_
#define _CONFIG_READER_H_

#ifdef __cplusplus
extern "C" {
#endif

struct evpaxos_config;

struct evpaxos_config* evpaxos_config_read(const char* path);
void evpaxos_config_free(struct evpaxos_config* config);
struct sockaddr_in evpaxos_proposer_address(struct evpaxos_config* c, int i);
int evpaxos_proposer_listen_port(struct evpaxos_config* c, int i);
int evpaxos_acceptor_count(struct evpaxos_config* config);
struct sockaddr_in evpaxos_acceptor_address(struct evpaxos_config* c, int i);
int evpaxos_acceptor_listen_port(struct evpaxos_config* c, int i);

#ifdef __cplusplus
}
#endif

#endif


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__int64_t_malloc_67a.c
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-67a.tmpl.c
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: malloc Allocate data using malloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

typedef struct _CWE401_Memory_Leak__int64_t_malloc_67_structType
{
    int64_t * structFirst;
} CWE401_Memory_Leak__int64_t_malloc_67_structType;

#ifndef OMITBAD

/* bad function declaration */
void CWE401_Memory_Leak__int64_t_malloc_67b_badSink(CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct);

void CWE401_Memory_Leak__int64_t_malloc_67_bad()
{
    int64_t * data;
    CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct;
    data = NULL;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (int64_t *)malloc(100*sizeof(int64_t));
    if (data == NULL) {exit(-1);}
    /* Initialize and make use of data */
    data[0] = 5LL;
    printLongLongLine(data[0]);
    myStruct.structFirst = data;
    CWE401_Memory_Leak__int64_t_malloc_67b_badSink(myStruct);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE401_Memory_Leak__int64_t_malloc_67b_goodG2BSink(CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct);

static void goodG2B()
{
    int64_t * data;
    CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct;
    data = NULL;
    /* FIX: Use memory allocated on the stack with ALLOCA */
    data = (int64_t *)ALLOCA(100*sizeof(int64_t));
    /* Initialize and make use of data */
    data[0] = 5LL;
    printLongLongLine(data[0]);
    myStruct.structFirst = data;
    CWE401_Memory_Leak__int64_t_malloc_67b_goodG2BSink(myStruct);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE401_Memory_Leak__int64_t_malloc_67b_goodB2GSink(CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct);

static void goodB2G()
{
    int64_t * data;
    CWE401_Memory_Leak__int64_t_malloc_67_structType myStruct;
    data = NULL;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (int64_t *)malloc(100*sizeof(int64_t));
    if (data == NULL) {exit(-1);}
    /* Initialize and make use of data */
    data[0] = 5LL;
    printLongLongLine(data[0]);
    myStruct.structFirst = data;
    CWE401_Memory_Leak__int64_t_malloc_67b_goodB2GSink(myStruct);
}

void CWE401_Memory_Leak__int64_t_malloc_67_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE401_Memory_Leak__int64_t_malloc_67_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE401_Memory_Leak__int64_t_malloc_67_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import os, sys, time

def main():
    if len(sys.argv) != 4:
        print os.path.basename(sys.argv[0]),
        print '<hours> <minutes> <seconds>'
    else:
        try:
            timer(*[int(x) for x in sys.argv[1:]])
        except Exception, error:
            print error

def timer(hours, minutes, seconds):
    time.sleep(abs(hours * 3600 + minutes * 60 + seconds))
    while True:
        print '\x07',

if __name__ == '__main__':
    main()


text:
var vscode = require('vscode');
var _ = require('lodash');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "assignalign" is now active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    var disposable = vscode.commands.registerCommand('extension.assignAlign', function() {
        var editor = vscode.window.activeTextEditor;
        if (!editor) {
            return;
        }

        var lines = _.flatMap(editor.selections, function(s) {
            return _.range(s.start.line, s.end.line + 1).map(function(i) {
                return editor.document.lineAt(i);
            });
        });

        lines.sort(function(a,b) {
            return _.clamp(a.lineNumber - b.lineNumber, -1, 1);
        });

        lines = _.filter(lines, function findAssignment(l) {
           return _.some(['='], function hasAssignmentOperator(c) {
               var firstIndex = l.text.indexOf(c);
               return ~firstIndex ? firstIndex === l.text.lastIndexOf(c) : false;
           });
        });

        if(lines.length <= 1) {
            return;
        }

        var exp = /(\w+)\s*=/;
        var maxAssignmentIndex = -1;
        var newLines = _.map(lines, function(line) {
            return line.text.replace(exp, function(match, p1, offset, str) {
                var replacement = p1 + ' =';
                maxAssignmentIndex = Math.max(offset + replacement.length - 1, maxAssignmentIndex);
                return replacement;
            });
        });

        newLines = _.map(newLines, function(newLine) {
            var currentIndex = newLine.indexOf('=');
            var spaceRequired = maxAssignmentIndex - currentIndex;
            var offsetAssignment = ' '.repeat(spaceRequired) + '=';
            return newLine.replace('=', offsetAssignment);
        });

        editor.edit(function(edit) {
           _.forEach(lines, function(line, index) {
             edit.replace(line.range, newLines[index]);
           });
        });
    });

    context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;


text:
package org.jclouds.azurecompute.xml;

import static org.jclouds.util.SaxUtils.currentOrNull;

import com.google.common.base.Throwables;
import java.net.MalformedURLException;
import java.net.URL;
import org.jclouds.azurecompute.domain.StorageServiceKeys;
import org.jclouds.http.functions.ParseSax;

public class StorageServiceKeysHandler extends ParseSax.HandlerForGeneratedRequestWithResult<StorageServiceKeys> {

   private URL url;

   private String primary;

   private String secondary;

   private final StringBuilder currentText = new StringBuilder();

   @Override
   public StorageServiceKeys getResult() {
      final StorageServiceKeys result = StorageServiceKeys.create(url, primary, secondary);
      url = null;
      primary = null;
      secondary = null;
      return result;
   }

   @Override
   public void endElement(final String ignoredUri, final String ignoredName, final String qName) {
      if ("Url".equals(qName)) {
         final String urlText = currentOrNull(currentText);
         if (urlText != null) {
            try {
               url = new URL(urlText);
            } catch (MalformedURLException e) {
               throw Throwables.propagate(e);
            }
         }
      } else if ("Primary".equals(qName)) {
         primary = currentOrNull(currentText);
      } else if ("Secondary".equals(qName)) {
         secondary = currentOrNull(currentText);
      }

      currentText.setLength(0);
   }

   @Override
   public void characters(final char ch[], final int start, final int length) {
      currentText.append(ch, start, length);
   }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../print.css" type="text/css" media="print">
<meta content="INotification,org.puremvc.as3.interfaces.INotification,getBody,getName,getType,setBody,setType,toString" name="keywords">
<title>org.puremvc.as3.interfaces.INotification</title>

PureMVC AS3 Framework - [Standard Version]	All Packages | All Classes | Index | FramesNo Frames

Interface INotification	Methods

Package	org.puremvc.as3.interfaces

Interface	public interface INotification

Implementors	Notification

  The interface definition for a PureMVC Notification.

  PureMVC does not rely upon underlying event models such
  as the one provided with Flash, and ActionScript 3 does
  not have an inherent event model.

  The Observer Pattern as implemented within PureMVC exists
  to support event-driven communication between the
  application and the actors of the MVC triad.

  Notifications are not meant to be a replacement for Events
  in Flex/Flash/AIR. Generally, IMediator implementors
  place event listeners on their view components, which they
  then handle in the usual way. This may lead to the broadcast of Notifications to
  trigger ICommands or to communicate with other IMediators. IProxy and ICommand
  instances communicate with each other and IMediators
  by broadcasting INotifications.

  A key difference between Flash Events and PureMVC
  Notifications is that Events follow the
  'Chain of Responsibility' pattern, 'bubbling' up the display hierarchy
  until some parent component handles the Event, while
  PureMVC Notifications follow a 'Publish/Subscribe'
  pattern. PureMVC classes need not be related to each other in a
  parent/child relationship in order to communicate with one another
  using Notifications.

See also

IView

IObserver

Public Methods

 	Method	Defined by

getBody():Object

   Get the body of the INotification instance

	INotification

getName():String

   Get the name of the INotification instance.

	INotification

getType():String

   Get the type of the INotification instance

	INotification

setBody(body:Object):void

   Set the body of the INotification instance

	INotification

setType(type:String):void

   Set the type of the INotification instance

	INotification

toString():String

   Get the string representation of the INotification instance

	INotification

Method detail

getBody	()	method

public function getBody():Object

   Get the body of the INotification instance

Returns

	Object

getName	()	method

public function getName():String

   Get the name of the INotification instance.
   No setter, should be set by constructor only

Returns

	String

getType	()	method

public function getType():String

   Get the type of the INotification instance

Returns

	String

setBody	()	method

public function setBody(body:Object):void

   Set the body of the INotification instance

Parameters

	body:Object

setType	()	method

public function setType(type:String):void

   Set the type of the INotification instance

Parameters

	type:String

toString	()	method

public function toString():String

   Get the string representation of the INotification instance

Returns

	String


text:
\ifUseColumns
	\end{multicols}
\fi

\end{document}


text:
package ru.sdroman.carstore.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * @author sdroman
 * @since 08.2018
 */
@Entity(name = "drivetype")
public class DriveType {
    /**
     * Id.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    /**
     * Name.
     */
    private String name;

    /**
     * Constructor.
     */
    public DriveType() {
    }

    /**
     * Returns id.
     *
     * @return int id
     */
    public int getId() {
        return id;
    }

    /**
     * Sets id.
     *
     * @param id int
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * Returns name.
     *
     * @return String name
     */
    public String getName() {
        return name;
    }

    /**
     * Sets name.
     *
     * @param name String
     */
    public void setName(String name) {
        this.name = name;
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.20"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Luwra: luwra::internal::_ReadResults< Types > Struct Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Luwra

Minimal-overhead Lua wrapper for C++

luwra

internal

_ReadResults

Public Types |
List of all members

luwra::internal::_ReadResults< Types > Struct Template Reference

Public Types

using 	Type = TypeList< ReturnTypeOf< decltype(read< Types >)>... >

Member Typedef Documentation

◆ Type

template<typename... Types>

          using luwra::internal::_ReadResults< Types >::Type =  TypeList<ReturnTypeOf<decltype(read<Types>)>...>

<address class="footer">
Generated by  1.8.20
</address>


text:
package com.microsoft.azure.management.containerinstance.v2019_12_01.implementation;

import com.microsoft.azure.management.containerinstance.v2019_12_01.UsageName;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A single usage result.
 */
public class UsageInner {
    /**
     * Unit of the usage result.
     */
    @JsonProperty(value = "unit", access = JsonProperty.Access.WRITE_ONLY)
    private String unit;

    /**
     * The current usage of the resource.
     */
    @JsonProperty(value = "currentValue", access = JsonProperty.Access.WRITE_ONLY)
    private Integer currentValue;

    /**
     * The maximum permitted usage of the resource.
     */
    @JsonProperty(value = "limit", access = JsonProperty.Access.WRITE_ONLY)
    private Integer limit;

    /**
     * The name object of the resource.
     */
    @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
    private UsageName name;

    /**
     * Get unit of the usage result.
     *
     * @return the unit value
     */
    public String unit() {
        return this.unit;
    }

    /**
     * Get the current usage of the resource.
     *
     * @return the currentValue value
     */
    public Integer currentValue() {
        return this.currentValue;
    }

    /**
     * Get the maximum permitted usage of the resource.
     *
     * @return the limit value
     */
    public Integer limit() {
        return this.limit;
    }

    /**
     * Get the name object of the resource.
     *
     * @return the name value
     */
    public UsageName name() {
        return this.name;
    }

}


text:
package org.kuali.kra.common.committee.notification;

import org.apache.commons.lang.StringUtils;
import org.kuali.kra.common.committee.bo.CommitteeBase;
import org.kuali.kra.common.committee.bo.CommitteeScheduleBase;
import org.kuali.kra.common.notification.bo.NotificationModuleRoleQualifier;
import org.kuali.kra.kim.bo.KcKimAttributes;

public class CommitteeNotificationRoleQualifierServiceImpl implements CommonCommitteeNotificationRoleQualifierService {

    private CommitteeBase committee;
    private CommitteeScheduleBase committeeSchedule;

    /**
     *
     * @see org.kuali.kra.common.notification.service.KcNotificationRoleQualifierService#getRoleQualifierValue(org.kuali.kra.common.notification.bo.NotificationModuleRoleQualifier)
     */
    @Override
    public String getRoleQualifierValue(NotificationModuleRoleQualifier qualifier) {
        String qName = qualifier.getQualifier();
        String qVal = null;
        if (StringUtils.equalsIgnoreCase(qName, KcKimAttributes.COMMITTEE)) {
            qVal = committee.getCommitteeId();
        }
        else if (StringUtils.equalsIgnoreCase(qName, KcKimAttributes.COMMITTEESCHEDULE)) {
            qVal = committeeSchedule.getScheduleId();
        }
        return qVal;
    }

    public CommitteeBase getCommittee() {
        return committee;
    }

    public void setCommittee(CommitteeBase committee) {
        this.committee = committee;
    }

    public CommitteeScheduleBase getCommitteeSchedule() {
        return committeeSchedule;
    }

    public void setCommitteeSchedule(CommitteeScheduleBase committeeSchedule) {
        this.committeeSchedule = committeeSchedule;
    }

}


text:
package org.revenj;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.time.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public abstract class Utils {
	public static final LocalDate MIN_LOCAL_DATE = LocalDate.of(1, 1, 1);
	public static final LocalDateTime MIN_LOCAL_DATE_TIME = LocalDateTime.of(1, 1, 1, 0, 0, 0, 0);
	public static final OffsetDateTime MIN_DATE_TIME = OffsetDateTime.of(MIN_LOCAL_DATE_TIME, ZoneOffset.UTC);
	public static final UUID MIN_UUID = new java.util.UUID(0L, 0L);
	public static final byte[] EMPTY_BINARY = new byte[0];
	public static final BigDecimal ZERO_0 = BigDecimal.ZERO.setScale(0);
	public static final BigDecimal ZERO_1 = BigDecimal.ZERO.setScale(1);
	public static final BigDecimal ZERO_2 = BigDecimal.ZERO.setScale(2);
	public static final BigDecimal ZERO_3 = BigDecimal.ZERO.setScale(3);

	private static final ConcurrentMap<String, GenericType> typeCache = new ConcurrentHashMap<>();

	private static class GenericType implements ParameterizedType {

		private final String name;
		private final Type raw;
		private final Type[] arguments;

		public GenericType(String name, Type raw, Type[] arguments) {
			this.name = name;
			this.raw = raw;
			this.arguments = arguments;
		}

		@Override
		public Type[] getActualTypeArguments() {
			return arguments;
		}

		@Override
		public Type getRawType() {
			return raw;
		}

		@Override
		public Type getOwnerType() {
			return null;
		}

		@Override
		public String toString() {
			return name;
		}
	}

	public static ParameterizedType makeGenericType(Class<?> container, Type argument, Type... arguments) {
		StringBuilder sb = new StringBuilder();
		sb.append(container.getTypeName());
		sb.append("<");
		sb.append(argument.getTypeName());
		for (Type arg : arguments) {
			sb.append(", ");
			sb.append(arg.getTypeName());
		}
		sb.append(">");
		String name = sb.toString();
		GenericType found = typeCache.get(name);
		if (found == null) {
			Type[] genericArgs = new Type[arguments.length + 1];
			genericArgs[0] = argument;
			for (int i = 0; i < arguments.length; i++) {
				genericArgs[i + 1] = arguments[i];
			}
			found = new GenericType(name, container, genericArgs);
			typeCache.put(name, found);
		}
		return found;
	}

}


text:
package org.apache.cassandra.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.CRC32;

import io.netty.buffer.ByteBuf;
import io.netty.util.concurrent.FastThreadLocal;

public class Crc
{
    private static final FastThreadLocal<CRC32> crc32 = new FastThreadLocal<CRC32>()
    {
        @Override
        protected CRC32 initialValue()
        {
            return new CRC32();
        }
    };

    private static final byte[] initialBytes = new byte[] { (byte) 0xFA, (byte) 0x2D, (byte) 0x55, (byte) 0xCA };

    public static final class InvalidCrc extends IOException
    {
        public InvalidCrc(int read, int computed)
        {
            super(String.format("Read %d, Computed %d", read, computed));
        }
    }

    static CRC32 crc32()
    {
        CRC32 crc = crc32.get();
        crc.reset();
        crc.update(initialBytes);
        return crc;
    }

    static int computeCrc32(ByteBuf buffer, int startReaderIndex, int endReaderIndex)
    {
        CRC32 crc = crc32();
        crc.update(buffer.internalNioBuffer(startReaderIndex, endReaderIndex - startReaderIndex));
        return (int) crc.getValue();
    }

    static int computeCrc32(ByteBuffer buffer, int start, int end)
    {
        CRC32 crc = crc32();
        updateCrc32(crc, buffer, start, end);
        return (int) crc.getValue();
    }

    static void updateCrc32(CRC32 crc, ByteBuffer buffer, int start, int end)
    {
        int savePosition = buffer.position();
        int saveLimit = buffer.limit();
        buffer.limit(end);
        buffer.position(start);
        crc.update(buffer);
        buffer.limit(saveLimit);
        buffer.position(savePosition);
    }

    private static final int CRC24_INIT = 0x875060;
    /**
     * Polynomial chosen from https://users.ece.cmu.edu/~koopman/crc/index.html, by Philip Koopman
     *
     * This webpage claims a copyright to Philip Koopman, which he licenses under the
     * Creative Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0)
     *
     * It is unclear if this copyright can extend to a 'fact' such as this specific number, particularly
     * as we do not use Koopman's notation to represent the polynomial, but we anyway attribute his work and
     * link the terms of his license since they are not incompatible with our usage and we greatly appreciate his work.
     *
     * This polynomial provides hamming distance of 8 for messages up to length 105 bits;
     * we only support 8-64 bits at present, with an expected range of 40-48.
     */
    private static final int CRC24_POLY = 0x1974F0B;

    /**
     * NOTE: the order of bytes must reach the wire in the same order the CRC is computed, with the CRC
     * immediately following in a trailer.  Since we read in least significant byte order, if you
     * write to a buffer using putInt or putLong, the byte order will be reversed and
     * you will lose the guarantee of protection from burst corruptions of 24 bits in length.
     *
     * Make sure either to write byte-by-byte to the wire, or to use Integer/Long.reverseBytes if you
     * write to a BIG_ENDIAN buffer.
     *
     * See http://users.ece.cmu.edu/~koopman/pubs/ray06_crcalgorithms.pdf
     *
     * Complain to the ethernet spec writers, for having inverse bit to byte significance order.
     *
     * Note we use the most naive algorithm here.  We support at most 8 bytes, and typically supply
     * 5 or fewer, so any efficiency of a table approach is swallowed by the time to hit L3, even
     * for a tiny (4bit) table.
     *
     * @param bytes an up to 8-byte register containing bytes to compute the CRC over
     *              the bytes AND bits will be read least-significant to most significant.
     * @param len   the number of bytes, greater than 0 and fewer than 9, to be read from bytes
     * @return      the least-significant bit AND byte order crc24 using the CRC24_POLY polynomial
     */
    static int crc24(long bytes, int len)
    {
        int crc = CRC24_INIT;
        while (len-- > 0)
        {
            crc ^= (bytes & 0xff) << 16;
            bytes >>= 8;

            for (int i = 0; i < 8; i++)
            {
                crc <<= 1;
                if ((crc & 0x1000000) != 0)
                    crc ^= CRC24_POLY;
            }
        }
        return crc;
    }
}


text:
from binding import *
from .namespace import llvm
from .LLVMContext import LLVMContext
from .Type import Type
from .ADT.SmallVector import SmallVector_Type

FunctionType = llvm.Class(Type)

@FunctionType
class FunctionType:
    if LLVM_VERSION >= (3, 3):
        _include_ = 'llvm/IR/DerivedTypes.h'
    else:
        _include_ = 'llvm/DerivedTypes.h'
    _downcast_ = Type

    _get = StaticMethod(ptr(FunctionType), ptr(Type), cast(bool, Bool))
    _get |= StaticMethod(ptr(FunctionType), ptr(Type), ref(SmallVector_Type),
                         cast(bool, Bool))
    _get.realname = 'get'

    @CustomPythonStaticMethod
    def get(*args):
        from llvmpy import extra
        if len(args) == 3:
            typelist = args[1]
            sv = extra.make_small_vector_from_types(*typelist)
            return FunctionType._get(args[0], sv, args[2])
        else:
            return FunctionType._get(*args)

    isVarArg = Method(cast(Bool, bool))
    getReturnType = Method(ptr(Type))
    getParamType = Method(ptr(Type), cast(int, Unsigned))
    getNumParams = Method(cast(Unsigned, int))


text:
"""
Django settings for restpython project.

Generated by 'django-admin startproject' using Django 4.0.4.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-_m64&om81sa8(=r__087mr8y8+88yfr33tm4+u_w9y&a8yktzy'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'restpython.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'restpython.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="org.nanocontainer.persistence.hibernate.classic.Pojo" table="pojo">
        <id unsaved-value="null" name="id" type="java.lang.Integer" access="field">
            <generator class="native"/>
        </id>
        <property name="foo" update="false" unique="true" not-null="true" insert="true" access="field"/>
    </class>
</hibernate-mapping>


text:
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { LifecyclePhase, ILifecycleService, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { language } from 'vs/base/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry';
import { configurationTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ITextFileService, ITextFileSaveEvent, ITextFileResolveEvent } from 'vs/workbench/services/textfile/common/textfiles';
import { extname, basename, isEqual, isEqualOrParent } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Schemas } from 'vs/base/common/network';
import { getMimeTypes } from 'vs/editor/common/services/languagesAssociations';
import { hash } from 'vs/base/common/hash';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { IUserDataProfileService } from 'vs/workbench/services/userDataProfile/common/userDataProfile';

type TelemetryData = {
	mimeType: string;
	ext: string;
	path: number;
	reason?: number;
	allowlistedjson?: string;
};

type FileTelemetryDataFragment = {
	mimeType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The language type of the file (for example XML).' };
	ext: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The file extension of the file (for example xml).' };
	path: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The path of the file as a hash.' };
	reason?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The reason why a file is read or written. Allows to e.g. distinguish auto save from normal save.' };
	allowlistedjson?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The name of the file but only if it matches some well known file names such as package.json or tsconfig.json.' };
};

export class TelemetryContribution extends Disposable implements IWorkbenchContribution {

	private static ALLOWLIST_JSON = ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json', 'bower.json', '.eslintrc.json', 'tslint.json', 'composer.json'];
	private static ALLOWLIST_WORKSPACE_JSON = ['settings.json', 'extensions.json', 'tasks.json', 'launch.json'];

	constructor(
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@ILifecycleService lifecycleService: ILifecycleService,
		@IEditorService editorService: IEditorService,
		@IKeybindingService keybindingsService: IKeybindingService,
		@IWorkbenchThemeService themeService: IWorkbenchThemeService,
		@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
		@IUserDataProfileService private readonly userDataProfileService: IUserDataProfileService,
		@IConfigurationService configurationService: IConfigurationService,
		@IPaneCompositePartService paneCompositeService: IPaneCompositePartService,
		@ITextFileService textFileService: ITextFileService
	) {
		super();

		const { filesToOpenOrCreate, filesToDiff, filesToMerge } = environmentService;
		const activeViewlet = paneCompositeService.getActivePaneComposite(ViewContainerLocation.Sidebar);

		type WindowSizeFragment = {
			innerHeight: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The height of the current window.' };
			innerWidth: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The width of the current window.' };
			outerHeight: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The height of the current window with all decoration removed.' };
			outerWidth: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The width of the current window with all decoration removed.' };
			comment: 'The size of the window.';
		};

		type WorkspaceLoadClassification = {
			owner: 'bpasero';
			userAgent: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The user agent as reported by `navigator.userAgent` by Electron or the web browser.' };
			emptyWorkbench: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Whether a folder or workspace is opened or not.' };
			windowSize: WindowSizeFragment;
			'workbench.filesToOpenOrCreate': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should open or be created.' };
			'workbench.filesToDiff': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should be compared.' };
			'workbench.filesToMerge': { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of files that should be merged.' };
			customKeybindingsCount: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true };
			theme: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The current theme of the window.' };
			language: { classification: 'SystemMetaData'; purpose: 'BusinessInsight'; comment: 'The display language of the window.' };
			pinnedViewlets: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifiers of views that are pinned.' };
			restoredViewlet?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The identifier of the view that is restored.' };
			restoredEditors: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'The number of editors that restored.' };
			startupKind: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'How the window was opened, e.g via reload or not.' };
			comment: 'Metadata around the workspace that is being loaded into a window.';
		};

		type WorkspaceLoadEvent = {
			userAgent: string;
			windowSize: { innerHeight: number; innerWidth: number; outerHeight: number; outerWidth: number };
			emptyWorkbench: boolean;
			'workbench.filesToOpenOrCreate': number;
			'workbench.filesToDiff': number;
			'workbench.filesToMerge': number;
			customKeybindingsCount: number;
			theme: string;
			language: string;
			pinnedViewlets: string[];
			restoredViewlet?: string;
			restoredEditors: number;
			startupKind: StartupKind;
		};

		telemetryService.publicLog2<WorkspaceLoadEvent, WorkspaceLoadClassification>('workspaceLoad', {
			userAgent: navigator.userAgent,
			windowSize: { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth },
			emptyWorkbench: contextService.getWorkbenchState() === WorkbenchState.EMPTY,
			'workbench.filesToOpenOrCreate': filesToOpenOrCreate && filesToOpenOrCreate.length || 0,
			'workbench.filesToDiff': filesToDiff && filesToDiff.length || 0,
			'workbench.filesToMerge': filesToMerge && filesToMerge.length || 0,
			customKeybindingsCount: keybindingsService.customKeybindingsCount(),
			theme: themeService.getColorTheme().id,
			language,
			pinnedViewlets: paneCompositeService.getPinnedPaneCompositeIds(ViewContainerLocation.Sidebar),
			restoredViewlet: activeViewlet ? activeViewlet.getId() : undefined,
			restoredEditors: editorService.visibleEditors.length,
			startupKind: lifecycleService.startupKind
		});

		// Error Telemetry
		this._register(new ErrorTelemetry(telemetryService));

		// Configuration Telemetry
		this._register(configurationTelemetry(telemetryService, configurationService));

		//  Files Telemetry
		this._register(textFileService.files.onDidResolve(e => this.onTextFileModelResolved(e)));
		this._register(textFileService.files.onDidSave(e => this.onTextFileModelSaved(e)));

		// Lifecycle
		this._register(lifecycleService.onDidShutdown(() => this.dispose()));
	}

	private onTextFileModelResolved(e: ITextFileResolveEvent): void {
		const settingsType = this.getTypeIfSettings(e.model.resource);
		if (settingsType) {
			type SettingsReadClassification = {
				owner: 'bpasero';
				settingsType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The type of the settings file that was read.' };
				comment: 'Track when a settings file was read, for example from an editor.';
			};

			this.telemetryService.publicLog2<{ settingsType: string }, SettingsReadClassification>('settingsRead', { settingsType }); // Do not log read to user settings.json and .vscode folder as a fileGet event as it ruins our JSON usage data
		} else {
			type FileGetClassification = {
				owner: 'bpasero';
				comment: 'Track when a file was read, for example from an editor.';
			} & FileTelemetryDataFragment;

			this.telemetryService.publicLog2<TelemetryData, FileGetClassification>('fileGet', this.getTelemetryData(e.model.resource, e.reason));
		}
	}

	private onTextFileModelSaved(e: ITextFileSaveEvent): void {
		const settingsType = this.getTypeIfSettings(e.model.resource);
		if (settingsType) {
			type SettingsWrittenClassification = {
				owner: 'bpasero';
				settingsType: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The type of the settings file that was written to.' };
				comment: 'Track when a settings file was written to, for example from an editor.';
			};
			this.telemetryService.publicLog2<{ settingsType: string }, SettingsWrittenClassification>('settingsWritten', { settingsType }); // Do not log write to user settings.json and .vscode folder as a filePUT event as it ruins our JSON usage data
		} else {
			type FilePutClassfication = {
				owner: 'bpasero';
				comment: 'Track when a file was written to, for example from an editor.';
			} & FileTelemetryDataFragment;
			this.telemetryService.publicLog2<TelemetryData, FilePutClassfication>('filePUT', this.getTelemetryData(e.model.resource, e.reason));
		}
	}

	private getTypeIfSettings(resource: URI): string {
		if (extname(resource) !== '.json') {
			return '';
		}

		// Check for global settings file
		if (isEqual(resource, this.userDataProfileService.currentProfile.settingsResource)) {
			return 'global-settings';
		}

		// Check for keybindings file
		if (isEqual(resource, this.userDataProfileService.currentProfile.keybindingsResource)) {
			return 'keybindings';
		}

		// Check for snippets
		if (isEqualOrParent(resource, this.userDataProfileService.currentProfile.snippetsHome)) {
			return 'snippets';
		}

		// Check for workspace settings file
		const folders = this.contextService.getWorkspace().folders;
		for (const folder of folders) {
			if (isEqualOrParent(resource, folder.toResource('.vscode'))) {
				const filename = basename(resource);
				if (TelemetryContribution.ALLOWLIST_WORKSPACE_JSON.indexOf(filename) > -1) {
					return `.vscode/${filename}`;
				}
			}
		}

		return '';
	}

	private getTelemetryData(resource: URI, reason?: number): TelemetryData {
		let ext = extname(resource);
		// Remove query parameters from the resource extension
		const queryStringLocation = ext.indexOf('?');
		ext = queryStringLocation !== -1 ? ext.substr(0, queryStringLocation) : ext;
		const fileName = basename(resource);
		const path = resource.scheme === Schemas.file ? resource.fsPath : resource.path;
		const telemetryData = {
			mimeType: getMimeTypes(resource).join(', '),
			ext,
			path: hash(path),
			reason,
			allowlistedjson: undefined as string | undefined
		};

		if (ext === '.json' && TelemetryContribution.ALLOWLIST_JSON.indexOf(fileName) > -1) {
			telemetryData['allowlistedjson'] = fileName;
		}

		return telemetryData;
	}
}

Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(TelemetryContribution, LifecyclePhase.Restored);