text:
This tutorial will guide you through the creation of various example C++
applications, highlighting important Chromium C++ concepts.
This tutorial assumes robust knowledge of C++ (the language) but does not
assume you know how to write an application specific to Chromium's style and
architecture. This tutorial does assume that you know how to check files out
of Chromium's repository.

As always, consider the following resources as of primary importance:

-   [Coding Style](https://chromium.googlesource.com/chromium/src/+/main/styleguide/styleguide.md)
-   [Callback<> and Bind()](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/callback.md)
-   [Threading and Tasks in Chrome](https://chromium.googlesource.com/chromium/src/+/main/docs/threading_and_tasks.md)
-   [Intro to Mojo & Services](https://chromium.googlesource.com/chromium/src.git/+/main/docs/mojo_and_services.md)
-   [Important Abstractions and Data Structures](https://sites.google.com/a/chromium.org/dev/developers/coding-style/important-abstractions-and-data-structures) (badly needs updating)

This tutorial does not assume you have read any of the above,
though you should feel free to peruse them when necessary.
This tutorial will cover information across all of those guides.

Exercise solutions are available in the [codelabs/cpp101/](
https://source.chromium.org/chromium/chromium/src/+/main:codelabs/cpp101/)
directory of the Chromium source code. Build all of the example solutions with
`autoninja -C out/Default codelabs`. You are encouraged to create a new
`base/cpp101/` directory locally if you want to try implementing these
exercises yourself.

### Prerequisite: Getting the Code

Before you can do the exercises you need to set up a system to checkout, build,
and run the code. Instructions can be found [here](https://sites.google.com/a/chromium.org/dev/developers/how-tos/get-the-code/).

### Exercise 0: "Hello World!"

This exercise demonstrates the use of the [ninja](https://ninja-build.org/)
build system to build a simple C++ binary and demonstrates how typical C++
builds are organized within Chromium.

Create a new target in `base/BUILD.gn` for a new executable
named `codelab_hello_world`. Then write the classic "Hello, world!" program in
C++. You should be able to build it with
`autoninja -C out/Default codelab_hello_world` and execute it directly by
finding the binary within `out/Default`.

Sample execution:
```shell
$ cd /path/to/chromium/src
$ gclient runhooks
$ autoninja -C out/Default codelab_hello_world
$ out/Default/codelab_hello_world
Hello, world!
[0923/185218.645640:INFO:hello_world.cc(27)] Hello, world!
```

### More information
[Targets](https://gn.googlesource.com/gn/+/refs/heads/main/docs/language.md#Targets)

[Git Tips](https://chromium.googlesource.com/chromium/src.git/+/main/docs/git_tips.md)
and [Git Cookbook](https://chromium.googlesource.com/chromium/src.git/+/main/docs/git_cookbook.md)

[Life of a Chromium Developer](https://docs.google.com/a/google.com/presentation/d/1abnqM9j6zFodPHA38JG1061rG2iGj_GABxEDgZsdbJg/)

## Part 1: Using command-line arguments

We will augment our `codelab_hello_world` binary to parse command-line flags and
use those values to print messages to the user.

Command-line arguments within Chromium are processed by the
`CommandLine::Init()` function, which takes command line flags from the
[argc and argv](https://crasseux.com/books/ctutorial/argc-and-argv.html)
(argument count & vector) variables of the main() method. A typical invocation
of `CommandLine::Init()` looks like the following:
```cpp
int main(int argc, char** argv) {
  CommandLine::Init(argc, argv);
  // Main program execution ...
  return 0;
}
```
Flags are not explicitly defined in Chromium. Instead, we
use `GetSwitchValueASCII()` and friends to retrieve values passed in.

### Important include files

```cpp
#include "base/command_line.h"
#include "base/logging.h"
```

### Exercise 1: Using command-line arguments

Change `codelab_hello_world` to take a `--greeting` and a `--name` switch.
The greeting, if not specified, should default to "Hello",
and the name, if not specified, should default to "World".

## Part 2: Callbacks and Bind

C++, unlike other languages such as Python, Javascript, or Lisp, has only
rudimentary support for [callbacks](https://en.wikipedia.org/wiki/Callbacks)
and no support for
[partial application](https://en.wikipedia.org/wiki/Partial_application).
However, Chromium has the `base::OnceCallback<Sig>` and
 `base::RepeatingCallback<Sig>`class, whose instances can be freely passed
around, returned, and generally be treated as first-class values.
base::OnceCallback<Sig> is the move-only, single-call variant,
and base::RepeatingCallback<Sig> is the copyable, multiple-call variant.

The `Sig` template parameter is a function signature type:
```cpp
// The type of a callback that:
//  - Can run only once.
//  - Is move-only and non-copyable.
//  - Takes no arguments and does not return anything.
// base::OnceClosure is an alias of this type.
base::OnceCallback<void()>

// The type of a callback that:
//  - Can run more than once.
//  - Is copyable.
//  - Takes no arguments and does not return anything.
// base::RepeatingClosure is an alias of this type.
base::RepeatingCallback<void()>

// The types of a callback that takes two arguments (a string and a double)
// and returns an int.
base::OnceCallback<int(std::string, double)>
base::RepeatingCallback<int(std::string, double)>
```
Callbacks are executed by invoking the `Run()` member function.
base::OnceCallback<Sig> needs to be rvalue to run.
```cpp
void MyFunction1(base::OnceCallback<int(std::string, double)> my_callback) {
  // OnceCallback
  int result1 = std::move(my_callback).Run("my string 1", 1.0);

  // After running a OnceCallback, it's consumed and nulled out.
  DCHECK(!my_callback);
  ...
}

void MyFunction2(base::RepeatingCallback<int(std::string, double)> my_callback) {
  int result1 = my_callback.Run("my string 1", 1.0);
  // Run() can be called as many times as you wish for RepeatingCallback.
  int result2 = my_callback.Run("my string 2", 2);
  ...
```
Callbacks are constructed using the `base::BindOnce()` or `base::BindRepeating()` function,
which handles partial application:
```cpp
// Declare a function.
void MyFunction(int32 a, double b);

base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10);
base::RepeatingCallback<void(double)> my_callback2 = base::BindRepeating(&MyFunction, 10);

// Equivalent to:
//
// MyFunction(10, 3.5);
//
std::move(my_callback1).Run(3.5);
my_callback2.Run(3.5);
```
`base::BindOnce()` and `base::BindRepeating()` can do a lot more, including
binding class member functions and binding additional arguments to an
existing `base::OnceCallback` or `base::RepeatingCallback`. See
[docs/callback.md](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/callback.md)
for details.

### Important Include Files

```cpp
#include "base/bind.h"
#include "base/callback.h"
```

### More Information

[Callback<> and Bind()](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/callback.md)

### Exercise 2: Fibonacci closures

Implement a function that returns a callback that takes no arguments and returns
successive Fibonacci numbers. That is, a function that can be used like this:
```cpp
base::RepeatingCallback<int()> fibonacci_closure = MakeFibonacciClosure();
LOG(INFO) << fibonacci_closure.Run(); // Prints "1"
LOG(INFO) << fibonacci_closure.Run(); // Prints "1"
LOG(INFO) << fibonacci_closure.Run(); // Prints "2"
...
```
Each returned Fibonacci callback should be independent;
running one callback shouldn't affect the result of running another callback.
Write a `fibonacci` executable that takes an integer argument `n`
and uses your function to print out the first `n` Fibonacci numbers.

(This exercise was inspired by
[this Go exercise: Function closures](https://tour.golang.org/moretypes/25).)

## Part 3: Threads and task runners

Chromium has a number of abstractions for sequencing and threading.
[Threading and Tasks in Chrome](https://chromium.googlesource.com/chromium/src/+/main/docs/threading_and_tasks.md)
is a must-read and go-to reference for anything related to tasks, thread pools,
task runners, and more.

Sequenced execution (on virtual threads) is strongly preferred to
single-threaded execution (on physical threads). Chromium's abstraction for
asynchronously running posted tasks is `base::TaskRunner`. Task runners allow
you to write code that posts tasks without depending on what exactly will run
those tasks.

`base::SequencedTaskRunner` (which extends `base::TaskRunner`) is a commonly
used abstraction which handles running tasks (which are instances
of `base::OnceClosure`) in sequential order. These tasks are not guaranteed to
run on the same thread. The preferred way of posting to the current (virtual)
thread is `base::SequencedTaskRunnerHandle::Get()`.

A task that can run on any thread and doesn't have ordering or mutual exclusion
requirements with other tasks should be posted using one of the
`base::ThreadPool::PostTask()` functions.

There are a number of ways to post tasks to a thread pool or task runner.

- `PostTask()`
- `PostDelayedTask()` if you want to add a delay.
- `PostTaskAndReply()` lets you post a task which will post a task back to your
  current thread when its done.
- `PostTaskAndReplyWithResult()` to automatically pass the return value of the
  first call as argument to the second call.

Normally you wouldn't have to worry about setting up a threading environment and
keeping it running, since that is automatically done by Chromium's thread
classes. However, since the main thread doesn't automatically start off with
`TaskEnvironment`, there's a bit of extra setup involved. The following setup
code should be enough to create the necessary TaskEnvironment.
Include `testonly=true` flag in the BUILD.gn file, along with
`"//base/test:test_support"` set as a dependency.

### Important header files
```cpp
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "base/at_exit.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h"
#include "base/command_line.h"
```
### Setup code:
```cpp
int main(int argc, char* argv[]) {
  base::AtExitManager exit_manager;
  base::CommandLine::Init(argc, argv);
  TestTimeouts::Initialize();
  base::test::TaskEnvironment task_environment{
      base::test::TaskEnvironment::TimeSource::SYSTEM_TIME};

  // The rest of your code will go here.
```

### Exercise 3a: Sleep

Implement the Unix command-line utility `sleep` using only
a `base::SequencedTaskRunnerHandle` (i.e., without using the `sleep` function
or `base::PlatformThread::Sleep`).
Hint: You will need to use `base::RunLoop` to prevent the main function from
exiting prematurely.

### Exercise 3b: Integer factorization

Take the given (slow) function to find a non-trivial factor of a given integer:
```cpp
absl::optional<int> FindNonTrivialFactor(int n) {
  // Really naive algorithm.
  for (int i = 2; i < n; ++i) {
    if (n % i == 0) {
      return i;
    }
  }
  return absl::nullopt;
}
```
Write a command-line utility `factor` that takes a number, posts a task to the
background using `FindNonTrivialFactor`, and prints a status update every second
as long as the factoring task is executing.

### More information

[Threading and Tasks in Chrome](https://chromium.googlesource.com/chromium/src/+/main/docs/threading_and_tasks.md)

## Part 4: Mojo

Mojo is Chromium's abstraction of IPC. Mojo allows for developers to easily
connect interface clients and implementations across arbitrary intra- and
inter-process boundaries. See the
[Intro to Mojo and Services](https://chromium.googlesource.com/chromium/src.git/+/main/docs/mojo_and_services.md)
guide to get started.

 ### Exercise 4: Building a simple out-of-process service

See the [building a simple out-of-process service](https://chromium.googlesource.com/chromium/src.git/+/main/docs/mojo_and_services.md#example_building-a-simple-out_of_process-service)
tutorial on using Mojo to define, hook up, and launch an out-of-process service.

### More Information

[Mojo C++ Bindings API Docs](https://chromium.googlesource.com/chromium/src.git/+/main/mojo/public/cpp/bindings/README.md)
[Mojo Docs](https://chromium.googlesource.com/chromium/src.git/+/main/mojo/README.md)


text:
Thanks for your interest in contributing to gitlint!

Instructions on how to get started can be found on [http://jorisroovers.github.io/gitlint/contributing](http://jorisroovers.github.io/gitlint/contributing/).

redpajama_set_name: RedPajamaGithub


text:
SHELL = /bin/bash -o pipefail
GO = go

# Flags to pass to go build
BUILD_FLAGS = -gcflags '-N -l'
BUILD_QUIET ?= -q

GOLANG_IMAGE ?= golang:1.14
GOPROXY ?= $(shell go env GOPROXY)

# Where to find your project
PROJECT_ROOT = github.com/uber/kraken
PACKAGE_VERSION ?= $(shell git describe --always --tags)

ALL_SRC = $(shell find . -name "*.go" | grep -v \
	-e ".*/\..*" \
	-e ".*/_.*" \
	-e ".*/mocks.*" \
	-e ".*/*.pb.go")

ALL_PKGS = $(shell go list $(sort $(dir $(ALL_SRC))))

# ==== BASIC ====

BUILD_LINUX = GOOS=linux GOARCH=amd64 $(GO) build -i -o $@ $(BUILD_FLAGS) $(BUILD_GC_FLAGS) $(BUILD_VERSION_FLAGS) ./$(dir $@)

# Cross compiling cgo for sqlite3 is not well supported in Mac OSX.
# This workaround builds the binary inside a linux container.
CROSS_COMPILER = docker run --rm -it -v $(shell pwd):/go/src/github.com/uber/kraken -w /go/src/github.com/uber/kraken -e GOPROXY=$(GOPROXY) $(GOLANG_IMAGE) go build -o ./$@ ./$(dir $@)

LINUX_BINS = \
	agent/agent \
	build-index/build-index \
	origin/origin \
	proxy/proxy \
	tools/bin/testfs/testfs \
	tracker/tracker

REGISTRY ?= gcr.io/uber-container-tools

$(LINUX_BINS):: $(ALL_SRC)
	$(CROSS_COMPILER)

define tag_image
	docker tag $(1):$(PACKAGE_VERSION) $(1):dev
	docker tag $(1):$(PACKAGE_VERSION) $(REGISTRY)/$(1):$(PACKAGE_VERSION)
endef

.PHONY: images
images: $(LINUX_BINS)
	docker build $(BUILD_QUIET) -t kraken-agent:$(PACKAGE_VERSION) -f docker/agent/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-build-index:$(PACKAGE_VERSION) -f docker/build-index/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-origin:$(PACKAGE_VERSION) -f docker/origin/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-proxy:$(PACKAGE_VERSION) -f docker/proxy/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-testfs:$(PACKAGE_VERSION) -f docker/testfs/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-tracker:$(PACKAGE_VERSION) -f docker/tracker/Dockerfile ./
	docker build $(BUILD_QUIET) -t kraken-herd:$(PACKAGE_VERSION) -f docker/herd/Dockerfile ./
	$(call tag_image,kraken-agent)
	$(call tag_image,kraken-build-index)
	$(call tag_image,kraken-origin)
	$(call tag_image,kraken-proxy)
	$(call tag_image,kraken-testfs)
	$(call tag_image,kraken-tracker)
	$(call tag_image,kraken-herd)

.PHONY: publish
publish: images
	docker push $(REGISTRY)/kraken-agent:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-build-index:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-origin:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-proxy:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-testfs:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-tracker:$(PACKAGE_VERSION)
	docker push $(REGISTRY)/kraken-herd:$(PACKAGE_VERSION)

clean::
	@rm -f $(LINUX_BINS)

.PHONY: bins
bins: $(LINUX_BINS)

# ==== TEST ====
.PHONY: unit-test
unit-test:
	-rm coverage.txt
	$(GO) test -timeout=30s -race -coverprofile=coverage.txt $(ALL_PKGS) --tags "unit"

.PHONY: docker_stop
docker_stop:
	-docker ps -a --format '{{.Names}}' | grep kraken | while read n; do docker rm -f $$n; done

venv: requirements-tests.txt
	virtualenv --python=$(shell which python2) --setuptools venv
	source venv/bin/activate
	venv/bin/pip install -r requirements-tests.txt

.PHONY: integration
FILE?=
NAME?=test_
USERNAME:=$(shell id -u -n)
USERID:=$(shell id -u)
integration: venv $(LINUX_BINS) docker_stop tools/bin/puller/puller
	docker build $(BUILD_QUIET) -t kraken-agent:$(PACKAGE_VERSION) -f docker/agent/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	docker build $(BUILD_QUIET) -t kraken-build-index:$(PACKAGE_VERSION) -f docker/build-index/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	docker build $(BUILD_QUIET) -t kraken-origin:$(PACKAGE_VERSION) -f docker/origin/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	docker build $(BUILD_QUIET) -t kraken-proxy:$(PACKAGE_VERSION) -f docker/proxy/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	docker build $(BUILD_QUIET) -t kraken-testfs:$(PACKAGE_VERSION) -f docker/testfs/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	docker build $(BUILD_QUIET) -t kraken-tracker:$(PACKAGE_VERSION) -f docker/tracker/Dockerfile --build-arg USERID=$(USERID) --build-arg USERNAME=$(USERNAME) ./
	PACKAGE_VERSION=$(PACKAGE_VERSION) venv/bin/py.test --timeout=120 -v -k $(NAME) test/python/$(FILE)

.PHONY: runtest
NAME?=test_
runtest: venv docker_stop
	source venv/bin/activate
	venv/bin/py.test --timeout=120 -v -k $(NAME) test/python

.PHONY: devcluster
devcluster: $(LINUX_BINS) docker_stop images
	./examples/devcluster/herd_start_container.sh
	./examples/devcluster/agent_one_start_container.sh
	./examples/devcluster/agent_two_start_container.sh

# ==== TOOLS ====

TOOLS = \
	tools/bin/puller/puller \
	tools/bin/reload/reload \
	tools/bin/visualization/visualization

tools/bin/puller/puller:: $(wildcard tools/bin/puller/puller/*.go)
	$(CROSS_COMPILER)

tools/bin/reload/reload:: $(wildcard tools/bin/reload/reload/*.go)
	$(CROSS_COMPILER)

tools/bin/visualization/visualization:: $(wildcard tools/bin/visualization/visualization/*.go)
	$(CROSS_COMPILER)

.PHONY: tools
tools: $(TOOLS)

# Creates a release summary containing the build revisions of each component
# for the specified version.
releases/%:
	./scripts/release.sh $(subst releases/,,$@)

# ==== CODE GENERATION ====

# In order for kraken to be imported by other projects, we need to check in all
# the generated code, otherwise dependency management tools would report errors
# caused by missing dependencies of kraken itself.

# protoc must be installed on the system to make this work.
# Install it by by following instructions on:
# https://github.com/protocolbuffers/protobuf.
PROTOC_BIN = protoc

PROTO = $(GEN_DIR)/proto/p2p/p2p.pb.go

GEN_DIR = gen/go

.PHONY: protoc
protoc:
	mkdir -p $(GEN_DIR)
	go get -u github.com/golang/protobuf/protoc-gen-go
	$(PROTOC_BIN) --plugin=$(shell go env GOPATH)/bin/protoc-gen-go --go_out=$(GEN_DIR) $(subst .pb.go,.proto,$(subst $(GEN_DIR)/,,$(PROTO)))

# mockgen must be installed on the system to make this work.
# Install it by running:
# `go get github.com/golang/mock/mockgen`.
mockgen = $(shell go env GOPATH)/bin/mockgen

define lowercase
$(shell tr '[:upper:]' '[:lower:]' <<< $(1))
endef

define add_mock
	mkdir -p mocks/$(1)
	$(mockgen) \
		-destination=mocks/$(1)/$(call lowercase,$(2)).go \
		-package mock$(notdir $(1)) \
		$(PROJECT_ROOT)/$(1) $(2)
endef

.PHONY: mocks
mocks:
	rm -rf mocks
	mkdir -p $(shell go env GOPATH)/bin

	$(call add_mock,agent/agentclient,Client)

	$(call add_mock,lib/backend/s3backend,S3)
	# mockgen doesn't play nice when importing vendor code. Must strip the vendor prefix
	# from the imports.
	sed -i '' s,github.com/uber/kraken/vendor/,, mocks/lib/backend/s3backend/s3.go

	$(call add_mock,lib/backend/gcsbackend,GCS)
	sed -i '' s,github.com/uber/kraken/vendor/,, mocks/lib/backend/gcsbackend/gcs.go

	$(call add_mock,lib/hashring,Ring)
	$(call add_mock,lib/hashring,Watcher)

	$(call add_mock,lib/backend/hdfsbackend/webhdfs,Client)

	$(call add_mock,lib/hostlist,List)

	$(call add_mock,lib/healthcheck,Checker)
	$(call add_mock,lib/healthcheck,Filter)
	$(call add_mock,lib/healthcheck,PassiveFilter)

	$(call add_mock,tracker/originstore,Store)

	$(call add_mock,build-index/tagstore,Store)
	$(call add_mock,build-index/tagstore,FileStore)

	$(call add_mock,build-index/tagtype,DependencyResolver)

	$(call add_mock,build-index/tagclient,Provider)
	$(call add_mock,build-index/tagclient,Client)

	$(call add_mock,tracker/announceclient,Client)

	$(call add_mock,utils/dedup,TaskRunner)
	$(call add_mock,utils/dedup,IntervalTask)

	$(call add_mock,lib/backend,Client)

	$(call add_mock,tracker/peerstore,Store)

	$(call add_mock,lib/store,FileReadWriter)

	$(call add_mock,lib/torrent/scheduler,ReloadableScheduler)
	$(call add_mock,lib/torrent/scheduler,Scheduler)

	$(call add_mock,origin/blobclient,Client)
	$(call add_mock,origin/blobclient,Provider)
	$(call add_mock,origin/blobclient,ClusterClient)
	$(call add_mock,origin/blobclient,ClusterProvider)
	$(call add_mock,origin/blobclient,ClientResolver)

	$(call add_mock,lib/containerruntime,Factory)
	$(call add_mock,lib/containerruntime/containerd,Client)
	$(call add_mock,lib/containerruntime/dockerdaemon,DockerClient)
	$(call add_mock,lib/dockerregistry/transfer,ImageTransferer)

	$(call add_mock,tracker/metainfoclient,Client)

	$(call add_mock,lib/persistedretry,Store)
	$(call add_mock,lib/persistedretry,Task)
	$(call add_mock,lib/persistedretry,Executor)
	$(call add_mock,lib/persistedretry,Manager)

	$(call add_mock,lib/persistedretry/tagreplication,RemoteValidator)

	$(call add_mock,utils/httputil,RoundTripper)

# ==== MISC ====

kubecluster:
	cd ./examples/k8s && bash deploy.sh

.PHONY: docs
docs:
	@./scripts/mkdocs.sh -q serve


text:
files = Dir["packages/ember-*/lib/**/*.js"] - Dir["packages/ember-runtime/**/*.js"]
files = Dir["packages/ember-{metal,views,handlebars}/lib/**/*.js"]

def uglify(string)
  IO.popen("uglifyjs", "r+") do |io|
    io.puts string
    io.close_write
    return io.read
  end
end

def gzip(string)
  IO.popen("gzip -f", "r+") do |io|
    io.puts string
    io.close_write
    return io.read
  end
end

string = ""

files.each do |file|
  this_file = File.read(file)
  string += this_file
  size = this_file.size
  uglified = uglify(this_file)
  gzipped = gzip(uglified)

  puts "%8d %8d %8d - %s" % [size, uglified.size, gzipped.size, file]
end

uglified = uglify(string)
gzipped = gzip(uglified)

puts "%8d %8d %8d" % [string.size, uglified.size, gzipped.size]


text:
<menu></menu>

Debug:

                                    old: {{old|json}} new: {{new |json}}

                                    <form name="oform"  ng-submit="change()" role="form">

                                            Password actual
                                            <input  type="password" name="old" id="old" class="form-control" ng-model="old" required/>
                                            Debes introducir el password

                                            Nuevo Password
                                            <input type="password" name="new" id="new" class="form-control" ng-model="new" required/>
                                            Debes introducir un password

                                            <button  ng-disabled="form.$invalid" class="btn btn-primary" ng-click="passchange()">Cambiar</button>

                                    </form>

{{status}}

                                        Continuar

ERROR: {{status}}


text:
var mysql = require("mysql"),
		utils = require('../utils/utils'),
		config = utils.getConfig();

var connection = mysql.createConnection({
		host: config.db.host,
		user: config.db.user,
		password: config.db.password,
		port: config.db.port,
		database: config.db.database
	});

var table_prefix = config.db.table_prefix;

function query (sql, callback){
	console.log('[' + utils.getNowtime() + '] ' + sql);
	connection.query(sql, function(err, res, fields){
		if (err) {
			connection.rollback(function() {
				throw err;
			});
		}
		callback(err, res);
	});
}

function insert(sql, param, callback){
	console.log('[' + utils.getNowtime() + '] ' + sql);
	connection.query(sql, param, function(err, result) {
		if (err) throw err;
		connection.commit(function(err) {
			if (err) {
				connection.rollback(function() {
					throw err;
				});
			}
			callback(err, result);
		});
	});
}

function update(sql, arr, callback){
	console.log('[' + utils.getNowtime() + '] ' + sql);
	connection.query(sql, arr, function(err, result){
		if (err) throw err;
		connection.commit(function(err) {
			if (err) {
				connection.rollback(function() {
					throw err;
				});
			}
			callback(err,result);
		});
	});
}

function deleteData(sql, param, callback){
	console.log('[' + utils.getNowtime() + '] ' + sql);
	connection.query(sql, param, function(err, result) {
		if (err) throw err;
		connection.commit(function(err) {
			if (err) {
				connection.rollback(function() {
					throw err;
				});
			}
			callback(err,result);
		});
	});
}

function checkConnection(configInfo, errCbak, succCbak) {
	var connection = mysql.createConnection({
		host: configInfo.db.host,
		user: configInfo.db.user,
		password: configInfo.db.password,
		port: configInfo.db.port,
		database: configInfo.db.database
	});

	connection.connect(function (err) {
    if (err) {
      console.log('[' + utils.getNowtime() + '] error when connecting to db:', err);
      errCbak();
    } else {
    	console.log('[' + utils.getNowtime() + '] connecting to db success');
    	succCbak();
    }
  });
}

function createTable(configInfo, errCbak, succCbak) {

	var bk_article = 'CREATE TABLE ' + configInfo.db.table_prefix + '_article (' +
	  'id int(11) NOT NULL AUTO_INCREMENT,' +
	  'title varchar(255) NOT NULL,' +
	  'create_time varchar(255) NOT NULL,' +
	  'content longtext NOT NULL,' +
	  'user_id int(11) unsigned NOT NULL,' +
	  'update_time varchar(255) DEFAULT NULL,' +
	  'is_public tinyint(11) NOT NULL DEFAULT "1" COMMENT "1 为公开,0 为不公开",' +
	  'is_allowcomment tinyint(11) NOT NULL COMMENT "1 为允许评论, 0 为不允许评论",' +
	  'comment_num int(11) NOT NULL DEFAULT "0",' +
	  'status tinyint(11) NOT NULL DEFAULT "0" COMMENT "0 为草稿,1 为待审核,2 为已拒绝,3 为已经发布",' +
	  'type tinyint(11) NOT NULL DEFAULT "0" COMMENT "0 为文章,1 为页面",' +
	  'summary longtext NOT NULL COMMENT "摘要",' +
	  'options mediumtext COMMENT "一些选项,JSON 结构",' +
	  'markdown_content longtext NOT NULL,' +
	  'PRIMARY KEY (id)' +
	') ENGINE=InnoDB DEFAULT CHARSET=utf8;';

	var bk_cate = 'CREATE TABLE ' + configInfo.db.table_prefix + '_cate (' +
		'id int(10) unsigned NOT NULL AUTO_INCREMENT,' +
		'name varchar(255) NOT NULL,' +
	  'pid int(11) NOT NULL DEFAULT 0,' +
	  'pathname varchar(255) DEFAULT NULL,' +
		'PRIMARY KEY (id),' +
		'UNIQUE KEY name (name)' +
	') ENGINE=InnoDB DEFAULT CHARSET=utf8;';

	var bk_tag = 'CREATE TABLE ' + configInfo.db.table_prefix + '_tag (' +
	  'id int(11) unsigned NOT NULL AUTO_INCREMENT,' +
	  'name varchar(255) DEFAULT NULL,' +
	  'shortname varchar(255) DEFAULT NULL,' +
	  'create_time varchar(255) NOT NULL,' +
	  'PRIMARY KEY (id),' +
	  'UNIQUE KEY name_UNIQUE (name)' +
	') ENGINE=InnoDB DEFAULT CHARSET=utf8;';

	var bk_user = 'CREATE TABLE ' + configInfo.db.table_prefix + '_user ( ' +
	  'id int(11) unsigned NOT NULL AUTO_INCREMENT,' +
	  'username varchar(255) NOT NULL DEFAULT "",' +
	  'password varchar(255) NOT NULL DEFAULT "",' +
	  'display_name varchar(255) DEFAULT NULL,' +
	  'type tinyint(11) NOT NULL DEFAULT "1" COMMENT "1 为管理员  2 为编辑",' +
	  'email varchar(255) NOT NULL DEFAULT "",' +
	  'status tinyint(11) NOT NULL DEFAULT "1" COMMENT "1 为有效 2 为禁用",' +
	  'create_time datetime NOT NULL,' +
	  'create_ip varchar(20) NOT NULL DEFAULT "",' +
	  'last_login_time datetime NOT NULL,' +
	  'last_login_ip varchar(20) NOT NULL DEFAULT "",' +
	  'app_key varchar(255) DEFAULT NULL,' +
	  'app_secret varchar(255) DEFAULT NULL,' +
	  'PRIMARY KEY (id),' +
	  'UNIQUE KEY username_UNIQUE (username),' +
	  'UNIQUE KEY email_UNIQUE (email)' +
	') ENGINE=InnoDB DEFAULT CHARSET=utf8;';

	connection.query(bk_article, function(arterr, artres){

		if (arterr) {
			console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_article error');
			errCbak(arterr);
		}else {
			console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_article success');
			connection.query(bk_cate, function(cateerr, cateres){
				if (cateerr) {
					console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_cate error');
					errCbak(cateerr);
				}else {
					console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_cate success');
					connection.query(bk_tag, function(tagerr, tagres){
						if (tagerr) {
							console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_tag error');
							errCbak(tagerr);
						}else {
							console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_tag success');
							connection.query(bk_user, function(usererr, userres){
								if (usererr) {
									console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_user error');
									errCbak(usererr);
								}else {
									console.log('[' + utils.getNowtime() + '] create table ' + configInfo.db.table_prefix + '_user success');
									succCbak();
								}
							});
						}
					});
				}
			});
		}
	});
}

function resetConnection(configInfo) {
	connection = mysql.createConnection({
		host: configInfo.db.host,
		user: configInfo.db.user,
		password: configInfo.db.password,
		port: configInfo.db.port,
		database: configInfo.db.database
	});
}

function resetTablePrefix(prefix) {
	table_prefix = prefix;
}

function getTablePrefix() {
	return table_prefix;
}

exports.query = query;
exports.insert = insert;
exports.update = update;
exports.deleteData = deleteData;
exports.checkConnection = checkConnection;
exports.createTable = createTable;
exports.resetConnection = resetConnection;
exports.resetTablePrefix = resetTablePrefix;
exports.getTablePrefix = getTablePrefix;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>dbg4j</groupId>
    <artifactId>dbg4j-core</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0-SNAPSHOT</version>

    <name>dbg4j-core</name>
    <description>
        Dbg4j - java debugging library (core)
    </description>
    <licenses>
        <license>
            <name>Apache License 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>mak-sym</id>
            <name>Maksym Fedoryshyn</name>
            <email>maksym.fedoryshyn@gmail.com</email>
            <timezone>-6</timezone>
        </developer>
    </developers>

    <properties>
        <aspectjVersion>1.7.4</aspectjVersion>
    </properties>

    <build>
        <plugins>
            <plugin>
                <!-- override plugin to java 6 -->
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.0.4</version>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>install</phase>
                        <goals>
                            <goal>jar</goal>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.6</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <complianceLevel>1.6</complianceLevel>
                    <verbose>true</verbose>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>${aspectjVersion}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectjVersion}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectjVersion}</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>1.3.9</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.5</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>3.0.0</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.18</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>3.2</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.1</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>javadoc</report>
                        </reports>
                    </reportSet>
                </reportSets>
                <configuration>
                    <show>public</show>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.6</version>
            </plugin>
        </plugins>
    </reporting>
</project>


text:
const fs = require('fs')
const moment = require('moment')
const P2PGraph = require('p2p-graph')
const path = require('path')
const prettierBytes = require('prettier-bytes')
const throttle = require('throttleit')
const WebTorrent = require('webtorrent')

const TORRENT = fs.readFileSync(
  path.join(__dirname, '../../static/torrents/sintel.torrent')
)

module.exports = function () {
  let graph
  let hero = document.querySelector('#hero')
  let torrent

  // Don't start the demo automatically on mobile.
  if (window.innerWidth <= 899) {
    let beginButton = document.createElement('a')
    beginButton.href = '#'
    beginButton.id = 'begin'
    beginButton.className = 'btn large'
    beginButton.textContent = 'Begin Demo'

    beginButton.addEventListener('click', function onClick () {
      beginButton.removeEventListener('click', onClick, false)
      beginButton.parentNode.removeChild(beginButton)
      beginButton = null

      init()
    })
    hero.appendChild(beginButton)
  } else {
    init()
  }

  function init () {
    // Display video and related information.
    hero.className = 'loading'
    hero = null

    graph = window.graph = new P2PGraph('.torrent-graph')
    graph.add({ id: 'You', name: 'You', me: true })

    // Create client
    const client = window.client = new WebTorrent()
    client.on('warning', onWarning)
    client.on('error', onError)

    // Create torrent
    torrent = client.add(TORRENT, onTorrent)
  }

  const $body = document.body
  const $progressBar = document.querySelector('#progressBar')
  const $numPeers = document.querySelector('#numPeers')
  const $downloaded = document.querySelector('#downloaded')
  const $total = document.querySelector('#total')
  const $remaining = document.querySelector('#remaining')

  function onTorrent () {
    const file = torrent.files.find(function (file) {
      return file.name.endsWith('.mp4')
    })

    const opts = {
      autoplay: true,
      muted: true
    }

    const videoOverlay = document.querySelector('.videoOverlay')

    file.appendTo('#videoWrap .video', opts, function (err, elem) {
      if (err) return onError(err)
      elem.parentElement.classList.add('canplay')
      elem.parentElement.classList.add('muted')

      videoOverlay.addEventListener('click', onClick1)

      // First click unmutes the video!
      function onClick1 () {
        videoOverlay.removeEventListener('click', onClick1)

        elem.muted = false
        elem.parentElement.classList.remove('muted')
      }
    })

    torrent.on('wire', onWire)
    torrent.on('done', onDone)

    torrent.on('download', throttle(onProgress, 250))
    torrent.on('upload', throttle(onProgress, 250))
    setInterval(onProgress, 5000)
    onProgress()
  }

  function onWire (wire) {
    const id = wire.peerId.toString()
    graph.add({ id: id, name: wire.remoteAddress || 'Unknown' })
    graph.connect('You', id)
    wire.once('close', function () {
      graph.disconnect('You', id)
      graph.remove(id)
    })
  }

  function onProgress () {
    const percent = Math.round(torrent.progress * 100 * 100) / 100
    $progressBar.style.width = percent + '%'
    $numPeers.innerHTML = torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers')

    $downloaded.innerHTML = prettierBytes(torrent.downloaded)
    $total.innerHTML = prettierBytes(torrent.length)

    let remaining
    if (torrent.done) {
      remaining = 'Done.'
    } else {
      remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
      remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining.'
    }
    $remaining.innerHTML = remaining
  }

  function onDone () {
    $body.className += ' is-seed'
    onProgress()
  }

  function onError (err) {
    if (err) {
      window.alert(err)
      console.error(err)
    }
  }

  function onWarning (err) {
    if (err) {
      console.error(err)
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2019 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="exo_controls_show">Pleyer tugmalarini chiqarish</string>
  <string name="exo_controls_hide">Pleyer tugmalarini berkitish</string>
  <string name="exo_controls_seek_bar_description">Ijro rivoji</string>
  <string name="exo_controls_settings_description">Sozlamalar</string>
  <string name="exo_controls_overflow_hide_description">Qoʻshimcha sozlamalarni yashirish</string>
  <string name="exo_controls_overflow_show_description">Qoʻshimcha sozlamalarni chiqarish</string>
  <string name="exo_controls_fullscreen_enter_description">Butun ekran rejimiga kirish</string>
  <string name="exo_controls_fullscreen_exit_description">Butun ekran rejimidan chiqish</string>
  <string name="exo_controls_previous_description">Avvalgisi</string>
  <string name="exo_controls_next_description">Keyingisi</string>
  <string name="exo_controls_pause_description">Pauza</string>
  <string name="exo_controls_play_description">Ijro</string>
  <string name="exo_controls_stop_description">To'xtatish</string>
  <string name="exo_controls_rewind_description">Orqaga qaytarish</string>
  <plurals name="exo_controls_rewind_by_amount_description">
    <item quantity="one">%d soniya orqaga</item>
    <item quantity="other">%d soniya orqaga</item>
  </plurals>
  <string name="exo_controls_fastforward_description">Oldinga o'tkazish</string>
  <plurals name="exo_controls_fastforward_by_amount_description">
    <item quantity="one">%d soniya oldinga</item>
    <item quantity="other">%d soniya oldinga</item>
  </plurals>
  <string name="exo_controls_repeat_off_description">Joriy rejim: Hech qaysi takrorlanmaydi. Takrorlash rejimiga oʻting.</string>
  <string name="exo_controls_repeat_one_description">Joriy rejim: Bittasi takrorlanadi. Takrorlash rejimiga oʻting.</string>
  <string name="exo_controls_repeat_all_description">Joriy rejim: Barchasi takrorlanadi. Takrorlash rejimiga oʻting.</string>
  <string name="exo_controls_shuffle_on_description">Tasodifiy rejimni faolsizlantiring</string>
  <string name="exo_controls_shuffle_off_description">Tasodifiy rejimni yoqing</string>
  <string name="exo_controls_vr_description">VR rejimi</string>
  <string name="exo_controls_cc_enabled_description">Taglavhalarni faolsizlantirish</string>
  <string name="exo_controls_cc_disabled_description">Taglavhalarni yoqish</string>
  <string name="exo_controls_playback_speed">Tezlik</string>
  <string-array name="exo_controls_playback_speeds">
    <item>0,25x</item>
    <item>0,5x</item>
    <item>0,75x</item>
    <item>Normal</item>
    <item>1,25x</item>
    <item>1,5x</item>
    <item>2x</item>
  </string-array>
  <string name="exo_track_selection_title_video">Video</string>
  <string name="exo_track_selection_title_audio">Audio</string>
  <string name="exo_track_selection_title_text">Matn</string>
  <string name="exo_track_selection_none">Hech qanday</string>
  <string name="exo_track_selection_auto">Avtomatik</string>
  <string name="exo_track_unknown">Noaniq</string>
  <string name="exo_track_resolution">%1$d × %2$d</string>
  <string name="exo_track_mono">Mono</string>
  <string name="exo_track_stereo">Stereo</string>
  <string name="exo_track_surround">Qamrovli ovoz</string>
  <string name="exo_track_surround_5_point_1">5.1 qamrovli ovoz</string>
  <string name="exo_track_surround_7_point_1">7.1 qamrovli ovoz</string>
  <string name="exo_track_role_alternate">Muqobil</string>
  <string name="exo_track_role_supplementary">Qoʻshimcha</string>
  <string name="exo_track_role_commentary">Sharh</string>
  <string name="exo_track_role_closed_captions">Taglavhalar</string>
  <string name="exo_track_bitrate">%1$.2f Mbit/s</string>
  <string name="exo_item_list">%1$s, %2$s</string>
</resources>


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<component-set>
  <components>
    <component>
      <role>org.apache.maven.lifecycle.mapping.LifecycleMapping</role>
      <role-hint>scmpublish</role-hint>
      <implementation>
        org.apache.maven.lifecycle.mapping.DefaultLifecycleMapping
      </implementation>
      <configuration>
        <phases>
          <scmpublish-prepare>
          </scmpublish-prepare>
          <scmpublish-site>
            org.apache.maven.plugins:maven-site-plugin:3.1:site
          </scmpublish-site>
          <scmpublish-post-site>
            org.apache.maven.plugins:maven-site-plugin:3.1:stage
          </scmpublish-post-site>
          <scmpublish-publish>
            org.apache.maven.plugins:maven-site-scm-publish-plugin:${project.version}:publish-scm
          </scmpublish-publish>
        </phases>
      </configuration>
    </component>
    <component>
      <role>org.apache.maven.lifecycle.Lifecycle</role>
      <implementation>org.apache.maven.lifecycle.Lifecycle</implementation>
      <role-hint>scmpublish</role-hint>
      <configuration>
        <id>scmpublish</id>
        <phases>
          <phase>scmpublish-prepare</phase>
          <phase>scmpublish-site</phase>
          <phase>scmpublish-post-site</phase>
          <phase>scmpublish-publish</phase>
        </phases>
        <default-phases>
          <scmpublish-prepare>
          </scmpublish-prepare>
          <scmpublish-site>
            org.apache.maven.plugins:maven-site-plugin:3.1:site
          </scmpublish-site>
          <scmpublish-post-site>
            org.apache.maven.plugins:maven-site-plugin:3.1:stage
          </scmpublish-post-site>
          <scmpublish-publish>
            org.apache.maven.plugins:maven-site-scm-publish-plugin:${project.version}:publish-scm
          </scmpublish-publish>
        </default-phases>
      </configuration>
    </component>
  </components>
</component-set>


text:
#pragma once

#include <generatorBase/simpleGenerators/bindingGenerator.h>

namespace pioneer {
namespace lua {

/// Generates setup of specified color to given LED
class PioneerLedGenerator : public generatorBase::simple::BindingGenerator
{
public:
	PioneerLedGenerator(const qrRepo::RepoApi &repo
			, generatorBase::GeneratorCustomizer &customizer
			, const qReal::Id &id
			, QObject *parent);
};

}
}


text:
package builtin

import (
	"fmt"

	"github.com/boltdb/bolt"
	"github.com/go-kit/kit/log"
	"github.com/pkg/errors"

	"github.com/micromdm/micromdm/platform/user"
)

const (
	UserBucket = "mdm.Users"

	userIndexBucket = "mdm.UserIdx"
)

type DB struct {
	*bolt.DB
	logger log.Logger
}

func NewDB(db *bolt.DB) (*DB, error) {
	err := db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(userIndexBucket))
		if err != nil {
			return err
		}
		_, err = tx.CreateBucketIfNotExists([]byte(UserBucket))
		return err
	})
	if err != nil {
		return nil, errors.Wrapf(err, "creating %s bucket", UserBucket)
	}

	datastore := &DB{
		DB: db,
	}
	return datastore, nil
}

func (db *DB) List() ([]user.User, error) {
	var users []user.User
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(UserBucket))
		c := b.Cursor()
		for k, v := c.First(); k != nil; k, v = c.Next() {
			var u user.User
			if err := user.UnmarshalUser(v, &u); err != nil {
				return err
			}
			users = append(users, u)
		}
		return nil
	})
	return users, errors.Wrap(err, "list users")
}

func (db *DB) Save(u *user.User) error {
	tx, err := db.DB.Begin(true)
	if err != nil {
		return errors.Wrap(err, "begin transaction")
	}
	bkt := tx.Bucket([]byte(UserBucket))
	if bkt == nil {
		return fmt.Errorf("bucket %q not found!", UserBucket)
	}
	userpb, err := user.MarshalUser(u)
	if err != nil {
		return errors.Wrap(err, "marshalling user")
	}

	// store an array of indices to reference the UUID, which will be the
	// key used to store the actual user.
	indexes := []string{u.UDID, u.UserID}
	idxBucket := tx.Bucket([]byte(userIndexBucket))
	if idxBucket == nil {
		return fmt.Errorf("bucket %q not found!", userIndexBucket)
	}
	for _, idx := range indexes {
		if idx == "" {
			continue
		}
		key := []byte(idx)
		if err := idxBucket.Put(key, []byte(u.UUID)); err != nil {
			return errors.Wrap(err, "user userIdx in boltdb")
		}
	}

	key := []byte(u.UUID)
	if err := bkt.Put(key, userpb); err != nil {
		return errors.Wrap(err, "store user in boltdb")
	}
	return tx.Commit()
}

func (db *DB) User(uuid string) (*user.User, error) {
	var u user.User
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(UserBucket))
		v := b.Get([]byte(uuid))
		if v == nil {
			return &notFound{"User", fmt.Sprintf("uuid %s", uuid)}
		}
		return user.UnmarshalUser(v, &u)
	})
	if err != nil {
		return nil, errors.Wrap(err, "get user by uuid from bolt")
	}
	return &u, nil
}

func (db *DB) UserByUserID(userID string) (*user.User, error) {
	var u user.User
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(UserBucket))
		ib := tx.Bucket([]byte(userIndexBucket))
		idx := ib.Get([]byte(userID))
		if idx == nil {
			return &notFound{"User", fmt.Sprintf("user id %s", userID)}
		}
		v := b.Get(idx)
		if idx == nil {
			return &notFound{"User", fmt.Sprintf("uuid %s", string(idx))}
		}
		return user.UnmarshalUser(v, &u)
	})
	if err != nil {
		return nil, errors.Wrap(err, "get user by user id from bolt")
	}
	return &u, nil
}

func (db *DB) DeviceUsers(udid string) ([]user.User, error) {
	var users []user.User
	err := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(UserBucket))
		c := b.Cursor()
		for k, v := c.First(); k != nil; k, v = c.Next() {
			var u user.User
			if err := user.UnmarshalUser(v, &u); err != nil {
				return errors.Wrap(err, "unmarshal user for DeviceUsers")
			}
			if u.UDID == udid {
				users = append(users, u)
			}
		}
		return nil
	})
	if err != nil {
		return nil, errors.Wrap(err, "get device users")
	}
	return users, nil
}

func (db *DB) DeleteDeviceUsers(udid string) error {
	err := db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(UserBucket))
		c := b.Cursor()
		for k, v := c.First(); k != nil; k, v = c.Next() {
			var u user.User
			if err := user.UnmarshalUser(v, &u); err != nil {
				return errors.Wrap(err, "unmarshal user for DeviceUsers")
			}
			if u.UDID != udid {
				continue
			}
			if err := b.Delete(k); err != nil {
				return errors.Wrapf(err, "delete user %s from device %s", u.UserID, udid)
			}
		}
		return nil
	})
	return errors.Wrapf(err, "delete users for UDID %s", udid)
}

type notFound struct {
	ResourceType string
	Message      string
}

func (e *notFound) Error() string {
	return fmt.Sprintf("not found: %s %s", e.ResourceType, e.Message)
}

func (e *notFound) NotFound() bool {
	return true
}


text:
var http = require('http');
var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var socketListeners = require('./socketListeners');

mongoose.connect('mongodb://localhost/CodeShare');

var app = express();

app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());

app.use(app.router);
app.use('/lib', express.static(__dirname + '/lib'));
app.use('/app', express.static(__dirname + '/app'));
app.use('/css', express.static(__dirname + '/css'));

var server = http.createServer(app).listen('3000','127.0.0.1');
socketListeners.listen(server);

app.get('/', function(req,res){
    res.sendfile(__dirname + '/index.html');
});

console.log('Server is listening at 3000...');


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

<TITLE>
Overview
</TITLE>

<META NAME="keywords" CONTENT="Overview">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Packages

javagene.io

javagene.seq

javagene.util


text:
package kieker.tools.opad.model;

/**
 * @author Tillmann Carlos Bielefeld
 * @since 1.10
 */
public interface IDoubleValue {

	/**
	 * Returns the double value as basic type.
	 *
	 * @since 1.10
	 */
	public double getValue();

}


text:
/*----------------------------------------
   TESTMCI.C -- MCI Command String Tester
                (c) Charles Petzold, 1998
  ----------------------------------------*/

#include <windows.h>
#include "resource.h"

#define ID_TIMER    1

BOOL CALLBACK DlgProc (HWND, UINT, WPARAM, LPARAM) ;

TCHAR szAppName [] = TEXT ("TestMci") ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
     if (-1 == DialogBox (hInstance, szAppName, NULL, DlgProc))
     {
          MessageBox (NULL, TEXT ("This program requires Windows NT!"),
                      szAppName, MB_ICONERROR) ;
     }
     return 0 ;
}

BOOL CALLBACK DlgProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     static HWND hwndEdit ;
     int         iCharBeg, iCharEnd, iLineBeg, iLineEnd, iChar, iLine, iLength ;
     MCIERROR    error ;
     RECT        rect ;
     TCHAR       szCommand [1024], szReturn [1024],
                 szError [1024], szBuffer [32] ;

     switch (message)
     {
     case WM_INITDIALOG:
               // Center the window on screen

          GetWindowRect (hwnd, &rect) ;
          SetWindowPos (hwnd, NULL,
               (GetSystemMetrics (SM_CXSCREEN) - rect.right + rect.left) / 2,
               (GetSystemMetrics (SM_CYSCREEN) - rect.bottom + rect.top) / 2,
               0, 0, SWP_NOZORDER | SWP_NOSIZE) ;

          hwndEdit = GetDlgItem (hwnd, IDC_MAIN_EDIT) ;
          SetFocus (hwndEdit) ;
          return FALSE ;

     case WM_COMMAND:
          switch (LOWORD (wParam))
          {
          case IDOK:
                    // Find the line numbers corresponding to the selection

               SendMessage (hwndEdit, EM_GETSEL, (WPARAM) &iCharBeg,
                                                 (LPARAM) &iCharEnd) ;

               iLineBeg = SendMessage (hwndEdit, EM_LINEFROMCHAR, iCharBeg, 0) ;
               iLineEnd = SendMessage (hwndEdit, EM_LINEFROMCHAR, iCharEnd, 0) ;

                    // Loop through all the lines

               for (iLine = iLineBeg ; iLine <= iLineEnd ; iLine++)
               {
                         // Get the line and terminate it; ignore if blank

                    * (WORD *) szCommand = sizeof (szCommand) / sizeof (TCHAR) ;

                    iLength = SendMessage (hwndEdit, EM_GETLINE, iLine,
                                                     (LPARAM) szCommand) ;
                    szCommand [iLength] = '\0' ;

                    if (iLength == 0)
                         continue ;

                         // Send the MCI command

                    error = mciSendString (szCommand, szReturn,
                              sizeof (szReturn) / sizeof (TCHAR), hwnd) ;

                         // Set the Return String field

                    SetDlgItemText (hwnd, IDC_RETURN_STRING, szReturn) ;

                         // Set the Error String field (even if no error)

                    mciGetErrorString (error, szError,
                                       sizeof (szError) / sizeof (TCHAR)) ;

                    SetDlgItemText (hwnd, IDC_ERROR_STRING, szError) ;
               }
                    // Send the caret to the end of the last selected line

               iChar  = SendMessage (hwndEdit, EM_LINEINDEX,  iLineEnd, 0) ;
               iChar += SendMessage (hwndEdit, EM_LINELENGTH, iCharEnd, 0) ;
               SendMessage (hwndEdit, EM_SETSEL, iChar, iChar) ;

                    // Insert a carriage return/line feed combination

               SendMessage (hwndEdit, EM_REPLACESEL, FALSE,
                                      (LPARAM) TEXT ("\r\n")) ;
               SetFocus (hwndEdit) ;
               return TRUE ;

          case IDCANCEL:
               EndDialog (hwnd, 0) ;
               return TRUE ;

          case IDC_MAIN_EDIT:
               if (HIWORD (wParam) == EN_ERRSPACE)
               {
                    MessageBox (hwnd, TEXT ("Error control out of space."),
                                szAppName, MB_OK | MB_ICONINFORMATION) ;
                    return TRUE ;
               }
               break ;
          }
          break ;

     case MM_MCINOTIFY:
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_MESSAGE), TRUE) ;

          wsprintf (szBuffer, TEXT ("Device ID = %i"), lParam) ;
          SetDlgItemText (hwnd, IDC_NOTIFY_ID, szBuffer) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_ID), TRUE) ;

          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_SUCCESSFUL),
                              wParam & MCI_NOTIFY_SUCCESSFUL) ;

          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_SUPERSEDED),
                              wParam & MCI_NOTIFY_SUPERSEDED) ;

          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_ABORTED),
                              wParam & MCI_NOTIFY_ABORTED) ;

          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_FAILURE),
                              wParam & MCI_NOTIFY_FAILURE) ;

          SetTimer (hwnd, ID_TIMER, 5000, NULL) ;
          return TRUE ;

     case WM_TIMER:
          KillTimer (hwnd, ID_TIMER) ;

          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_MESSAGE), FALSE) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_ID), FALSE) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_SUCCESSFUL), FALSE) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_SUPERSEDED), FALSE) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_ABORTED), FALSE) ;
          EnableWindow (GetDlgItem (hwnd, IDC_NOTIFY_FAILURE), FALSE) ;
          return TRUE ;

     case WM_SYSCOMMAND:
          switch (LOWORD (wParam))
          {
          case SC_CLOSE:
               EndDialog (hwnd, 0) ;
               return TRUE ;
          }
          break ;
     }
     return FALSE ;
}


text:
package org.fiolino.common.ioc;

/**
 * This exception is thrown if an {@link FactoryFinder} is asked for a provider
 * where it can't find an accessible factory handle with the given parameters.
 */
public class NoMatchingFactoryException extends RuntimeException {

    private static final long serialVersionUID = -5416040085073505996L;

    private final Class<?> returnType;
    private final Class<?>[] parameterTypes;

    NoMatchingFactoryException(Class<?> returnType, Class<?>[] parameterTypes, String message) {
        super(message);
        this.returnType = returnType;
        this.parameterTypes = parameterTypes;
    }

    NoMatchingFactoryException(Class<?> returnType, Class<?>[] parameterTypes, String message, Throwable cause) {
        super(message, cause);
        this.returnType = returnType;
        this.parameterTypes = parameterTypes;
    }

    NoMatchingFactoryException(Class<?> returnType, Class<?>[] parameterTypes, Throwable cause) {
        super(cause);
        this.returnType = returnType;
        this.parameterTypes = parameterTypes;
    }

    /**
     * This type was asked as the return type, i.e. such a type should have been instantiated or converted to.
     */
    public Class<?> getReturnType() {
        return returnType;
    }

    /**
     * These types were asked as parameter types.
     *
     * @return No defensive copy, it's informational only anyway
     */
    public Class<?>[] getParameterTypes() {
        return parameterTypes;
    }
}


text:
using Rhino.Etl.Core;
using Rhino.Etl.Core.Operations;
using Rhino.Etl.Core.Pipelines;

namespace Rhino.Etl.Tests.Branches
{
    public class MultiThreadedWithMultiThreadPipelineFibonacciBranchingProcess : AbstractFibonacciBranchingProcess
    {
        public MultiThreadedWithMultiThreadPipelineFibonacciBranchingProcess(int numberOfFibonacciIterations, int numberOfChildOperations)
            : base(numberOfFibonacciIterations, numberOfChildOperations)
        {
        }

        protected override AbstractBranchingOperation CreateBranchingOperation()
        {
            return new MultiThreadedBranchingOperation();
        }

        protected override IPipelineExecuter CreatePipelineExecuter()
        {
            return new ThreadPoolPipelineExecuter();
        }
    }
}


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

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Alani factsheet on ARKive - Melicope mucronulata</title>
        <link rel="canonical" href="http://www.arkive.org/alani/melicope-mucronulata/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Alani (Melicope mucronulata)

Kingdom	Plantae

Phylum	Tracheophyta

Class	Magnoliopsida

Order	Sapindales

Family	Rutaceae

Genus	Melicope (1)

Classified as Critically Endangered (CR) on the IUCN Red List (1).

Information on the alani is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact:
arkive@wildscreen.org.uk

IUCN Red List (August, 2009)
http://www.iucnredlist.org/


text:
package libcore.java.lang;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

public class OldThreadTest extends junit.framework.TestCase {

    static class SimpleThread implements Runnable {
        int delay;

        public void run() {
            try {
                synchronized (this) {
                    this.notify();
                    this.wait(delay);
                }
            } catch (InterruptedException e) {
                return;
            }

        }

        public SimpleThread(int d) {
            if (d >= 0)
                delay = d;
        }
    }

    public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_StringL$L() {
        ThreadGroup tg = new ThreadGroup("Test Group2");
        st = new Thread(tg, new SimpleThread(1), "SimpleThread3", 1);
        assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
                && st.getName().equals("SimpleThread3"));
        st.start();
        try {
            st.join();
        } catch (InterruptedException e) {
        }
        tg.destroy();

        try {
            new Thread(tg, new SimpleThread(1), "SimpleThread3",
                    Integer.MAX_VALUE);
            fail("StackOverflowError/OutOfMemoryError is not thrown.");
        } catch(IllegalThreadStateException itse) {
            //expected
        }

    }

    public void test_dumpStack() {
        try {
            PrintStream savedErr = System.err;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            System.setErr(new PrintStream(baos));
            Thread.dumpStack();
            System.setErr(savedErr);

            String s = new String(baos.toByteArray());

            assertTrue(s.contains("java.lang.Thread.dumpStack"));

        } catch(Exception e) {
            fail("Unexpected exception was thrown: " + e.toString());
        }
    }

    class MonitoredClass {
        public synchronized void enterLocked() {
            boolean b = Thread.holdsLock(this);
            assertTrue("Thread should hold lock for object", b);
        }

        public void enterNonLocked() {
            boolean b = Thread.holdsLock(this);
            assertFalse("Thread should not hold lock for object", b);
        }

    }

    boolean wasInterrupted = false;

    public void test_joinWithSpuriousInterruption() throws InterruptedException {
        final Thread parker = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    // we used to get spurious wakeups upon unparking
                    LockSupport.park();
                }
            }
        };
        Thread unparker = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(100);
                        LockSupport.unpark(parker);
                    } catch (InterruptedException expected) {
                    }
                }
            }
        };

        long startNanos = System.nanoTime();
        parker.start();
        unparker.start();
        parker.join(500, 500000);
        long netWaitTime = System.nanoTime() - startNanos;
        assertTrue("Expected to wait at least 500000000ns, but was " + netWaitTime + "ns",
                netWaitTime > 500000000);
    }

    public void test_setContextClassLoader() {
        ClassLoader pcl = new ClassLoader() {};
        st = new Thread();
        st.setContextClassLoader(pcl);
        assertEquals(pcl, st.getContextClassLoader());

        st.setContextClassLoader(null);
        assertNull(st.getContextClassLoader());
    }

    public void test_setDaemonZ() {
        st = new Thread(new SimpleThread(5));
        st.start();
        try {
            st.setDaemon(false);
            fail("setDaemon() must throw exception for started thread");
        } catch (IllegalThreadStateException ex) {
            // We expect this one.
        }
    }

    private Thread launchFiveSecondDummyThread() {
        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // Ignore
                }
            }
        };

        thread.start();

        return thread;
    }

    /**
     * java.lang.Thread#sleep(long)
     */
    public void test_sleepJ() {
        // Note: Not too much we can test here that can be reliably measured.

        // Check that basic behavior is about right (with some tolerance)
        long stime = System.currentTimeMillis();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        long ftime = System.currentTimeMillis();

        assertTrue("Failed to sleep long enough", (ftime - stime) >= 500);
        assertTrue("Failed to wake up early enough", (ftime - stime) <= 1500);

        // Check that interrupt works
        st = new Thread() {
            public void run() {
                try {
                    sleep(10000);
                } catch(InterruptedException ie) {
                    wasInterrupted = true;
                }
            }
        };

        st.start();

        try {
            Thread.sleep(5000);
        } catch(InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        st.interrupt();

        try {
            Thread.sleep(5000);
        } catch(InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        assertTrue(wasInterrupted);
    }

    public void test_sleepJI() {
        // Note: Not too much we can test here that can be reliably measured.

        // Check that basic behavior is about right (with some tolerance)
        long stime = System.currentTimeMillis();

        try {
            Thread.sleep(1000, 99999);
        } catch (InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        long ftime = System.currentTimeMillis();

        assertTrue("Failed to sleep long enough", (ftime - stime) >= 500);
        assertTrue("Failed to wake up early enough", (ftime - stime) <= 1500);

        // Check that interrupt works
        st = new Thread() {
            public void run() {
                try {
                    sleep(10000, 99999);
                } catch(InterruptedException ie) {
                    wasInterrupted = true;
                }
            }
        };

        st.start();

        try {
            Thread.sleep(5000, 99999);
        } catch(InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        st.interrupt();

        try {
            Thread.sleep(5000);
        } catch(InterruptedException e) {
            fail("Unexpected InterruptedException was thrown");
        }

        assertTrue(wasInterrupted);
    }

    public void test_yield() {

        Counter [] countersNotYeld = new Counter[10];

        for(int i = 0; i < 10; i++) {
            countersNotYeld[i] = new Counter(false);
        }
        Counter countersYeld = new Counter(true);
        try {
            Thread.sleep(11000);
        } catch(InterruptedException ie) {}

        for(Counter c:countersNotYeld) {
            assertTrue(countersYeld.counter == c.counter);
        }
    }

    class Counter extends Thread {
        public int counter = 0;
        boolean isDoYield = false;

        public Counter(boolean isDoYield) {
            this.isDoYield = isDoYield;
            start();
        }

        public void run() {
            for(int i = 0; i < 10000; i++) {
                if(isDoYield)
                    yield();
                counter ++;
            }
        }
    }

    public void test_getState() throws InterruptedException {
        Thread.State state = Thread.currentThread().getState();
        assertNotNull(state);
        assertEquals(Thread.State.RUNNABLE, state);

        final Semaphore sem = new Semaphore(0);
        final Object lock = new Object();
        Thread th = new Thread() {
            @Override
            public void run() {
                  while (!sem.hasQueuedThreads()) {}
                  sem.release();

                  // RUNNABLE
                  while (run) {}

                  try {
                      // WAITING
                      sem.acquire();
                  } catch (InterruptedException e) {
                      fail("InterruptedException was thrown.");
                  }

                  // BLOCKED
                  synchronized (lock) {
                      lock.equals(new Object());
                  }
                  synchronized (lock) {
                      try {
                        sem.release();

                        // TIMED_WAITING
                        lock.wait(Long.MAX_VALUE);
                      } catch (InterruptedException e) {
                          // expected
                      }
                  }

                  // TERMINATED upon return
            }
        };
        assertEquals(Thread.State.NEW, th.getState());
        th.start();
        sem.acquire();
        assertEquals(Thread.State.RUNNABLE, th.getState());
        run = false;

        Thread.sleep(200);

        assertEquals(Thread.State.WAITING, th.getState());
        synchronized (lock) {
            sem.release();
            long start = System.currentTimeMillis();
            while(start + 1000 > System.currentTimeMillis()) {}
            assertEquals(Thread.State.BLOCKED, th.getState());
        }

        sem.acquire();

        synchronized (lock) {
            assertEquals(Thread.State.TIMED_WAITING, th.getState());
            th.interrupt();
        }

        th.join(1000);
        assertEquals(Thread.State.TERMINATED, th.getState());
    }
    volatile boolean run = true;

    public void test_holdsLock() {
        MonitoredClass monitor = new MonitoredClass();

        monitor.enterLocked();
        monitor.enterNonLocked();

        try {
            Thread.holdsLock(null);
            fail("NullPointerException was not thrown.");
        } catch(NullPointerException npe) {
            //expected
        }
    }

    @SuppressWarnings("deprecation")
    public void test_stop() {
        Thread thread = launchFiveSecondDummyThread();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }

        try {
            thread.stop();
            fail();
        } catch (UnsupportedOperationException expected) {
        }
    }

    public void test_start() {
        Thread thr = new Thread();
        thr.start();
        try {
            thr.start();
        } catch(IllegalThreadStateException itse){
            //expected
        }
    }

    @SuppressWarnings("deprecation")
    public void test_stopLjava_lang_Throwable_subtest0() {
        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // Ignore
                }
            }
        };

        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }

        try {
            thread.stop(new Exception("Oops!"));
            fail();
        } catch (UnsupportedOperationException expected) {
        }
    }

    @SuppressWarnings("deprecation")
    public void test_suspend() {
        Thread thread = launchFiveSecondDummyThread();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }

        try {
            thread.suspend();
            fail();
        } catch (UnsupportedOperationException expected) {
        }
    }

    Thread st, ct, spinner;

    @Override
    protected void tearDown() {
        try {
            if (st != null)
                st.interrupt();
        } catch (Exception e) {
        }
        try {
            if (spinner != null)
                spinner.interrupt();
        } catch (Exception e) {
        }
        try {
            if (ct != null)
                ct.interrupt();
        } catch (Exception e) {
        }

        try {
            spinner = null;
            st = null;
            ct = null;
            System.runFinalization();
        } catch (Exception e) {
        }
    }
}


text:
@interface DinesafeAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


text:
package org.modeshape.webdav.locking;

import java.util.UUID;
import org.modeshape.common.i18n.TextI18n;
import org.modeshape.common.logging.Logger;

/**
 * a helper class for ResourceLocks, represents the Locks
 *
 * @author re
 */
public class LockedObject {

    private static final Logger LOGGER = Logger.getLogger(LockedObject.class);

    private ResourceLocks resourceLocks;

    private String path;

    private String id;

    /**
     * Describing the depth of a locked collection. If the locked resource is not a collection, depth is 0 / doesn't matter.
     */
    protected int lockDepth;

    /**
     * Describing the timeout of a locked object (ms)
     */
    protected long expiresAt;

    /**
     * owner of the lock. shared locks can have multiple owners. is null if no owner is present
     */
    protected String[] owner = null;

    /**
     * children of that lock
     */
    protected LockedObject[] children = null;

    protected LockedObject parent = null;

    /**
     * weather the lock is exclusive or not. if owner=null the exclusive value doesn't matter
     */
    protected boolean exclusive = false;

    /**
     * weather the lock is a write or read lock
     */
    protected String type = null;

    /**
     * @param resLocks the resourceLocks where locks are stored
     * @param path the path to the locked object
     * @param temporary indicates if the LockedObject should be temporary or not
     */
    public LockedObject( ResourceLocks resLocks,
                         String path,
                         boolean temporary ) {
        this.path = path;
        id = UUID.randomUUID().toString();
        resourceLocks = resLocks;

        if (!temporary) {
            resourceLocks.locks.put(path, this);
            resourceLocks.locksByID.put(id, this);
        } else {
            resourceLocks.tempLocks.put(path, this);
            resourceLocks.tempLocksByID.put(id, this);
        }
        resourceLocks.cleanupCounter++;
    }

    /**
     * adds a new owner to a lock
     *
     * @param owner string that represents the owner
     * @return true if the owner was added, false otherwise
     */
    public boolean addLockedObjectOwner( String owner ) {

        if (this.owner == null) {
            this.owner = new String[1];
        } else {

            int size = this.owner.length;
            String[] newLockObjectOwner = new String[size + 1];

            // check if the owner is already here (that should actually not
            // happen)
            for (int i = 0; i < size; i++) {
                if (this.owner[i].equals(owner)) {
                    return false;
                }
            }

            System.arraycopy(this.owner, 0, newLockObjectOwner, 0, size);
            this.owner = newLockObjectOwner;
        }

        this.owner[this.owner.length - 1] = owner;
        return true;
    }

    /**
     * tries to remove the owner from the lock
     *
     * @param owner string that represents the owner
     */
    public void removeLockedObjectOwner( String owner ) {

        try {
            if (this.owner != null) {
                int size = this.owner.length;
                for (int i = 0; i < size; i++) {
                    // check every owner if it is the requested one
                    if (this.owner[i].equals(owner)) {
                        // remove the owner
                        size -= 1;
                        String[] newLockedObjectOwner = new String[size];
                        for (int j = 0; j < size; j++) {
                            if (j < i) {
                                newLockedObjectOwner[j] = this.owner[j];
                            } else {
                                newLockedObjectOwner[j] = this.owner[j + 1];
                            }
                        }
                        this.owner = newLockedObjectOwner;

                    }
                }
                if (this.owner.length == 0) {
                    this.owner = null;
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            LOGGER.error(e, new TextI18n("LockedObject.removeLockedObjectOwner()"));
        }
    }

    /**
     * adds a new child lock to this lock
     *
     * @param newChild new child
     */
    public void addChild( LockedObject newChild ) {
        if (children == null) {
            children = new LockedObject[0];
        }
        int size = children.length;
        LockedObject[] newChildren = new LockedObject[size + 1];
        System.arraycopy(children, 0, newChildren, 0, size);
        newChildren[size] = newChild;
        children = newChildren;
    }

    /**
     * deletes this Lock object. assumes that it has no children and no owners (does not check this itself)
     */
    public void removeLockedObject() {
        if (this != resourceLocks.root && !this.getPath().equals("/")) {

            int size = parent.children.length;
            for (int i = 0; i < size; i++) {
                if (parent.children[i].equals(this)) {
                    LockedObject[] newChildren = new LockedObject[size - 1];
                    for (int i2 = 0; i2 < (size - 1); i2++) {
                        if (i2 < i) {
                            newChildren[i2] = parent.children[i2];
                        } else {
                            newChildren[i2] = parent.children[i2 + 1];
                        }
                    }
                    if (newChildren.length != 0) {
                        parent.children = newChildren;
                    } else {
                        parent.children = null;
                    }
                    break;
                }
            }

            // removing from hashtable
            resourceLocks.locksByID.remove(getID());
            resourceLocks.locks.remove(getPath());

            // now the garbage collector has some work to do
        }
    }

    /**
     * deletes this Lock object. assumes that it has no children and no owners (does not check this itself)
     */
    public void removeTempLockedObject() {
        if (this != resourceLocks.tempRoot) {
            // removing from tree
            if (parent != null && parent.children != null) {
                int size = parent.children.length;
                for (int i = 0; i < size; i++) {
                    if (parent.children[i].equals(this)) {
                        LockedObject[] newChildren = new LockedObject[size - 1];
                        for (int i2 = 0; i2 < (size - 1); i2++) {
                            if (i2 < i) {
                                newChildren[i2] = parent.children[i2];
                            } else {
                                newChildren[i2] = parent.children[i2 + 1];
                            }
                        }
                        if (newChildren.length != 0) {
                            parent.children = newChildren;
                        } else {
                            parent.children = null;
                        }
                        break;
                    }
                }

                // removing from hashtable
                resourceLocks.tempLocksByID.remove(getID());
                resourceLocks.tempLocks.remove(getPath());

                // now the garbage collector has some work to do
            }
        }
    }

    /**
     * checks if a lock of the given exclusivity can be placed, only considering children up to "depth"
     *
     * @param exclusive wheather the new lock should be exclusive
     * @param depth the depth to which should be checked
     * @return true if the lock can be placed
     */
    public boolean checkLocks( boolean exclusive,
                               int depth ) {
        if (checkParents(exclusive) && checkChildren(exclusive, depth)) {
            return true;
        }
        return false;
    }

    /**
     * helper of checkLocks(). looks if the parents are locked
     *
     * @param exclusive wheather the new lock should be exclusive
     * @return true if no locks at the parent path are forbidding a new lock
     */
    private boolean checkParents( boolean exclusive ) {
        if (path.equals("/")) {
            return true;
        }
        if (owner == null) {
            // no owner, checking parents
            return parent != null && parent.checkParents(exclusive);
        }
        // there already is a owner
        return !(this.exclusive || exclusive) && parent.checkParents(exclusive);
    }

    /**
     * helper of checkLocks(). looks if the children are locked
     *
     * @param exclusive whether the new lock should be exclusive
     * @param depth depth
     * @return true if no locks at the children paths are forbidding a new lock
     */
    private boolean checkChildren( boolean exclusive,
                                   int depth ) {
        if (children == null) {
            // a file

            return owner == null || !(this.exclusive || exclusive);
        }
        // a folder

        if (owner == null) {
            // no owner, checking children

            if (depth != 0) {
                boolean canLock = true;
                int limit = children.length;
                for (int i = 0; i < limit; i++) {
                    if (!children[i].checkChildren(exclusive, depth - 1)) {
                        canLock = false;
                    }
                }
                return canLock;
            }
            // depth == 0 -> we don't care for children
            return true;
        }
        // there already is a owner
        return !(this.exclusive || exclusive);

    }

    /**
     * Sets a new timeout for the LockedObject
     *
     * @param timeout
     */
    public void refreshTimeout( int timeout ) {
        expiresAt = System.currentTimeMillis() + (timeout * 1000);
    }

    /**
     * Gets the timeout for the LockedObject
     *
     * @return timeout
     */
    public long getTimeoutMillis() {
        return (expiresAt - System.currentTimeMillis());
    }

    /**
     * Return true if the lock has expired.
     *
     * @return true if timeout has passed
     */
    public boolean hasExpired() {
        if (expiresAt != 0) {
            return (System.currentTimeMillis() > expiresAt);
        }
        return true;
    }

    /**
     * Gets the LockID (locktoken) for the LockedObject
     *
     * @return locktoken
     */
    public String getID() {
        return id;
    }

    /**
     * Gets the owners for the LockedObject
     *
     * @return owners
     */
    public String[] getOwner() {
        return owner;
    }

    /**
     * Gets the path for the LockedObject
     *
     * @return path
     */
    public String getPath() {
        return path;
    }

    /**
     * Sets the exclusivity for the LockedObject
     *
     * @param exclusive
     */
    public void setExclusive( boolean exclusive ) {
        this.exclusive = exclusive;
    }

    /**
     * Gets the exclusivity for the LockedObject
     *
     * @return exclusivity
     */
    public boolean isExclusive() {
        return exclusive;
    }

    /**
     * Gets the exclusivity for the LockedObject
     *
     * @return exclusivity
     */
    public boolean isShared() {
        return !exclusive;
    }

    /**
     * Gets the type of the lock
     *
     * @return type
     */
    public String getType() {
        return type;
    }

    /**
     * Gets the depth of the lock
     *
     * @return depth
     */
    public int getLockDepth() {
        return lockDepth;
    }

}


text:
module Puree

  module Extractor

    # Publisher extractor.
    #
    class Publisher < Puree::Extractor::Resource

      # @param id [String]
      # @return [Puree::Model::Publisher, nil]
      def find(id)
        super id: id,
              api_resource_type: :publisher,
              xml_extractor_resource_type: :publisher
      end

      # Count of records available.
      #
      # @param params [Hash] Combined GET and POST parameters for all records
      # @return [Integer]
      def count(params = {})
        record_count :publisher, params
      end

      # Random record.
      #
      # @param params [Hash] Combined GET and POST parameters for all records
      # @return [Puree::Model::Publisher, nil]
      def random(params = {})
        super :publisher, params
      end

    end

  end

end


text:
package org.cats.analytics.resource.repository;

import org.cats.analytics.resource.domain.GiftCertificate;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface GiftCertificateRepository extends MongoRepository<GiftCertificate, Long> {
}


text:
UjianPMB
========

Laravel untuk Kasus Penerimaan Mahasiswa Baru Ujian PMB STMIK Bumigora Mataram

Muhammad Erwin Indrawan erwin.jneferboy@gmail.com

Agus Farhan Suriaz

Dhedet Pratama dhedet.pratama@gmail.com

Kasus ini dikerjakan untuk menyelesaikan tugas akhir mata kuliah Pemrograman Web 2


text:
package com.example.michael.statstracker;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Michael on 5/5/2015.
 */
public class StatsDbHelper extends SQLiteOpenHelper {

    public StatsDbHelper(Context context) {
        super(context, StatsContract.DATABASE_NAME, null, StatsContract.DATABASE_VERSION);
    }

    // Method is called during creation of the database
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(StatsContract.StatsEntry.CREATE_TABLE);
    }

    // Method is called during an upgrade of the database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(StatsContract.StatsEntry.DELETE_TABLE);
        onCreate(db);
    }
}


text:
> Stringify and write JSON to a file [atomically](https://github.com/npm/write-file-atomic)

Creates directories for you as needed.

## Install

```
$ npm install --save write-json-file
```

## Usage

```js
const writeJsonFile = require('write-json-file');

writeJsonFile('foo.json', {foo: true}).then(() => {
	console.log('done');
});
```

## API

### writeJsonFile(filepath, data, [options])

Returns a `Promise`.

### writeJsonFile.sync(filepath, data, [options])

#### options

Type: `Object`

##### indent

Type: `string` `number`

Default: `\t`

Indentation as a string or number of spaces.

Pass in `null` for no formatting.

##### detectIndent

Type: `boolean`

Default: `false`

Detect indentation automatically if the file exists.

##### sortKeys

Type: `boolean` `function`

Default: `false`

Sort the keys recursively.

Optionally pass in a [`compare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) function.

##### replacer

Type: `function`

Passed into [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter).

##### mode

Type: `number`

Default: `0o666`

[Mode](https://en.wikipedia.org/wiki/File_system_permissions#Numeric_notation) used when writing the file.

## Related

- [load-json-file](https://github.com/sindresorhus/load-json-file) - Read and parse a JSON file
- [make-dir](https://github.com/sindresorhus/make-dir) - Make a directory and its parents if needed

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


text:
/*jslint indent: 2, eqeqeq: false, onevar: false, forin: true, nomen: false*/
/*global module, require, __dirname*/
/**
 * Sinon core utilities. For internal use only.
 *
 * @author Christian Johansen (christian@cjohansen.no)
 * @license BSD
 *
 * Copyright (c) 2010 Christian Johansen
 */
var sinon = (function () {
  return {
    wrapMethod: function wrapMethod(object, property, method) {
      if (!object) {
        throw new TypeError("Should wrap property of object");
      }

      if (typeof method != "function") {
        throw new TypeError("Method wrapper should be function");
      }

      var wrappedMethod = object[property];
      var type = typeof wrappedMethod;

      if (type != "function") {
        throw new TypeError("Attempted to wrap " + type + " property " + property +
                            " as function");
      }

      object[property] = method;
      method.originalName = property;

      method.restore = function () {
        object[property] = wrappedMethod;
      };

      method.toString = function () {
        return sinon.fakeName(method);
      };

      return method;
    },

    extend: function extend(target) {
      for (var i = 1, l = arguments.length; i < l; i += 1) {
        for (var prop in arguments[i]) {
          if (arguments[i].hasOwnProperty(prop)) {
            target[prop] = arguments[i][prop];
          }
        }
      }

      return target;
    },

    create: function create(proto) {
      if (Object.create) {
        return Object.create(proto);
      } else {
        var F = function () {};
        F.prototype = proto;
        return new F();
      }
    },

    deepEqual: function deepEqual(a, b) {
      if (typeof a != "object" || typeof b != "object") {
        return a === b;
      }

      if (a === b) {
        return true;
      }

      if (Object.prototype.toString.call(a) == "[object Array]") {
        if (a.length !== b.length) {
          return false;
        }

        for (var i = 0, l = a.length; i < l; i += 1) {
          if (!deepEqual(a[i], b[i])) {
            return false;
          }
        }

        return true;
      }

      var prop, aLength = 0, bLength = 0;

      for (prop in a) {
        aLength += 1;

        if (!deepEqual(a[prop], b[prop])) {
          return false;
        }
      }

      for (prop in b) {
        bLength += 1;
      }

      if (aLength != bLength) {
        return false;
      }

      return true;
    },

    keys: function keys(object) {
      var objectKeys = [];

      for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
          objectKeys.push(prop);
        }
      }

      return objectKeys.sort();
    },

    fakeName: function fakeName(method) {
      if (method.originalName) {
        return method.originalName;
      }

      if (method.getCall) {
        var thisObj = method.getCall(method.callCount - 1).thisObj;

        for (var prop in thisObj) {
          if (thisObj[prop] === method) {
            return prop;
          }
        }
      }

      return method.name || "sinon fake";
    }
  };
}());

if (typeof module == "object" && typeof require == "function") {
  require.paths.unshift(__dirname);
  module.exports = sinon;
  module.exports.spy = require("sinon/spy");
  module.exports.stub = require("sinon/stub");
  module.exports.mock = require("sinon/mock");
  module.exports.collection = require("sinon/collection");
  module.exports.assert = require("sinon/assert");
  module.exports.test = require("sinon/test");
  module.exports.testCase = require("sinon/test_case");
  require.paths.shift();
}


text:
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this data, including any software or models in source or binary
// form, as well as any drawings, specifications, and documentation
// (collectively "the Data"), to deal in the Data without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Data, and to
// permit persons to whom the Data is furnished to do so, subject to the
// following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Data.

// THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.

// =======================
// This version of the META tools is a fork of an original version produced
// by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
// Their license statement:

// Copyright (C) 2011-2014 Vanderbilt University

// Developed with the sponsorship of the Defense Advanced Research Projects
// Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
// as defined in DFARS 252.227-7013.

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this data, including any software or models in source or binary
// form, as well as any drawings, specifications, and documentation
// (collectively "the Data"), to deal in the Data without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Data, and to
// permit persons to whom the Data is furnished to do so, subject to the
// following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Data.

// THE DATA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS, SPONSORS, DEVELOPERS, CONTRIBUTORS, OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE DATA OR THE USE OR OTHER DEALINGS IN THE DATA.

#ifndef __FMUCODEGEN_H__
#define __FMUCODEGEN_H__

#include "SFC.h"
#include "FMI.h"

class FMUCodeGen
{
public:
	FMUCodeGen(SFC::Project &prj, const std::string &topSubsystemName, const std::string &outputDirectory);
	void gen();

private:
	SFC::Project _sfprj;
	std::string _topSubsystemName;
	std::string _fmiFile;
	std::string _cWrapperFile;

	std::string _define;
	std::string _setStartValues;
	std::string _getReal;

	int _nReal;
	int _nInt;
	int _nBool;
	int _nStr;
	int _nState;
	int _nEvent;

	void getArgs();
	std::string generateGUID();
	void genModelVariables(FMI::ModelVariables &mvars);
	void processArg(FMI::ModelVariables &mvars, const SFC::Arg &arg);
};

#endif