text:
Project: /_project.yaml
Book: /_book.yaml

# Action Graph Query (aquery)

The `aquery` command allows you to query for actions in your build graph.
It operates on the post-analysis Configured Target Graph and exposes
information about **Actions, Artifacts and their relationships.**

`aquery` is useful when you are interested in the properties of the Actions/Artifacts
generated from the Configured Target Graph. For example, the actual commands run
and their inputs/outputs/mnemonics.

The tool accepts several command-line [options](#command-options).
Notably, the aquery command runs on top of a regular Bazel build and inherits
the set of options available during a build.

It supports the same set of functions that is also available to traditional
`query` but `siblings`, `buildfiles` and
`tests`.

An example `aquery` output (without specific details):

$ bazel aquery 'deps(//some:label)'
action 'Writing file some_file_name'
  Mnemonic: ...
  Target: ...
  Configuration: ...
  ActionKey: ...
  Inputs: [...]
  Outputs: [...]

## Basic syntax {:#basic-syntax}

A simple example of the syntax for `aquery` is as follows:

`bazel aquery "aquery_function(function(//target))"`

The query expression (in quotes) consists of the following:

*   `aquery_function(...)`: functions specific to `aquery`.
    More details [below](#using-aquery-functions).
*   `function(...)`: the standard [functions](/reference/query#functions)
    as traditional `query`.
*   `//target` is the label to the interested target.

# aquery examples:
# Get the action graph generated while building //src/target_a
$ bazel aquery '//src/target_a'

# Get the action graph generated while building all dependencies of //src/target_a
$ bazel aquery 'deps(//src/target_a)'

# Get the action graph generated while building all dependencies of //src/target_a
# whose inputs filenames match the regex ".*cpp".
$ bazel aquery 'inputs(".*cpp", deps(//src/target_a))'

## Using aquery functions {:#using-aquery-functions}

There are three `aquery` functions:

*   `inputs`: filter actions by inputs.
*   `outputs`: filter actions by outputs
*   `mnemonic`: filter actions by mnemonic

`expr ::= inputs(word, expr)`

  The `inputs` operator returns the actions generated from building `expr`,
  whose input filenames match the regex provided by `word`.

`$ bazel aquery 'inputs(".*cpp", deps(//src/target_a))'`

`outputs` and `mnemonic` functions share a similar syntax.

You can also combine functions to achieve the AND operation. For example:

  $ bazel aquery 'mnemonic("Cpp.*", (inputs(".*cpp", inputs("foo.*", //src/target_a))))'

  The above command would find all actions involved in building `//src/target_a`,
  whose mnemonics match `"Cpp.*"` and inputs match the patterns
  `".*cpp"` and `"foo.*"`.

Important: aquery functions can't be nested inside non-aquery functions.
Conceptually, this makes sense since the output of aquery functions is Actions,
not Configured Targets.

An example of the syntax error produced:

        $ bazel aquery 'deps(inputs(".*cpp", //src/target_a))'
        ERROR: aquery filter functions (inputs, outputs, mnemonic) produce actions,
        and therefore can't be the input of other function types: deps
        deps(inputs(".*cpp", //src/target_a))

## Options {:#options}

### Build options {:#build-options}

`aquery` runs on top of a regular Bazel build and thus inherits the set of
[options](/reference/command-line-reference#build-options)
available during a build.

### Aquery options {:#aquery-options}

#### `--output=(text|summary|proto|jsonproto|textproto), default=text` {:#output}

The default output format (`text`) is human-readable,
use `proto`, `textproto`, or `jsonproto` for machine-readable format.
The proto message is `analysis.ActionGraphContainer`.

#### `--include_commandline, default=true` {:#include-commandline}

Includes the content of the action command lines in the output (potentially large).

#### `--include_artifacts, default=true` {:#include-artifacts}

Includes names of the action inputs and outputs in the output (potentially large).

#### `--include_aspects, default=true` {:#include-aspects}

Whether to include Aspect-generated actions in the output.

#### `--include_param_files, default=false` {:#include-param-files}

Include the content of the param files used in the command (potentially large).

Warning: Enabling this flag will automatically enable the `--include_commandline` flag.

#### `--include_file_write_contents, default=false` {:#include-file-write-contents}

Include file contents for the `actions.write()` action and the contents of the
manifest file for the `SourceSymlinkManifest` action The file contents is
returned in the `file_contents` field with `--output=`xxx`proto`.
With `--output=text`, the output has
```
FileWriteContents: [<base64-encoded file contents>]
```
line

#### `--skyframe_state, default=false` {:#skyframe-state}

Without performing extra analysis, dump the Action Graph from Skyframe.

Note: Specifying a target with `--skyframe_state` is currently not supported.
This flag is only available with `--output=proto` or `--output=textproto`.

## Other tools and features {:#other-tools-features}

### Querying against the state of Skyframe {:#querying-against-skyframe}

[Skyframe](/reference/skyframe) is the evaluation and
incrementality model of Bazel. On each instance of Bazel server, Skyframe stores the dependency graph
constructed from the previous runs of the [Analysis phase](/docs/build#analysis).

In some cases, it is useful to query the Action Graph on Skyframe.
An example use case would be:

1.  Run `bazel build //target_a`
2.  Run `bazel build //target_b`
3.  File `foo.out` was generated.

_As a Bazel user, I want to determine if `foo.out` was generated from building
`//target_a` or `//target_b`_.

One could run `bazel aquery 'outputs("foo.out", //target_a)'` and
`bazel aquery 'outputs("foo.out", //target_b)'` to figure out the action responsible
for creating `foo.out`, and in turn the target. However, the number of different
targets previously built can be larger than 2, which makes running multiple `aquery`
commands a hassle.

As an alternative, the `--skyframe_state` flag can be used:

  # List all actions on Skyframe's action graph
  $ bazel aquery --output=proto --skyframe_state

  # or

  # List all actions on Skyframe's action graph, whose output matches "foo.out"
  $ bazel aquery --output=proto --skyframe_state 'outputs("foo.out")'

With `--skyframe_state` mode, `aquery` takes the content of the Action Graph
that Skyframe keeps on the instance of Bazel, (optionally) performs filtering on it and
outputs the content, without re-running the analysis phase.

#### Special considerations {:#special-considerations}

##### Output format {:#output-format}

`--skyframe_state` is currently only available for `--output=proto`
and `--output=textproto`

##### Non-inclusion of target labels in the query expression {:#target-labels-non-inclusion}

Currently, `--skyframe_state` queries the whole action graph that exists on Skyframe,
regardless of the targets. Having the target label specified in the query together with
`--skyframe_state` is considered a syntax error:

  # WRONG: Target Included
  $ bazel aquery --output=proto --skyframe_state **//target_a**
  ERROR: Error while parsing '//target_a)': Specifying build target(s) [//target_a] with --skyframe_state is currently not supported.

  # WRONG: Target Included
  $ bazel aquery --output=proto --skyframe_state 'inputs(".*.java", **//target_a**)'
  ERROR: Error while parsing '//target_a)': Specifying build target(s) [//target_a] with --skyframe_state is currently not supported.

  # CORRECT: Without Target
  $ bazel aquery --output=proto --skyframe_state
  $ bazel aquery --output=proto --skyframe_state 'inputs(".*.java")'

### Comparing aquery outputs {:#comparing-aquery-outputs}

You can compare the outputs of two different aquery invocations using the `aquery_differ` tool.
For instance: when you make some changes to your rule definition and want to verify that the
command lines being run did not change. `aquery_differ` is the tool for that.

The tool is available in the [bazelbuild/bazel](https://github.com/bazelbuild/bazel/tree/master/tools/aquery_differ){: .external} repository.
To use it, clone the repository to your local machine. An example usage:

  $ bazel run //tools/aquery_differ -- \
  --before=/path/to/before.proto \
  --after=/path/to/after.proto \
  --input_type=proto \
  --attrs=cmdline \
  --attrs=inputs

The above command returns the difference between the `before` and `after` aquery outputs:
which actions were present in one but not the other, which actions have different
command line/inputs in each aquery output, ...). The result of running the above command would be:

  Aquery output 'after' change contains an action that generates the following outputs that aquery output 'before' change doesn't:
  ...
  /list of output files/
  ...

  [cmdline]
  Difference in the action that generates the following output(s):
    /path/to/abc.out
  --- /path/to/before.proto
  +++ /path/to/after.proto
  @@ -1,3 +1,3 @@
    ...
    /cmdline diff, in unified diff format/
    ...

#### Command options {:#command-options}

`--before, --after`: The aquery output files to be compared

`--input_type=(proto|text_proto), default=proto`: the format of the input
files. Support is provided for `proto` and `textproto` aquery output.

`--attrs=(cmdline|inputs), default=cmdline`: the attributes of actions
to be compared.

### Aspect-on-aspect {:#aspect-on-aspect}

It is possible for [Aspects](/rules/aspects)
to be applied on top of each other. The aquery output of the action generated by
these Aspects would then include the _Aspect path_, which is the sequence of
Aspects applied to the target which generated the action.

An example of Aspect-on-Aspect:

  t0
  ^
  | <- a1
  t1
  ^
  | <- a2
  t2

Let ti be a target of rule ri, which applies an Aspect ai
to its dependencies.

Assume that a2 generates an action X when applied to target t0. The text output of
`bazel aquery --include_aspects 'deps(//t2)'` for action X would be:

  action ...
  Mnemonic: ...
  Target: //my_pkg:t0
  Configuration: ...
  AspectDescriptors: [//my_pkg:rule.bzl%**a2**(foo=...)
    -> //my_pkg:rule.bzl%**a1**(bar=...)]
  ...

This means that action `X` was generated by Aspect `a2` applied onto
`a1(t0)`, where `a1(t0)` is the result of Aspect `a1` applied
onto target `t0`.

Each `AspectDescriptor` has the following format:

  AspectClass([param=value,...])

`AspectClass` could be the name of the Aspect class (for native Aspects) or
`bzl_file%aspect_name` (for Starlark Aspects). `AspectDescriptor` are
sorted in topological order of the
[dependency graph](/rules/aspects#aspect_basics).

### Linking with the JSON profile {:#linking-with-json-profile}

While aquery provides information about the actions being run in a build (why they're being run,
their inputs/outputs), the [JSON profile](/rules/performance#performance-profiling)
tells us the timing and duration of their execution.
It is possible to combine these 2 sets of information via a common denominator: an action's primary output.

To include actions' outputs in the JSON profile, generate the profile with
`--experimental_include_primary_output --noexperimental_slim_json_profile`.
Slim profiles are incompatible with the inclusion of primary outputs. An action's primary output
is included by default by aquery.

We don't currently provide a canonical tool to combine these 2 data sources, but you should be
able to build your own script with the above information.

## Known issues {:#known-issues}

### Handling shared actions {:#handling-shared-actions}

Sometimes actions are
[shared](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/Actions.java;l=59;drc=146d51aa1ec9dcb721a7483479ef0b1ac21d39f1){: .external}
between configured targets.

In the execution phase, those shared actions are
[simply considered as one](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/Actions.java;l=241;drc=003b8734036a07b496012730964ac220f486b61f){: .external} and only executed once.
However, aquery operates on the pre-execution, post-analysis action graph, and hence treats these
like separate actions whose output Artifacts have the exact same `execPath`. As a result,
equivalent Artifacts appear duplicated.

The list of aquery issues/planned features can be found on
[GitHub](https://github.com/bazelbuild/bazel/labels/team-Performance){: .external}.

## FAQs {:#faqs}

### The ActionKey remains the same even though the content of an input file changed. {:#actionkey-same}

In the context of aquery, the `ActionKey` refers to the `String` gotten from
[ActionAnalysisMetadata#getKey](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/ActionAnalysisMetadata.java;l=89;drc=8b856f5484f0117b2aebc302f849c2a15f273310){: .external}:

  Returns a string encoding all of the significant behaviour of this Action that might affect the
  output. The general contract of `getKey` is this: if the work to be performed by the
  execution of this action changes, the key must change.

  ...

  Examples of changes that should affect the key are:

  - Changes to the BUILD file that materially affect the rule which gave rise to this Action.
  - Changes to the command-line options, environment, or other global configuration resources
      which affect the behaviour of this kind of Action (other than changes to the names of the
      input/output files, which are handled externally).
  - An upgrade to the build tools which changes the program logic of this kind of Action
      (typically this is achieved by incorporating a UUID into the key, which is changed each
      time the program logic of this action changes).
  Note the following exception: for actions that discover inputs, the key must change if any
  input names change or else action validation may falsely validate.

This excludes the changes to the content of the input files, and is not to be confused with
[RemoteCacheClient#ActionKey](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java;l=38;drc=21577f202eb90ce94a337ebd2ede824d609537b6){: .external}.

## Updates {:#updates}

For any issues/feature requests, please file an issue [here](https://github.com/bazelbuild/bazel/issues/new).


text:
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;

namespace GymFitnessOlympic.Models.Mapping
{
    class GoiTapMap : EntityTypeConfiguration<GoiTap>
    {
        public GoiTapMap()
        {
            // Khoá chính
            this.HasKey(t => t.MaGoiTap);
            //Các cột
            this.Property(t => t.Gia).IsRequired();
            this.Property(t => t.SoThang).IsRequired();

            this.ToTable("GoiTap");
            this.Property(t => t.MaGoiTap).HasColumnName("MaGoiTap");
            this.Property(t => t.Gia).HasColumnName("Gia");
            this.Property(t => t.TenGoiTap).HasColumnName("TenGoiTap");
            this.Property(t => t.SoThang).HasColumnName("SoThang");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
    {% for artifact in filter %}
        <button class="btn btn-default btn-block artifact-assign-choice artifact-popover" data-placement="right" data-artifact-id="{{ artifact.pk.hex }}" data-instance-id="{{ instance_id }}">
            {% include 'herders/profile/artifacts/artifact_image_fragment.html' with artifact=artifact only %}

{{ artifact }}

{{ artifact.get_main_stat_artifact_display }}

        </button>
    {% empty %}

            Your search has no results.

    {% endfor %}


text:
/* vi: set sw=4 ts=4: */
/* printf - format and print data

   Copyright 1999 Dave Cinege
   Portions copyright (C) 1990-1996 Free Software Foundation, Inc.

   Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/

/* Usage: printf format [argument...]

   A front end to the printf function that lets it be used from the shell.

   Backslash escapes:

   \" = double quote
   \\ = backslash
   \a = alert (bell)
   \b = backspace
   \c = produce no further output
   \f = form feed
   \n = new line
   \r = carriage return
   \t = horizontal tab
   \v = vertical tab
   \0ooo = octal number (ooo is 0 to 3 digits)
   \xhhh = hexadecimal number (hhh is 1 to 3 digits)

   Additional directive:

   %b = print an argument string, interpreting backslash escapes

   The 'format' argument is re-used as many times as necessary
   to convert all of the given arguments.

   David MacKenzie <djm@gnu.ai.mit.edu>
*/

/* 19990508 Busy Boxed! Dave Cinege */

//config:config PRINTF
//config:	bool "printf"
//config:	default y
//config:	help
//config:	  printf is used to format and print specified strings.
//config:	  It's similar to `echo' except it has more options.

//applet:IF_PRINTF(APPLET_NOFORK(printf, printf, BB_DIR_USR_BIN, BB_SUID_DROP, printf))

//kbuild:lib-$(CONFIG_PRINTF) += printf.o

//usage:#define printf_trivial_usage
//usage:       "FORMAT [ARG]..."
//usage:#define printf_full_usage "\n\n"
//usage:       "Format and print ARG(s) according to FORMAT (a-la C printf)"
//usage:
//usage:#define printf_example_usage
//usage:       "$ printf \"Val=%d\\n\" 5\n"
//usage:       "Val=5\n"

#include "libbb.h"

/* A note on bad input: neither bash 3.2 nor coreutils 6.10 stop on it.
 * They report it:
 *  bash: printf: XXX: invalid number
 *  printf: XXX: expected a numeric value
 *  bash: printf: 123XXX: invalid number
 *  printf: 123XXX: value not completely converted
 * but then they use 0 (or partially converted numeric prefix) as a value
 * and continue. They exit with 1 in this case.
 * Both accept insane field width/precision (e.g. %9999999999.9999999999d).
 * Both print error message and assume 0 if %*.*f width/precision is "bad"
 *  (but negative numbers are not "bad").
 * Both accept negative numbers for %u specifier.
 *
 * We try to be compatible.
 */

typedef void FAST_FUNC (*converter)(const char *arg, void *result);

static int multiconvert(const char *arg, void *result, converter convert)
{
	if (*arg == '"' || *arg == '\'') {
		arg = utoa((unsigned char)arg[1]);
	}
	errno = 0;
	convert(arg, result);
	if (errno) {
		bb_error_msg("invalid number '%s'", arg);
		return 1;
	}
	return 0;
}

static void FAST_FUNC conv_strtoull(const char *arg, void *result)
{
	*(unsigned long long*)result = bb_strtoull(arg, NULL, 0);
	/* both coreutils 6.10 and bash 3.2:
	 * $ printf '%x\n' -2
	 * fffffffffffffffe
	 * Mimic that:
	 */
	if (errno) {
		*(unsigned long long*)result = bb_strtoll(arg, NULL, 0);
	}
}
static void FAST_FUNC conv_strtoll(const char *arg, void *result)
{
	*(long long*)result = bb_strtoll(arg, NULL, 0);
}
static void FAST_FUNC conv_strtod(const char *arg, void *result)
{
	char *end;
	/* Well, this one allows leading whitespace... so what? */
	/* What I like much less is that "-" accepted too! :( */
	*(double*)result = strtod(arg, &end);
	if (end[0]) {
		errno = ERANGE;
		*(double*)result = 0;
	}
}

/* Callers should check errno to detect errors */
static unsigned long long my_xstrtoull(const char *arg)
{
	unsigned long long result;
	if (multiconvert(arg, &result, conv_strtoull))
		result = 0;
	return result;
}
static long long my_xstrtoll(const char *arg)
{
	long long result;
	if (multiconvert(arg, &result, conv_strtoll))
		result = 0;
	return result;
}
static double my_xstrtod(const char *arg)
{
	double result;
	multiconvert(arg, &result, conv_strtod);
	return result;
}

/* Handles %b; return 1 if output is to be short-circuited by \c */
static int print_esc_string(const char *str)
{
	char c;
	while ((c = *str) != '\0') {
		str++;
		if (c == '\\') {
			/* %b also accepts 4-digit octals of the form \0### */
			if (*str == '0') {
				if ((unsigned char)(str[1] - '0') < 8) {
					/* 2nd char is 0..7: skip leading '0' */
					str++;
				}
			}
			else if (*str == 'c') {
				return 1;
			}
			{
				/* optimization: don't force arg to be on-stack,
				 * use another variable for that. */
				const char *z = str;
				c = bb_process_escape_sequence(&z);
				str = z;
			}
		}
		putchar(c);
	}

	return 0;
}

static void print_direc(char *format, unsigned fmt_length,
		int field_width, int precision,
		const char *argument)
{
	long long llv;
	double dv;
	char saved;
	char *have_prec, *have_width;

	saved = format[fmt_length];
	format[fmt_length] = '\0';

	have_prec = strstr(format, ".*");
	have_width = strchr(format, '*');
	if (have_width - 1 == have_prec)
		have_width = NULL;

	errno = 0;

	switch (format[fmt_length - 1]) {
	case 'c':
		printf(format, *argument);
		break;
	case 'd':
	case 'i':
		llv = my_xstrtoll(argument);
 print_long:
		if (!have_width) {
			if (!have_prec)
				printf(format, llv);
			else
				printf(format, precision, llv);
		} else {
			if (!have_prec)
				printf(format, field_width, llv);
			else
				printf(format, field_width, precision, llv);
		}
		break;
	case 'o':
	case 'u':
	case 'x':
	case 'X':
		llv = my_xstrtoull(argument);
		/* cheat: unsigned long and long have same width, so... */
		goto print_long;
	case 's':
		/* Are char* and long long the same? */
		if (sizeof(argument) == sizeof(llv)) {
			llv = (long long)(ptrdiff_t)argument;
			goto print_long;
		} else {
			/* Hope compiler will optimize it out by moving call
			 * instruction after the ifs... */
			if (!have_width) {
				if (!have_prec)
					printf(format, argument, /*unused:*/ argument, argument);
				else
					printf(format, precision, argument, /*unused:*/ argument);
			} else {
				if (!have_prec)
					printf(format, field_width, argument, /*unused:*/ argument);
				else
					printf(format, field_width, precision, argument);
			}
			break;
		}
	case 'f':
	case 'e':
	case 'E':
	case 'g':
	case 'G':
		dv = my_xstrtod(argument);
		if (!have_width) {
			if (!have_prec)
				printf(format, dv);
			else
				printf(format, precision, dv);
		} else {
			if (!have_prec)
				printf(format, field_width, dv);
			else
				printf(format, field_width, precision, dv);
		}
		break;
	} /* switch */

	format[fmt_length] = saved;
}

/* Handle params for "%*.*f". Negative numbers are ok (compat). */
static int get_width_prec(const char *str)
{
	int v = bb_strtoi(str, NULL, 10);
	if (errno) {
		bb_error_msg("invalid number '%s'", str);
		v = 0;
	}
	return v;
}

/* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
   Return advanced ARGV.  */
static char **print_formatted(char *f, char **argv, int *conv_err)
{
	char *direc_start;      /* Start of % directive.  */
	unsigned direc_length;  /* Length of % directive.  */
	int field_width;        /* Arg to first '*' */
	int precision;          /* Arg to second '*' */
	char **saved_argv = argv;

	for (; *f; ++f) {
		switch (*f) {
		case '%':
			direc_start = f++;
			direc_length = 1;
			field_width = precision = 0;
			if (*f == '%') {
				bb_putchar('%');
				break;
			}
			if (*f == 'b') {
				if (*argv) {
					if (print_esc_string(*argv))
						return saved_argv; /* causes main() to exit */
					++argv;
				}
				break;
			}
			if (strchr("-+ #", *f)) {
				++f;
				++direc_length;
			}
			if (*f == '*') {
				++f;
				++direc_length;
				if (*argv)
					field_width = get_width_prec(*argv++);
			} else {
				while (isdigit(*f)) {
					++f;
					++direc_length;
				}
			}
			if (*f == '.') {
				++f;
				++direc_length;
				if (*f == '*') {
					++f;
					++direc_length;
					if (*argv)
						precision = get_width_prec(*argv++);
				} else {
					while (isdigit(*f)) {
						++f;
						++direc_length;
					}
				}
			}

			/* Remove "lLhz" size modifiers, repeatedly.
			 * bash does not like "%lld", but coreutils
			 * happily takes even "%Llllhhzhhzd"!
			 * We are permissive like coreutils */
			while ((*f | 0x20) == 'l' || *f == 'h' || *f == 'z') {
				overlapping_strcpy(f, f + 1);
			}
			/* Add "ll" if integer modifier, then print */
			{
				static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
				char *p = strchr(format_chars, *f);
				/* needed - try "printf %" without it */
				if (p == NULL) {
					bb_error_msg("%s: invalid format", direc_start);
					/* causes main() to exit with error */
					return saved_argv - 1;
				}
				++direc_length;
				if (p - format_chars <= 5) {
					/* it is one of "diouxX" */
					p = xmalloc(direc_length + 3);
					memcpy(p, direc_start, direc_length);
					p[direc_length + 1] = p[direc_length - 1];
					p[direc_length - 1] = 'l';
					p[direc_length] = 'l';
					//bb_error_msg("<%s>", p);
					direc_length += 2;
					direc_start = p;
				} else {
					p = NULL;
				}
				if (*argv) {
					print_direc(direc_start, direc_length, field_width,
								precision, *argv++);
				} else {
					print_direc(direc_start, direc_length, field_width,
								precision, "");
				}
				*conv_err |= errno;
				free(p);
			}
			break;
		case '\\':
			if (*++f == 'c') {
				return saved_argv; /* causes main() to exit */
			}
			bb_putchar(bb_process_escape_sequence((const char **)&f));
			f--;
			break;
		default:
			putchar(*f);
		}
	}

	return argv;
}

int printf_main(int argc UNUSED_PARAM, char **argv)
{
	int conv_err;
	char *format;
	char **argv2;

	/* We must check that stdout is not closed.
	 * The reason for this is highly non-obvious.
	 * printf_main is used from shell.
	 * Shell must correctly handle 'printf "%s" foo'
	 * if stdout is closed. With stdio, output gets shoveled into
	 * stdout buffer, and even fflush cannot clear it out. It seems that
	 * even if libc receives EBADF on write attempts, it feels determined
	 * to output data no matter what. So it will try later,
	 * and possibly will clobber future output. Not good. */
// TODO: check fcntl() & O_ACCMODE == O_WRONLY or O_RDWR?
	if (fcntl(1, F_GETFL) == -1)
		return 1; /* match coreutils 6.10 (sans error msg to stderr) */
	//if (dup2(1, 1) != 1) - old way
	//	return 1;

	/* bash builtin errors out on "printf '-%s-\n' foo",
	 * coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
	 * We will mimic coreutils. */
	if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
		argv++;
	if (!argv[1]) {
		if (ENABLE_ASH_BUILTIN_PRINTF
		 && applet_name[0] != 'p'
		) {
			bb_error_msg("usage: printf FORMAT [ARGUMENT...]");
			return 2; /* bash compat */
		}
		bb_show_usage();
	}

	format = argv[1];
	argv2 = argv + 2;

	conv_err = 0;
	do {
		argv = argv2;
		argv2 = print_formatted(format, argv, &conv_err);
	} while (argv2 > argv && *argv2);

	/* coreutils compat (bash doesn't do this):
	if (*argv)
		fprintf(stderr, "excess args ignored");
	*/

	return (argv2 < argv) /* if true, print_formatted errored out */
		|| conv_err; /* print_formatted saw invalid number */
}


text:
from distutils.core import setup

setup(
    name = 'django-profile-middleware',
    packages = ['django_profile_middleware'],
    version= '0.1',
    license = 'MIT',
    description = 'an easy to use middleware to profile your custom middlewares and code',
    author = 'Himanshu Goyal',
    author_email = 'hggoyal06@gmail.com',
    url = 'https://github.com/lavi06/django-profile-middleware',
    download_url = 'https://github.com/lavi06/django-profile-middleware/archive/0.1.tar.gz',
    keywords = ['django','profiling','cProfile','profile','profiler'],
    classifiers = [],
)


text:
package com.jetbrains.python.debugger;

import com.jetbrains.python.psi.PyFunction;
import com.jetbrains.python.psi.PyNamedParameter;
import com.jetbrains.python.psi.types.*;
import org.jetbrains.annotations.NotNull;

/**
 * @author traff
 */
public class PyCallSignatureTypeProvider extends PyTypeProviderBase {
  public PyType getParameterType(@NotNull final PyNamedParameter param, @NotNull final PyFunction func, @NotNull TypeEvalContext context) {
    final String name = param.getName();
    if (name != null) {
      final String typeName = PySignatureCacheManager.getInstance(param.getProject()).findParameterType(func, name);
      if (typeName != null) {
        final PyType type = PyTypeParser.getTypeByName(param, typeName);
        if (type != null) {
          return PyDynamicallyEvaluatedType.create(type);
        }
      }
    }
    return null;
  }
}


text:
Paths and Trajectories
======================================

Klamp't distinguishes between *paths* and *trajectories*: paths are
geometric, time-free curves, while trajectories are paths with an
explicit time parameterization. Mathematically, paths are expressed as a
continuous curve

    :math:`y(s):[0,1] \rightarrow C`

while trajectories are expressed as continuous curves

    :math:`y(t):[t_i,t_f] \rightarrow C`

where :math:`C` is the configuration space and :math:`t_i,t_f` are the initial and
final times of the trajectory, respectively.

Classical motion planners compute paths, because time is essentially
irrelevant for fully actuated robots in static environments. However, a
robot must ultimately execute trajectories, so a planner must somehow
prescribe times to paths before executing them. Various methods are
available in Klamp't to convert paths into trajectories.

Path and trajectory representations
-----------------------------------

+-----------+---------------+-----------+-----------------------------------------------------------------+
| Type      | Continuity    | Timed?    | Description                                                     |
+===========+===============+===========+=================================================================+
| Configs   | C0            | No        | The simplest path type: a  list of ``Config``  milestones*      |
|           |               |           | that should be piecewise linearly interpolated.  *These are     |
|           |               |           | outputted from kinematic motion planners*.                      |
+-----------+---------------+-----------+-----------------------------------------------------------------+
| Piecewise | C0            | Yes       | Given by lists of ``times`` and  ``milestones`` that should be  |
| linear    |               |           | piecewise linearly interpolated. *The most compatible trajectory|
|           |               |           | type*.  Implemented for Euclidean spaces via the                |
|           |               |           | :class:~`klampt.model.trajectory.Trajectory` class              |
+-----------+---------------+-----------+-----------------------------------------------------------------+
| Cubic     | C1            | Yes       | Piecewise cubic curve, with time. Implemented for Euclidean     |
| spline    |               |           | spaces by :class:~`klampt.model.trajectory.HermiteTrajectory`.  |
+-----------+---------------+-----------+-----------------------------------------------------------------+
| MultiPath | C0 or C1      | Either    | A rich container type for paths/trajectories annotated with     |
|           |               |           | changing contacts and  IK constraints.                          |
+-----------+---------------+-----------+-----------------------------------------------------------------+

.. note::
    To properly handle a robot's rotational joints, milestones should
    be interpolated via robot-specific interpolation functions. Cartesian
    linear interpolation does not correctly handle floating and spin joints.
    We provide the :class:`~klampt.model.trajectory.RobotTrajectory` class
    to do this automatically.

For legged robots and multi-step manipulations, the preferred path type is ``MultiPath``,
which allows storing both untimed paths and timed trajectories. It can
also store multiple path sections with inverse kinematics constraints on
each section. More details on the ``MultiPath`` type `are given below <#multipaths>`__.

API summary
~~~~~~~~~~~

The code for implementing `klampt.model.trajectory <klampt.model.trajectory.html>`__.
Piecewise linear trajectories are given in the :class:`~klampt.model.trajectory.Trajectory` class.
Paths in non-Euclidean spaces are represented by the :class:`~klampt.model.trajectory.SO3Trajectory`,
:class:`~klampt.model.trajectory.SE3Trajectory`,
and :class:`~klampt.model.trajectory.RobotTrajectory` classes.

Members include:

-  ``times``: an array of N floats, in increasing order, listing points in time.
-  ``milestones`` a list of N ``Config`` milestones reached at each of those times.

Typically, a trajectory has ``times[0]=0``, but this is not required.

The difference between these classes is the space in which "straight line"
interpolation is performed.

- The standard ``Trajectory`` class assumes the space is an N-D Euclidean space.
- ``RobotTrajectory`` requires that each milestone is a ``Config`` for the
  specified robot. It will also take any special joints, like freely-rotating
  joints, into account during interpolation, so that, for
  example, a mobile base robot will interpolate its orientation DOF from 0.1
  radians to 6.1 radians the "short way around".
- ``SO3Trajectory`` interpolates in SO(3), in the space of rotation matrices.
  Each milestone is a 9-element rotation matrix (see the `so3 module <klampt.math.so3.html>`__)
  and interpolation is performed using geodesics in SO(3).
- ``SE3Trajectory`` interpolates in SE(3), in the space of rigid transforms.
  Each milestone is a 12-element rotation matrix + translation vector concatenated
  together (see the `se3 module <klampt.math.se3.html>`__) and interpolation
  is performed using geodesics in SE(3).

The basic API uses the following methods:

- ``traj = Trajectory()``: constructs an empty trajectory.  You will need to
  populate the ``times`` and ``milestones`` attributes before using any other
  methods.
- ``traj = Trajectory([t0,t1,...,tn],[q0,q1,...qn])``: constructs a trajectory with
  times t0,t1,...tn and milestones q0,q1,...qn.
- ``traj = Trajectory(milestones=[q0,q1,,...,qn])``: constructs a trajectory with
  milestones q0,q1,...,tn and default uniform timing, times 0,1,...,n.
- ``traj.eval(t)``: evaluates the trajectory, handling out-of-bounds
  times by clamping.  O(log n) time, where n is the number of milestones.
- ``traj.eval(t,'loop')``: evaluates the trajectory, handling out-of-bounds
  times by cycling.
- ``traj.deriv(t)``: evaluates the trajectory derivative, handling out-of-bounds
  times by clamping.  O(log n) time, where n is the number of milestones.
- ``traj.deriv(t,'loop')``: evaluates the trajectory derivative, handling
  out-of-bounds times by cycling.
- ``traj.start/endTime()``: returns the start/end time.
- ``traj.duration()``: returns traj.endTime()-traj.startTime().
- ``traj.load/save(fn)``: loads / saves to a file on disk.

Trajectories can also be modified through concatenation and splicing operations:

- ``traj.concat(suffix,relative=False,jumpPolicy='strict')``: appends a suffix Trajectory
  onto this one.
- ``traj.before/after(t)``: returns the portion of the path before and after time t.
- ``traj.split(t)``: equivalent to ``(traj.before(t),traj.after(t))``
- ``traj.splice(suffix,time=None,relative=False,jumpPolicy='strict')``: splices
  another Trajectory onto this one at a given time.

The ``relative`` parameter, if set to True, means that the suffix starts at
time 0, but should be time-shifted so that it starts at the given insertion
time.  ``jumpPolicy='strict'`` means that an exception will be thrown if the
suffix does not match the trajectory at the insertion time

The knot points in the time domain can also be revised without modifying the
shape of the path (much):

- ``traj.insert(t)``: inserts a milestone at time t, if one doesn't exist.
- ``traj.discretize(dt)``: makes milestones evenly spaced in time, with time dt
  apart. This might slightly change the shape of the path.
- ``traj.remesh(times)``: inserts new milestones at each of the points in
  times.  Equivalent to ``for t in times: traj.insert(t)``, but faster.

Hermite spline interpolation is available in the :class:`~klampt.model.trajectory.HermiteTrajectory`
class in `klampt.model.trajectory <klampt.model.trajectory.html>`__.  You may
either set tangents manually or automatically using the ``makeSpline`` method,
as follows:

.. code:: python

    from klampt.model import trajectory

    traj = trajectory.Trajectory()
    #... set up traj
    traj2 = trajectory.HermiteTrajectory()
    traj2.makeSpline(traj)

For non-Euclidean Hermite splines, you may use the :class:`~klampt.model.trajectory.GeodesicHermiteTrajectory`
representation.  The :class:`~klampt.model.trajectory.SO3HermiteTrajectory` and :class:`~klampt.model.trajectory.SE3HermiteTrajectory`
classes are available for smooth curves in SO(3) and SE(3).  [New in 0.8.3]

Conversions
~~~~~~~~~~~

Conversions between path types are found in
`klampt.model.trajectory <klampt.model.trajectory.html>`__.

In particular the :meth:`~klampt.model.trajectory.path_to_trajectory` method
converts an untimed path into a timed trajectory.  This has many options, and
the example program `path_test.py <https://github.com/krishauser/Klampt-examples/blob/master/Python3/demos/path_test.py>`__
demos several of these options.

To convert from a cubic trajectory to an approximate linear trajectory, the
``discretize_config`` method should be used.

To get the SE(3) trajectory of a link's transform as the robot follows a
RobotTrajectory, use ``RobotTrajectory.getLinkTrajectory(link,dt)``.  Here, dt
is a discretization resolution.  To further convert this to the trajectory of
the position of a point on the link, use ``RobotTrajectory.getLinkTrajectory(link,dt).getPositionTrajectory(localPt)``,
where ``localPt`` gives the local coordinates of the point.

Example
~~~~~~~~~~~~

It is a common task to take a sequence of waypoints, either from a planner or
from manual editing, and convert them into a timed trajectory to be executed.

A list of waypoints is also known as a ``Configs`` object.  We will first
define 7 milestones manually, on an XZ plane:

.. code:: python

    from klampt.model import trajectory

    milestones = [[0,0,0],[0.02,0,0],[1,0,0],[2,0,1],[2.2,0,1.5],[3,0,1],[4,0,-0.3]]

Now let's create a ``Trajectory`` out of it.  The constructor will just assign
a default timing, which is uniformly spaced in time.

.. code:: python

    traj = trajectory.Trajectory(milestones=milestones)

Now, let's see how the eval function works:

.. code:: python

    #prints milestones 0-5
    print(0,":",traj.eval(0))
    print(1,":",traj.eval(1))
    print(2,":",traj.eval(2))
    print(3,":",traj.eval(3))
    print(4,":",traj.eval(4))
    print(5,":",traj.eval(5))
    print(6,":",traj.eval(6))
    #print some interpolated points
    print(0.5,":",traj.eval(0.5))
    print(2.5,":",traj.eval(2.5))
    #print some stuff after the end of trajectory
    print(7,":",traj.eval(7))
    print(100.3,":",traj.eval(100.3))
    print(-2,":",traj.eval(-2))

OK, that seems reasonable.  But it's a little hard to understand what this
looks like through text printouts.  Let's use the visualization to see
how this path behaves:

.. code:: python

    from klampt import vis

    vis.add("point",[0,0,0])
    vis.animate("point",traj)
    vis.add("traj",traj)
    vis.spin(float('inf'))   #show the window until you close it

This will pop up a visualization, show the path, and animate a point along it
as well.

.. image:: _static/images/traj_test1.png

It looks a little like a mountain, and the point moves slowly at the start
before moving along the curve.

Let's now look at what happens when we convert this to a HermiteTrajectory...

.. code:: python

    traj2 = trajectory.HermiteTrajectory()
    traj2.makeSpline(traj)

    vis.animate("point",traj2)
    vis.add("traj2",traj2)
    vis.spin(float('inf'))

.. image:: _static/images/traj_test2.png

Now the point curves smoothly through the milestones we defined!

Finally we might want to address the problem that the milestones are executed
uniformly in the time domain, even though the first two milestones are
identical.  The :meth:`~klampt.model.trajectory.path_to_trajectory` function
has a whole host of options, and you can play around with them until you
get the results that you want.

.. code:: python

    traj_timed = trajectory.path_to_trajectory(traj,vmax=2,amax=4)
    #next, try this line instead
    #traj_timed = trajectory.path_to_trajectory(traj,timing='sqrt-L2',speed='limited',vmax=2,amax=4)
    #or this line
    #traj_timed = trajectory.path_to_trajectory(traj2.discretize(0.1),timing='sqrt-L2',speed=0.3)
    vis.animate("point",traj_timed)
    vis.spin(float('inf'))

Visual keyframe editing
~~~~~~~~~~~~~~~~~~~~~~~~

Trajectories can be edited as keyframes in ``klampt_browser`` or Python code.

As an example of using ``klampt_browser``, run the following script in a command-line terminal:

.. code:: sh

    cd Klampt-examples/data
    klampt_browser athlete_plane.xml

Then expand the "motions" directory and click on one of the motions, such as ``athlete_flex.path``.
Then, click the ``Edit`` button.  You may modify milestones and timing by hand, and save the edited
path back to disk.

In Python code, the same effect is achieved by the :func:`klampt.io.resource.edit` function.

.. code:: python

    from klampt.io import resource

    save,result = resource.edit("my trajectory",traj,world=world)
    if save:
        #the user pressed 'OK'
        traj = result
        #do something with the result, e.g., save it to disk
        from klampt.io import loader
        loader.save(traj,'Trajectory','mytraj.path')
    else:
        #the user pressed 'Cancel'.  result is the last state of the edited trajectory
        pass

Multipaths
----------

A :class:`~klampt.model.multipath.MultiPath` is a rich path representation
for legged robot motion.
They contain one or more path(or trajectory) *sections* along with a set
of IK constraints and holds that should be satisfied during each of the
sections. This information can be used to interpolate between milestones
more intelligently, or for controllers to compute feedforward torques
more intelligently than a raw path. They are loaded and saved to XML
files.

Each ``MultiPath`` section maintains a list of IK constraints in the
``ikObjectives`` member, and a list of ``Hold``\ s in the holds member.
There is also support for storing common holds in the ``MultiPath``\ s
``holdSet`` member, and referencing them through a section's
``holdNames`` or ``holdIndices`` lists (keyed via string or integer
index, respectively). This functionality helps determine which
constraints are shared between sections, and also saves a bit of storage
space.

``MultiPath``\ s also contain arbitrary application-specific settings,
which are stored in a string-keyed dictionary member ``settings``.
Common settings include:

-  ``robot``, which indicates the name of the robot for which the path
   was generated.
-  ``resolution``, which indicates the resolution to which a path has
   been discretized. If resolution has not been set or is too large for
   the given application, a program should use IK to interpolate the
   path.
-  ``program``, the name of the procedure used to generate the path.
-  ``command_line``, the shell command used to invoke the program that
   generated the path.

Sections may also have custom settings. No common settings have yet been
defined for sections, these are all application-dependent.

API summary
~~~~~~~~~~~

Details can be found in the :class:`~klampt.model.multipath.MultiPath` documentation.

The ``klampt_path`` script can also be run to perform various simple transformations
and conversions on ``MultiPath``\ s.

Also, you may see the utility scripts in

  ``Klampt-examples/Python3/utils/multipath\_to\_timed\_path.py``

for an example of assigning times to a multipath.

Cartesian Trajectories
----------------------

A number of Cartesian path generation functions are available in the `cartesian\_trajectory <klampt.model.cartesian_trajectory.html>`__ module.

See the `Control <Manual-Control.html#cartesian-control>`__ manual for more detail about Cartesian motion execution.

Trajectory Execution
--------------------

Sending to a Klamp't simulated robot
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The simplest way to send a path to a :class:`~klampt.SimRobotController` is to use
:meth:`~klampt.model.trajectory.execute_path` (untimed path).  You can also use
:meth:`~klampt.model.trajectory.path_to_trajectory` to generate a timed trajectory,
then :meth:`~klampt.model.trajectory.execute_trajectory`.

For greater control, you may either run an ``eval(t)`` loop to send position
commands, or use the `controller motion queuing process <Manual-Control.html#default-motion-queue-controller>`__.

If you have built or installed the Klampt binaries, you may use the SimTest
program to observe a trajectory in simulation.  Save the trajectory to disk as
a ``Trajectory`` file and the starting ``Config`` as follows:

.. code:: python

    from klampt.io import loader
    loader.save(traj,'Trajectory','my_traj.path')
    loader.save(traj.milestones[0],'Config','my_traj_start.config')

then run

.. code:: sh

    SimTest [world file] -path [name of path file] -config [start config]

Sending to a real robot
~~~~~~~~~~~~~~~~~~~~~~~

To send a Trajectory to your own robot, you can either 1) build your own
control loop or 2) build a `Robot Interface Layer <Manual-Control.html#experimental-robot-interface-layer>`__
object.

**If your robot accepts PID commands**

Set up a while loop to advance time forward and manually send PID commands, like this:

.. code:: python

    import time

    #this code assumes traj is already given, and your controller provides a function pid_command(q,dq)

    def convert_klampt_config(q):
        """Converts klampt config to my robot's config, e.g., extract DOFs,
        convert units, account for joint offsets.

        Right now, does a straight pass-through.
        """
        return q

    def convert_klampt_velocity(dq):
        """Converts klampt velocity to my robot's velocity, e.g., extract DOFs,
        convert units.

        Right now, does a straight pass-through.
        """
        return dq

    dt = 0.01  #approximately a 100Hz control loop
    t0 = time.time())
    while True:
        t = time.time()-t0
        if t > traj.endTime():
            break
        qklampt = traj.eval(t)
        dqklampt = traj.eval(t)
        qrobot = convert_klampt_config(qklampt)
        dqrobot = convert_klampt_velocity(dqklampt)
        pid_command(qrobot,dqrobot)
        time.sleep(dt)
    print("Done")

**If your robot accepts queued, timed waypoints**

Feed each of the trajectory milestones to the robot's queue, like this:

.. code:: python

    #this code assumes traj is already given, and your controller provides a function queue_move(q,duration)
    move_home_duration = 10  #moves slowly to the home configuration over 10 seconds
    lastt = None
    for t,q in zip(traj.times,traj.milestones):
        if lastt is None:
            queue_move(q,move_home_duration)
        else:
            queue_move(q,t-lastt)
        lastt = t

**If your robot uses ROS JointTrajectory messages**

Set up a ROS publisher, and run the conversion utilities in :mod:`klampt.io.ros`:

.. code:: python

    import rospy
    from klampt import io

    ros_publisher = rospy.Publisher(TOPIC,...args...)
    link_joint_names = [... the list of ROS joints corresponding to Klamp't DOFs...]
    msg = io.ros.to_JointTrajectory(traj,link_joint_names=link_joint_names)
    ros_publisher.publish(msg)

**If you have a Robot Interface Layer class**

Use the :meth:`~klampt.control.robotinterface.RobotInterfaceBase.setPiecewiseLinear` function, as follows:

.. code:: python

    ril = MyRobotInterfaceLayer()
    if not ril.initialize():
        raise RuntimeError("Couldn't initialize my robot")
    ril.setPiecewiseLinear(traj.times,traj.milestones)


text:
<?php

namespace pq\Gateway;

include_once __DIR__."/../../../setup.inc";

class TableTest extends \PHPUnit_Framework_TestCase {

	/**
	 * @var \pq\Connection
	 */
	protected $conn;

	/**
	 * @var Table
	 */
	protected $table;

	protected function setUp() {
		$this->conn = new \pq\Connection(PQ_TEST_DSN);
		$this->conn->exec(PQ_TEST_SETUP_SQL);
		Table::$defaultConnection = $this->conn;
		$this->table = new Table("test");
		$this->table->getQueryExecutor()->attach(new \QueryLogger());
	}

	protected function tearDown() {
		$this->conn->exec(PQ_TEST_TEARDOWN_SQL);
	}

	public function testSetRowsetPrototype() {
		$prop = new \ReflectionProperty("\\pq\\Gateway\\Table", "rowset");
		$prop->setAccessible(true);
		$this->assertEquals("\\pq\\Gateway\\Rowset", $prop->getValue($this->table));
		$this->table->setRowsetPrototype(null);
		$this->assertNull($prop->getValue($this->table));
		$rowset = new \pq\Gateway\Rowset($this->table);
		$this->table->setRowsetPrototype($rowset);
		$this->assertSame($rowset, $prop->getValue($this->table));
	}

	public function testGetConnection() {
		$this->assertSame($this->conn, $this->table->getConnection());
	}

	public function testGetName() {
		$this->assertSame("test", $this->table->getName());
	}

	public function testFind() {
		$rowset = $this->table->find();
		$this->assertInstanceOf("\\pq\\Gateway\\Rowset", $rowset);
		$rowset = $this->table->find(array("id = " => 1));
		$this->assertInstanceOf("\\pq\\Gateway\\Rowset", $rowset);
		$rowset = $this->table->find(array("id = " => 0));
		$this->assertInstanceOf("\\pq\\Gateway\\Rowset", $rowset);
		$rowset = $this->table->find(array(array("id<" => 2), array("id>" => 2)));
		$this->assertInstanceOf("\\pq\\Gateway\\Rowset", $rowset);
	}

	public function testCreate() {
		$rowset = $this->table->create(array("id" => new \pq\Query\Expr("DEFAULT")));
		$this->assertInstanceOf("\\pq\\Gateway\\Rowset", $rowset);
		$this->assertCount(1, $rowset);
	}

	public function testUpdate() {
		$row = $this->table->create(array())->current();
		$data = array(
			"created" => new \pq\DateTime("2013-03-03 03:03:03"),
			"counter" => 2,
			"number" => 2.2,
			"data" => "this is a test",
			"list" => array(3,2,1),
			"prop" => null
		);
		$row = $this->table->update(array("id = " => $row->id), $data)->current();
		$data = array("id" => $row->id->get()) + $data;
		$this->assertEquals($data, $row->getData());
	}

	public function testDelete() {
		$this->table->delete(array("id!=" => 0));
		$this->assertCount(0, $this->table->find());
	}

	public function testWith() {
		$rowset = $this->table->with(["reftest"], array("another_test_id=" => 2));
		$this->assertCount(1, $rowset);
		$this->assertEquals(array(
			"id" => 2,
			"created" => new \pq\DateTime("today"),
			"counter" => 0,
			"number" => 0,
			"data" => "today",
			"list" => array(0,1,2),
			"prop" => null
		), $rowset->current()->getData());
	}
}


text:
import Backbone from 'backbone';
import Config from 'config';

var Job = Backbone.Model.extend({
  idAttribute: 'id',
  urlRoot: Config.get('Client.restServer.address') + Config.get('Client.restServer.apiRoot') + Config.get('Client.restServer.jobPath')
});

export default Job;


text:
"""
Copyright 2015 SmartBear Software

    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.

    Ref: https://github.com/swagger-api/swagger-codegen
"""

from pprint import pformat
from six import iteritems

class NetworkIdInfo(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self):
        """
        NetworkIdInfo - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'network_id': 'int'
        }

        self.attribute_map = {
            'network_id': 'networkId'
        }

        self._network_id = None

    @property
    def network_id(self):
        """
        Gets the network_id of this NetworkIdInfo.
        Network id

        :return: The network_id of this NetworkIdInfo.
        :rtype: int
        """
        return self._network_id

    @network_id.setter
    def network_id(self, network_id):
        """
        Sets the network_id of this NetworkIdInfo.
        Network id

        :param network_id: The network_id of this NetworkIdInfo.
        :type: int
        """
        self._network_id = network_id

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace OpenIddict.Abstractions.Tests
{
    public class OpenIddictBuilderTests
    {
        [Fact]
        public void Constructor_ThrowsAnExceptionForNullServices()
        {
            // Arrange
            var services = (IServiceCollection) null;

            // Act and assert
            var exception = Assert.Throws<ArgumentNullException>(() => new OpenIddictBuilder(services));

            Assert.Equal("services", exception.ParamName);
        }
    }
}


text:
"""
    flask_admin._backwards
    ~~~~~~~~~~~~~~~~~~~~~~~~~~

    Backward compatibility helpers.
"""
import sys
import warnings

def get_property(obj, name, old_name, default=None):
    """
        Check if old property name exists and if it does - show warning message
        and return value.

        Otherwise, return new property value

        :param name:
            New property name
        :param old_name:
            Old property name
        :param default:
            Default value
    """
    if hasattr(obj, old_name):
        warnings.warn('Property %s is obsolete, please use %s instead' %
                      (old_name, name), stacklevel=2)
        return getattr(obj, old_name)

    return getattr(obj, name, default)

class ObsoleteAttr(object):
    def __init__(self, new_name, old_name, default):
        self.new_name = new_name
        self.old_name = old_name
        self.cache = '_cache_' + new_name
        self.default = default

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self

        # Check if we have new cached value
        if hasattr(obj, self.cache):
            return getattr(obj, self.cache)

        # Check if there's old attribute
        if hasattr(obj, self.old_name):
            warnings.warn('Property %s is obsolete, please use %s instead' %
                          (self.old_name, self.new_name), stacklevel=2)
            return getattr(obj, self.old_name)

        # Return default otherwise
        return self.default

    def __set__(self, obj, value):
        setattr(obj, self.cache, value)

class ImportRedirect(object):
    def __init__(self, prefix, target):
        self.prefix = prefix
        self.target = target

    def find_module(self, fullname, path=None):
        if fullname.startswith(self.prefix):
            return self

    def load_module(self, fullname):
        if fullname in sys.modules:
            return sys.modules[fullname]

        path = self.target + fullname[len(self.prefix):]
        __import__(path)

        module = sys.modules[fullname] = sys.modules[path]
        return module

def import_redirect(old, new):
    sys.meta_path.append(ImportRedirect(old, new))


text:
Ruby Capstone Project

## Project Vision

This is a small command line cigar review program. You can set options for
cigar length, ring size, type, contruction, and country of origin.

## Features

### Adding a new cigar

Add pleasurable cigars to a central list.

Usage Example:

  > ./ash_tray manage
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit
  > 1
  > Enter name
  > Mille Fleurs
  > Enter length
  > 5"
  > Enter ring gauge
  > 42
  > Enter maker
  > Romeo y Julieta
  > Select type
  > Petit Coronas
  > Select wrapper country of origin
  > Cuba
  > Select filler country of origin
  > Cuba
  > Select binder country of origini
  > Cuba
  > Enter rating (1-5)
  > 4
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit

Accaptence Criteria:

  * Program allows for entries
  * Returns to menu

### Editting an existing cigar for updating cigar reviews

Sometimes your taste for a particular cigar will change and you will
want to change you review accordingly.

Usage Example:

  > ./ash_tray manage
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit
  > 2
  1. Name: Mille Fleurs
  2. Length: 5"
  3. Ring Gauge: 42
  4. Maker: Romeo y Julieta
  5. Type: Petit Coronas
  6. Wrapper: Cuba
  7. Filler: Cuba
  8. Binder: Cuba
  9. Rating: 3
  > 9
  Enter rating
  > 3
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit

 Accaptence Criteria:

  * Program allows entries to be edited
  * Returns user to menu after editing the selection

### Deleting a cigar

And then somtimes you just want to forget about a cigar.

Usage Example:

  > ./ash_tray manage
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit
  > 3
  1. Mille Fleurs
  > 1
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit

Accapt

### Veiwing list of all cigars

Keep a list of all the cigars you have tried. Also maybe be a little
ashamed of all the money you have spent on them. Regret nothing.

Usage Example:

  > ./ash_tray manage
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit
  > 4
  1. Romeo y Julieta, Mille Fleurs, Wrapper: Cuba, Binder: Cuba,
     Filler: Cuba, Length: 5", Ring Gauge: 42, Shape: Petit Coronas,
     Rating: 3
  1. Add a cigar
  2. List cigars
  3. Edit a cigar
  4. Delete a cigar
  5. Exit

Accaptence Criteria:

  * Lists of cigars populates
  * Returns to menu after list populates


text:
TESTLIST=$2
if [ "$ne" == '1' ]
then
  echo "Usage: $0 <verilator, vcs> <testlist> [num_cores]"
  exit 1
elif [ $1 == "vcs" ]
then
    SUFFIX=v
elif [ $1 == "verilator" ]
then
    SUFFIX=sc
else
  echo "Usage: $0 <verilator, vcs> <testlist> [num_cores]"
  exit 1
fi

# Default to 1 core
N=${3:-1}

# Bash array to iterate over for configurations
cfgs=(\
    "e_bp_multicore_4_l2e_cfg"
    "e_bp_multicore_1_l2e_cfg"
    )

# Any setup needed for the job
echo "Cleaning bp_top"
make -C bp_top/syn clean

let JOBS=${#cfgs[@]}
let CORES_PER_JOB=${N}/${JOBS}+1

# Run the regression in parallel on each configuration
cmd_base="make -C bp_top/syn build.${SUFFIX} sim.${SUFFIX} COSIM_P=1 SUITE=bp-tests PROG=cache_hammer DRAM=axi"
echo "Running ${JOBS} jobs with ${CORES_PER_JOB} cores per job"
parallel --jobs ${JOBS} --results regress_logs --progress "$cmd_base CFG={}" ::: "${cfgs[@]}"

# Check for failures in the report directory
grep -cr "FAIL" */syn/reports/ && echo "[CI CHECK] $0: FAILED" && exit 1
echo "[CI CHECK] $0: PASSED" && exit 0


text:
FactoryGirl.define do
  factory :course_summary do
    content "This is a great party! I really like it!"
    course
  end
end


text:
namespace P04.Generic_Swap_Method_Integer
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using P01.Generic_Box_of_String;

    public class StartUp
    {
        public static void Main()
        {
            IList<Box<int>> boxes = MakeBoxes();
            boxes = SwapPositions(boxes);
            PrintBoxes(boxes);
        }

        private static void PrintBoxes(IList<Box<int>> boxes)
        {
            foreach (var box in boxes)
            {
                Console.WriteLine(box);
            }
        }

        private static IList<Box<int>> SwapPositions(IList<Box<int>> boxes)
        {
            int[] swapPositions = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int firstIndex = swapPositions[0];
            int secondIndex = swapPositions[1];
            var firstPosition = boxes[firstIndex];
            boxes[firstIndex] = boxes[secondIndex];
            boxes[secondIndex] = firstPosition;

            return boxes;
        }

        private static IList<Box<int>> MakeBoxes()
        {
            int numberOfStrings = int.Parse(Console.ReadLine());
            IList<Box<int>> boxes = new List<Box<int>>();

            for (int i = 0; i < numberOfStrings; i++)
            {
                string content = Console.ReadLine();

                Box<int> box = new Box<int>(int.Parse(content));
                boxes.Add(box);
            }

            return boxes;
        }
    }
}


text:
import { Event } from 'microevent.ts';

import Pool from '../../tools/pool/Pool';
import InducedPool from '../../tools/pool/InducedPool';
import PoolMemberInterface from '../../tools/pool/PoolMemberInterface';
import PCMAudioEndpointInterface from './PCMAudioEndpointInterface';
import PCMAudioOutputInterface from '../../machine/io/PCMAudioOutputInterface';
import AudioOutputBuffer from '../../tools/AudioOutputBuffer';

class PCMAudioEndpoint implements PCMAudioEndpointInterface {
    constructor(private _output: PCMAudioOutputInterface) {
        this._output.newFrame.addHandler((buffer: AudioOutputBuffer) =>
            this.newFrame.dispatch(this._pcmDataPool.get(this._audioBufferMap.get(buffer)))
        );

        this._output.togglePause.addHandler((paused: boolean) => this.togglePause.dispatch(paused));

        this._output.setFrameBufferFactory(() => {
            const wrappedBuffer = this._audioBufferPool.get();

            if (!this._audioBufferMap.has(wrappedBuffer.get())) {
                this._audioBufferMap.set(wrappedBuffer.get(), wrappedBuffer);
            }

            return wrappedBuffer.get();
        });
    }

    getSampleRate(): number {
        return this._output.getSampleRate();
    }

    getFrameSize(): number {
        return this._output.getFrameSize();
    }

    isPaused(): boolean {
        return this._output.isPaused();
    }

    newFrame = new Event<PoolMemberInterface<Float32Array>>();

    togglePause = new Event<boolean>();

    private _audioBufferPool = new Pool<AudioOutputBuffer>(
        () => new AudioOutputBuffer(new Float32Array(this.getFrameSize()), this.getSampleRate())
    );

    private _audioBufferMap = new WeakMap<AudioOutputBuffer, PoolMemberInterface<AudioOutputBuffer>>();

    private _pcmDataPool = new InducedPool(
        (buffer: AudioOutputBuffer) => buffer.getContent(),
        (value: PoolMemberInterface<AudioOutputBuffer>, target: Float32Array) =>
            value.get().replaceUnderlyingBuffer(target)
    );
}

export { PCMAudioEndpoint as default };


text:
using System;
using System.ComponentModel;
using System.Linq;

using JetBrains.Annotations;

using Newtonsoft.Json;

using Tauco.Dicom.Shared.Converters;

namespace Tauco.Dicom.Shared
{
    /// <summary>
    /// Represents dicom patient name.
    /// </summary>
    [TypeConverter(typeof(PatientNameTypeConverter))]
    [JsonConverter(typeof(PatientNameJsonConverter))]
    public class PatientName
    {
        /// <summary>
        /// Instantiate new instance of <see cref="PatientName"/>
        /// </summary>
        /// <param name="dicomString">Name in dicom format (Last Name^First Name^Middle Name^Prefix^Suffix)</param>
        /// <exception cref="ArgumentNullException"><paramref name="dicomString"/> is <see langword="null"/></exception>
        public PatientName([NotNull] string dicomString)
        {
            if (dicomString == null)
            {
                throw new ArgumentNullException(nameof(dicomString));
            }

            var names = dicomString.Split('^');

            LastName = GetName(names, 0);
            FirstName = GetName(names, 1);
            MiddleName = GetName(names, 2);
            Prefix = GetName(names, 3);
            Suffix = GetName(names, 4);
        }

        /// <summary>
        /// Gets or sets first name of the patient.
        /// </summary>
        public string FirstName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets middle name fo the patient.
        /// </summary>
        public string MiddleName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets last name of the patient.
        /// </summary>
        public string LastName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets patient's name prefix.
        /// </summary>
        public string Prefix
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets patient's name suffix.
        /// </summary>
        public string Suffix
        {
            get;
            set;
        }

        /// <summary>
        /// Gets dicom string representation of name in format Last Name^First Name^Middle Name^Prefix^Suffix
        /// </summary>
        public string DicomString
        {
            get
            {
                var names = new[]
                {
                    LastName, FirstName, MiddleName, Prefix, Suffix
                };

                return string.Join("^", names).TrimEnd('^');
            }
        }

        /// <summary>
        /// Returns string representation of the patient name.
        /// </summary>
        /// <returns>
        /// String representation of the patient name
        /// </returns>
        public override string ToString()
        {
            var names = new[]
            {
                Prefix, FirstName, MiddleName, LastName, Suffix
            };

            return string.Join(" ", names.Where(c => !string.IsNullOrWhiteSpace(c)));
        }

        /// <summary>
        /// Gets single name from the given <paramref name="nameArray"/> according to the given <paramref name="index"/>.
        /// </summary>
        /// <param name="nameArray">Array of all names</param>
        /// <param name="index">Index of name to be obtained</param>
        /// <returns>If element at <paramref name="index"/> is empty or <see langword="null"/>, returns <see langword="null"/>; otherwise, returns the value</returns>
        private string GetName(string[] nameArray, int index)
        {
            var name = nameArray.ElementAtOrDefault(index);
            if (name == string.Empty)
            {
                return null;
            }

            return name;
        }

        /// <summary>
        /// Compares with another <see cref="PatientName"/> and returns whether their string representations equals.
        /// </summary>
        /// <param name="other">Other object to be checked</param>
        /// <returns>True, if <see cref="DicomString"/> is equal; otherwise, false</returns>
        protected bool Equals(PatientName other)
        {
            return DicomString.Equals(other.DicomString);
        }

        /// <summary>
        /// Compares with another object and returns whether their string representations equals.
        /// </summary>
        /// <param name="obj">Other object to be checked</param>
        /// <returns>True, if object is equal; otherwise, false</returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }
            if (ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj is string)
            {
                return DicomString == (string) obj;
            }
            if (obj.GetType() != GetType())
            {
                return false;
            }
            return Equals((PatientName) obj);
        }

        /// <summary>
        /// Compares with another object and returns whether string representation of <paramref name="obj"/> is contained within <see cref="DicomString"/>.
        /// </summary>
        /// <param name="obj">Other object to be checked</param>
        /// <returns>True, if object is contained; otherwise, false</returns>
        public bool Contains(object obj)
        {
            if (obj is string)
            {
                string objString = (string) obj;
                return DicomString.Contains(objString);
            }

            return DicomString.Contains(obj.ToString());
        }

        /// <summary>
        /// Returns the hash code for the identifier.
        /// </summary>
        /// <returns>
        /// A 32-bit signed integer hash code.
        /// </returns>
        public override int GetHashCode()
        {
            return DicomString.GetHashCode();
        }
    }
}


text:
/**
 * BaseControllerTest.java
 */
package com.canzs.lhjz.base;

import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * 控制层测试基类.
 *
 * @creation 2013年12月26日 下午3:44:55
 * @modification 2013年12月26日 下午3:44:55
 * @company Canzs
 * @author xiweicheng
 * @version 1.0
 *
 */
@WebAppConfiguration
public class BaseControllerTest extends BaseTest {

	@Autowired
	protected WebApplicationContext context;

	@Autowired
	protected MockHttpSession session;

	@Autowired
	protected MockHttpServletRequest request;

	protected MockMvc mockMvc;

	@Before
	public void setup() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}
}


text:
<?php
/**
 * This file is part of the Ray.RoleModule
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace Ray\RoleModule;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\Reader;
use Koriym\Attributes\AttributeReader;
use Koriym\Attributes\DualReader;
use Ray\RoleModule\Annotation\RequiresRoles;
use Ray\Di\AbstractModule;
use Ray\Di\Scope;
use Laminas\Permissions\Acl\AclInterface;

class ZendAclModule extends AbstractModule
{
    /**
     * @var AclInterface
     */
    private $acl;

    /**
     * @var string
     */
    private $roleProvider;

    /**
     * @param AclInterface $acl
     * @param string       $roleProviderClass
     */
    public function __construct(AclInterface $acl, $roleProviderClass)
    {
        $this->acl = $acl;
        $this->roleProvider = $roleProviderClass;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->bind(Reader::class)->toConstructor(DualReader::class, [
            'annotationReader' => 'annotation',
            'attributeReader' => 'attribute',
        ]);
        $this->bind(Reader::class)->annotatedWith('annotation')->to(AnnotationReader::class);
        $this->bind(Reader::class)->annotatedWith('attribute')->to(AttributeReader::class);
        $this->bind(AclInterface::class)->toInstance($this->acl);
        $this->bind(RoleProviderInterface::class)->to($this->roleProvider)->in(Scope::SINGLETON);
        // method
        $this->bindInterceptor(
            $this->matcher->any(),
            $this->matcher->annotatedWith(RequiresRoles::class),
            [RequiredRolesInterceptor::class]
        );
        //  class
        $this->bindInterceptor(
            $this->matcher->annotatedWith(RequiresRoles::class),
            $this->matcher->any(),
            [RequiredRolesInterceptor::class]
        );
    }
}


text:
<html>
<head>
<script>
// When we create an XHR from onunload, we expect it to be cancelled almost
// immediately afterwards.  When that happens the XHR's onabort handler is
// called.  The XHR created from there is cancelled again, but at a later point
// after this FRAME has already been detached from its parent.
var requests = [];
function startRequest() {
  var x = new XMLHttpRequest();
  x.open("GET", location, true);
  x.onabort = startRequest;
  x.send(null);
  requests.push(x);
}
</script>
</head>
<body onunload="startRequest()"></body>
</html>


text:
<?php

namespace Slashworks\AppBundle\Model\om;

use \Criteria;
use \Exception;
use \ModelCriteria;
use \ModelJoin;
use \PDO;
use \Propel;
use \PropelCollection;
use \PropelException;
use \PropelObjectCollection;
use \PropelPDO;
use Slashworks\AppBundle\Model\Customer;
use Slashworks\AppBundle\Model\UserCustomerRelation;
use Slashworks\AppBundle\Model\UserCustomerRelationPeer;
use Slashworks\AppBundle\Model\UserCustomerRelationQuery;
use Slashworks\BackendBundle\Model\User;

/**
 * @method UserCustomerRelationQuery orderById($order = Criteria::ASC) Order by the id column
 * @method UserCustomerRelationQuery orderByUserId($order = Criteria::ASC) Order by the user_id column
 * @method UserCustomerRelationQuery orderByCustomerId($order = Criteria::ASC) Order by the customer_id column
 *
 * @method UserCustomerRelationQuery groupById() Group by the id column
 * @method UserCustomerRelationQuery groupByUserId() Group by the user_id column
 * @method UserCustomerRelationQuery groupByCustomerId() Group by the customer_id column
 *
 * @method UserCustomerRelationQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method UserCustomerRelationQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method UserCustomerRelationQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method UserCustomerRelationQuery leftJoinUser($relationAlias = null) Adds a LEFT JOIN clause to the query using the User relation
 * @method UserCustomerRelationQuery rightJoinUser($relationAlias = null) Adds a RIGHT JOIN clause to the query using the User relation
 * @method UserCustomerRelationQuery innerJoinUser($relationAlias = null) Adds a INNER JOIN clause to the query using the User relation
 *
 * @method UserCustomerRelationQuery leftJoinCustomer($relationAlias = null) Adds a LEFT JOIN clause to the query using the Customer relation
 * @method UserCustomerRelationQuery rightJoinCustomer($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Customer relation
 * @method UserCustomerRelationQuery innerJoinCustomer($relationAlias = null) Adds a INNER JOIN clause to the query using the Customer relation
 *
 * @method UserCustomerRelation findOne(PropelPDO $con = null) Return the first UserCustomerRelation matching the query
 * @method UserCustomerRelation findOneOrCreate(PropelPDO $con = null) Return the first UserCustomerRelation matching the query, or a new UserCustomerRelation object populated from the query conditions when no match is found
 *
 * @method UserCustomerRelation findOneByUserId(int $user_id) Return the first UserCustomerRelation filtered by the user_id column
 * @method UserCustomerRelation findOneByCustomerId(int $customer_id) Return the first UserCustomerRelation filtered by the customer_id column
 *
 * @method array findById(int $id) Return UserCustomerRelation objects filtered by the id column
 * @method array findByUserId(int $user_id) Return UserCustomerRelation objects filtered by the user_id column
 * @method array findByCustomerId(int $customer_id) Return UserCustomerRelation objects filtered by the customer_id column
 */
abstract class BaseUserCustomerRelationQuery extends ModelCriteria
{
    /**
     * Initializes internal state of BaseUserCustomerRelationQuery object.
     *
     * @param     string $dbName The dabase name
     * @param     string $modelName The phpName of a model, e.g. 'Book'
     * @param     string $modelAlias The alias for the model in this query, e.g. 'b'
     */
    public function __construct($dbName = null, $modelName = null, $modelAlias = null)
    {
        if (null === $dbName) {
            $dbName = 'default';
        }
        if (null === $modelName) {
            $modelName = 'Slashworks\\AppBundle\\Model\\UserCustomerRelation';
        }
        parent::__construct($dbName, $modelName, $modelAlias);
    }

    /**
     * Returns a new UserCustomerRelationQuery object.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param   UserCustomerRelationQuery|Criteria $criteria Optional Criteria to build the query from
     *
     * @return UserCustomerRelationQuery
     */
    public static function create($modelAlias = null, $criteria = null)
    {
        if ($criteria instanceof UserCustomerRelationQuery) {
            return $criteria;
        }
        $query = new UserCustomerRelationQuery(null, null, $modelAlias);

        if ($criteria instanceof Criteria) {
            $query->mergeWith($criteria);
        }

        return $query;
    }

    /**
     * Find object by primary key.
     * Propel uses the instance pool to skip the database if the object exists.
     * Go fast if the query is untouched.
     *
     *
     * $obj  = $c->findPk(12, $con);
     *
     *
     * @param mixed $key Primary key to use for the query
     * @param     PropelPDO $con an optional connection object
     *
     * @return   UserCustomerRelation|UserCustomerRelation[]|mixed the result, formatted by the current formatter
     */
    public function findPk($key, $con = null)
    {
        if ($key === null) {
            return null;
        }
        if ((null !== ($obj = UserCustomerRelationPeer::getInstanceFromPool((string) $key))) && !$this->formatter) {
            // the object is already in the instance pool
            return $obj;
        }
        if ($con === null) {
            $con = Propel::getConnection(UserCustomerRelationPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }
        $this->basePreSelect($con);
        if ($this->formatter || $this->modelAlias || $this->with || $this->select
         || $this->selectColumns || $this->asColumns || $this->selectModifiers
         || $this->map || $this->having || $this->joins) {
            return $this->findPkComplex($key, $con);
        } else {
            return $this->findPkSimple($key, $con);
        }
    }

    /**
     * Alias of findPk to use instance pooling
     *
     * @param     mixed $key Primary key to use for the query
     * @param     PropelPDO $con A connection object
     *
     * @return                 UserCustomerRelation A model object, or null if the key is not found
     * @throws PropelException
     */
     public function findOneById($key, $con = null)
     {
        return $this->findPk($key, $con);
     }

    /**
     * Find object by primary key using raw SQL to go fast.
     * Bypass doSelect() and the object formatter by using generated code.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     PropelPDO $con A connection object
     *
     * @return                 UserCustomerRelation A model object, or null if the key is not found
     * @throws PropelException
     */
    protected function findPkSimple($key, $con)
    {
        $sql = 'SELECT `id`, `user_id`, `customer_id` FROM `user_customer_relation` WHERE `id` = :p0';
        try {
            $stmt = $con->prepare($sql);
            $stmt->bindValue(':p0', $key, PDO::PARAM_INT);
            $stmt->execute();
        } catch (Exception $e) {
            Propel::log($e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
        }
        $obj = null;
        if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $obj = new UserCustomerRelation();
            $obj->hydrate($row);
            UserCustomerRelationPeer::addInstanceToPool($obj, (string) $key);
        }
        $stmt->closeCursor();

        return $obj;
    }

    /**
     * Find object by primary key.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     PropelPDO $con A connection object
     *
     * @return UserCustomerRelation|UserCustomerRelation[]|mixed the result, formatted by the current formatter
     */
    protected function findPkComplex($key, $con)
    {
        // As the query uses a PK condition, no limit(1) is necessary.
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $stmt = $criteria
            ->filterByPrimaryKey($key)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
    }

    /**
     * Find objects by primary key
     *
     * $objs = $c->findPks(array(12, 56, 832), $con);
     *
     * @param     array $keys Primary keys to use for the query
     * @param     PropelPDO $con an optional connection object
     *
     * @return PropelObjectCollection|UserCustomerRelation[]|mixed the list of results, formatted by the current formatter
     */
    public function findPks($keys, $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
        }
        $this->basePreSelect($con);
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $stmt = $criteria
            ->filterByPrimaryKeys($keys)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->format($stmt);
    }

    /**
     * Filter the query by primary key
     *
     * @param     mixed $key Primary key to use for the query
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function filterByPrimaryKey($key)
    {

        return $this->addUsingAlias(UserCustomerRelationPeer::ID, $key, Criteria::EQUAL);
    }

    /**
     * Filter the query by a list of primary keys
     *
     * @param     array $keys The list of primary key to use for the query
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function filterByPrimaryKeys($keys)
    {

        return $this->addUsingAlias(UserCustomerRelationPeer::ID, $keys, Criteria::IN);
    }

    /**
     * Filter the query on the id column
     *
     * Example usage:
     *
     * $query->filterById(1234); // WHERE id = 1234
     * $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
     * $query->filterById(array('min' => 12)); // WHERE id >= 12
     * $query->filterById(array('max' => 12)); // WHERE id <= 12
     *
     *
     * @param     mixed $id The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function filterById($id = null, $comparison = null)
    {
        if (is_array($id)) {
            $useMinMax = false;
            if (isset($id['min'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::ID, $id['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($id['max'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::ID, $id['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(UserCustomerRelationPeer::ID, $id, $comparison);
    }

    /**
     * Filter the query on the user_id column
     *
     * Example usage:
     *
     * $query->filterByUserId(1234); // WHERE user_id = 1234
     * $query->filterByUserId(array(12, 34)); // WHERE user_id IN (12, 34)
     * $query->filterByUserId(array('min' => 12)); // WHERE user_id >= 12
     * $query->filterByUserId(array('max' => 12)); // WHERE user_id <= 12
     *
     *
     * @see       filterByUser()
     *
     * @param     mixed $userId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function filterByUserId($userId = null, $comparison = null)
    {
        if (is_array($userId)) {
            $useMinMax = false;
            if (isset($userId['min'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($userId['max'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(UserCustomerRelationPeer::USER_ID, $userId, $comparison);
    }

    /**
     * Filter the query on the customer_id column
     *
     * Example usage:
     *
     * $query->filterByCustomerId(1234); // WHERE customer_id = 1234
     * $query->filterByCustomerId(array(12, 34)); // WHERE customer_id IN (12, 34)
     * $query->filterByCustomerId(array('min' => 12)); // WHERE customer_id >= 12
     * $query->filterByCustomerId(array('max' => 12)); // WHERE customer_id <= 12
     *
     *
     * @see       filterByCustomer()
     *
     * @param     mixed $customerId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function filterByCustomerId($customerId = null, $comparison = null)
    {
        if (is_array($customerId)) {
            $useMinMax = false;
            if (isset($customerId['min'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customerId['min'], Criteria::GREATER_EQUAL);
                $useMinMax = true;
            }
            if (isset($customerId['max'])) {
                $this->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customerId['max'], Criteria::LESS_EQUAL);
                $useMinMax = true;
            }
            if ($useMinMax) {
                return $this;
            }
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }
        }

        return $this->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customerId, $comparison);
    }

    /**
     * Filter the query by a related User object
     *
     * @param   User|PropelObjectCollection $user The related object(s) to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return                 UserCustomerRelationQuery The current query, for fluid interface
     * @throws PropelException - if the provided filter is invalid.
     */
    public function filterByUser($user, $comparison = null)
    {
        if ($user instanceof User) {
            return $this
                ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->getId(), $comparison);
        } elseif ($user instanceof PropelObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(UserCustomerRelationPeer::USER_ID, $user->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterByUser() only accepts arguments of type User or PropelCollection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the User relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function joinUser($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('User');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'User');
        }

        return $this;
    }

    /**
     * Use the User relation User object
     *
     * @see       useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return   \Slashworks\BackendBundle\Model\UserQuery A secondary query class using the current class as primary query
     */
    public function useUserQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinUser($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'User', '\Slashworks\BackendBundle\Model\UserQuery');
    }

    /**
     * Filter the query by a related Customer object
     *
     * @param   Customer|PropelObjectCollection $customer The related object(s) to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return                 UserCustomerRelationQuery The current query, for fluid interface
     * @throws PropelException - if the provided filter is invalid.
     */
    public function filterByCustomer($customer, $comparison = null)
    {
        if ($customer instanceof Customer) {
            return $this
                ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->getId(), $comparison);
        } elseif ($customer instanceof PropelObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(UserCustomerRelationPeer::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterByCustomer() only accepts arguments of type Customer or PropelCollection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the Customer relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function joinCustomer($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('Customer');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'Customer');
        }

        return $this;
    }

    /**
     * Use the Customer relation Customer object
     *
     * @see       useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return   \Slashworks\AppBundle\Model\CustomerQuery A secondary query class using the current class as primary query
     */
    public function useCustomerQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinCustomer($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'Customer', '\Slashworks\AppBundle\Model\CustomerQuery');
    }

    /**
     * Exclude object from result
     *
     * @param   UserCustomerRelation $userCustomerRelation Object to remove from the list of results
     *
     * @return UserCustomerRelationQuery The current query, for fluid interface
     */
    public function prune($userCustomerRelation = null)
    {
        if ($userCustomerRelation) {
            $this->addUsingAlias(UserCustomerRelationPeer::ID, $userCustomerRelation->getId(), Criteria::NOT_EQUAL);
        }

        return $this;
    }

}


text:
<!--
  ~ Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
  ~
  ~ 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.
  -->

<html xmlns:wicket="http://wicket.apache.org">
<body>
<wicket:panel>
    <wicket:child/>
    <!--TODO mover essas propriedades para o singular static-->
    <style type="text/css">
        .action-column {
            text-align: right;
        }

        .studio-action:focus {
            box-shadow: none;
            color: #337ab7;
        }
    </style>
</wicket:panel>
</body>
</html>